Android:在“强制关闭"应用程序之后如何自动重新启动它? [英] Android: How to auto-restart an application after it has been "force closed"?

查看:1411
本文介绍了Android:在“强制关闭"应用程序之后如何自动重新启动它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android应用程序中,通常会获得强制关闭"错误,如果我们没有正确处理异常.

In an Android application, we usually got the "Force Closed" error if we didn't handle the exceptions properly.

如果强制关闭应用程序,如何自动重新启动应用程序?

How can I restart my application automatically if it is force closed?

有用于此的任何特定权限吗?

Is there any specific permission used for this?

推荐答案

要实现此目的,您必须做两件事:

To accomplish this you have to do two things:

  1. 避免强制关闭"-应用程序崩溃的标准方式.
  2. 无论何时发生崩溃,都要设置重启机制.

请参阅下面的步骤:

  1. 调用Thread.setDefaultUncaughtExceptionHandler()以便捕获所有未捕获的异常,在这种情况下将调用uncaughtException()方法. 强制关闭"将不会出现,并且应用程序将无响应,这不是一件好事. 为了在崩溃时重新启动应用程序,您应该执行以下操作:

  1. Call Thread.setDefaultUncaughtExceptionHandler() in order to catch all uncaught exception, in which case uncaughtException() method will be called. "Force close" will not appear and the application will be unresponsive, which is not a quite good thing. In order to restart your application when it crashed you should do the following :

onCreate方法中,在您的主要活动中初始化PendingIntent成员:

In the onCreate method, in your main activity initialize a PendingIntent member:

Intent intent = PendingIntent.getActivity(
    YourApplication.getInstance().getBaseContext(),
    0,
    new Intent(getIntent()),
    getIntent().getFlags());

然后将以下内容放入您的uncaughtException()方法:

Then put the following in your uncaughtException() method:

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
System.exit(2);

您还必须致电System.exit(),否则将不起作用. 这样,您的应用程序将在2秒钟后重新启动.

You also must call System.exit(), otherwise will not work. In this way your application will restart after 2 seconds.

最终,您可以在意图中设置一些标志,以指示应用程序崩溃了,在onCreate()方法中,您可以显示一个对话框很抱歉,应用程序崩溃了,希望再也没有了:)".

Eventually you can set some flag in your intent that the application crashed and in your onCreate() method you can show a dialog "I'm sorry, the application crashed, hope never again :)".

这篇关于Android:在“强制关闭"应用程序之后如何自动重新启动它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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