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

▼魔方 西西 提交于 2019-11-28 14:12:03

问题


If my app encounters a particular error, I want to end my app without any trace of it remaining in the system. I have already seen many threads on this topic, specially these two.

Is quitting an application frowned upon?

How to quit android application programmatically

The answers are great but the proposed solutions are too tedious and/or unnecessarily complex.


回答1:


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!



来源:https://stackoverflow.com/questions/27828083/android-perfect-solution-for-quitting-or-terminating-an-application-programmat

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