Android的 - 戒烟或编程终止应用程序完美的解决方案? [英] Android - Perfect solution for quitting or terminating an application programmatically?

查看:113
本文介绍了Android的 - 戒烟或编程终止应用程序完美的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的应用程序遇到特定的错误,我想结束我的应用程序来说,不会残留在系统中的任何痕​​迹。我已经看到很多线程关于这个主题,特别是这两个。

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.

<一个href="http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon">Quitting一个应用程序 - 这是令人难以接受的

<一个href="http://stackoverflow.com/questions/6330200/how-to-quit-android-application-programmatically">How退出Android应用程序编程

答案是伟大的,但所提出的解决方案是过于繁琐和/或不必要的复杂。

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

推荐答案

以从第一篇文章以上尼尔Traft的回答一个提示,我发现了这样的情况下的完美解决方案。

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)或android.os.Process.killProcess(android.os.Process.myPid()),双方似乎如果你在应用程序的backstack只有一个活动的工作,其他的Andr​​oid刚刚重新推出你的应用程序推在(上 - 1)活动的前景,也许是因为Android的假设用户与应用程序交互,它突然死机,所以他应该继续与它交互

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.

所以,我的解决办法是先用Activity.moveTaskToBack()发送应用程序到后台,然后调用这两种方法之上。

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

我看不出有什么问题,这种方法不同的是它违背了Android的设计原则......虽然这完美的作品,当你真的需要它。

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.

希望这可以帮助别人!

这篇关于Android的 - 戒烟或编程终止应用程序完美的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆