Android 全局异常捕获 重启app

来源:互联网 发布:c语言函数查询工具 编辑:程序博客网 时间:2024/04/27 22:39

参考地址  https://github.com/android-notes/Cockroach


package com.tianzl.androidvideo.crash;import android.os.Handler;import android.os.Looper;/** * Created by wanjian on 2017/2/14. */public final class Cockroach {    public interface ExceptionHandler {        void handlerException(Thread thread, Throwable throwable);    }    private Cockroach() {    }    private static ExceptionHandler sExceptionHandler;    private static Thread.UncaughtExceptionHandler sUncaughtExceptionHandler;    private static boolean sInstalled = false;//标记位,避免重复安装卸载    /**     * 当主线程或子线程抛出异常时会调用exceptionHandler.handlerException(Thread thread, Throwable throwable)     * <p>     * exceptionHandler.handlerException可能运行在非UI线程中。     * <p>     * 若设置了Thread.setDefaultUncaughtExceptionHandler则可能无法捕获子线程异常。     *     * @param exceptionHandler     */    public static synchronized void install(ExceptionHandler exceptionHandler) {        if (sInstalled) {            return;        }        sInstalled = true;        sExceptionHandler = exceptionHandler;        new Handler(Looper.getMainLooper()).post(new Runnable() {            @Override            public void run() {                while (true) {                    try {                        Looper.loop();                    } catch (Throwable e) {//                        Binder.clearCallingIdentity();                        if (e instanceof QuitCockroachException) {                            return;                        }                        if (sExceptionHandler != null) {                            sExceptionHandler.handlerException(Looper.getMainLooper().getThread(), e);                        }                    }                }            }        });        sUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {            @Override            public void uncaughtException(Thread t, Throwable e) {                if (sExceptionHandler != null) {                    sExceptionHandler.handlerException(t, e);                }            }        });    }    public static synchronized void uninstall() {        if (!sInstalled) {            return;        }        sInstalled = false;        sExceptionHandler = null;        //卸载后恢复默认的异常处理逻辑,否则主线程再次抛出异常后将导致ANR,并且无法捕获到异常位置        Thread.setDefaultUncaughtExceptionHandler(sUncaughtExceptionHandler);        new Handler(Looper.getMainLooper()).post(new Runnable() {            @Override            public void run() {                throw new QuitCockroachException("Quit Cockroach.....");//主线程抛出异常,迫使 while (true) {}结束            }        });    }}
package com.tianzl.androidvideo.crash;/** * Created by wanjian on 2017/2/15. */final class QuitCockroachException extends RuntimeException {    public QuitCockroachException(String message) {        super(message);    }}

package com.tianzl.androidvideo.crash;import android.app.Application;import android.content.Intent;import android.os.Handler;import android.os.Looper;import android.util.Log;import com.facebook.drawee.backends.pipeline.Fresco;import com.tianzl.androidvideo.MainActivity;/** * Created by wanjian on 2017/2/14. * <p> * Example */public class VideoApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        Fresco.initialize(this);        Cockroach.install(new Cockroach.ExceptionHandler() {            // handlerException内部建议手动try{  你的异常处理逻辑  }catch(Throwable e){ } ,以防handlerException内部再次抛出异常,导致循环调用handlerException            @Override            public void handlerException(final Thread thread, final Throwable throwable) {                new Handler(Looper.getMainLooper()).post(new Runnable() {                    @Override                    public void run() {                        try {                            Log.d("Cockroach", thread + "\n" + throwable.toString());                            throwable.printStackTrace();//                            Toast.makeText(VideoApplication.this, "Exception Happend\n" + thread + "\n" + throwable.toString(), Toast.LENGTH_SHORT).show();//                        throw new RuntimeException("..."+(i++));//                            Toast.makeText(VideoApplication.this, "哈哈哈异常了", Toast.LENGTH_SHORT).show();//                            Intent intent = new Intent();//                            intent.setClass(get.this,MainActivity.class);//                            startActivity(intent);                            Intent intent = new Intent();                            intent.setClass(getApplicationContext(), MainActivity.class);//                            intent.setAction("android.intent.action.MAIN1");                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                            startActivity(intent);                        } catch (Throwable e) {                        }                    }                });            }        });        // 卸载代码//        Cockroach.uninstall();    }}

崩溃后可以重启App


大家加油!!!