Android studio全局捕获异常
package com.example.dome1.abnormal;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import java.io.IOException;
public class Abnormal implements Thread.UncaughtExceptionHandler {
//单利模式
public Abnormal() {
}
private static class GetAbnormal{
private static Abnormal abnormal = new Abnormal();
}
public static Abnormal getInstance() {
return GetAbnormal.abnormal;
}
//系统默人的处理类
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
//上下文
private Context mContext;
public void init(Context context){
this.mContext=context;
uncaughtExceptionHandler=Thread.getDefaultUncaughtExceptionHandler();
//设置默认的处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
private boolean handleException(Throwable ex){
if (ex==null){
return false;
}
//使用Toast来显示异常信息
new Thread(){
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
@Override
public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
if (!handleException(e)&&uncaughtExceptionHandler!=null){
//如果用户没有处理则让系统默认的异常处理器来处理
uncaughtExceptionHandler.uncaughtException(t,e);
}else {
try{
Thread.sleep(3000);
}catch (Exception eee){
Log.e("CrashHandler","errror"+eee.getMessage());
}
}
}
}
定义一类继承Application在此类引用
package com.example.dome1.app;
import android.app.Application;
import android.content.Context;
import com.example.dome1.abnormal.Abnormal;
public class MyApplication extends Application {
public static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext=this;
//全局捕获异常引用
Abnormal.getInstance().init(this);
}
}