Karan Jtv Karan Jtv - 2 months ago 15
Android Question

Android App Exit on Back Button

I m trying to exit my application on touching the back button. I ve used the usual code, but it only takes out the app from the screen and when i Click on the square box on the bottom right (also tell me whats it called) i can still see the app running the background i want to remove it totally from the system.
i ve tried all of them finish(); and System.exit(0); they just pass the app to the background from the fore ground. I want to remove it completely from the system.

The following the code i am using.

@Override
public void onBackPressed() {

new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
System.exit(0);
}
}).setNegativeButton("no", null).show();

}

Answer

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); will clear previous activities. Using this, finish() call won't be necessary.

And System.exit(0); is used in java, not android, so don't use this anymore. Use finish() or getActivity().finish() in fragment to close current activity.

Update:

If you want to kill the app in order to not run any more in background, you need to do something like this

ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE); am.killBackgroundProcesses(packageName);

Where packagename is your app package. And you need to provide permission <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />. I think this need to be requested on M. Have a try.