How to kill process by clicking back button in Android?

15,149

Solution 1

Try this code

@Override
public void onBackPressed() {
   yourActivity.this.finish;
}

Solution 2

override onBackPressed() in your activity and add your necessary codes there

onBackPressed

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

Solution 3

you can do like this onclick of back button.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
         finish();// call finish() on click of back button
    }
    return super.onKeyDown(keyCode, event);
}

for example : When you moving from A activity to B activity using startActivity(new intent(...)); don't finish or kill A activity, It ll be in stack.So when you click on back button in B activity you can go back to A activity, which is already in stack.

when you want to go back to main menu call finish() on every activity when your moving to next activity.

for example : When you moving from A activity to B activity using startActivity(new intent(...)); call finish() to kill A activity.So when you click on back button in B activity you can go back to Main Menu coz every activity ll be killed.

snippet is here :

startActivity(new intent(A.this, B.class));
finish(); // when you click back button on B activity, directly you can go to main menu

Updated : Other way to kill the app using below code on back button pressed. But not recommended

 @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
         android.os.Process.killProcess(android.os.Process.myPid());// Kill the app on click of back button.
    }
    return super.onKeyDown(keyCode, event);
}

hope this might help you to understand the concept.

Solution 4

Just clear the activity history so that your application gets closed.And call finsh(); afterstartActivity();

  <activity
        android:name="com.example.abcd.Your_Acitivty"
        android:noHistory="true">
  </activity>

Happy Coding !

Share:
15,149
jimmy cool
Author by

jimmy cool

Crazzy boyy

Updated on June 04, 2022

Comments

  • jimmy cool
    jimmy cool almost 2 years

    I have made an application in android .It is an application related to timer.Now i have tried a lot to put controll on back button of android device that when it is pressed the process should be killed and directly displays main menu...Please help me...Thanking you in advance..!enter image description here