标题: Android Force Close和ANR等异常处理方法 [打印本页]

作者: 51hei小林    时间: 2016-9-25 11:03
标题: Android Force Close和ANR等异常处理方法
对android应用而言最常出现的异常是Force close和ANR(Application is not response).

对于这两类错误而言,应用是可以进行相关处理的。

一 Forceclose这类问题主要通过Thread.UncaughtExceptionHandler这个类来捕获异常。通过实现类里面的方法uncaughtException来实现应用在捕获到异常后进行相关的处理。一般这里处理基本放在应用的Application类中。为了方便大家进行相关处理,我这里写了个类,大家直接在Application回调即可。


  1. new ExceptionHandler(mContext).setFCListener(new ExceptionHandler.FCListener() {
  2.             
  3.             @Override
  4.             public void onFCDispose(Throwable paramThrowable) {
  5.                 Log.d(TAG, onFCListerner enter!!!);
  6.                 new Thread(){
  7.                     public void run(){
  8.                         Looper.prepare();
  9.                         Toast.makeText(mContext, APP is Force Close do what you want!, Toast.LENGTH_LONG).show();
  10.                         Looper.loop();
  11.                     }
  12.                 }.start();
  13.             }
  14.         });
复制代码



同样的对于ANR问题,应用也可以做相关处理。对ANR,我们可以这样处理。通过一个看门狗来实时的检测主线程,一旦主线程发生阻塞,则通知Application 做相关处理。

主要方法是在线程中每隔一段时间(Activity一般是5S,广播一般是10S),向主线程发送一个messager,使计数器加1,如果到点没有加1,则表明主线程阻塞。


  1. @Override
  2.     public void run() {
  3.         setName(|ANR-WatchDog|);

  4.         int lastTick;
  5.         while (!isInterrupted()) {
  6.             lastTick = mTick;
  7.             mUIHandler.post(tickerRunnable);
  8.             try {
  9.                 Thread.sleep(mTimeoutInterval);
  10.             }
  11.             catch (InterruptedException e) {
  12.                 mInterruptionListener.onInterrupted(e);
  13.                 return ;
  14.             }

  15.             // If the main thread has not handled _ticker, it is blocked. ANR.
  16.             if (mTick == lastTick) {
  17.                 ANRError error;
  18.                 if (mNamePrefix != null)
  19.                     error = ANRError.New(mNamePrefix, mLogThreadsWithoutStackTrace);
  20.                 else
  21.                     error = ANRError.NewMainOnly();
  22.                 mAnrListener.onAppNotResponding(error);
  23.                 return ;
  24.             }
  25.         }
  26.     }
复制代码
  1. private final Runnable tickerRunnable = new Runnable() {
  2.        @Override public void run() {
  3.            mTick = (mTick + 1) % 10;
  4.        }
  5.    };
复制代码








欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1