java 如何强制退出Android应用程序并重新启动它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6528231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to force quit the Android app and restart it?
提问by JoJo
My Android app has a WebViewthat requires the Flash plugin. The webview will provide a Market link to Adobe Flash if it's not installed. After installing Flash, the only way to instantiate it in my app is to force quit and restart the app. I would like to present a button to the user that does this for them because it's too complicated for casual users to open up their running processes and force quit the app manually. What is the Java code to implement such a restart button?
我的 Android 应用程序WebView需要 Flash 插件。如果未安装 Adobe Flash,webview 将提供一个市场链接。安装 Flash 后,在我的应用程序中实例化它的唯一方法是强制退出并重新启动应用程序。我想向用户展示一个按钮,为他们执行此操作,因为对于临时用户来说打开他们正在运行的进程并手动强制退出应用程序太复杂了。实现这种重启按钮的 Java 代码是什么?
回答by mportuesisf
You can restart your app in two steps:
您可以分两步重启应用:
- Kill your own process. Use
Process.myPid(), pass it intoProcess.killProcess(). You might need to add a permission to your manifest (possiblyandroid.permission.KILL_BACKGROUND_PROCESSES) to get this to work. - Before you kill your own process, register an Alarm with a pending intent to restart your Activity in the very near future. The second parameter to
alarm.setis thetriggerAtTime. Setting it to 0 causes the alarm to fire immediately. The example here sets a time to launch the app one second into the future.
- 杀死自己的进程。使用
Process.myPid(),传入Process.killProcess(). 您可能需要向清单(可能android.permission.KILL_BACKGROUND_PROCESSES)添加权限才能使其正常工作。 - 在您终止自己的进程之前,请注册一个带有挂起意图的警报,以便在不久的将来重新启动您的活动。的第二个参数
alarm.set是triggerAtTime. 将其设置为 0 会导致立即触发警报。此处的示例设置了在未来一秒内启动应用程序的时间。
The Code goes like this:
代码是这样的:
AlarmManager alm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alm.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()), 0));
回答by Robert Massaioli
I suppose you could call finishto make your activity stop but you will not be able to make your app start back up again. That would require (if it is even possible) root and it would be a terrible idea. It would mean that any app could start itself whenever it wanted to: which is just a bad idea and would actually be a bug if it was possible.
我想您可以调用完成来停止您的活动,但您将无法让您的应用程序重新启动。这将需要(如果可能的话)root,这将是一个糟糕的主意。这意味着任何应用程序都可以随时自行启动:这只是一个坏主意,如果可能的话,它实际上是一个错误。
回答by arnouf
you can exit of app with System.exit(0) : this doesn't require permission for your app
您可以使用 System.exit(0) 退出应用程序:这不需要您的应用程序的许可

