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
Calling the finish()
method on an Activity has your desired effect on that current activity.
by calling finish(); in OnClick button or on menu
case R.id.menu_settings:
finish(); return true;
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
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);
}
This is the way I did it:
I just put
Intent intent = new Intent(Main.this, SOMECLASSNAME.class);
Main.this.startActivityForResult(intent, 0);
inside of the method that opens an activity, then inside of the method of SOMECLASSNAME that is designed to close the app I put:
setResult(0);
finish();
And I put the following in my Main class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 0) {
finish();
}
}
public class CloseAppActivity extends AppCompatActivity
{
public static final void closeApp(Activity activity)
{
Intent intent = new Intent(activity, CloseAppActivity.class);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
finish();
}
}
and in manifest:
<activity
android:name=".presenter.activity.CloseAppActivity"
android:noHistory="true"
android:clearTaskOnLaunch="true"/>
Then you can call CloseAppActivity.closeApp(fromActivity)
and application will be closed.