Force quit of Android App using System.exit(0) doesn't work

4.2k views Asked by At

when I try to quit my Android application by overwriting the function for the back-button of Android devices and "System.exit(0)", this doesn't work.

I have an activity named "LoginActivity" and an activity named "OverviewActivity".

When I start an intent in OverviewActivity to switch to LoginActivity, this works.

Intent changeViewIntent = new Intent(OverviewActivity.this,
            LoginActivity.class);
startActivity(changeViewIntent);

Now I am in LoginActivity and there is the overwritten method:

@Override
public void onBackPressed() {
    System.exit(0);
}

But when I press the back-key (e.g. in the device simulator) the screen is blank for a millisecond and then it goes back to the OverviewActivity.

Why is this happening? I just want to force the close when the back-key is pressed.

History disabling for the OverviewActivity in the manifest is no option, because there are several ways to access the OverviewActivity from other activities.

Maybe there is an idea? Android 4 is minimium requirement, so it doesn't have to work on lower versions..

Thanks!

2

There are 2 answers

0
Maarkoize On BEST ANSWER

The Exit is possible by deleting the whole activity-call-history and starting the Home-Activity of the Home-Scrren.

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
0
Kostas Drak On

What you can do is

In your OverviewActivity:

Intent changeViewIntent = new Intent(OverviewActivity.this,
            LoginActivity.class);
startActivity(changeViewIntent);
OverviewActivity.this.finish();

after starting the intent you terminate the overview activity

and in LoginActivity

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

}

This way your app will exit.

The difference between finish() and System.exit(0)

The VM stops further execution and program will be exit.

Now, in your case the first activity comes back due to activity stack.

So when you move from one activity to another using Intent, do the finish() of current activity like this.

If you want to force quit you can use

        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
        getParent().finish();

But you should not use System.exit especially if your activity uses other recourses in the background e.g. Internet, Video, etc.