How can I close my application on back pressed in android

后端 未结 12 1272
轻奢々
轻奢々 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:17

    When you call NewAcitivy call finish().After startActivity so the previous acitivity gets closed.

    Then use

    @Override
        public void onBackPressed() {
            super.onBackPressed();
            this.finish();
        }
    
    0 讨论(0)
  • 2021-01-14 00:19

    You should override finish()

    @Override
    public void finish() {
        System.out.println("finish activity");      
        SaveData();     
        System.runFinalizersOnExit(true) ;          
        super.finish();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    

    Then invoke this method like this:

    @Override
        public void onBackPressed() {
         this.finish();
        }
    
    0 讨论(0)
  • 2021-01-14 00:19

    You can try this:

    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {       
      if(keyCode==KeyEvent.KEYCODE_BACK){
            this.finish ();
          }
        return true;
    }
    
    0 讨论(0)
  • 2021-01-14 00:23

    You can close application from anywhere to call this type of Intent:

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    This is the best way for close application from anywhere, on any click event

    0 讨论(0)
  • 2021-01-14 00:23

    You need to start an intent using a flag to clear the activities on top of the actual activity.

    public void onBackPressed() {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(intent);
        this.finish();
    }
    
    0 讨论(0)
  • 2021-01-14 00:24

    u want to Override the OnkeyDown & finish activity

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // do something on back.
           this.finish();
            return true;
        }
    
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
提交回复
热议问题