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

偶尔善良 提交于 2019-12-10 10:27:24

问题


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!


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/27050357/force-quit-of-android-app-using-system-exit0-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!