Android 捕获异常并在应用崩溃后重启应用

linshizhuce 7年前
   <h2>问题概述:</h2>    <p>在Android应用开发中,偶尔会因为测试的不充分导致一些异常没有被捕获,这时应用会出现异常并强制关闭,这样会导致很不好的用户体验,为了解决这个问题,我们需要捕获相关的异常并做处理。</p>    <p>首先捕获程序崩溃的异常就必须了解一下Java中UncaughtExceptionHandler这个接口,这个接口在Android开发上面也是可以使用的,在API文档中,我们可以了解到:通过实现此接口,能够处理线程被一个无法捕获的异常所终止的情况。如上所述的情况,handler将会报告线程终止和不明原因异常这个情况,如果没有自定义handler, 线程管理组就被默认为报告异常的handler。 ThreadGroup 这个类就是实现了UncaughtExceptionHandler这个接口,如果想捕获异常我们可以实现这个接口或者继承ThreadGroup,并重载uncaughtException方法。</p>    <h2>实例:</h2>    <p>实现Thread.UncaughtExceptionHandler 接口并复写uncaughtException(Thread thread, Throwable ex)方法来实现对运行时线程进行异常处理。实现 UncaughtExceptionHandler接口,并在uncaughtException方法中处理异常,这里我们关闭App并启动我们需要的Activity,下面看代码:</p>    <pre>  <code class="language-java">/***   * @Description: 捕获未处理的崩溃并进行相关处理的机制 --- 单例模式   */  public class CrashHandler implements UncaughtExceptionHandler {        public static final String TAG = "CrashHandler";        private static CrashHandler INSTANCE = new CrashHandler();        private Context mContext;        private CrashHandler() {        }        public static CrashHandler getInstance() {          return INSTANCE;      }        public void init(Context context) {          mContext = context;          Thread.setDefaultUncaughtExceptionHandler(this);      }        @Override      public void uncaughtException(Thread thread, Throwable ex) {          DebugTraceTool.debugTraceE(TAG, "some uncaughtException happend");          ex.printStackTrace();            new Thread() {              @Override              public void run() {                  Looper.prepare();                  new AlertDialog.Builder(mContext).setTitle("提示").setCancelable(false).setMessage("程序崩溃了,重新启动?")                  .setNeutralButton("确定", new OnClickListener() {                      @Override                      public void onClick(DialogInterface dialog, int which) {                          Intent intent = new Intent(mContext.getApplicationContext(), MainActivity.class);                            PendingIntent restartIntent = PendingIntent.getActivity(mContext.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);                                                                           //退出程序                                                                    AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);                          mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用                             android.os.Process.killProcess(android.os.Process.myPid());                      }                  }).setNegativeButton("退出", new OnClickListener() {                        @Override                      public void onClick(DialogInterface arg0, int arg1) {                          System.exit(0);                      }                  }).create().show();                  Looper.loop();              }          }.start();      }    }  </code></pre>    <p>在相应的Activity调用下面的方法:</p>    <pre>  <code class="language-java">CrashHandler crashHandler = CrashHandler.getInstance();  crashHandler.init(INSTANCE);  </code></pre>    <p>我们在Activity中主动抛出下面异常,就会发现应用遇到异常后重启了,如果不处理的话,应用在遇到异常后就关闭了。</p>    <pre>  <code class="language-java">throw new NullPointerException();   </code></pre>    <p> </p>    <p>来自:http://www.cnblogs.com/renhui/p/6163980.html</p>    <p> </p>