Android - Perfect solution for quitting or terminating an application programmatically?

北城余情 提交于 2019-11-29 18:15:56

Taking a cue from Neil Traft's answer in the first post above, I have found a perfect solution for such scenarios.

System.exit(0) or android.os.Process.killProcess(android.os.Process.myPid()) both seem to work if you have only one Activity in the app's backstack, else Android just relaunches your app pushing the (top - 1) Activity to the foreground, maybe because Android assumes that the user was interacting with the app and it suddenly "crashed", so he should continue interacting with it.

So, my solution is to first send the app into background using Activity.moveTaskToBack() and then invoke either of the two methods above.

private void terminateApp() {       

    // TODO: Don't forget to clean up your background threads, services, etc. 

    // send the app into background, otherwise Android will relaunch the app process if you have multiple Activities in your backstack.
    moveTaskToBack(true);

    // kill everything running in this process.
    System.exit(-1); // or you can use android.os.Process.killProcess(android.os.Process.myPid());
}

I don't see any problem with this approach except that it goes against Android design principles... though this works perfectly when you really, really need it.

Hope this helps someone!

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