How can I close my application on back pressed in android

后端 未结 12 1410
轻奢々
轻奢々 2021-01-14 00:04

I want to go on home screen when I press device\'s back button.I am using this code..

public void onBackPressed() {
   this.finish();
   return;
}

12条回答
  •  盖世英雄少女心
    2021-01-14 00:40

    Ok, for launching Home sceen of your device use this code in your onKeyDown()

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event)  { 
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 
            // do something on back.
            Intent startMain = new Intent(Intent.ACTION_MAIN); 
            startMain.addCategory(Intent.CATEGORY_HOME); 
            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            startActivity(startMain); 
    
           this.finish(); 
            return true; 
        } 
    
        return super.onKeyDown(keyCode, event); 
    } 
    

    And if you want to close your application then I think either you have to close your all activities by finish() in a manner (some standard way) or using

    android.os.Process.killProcess(android.os.Process.myPid()) this code kill your app. (Some ugly way..!)

提交回复
热议问题