全局捕获异常机制

自定义类继承Thread.UncaughtExceptionHandler

package gg.bw.com.wangshu20190405;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;

public class T implements Thread.UncaughtExceptionHandler {
    Context contex;
    private static T t;
    private T(){}

    public  static T GetInstance(){
        if (t==null){
            t = new T();
        }
        return t;
    }

    public void init(Context context){
        this.contex = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                Looper.prepare();
                Toast.makeText(contex, "出现异常", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
    }
}

自定义APP引用

 T.GetInstance().init(getApplicationContext());

猜你喜欢

转载自blog.csdn.net/weixin_44405056/article/details/89064795