I want to close my application, so that it no longer runs in the background.
How to do that? Is this good practice on Android platform?
If I rely on the \"ba
For exiting app ways:
Way 1 :
call finish();
and override onDestroy();
. Put the following code in onDestroy()
:
System.runFinalizersOnExit(true)
or
android.os.Process.killProcess(android.os.Process.myPid());
Way 2 :
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
Way 3 :
Quit();
protected void Quit() {
super.finish();
}
Way 4 :
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
Way 5 :
Sometimes calling finish()
will only exit the current activity, not the entire application. However, there is a workaround for this. Every time you start an activity
, start it using startActivityForResult()
. When you want to close the entire app, you can do something like the following:
setResult(RESULT_CLOSE_ALL);
finish();
Then define every activity's onActivityResult(...)
callback so when an activity
returns with the RESULT_CLOSE_ALL
value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode){
case RESULT_CLOSE_ALL:{
setResult(RESULT_CLOSE_ALL);
finish();
}
}
super.onActivityResult(requestCode, resultCode, data);
}