第一步:创建Application
public class App extends Application implements Thread.UncaughtExceptionHandler {
@Override
public void onCreate() {
//接口是Thread.UncaughtExceptionHandler
super.onCreate();
//进行异常捕获
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
//进行日志打印
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
throwable.printStackTrace(printWriter);
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
//如果发生崩溃Toast显示信息
Toast.makeText(App.this, "程序员跑路了,请稍候再试", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
}
}
//别忘记在清单文件中写:
android:name=".App"