package com.prisoner.prisoner.thread;
import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import static android.support.constraint.Constraints.TAG;
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static CrashHandler instance;
private Context mContext;
private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
public static synchronized CrashHandler getInstance(){
if (instance==null){
instance=new CrashHandler();
}
return instance;
}
public void init(Context context){
mContext=context;
uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
private void addCustomInfo() {
Log.i(TAG, "addCustomInfo: 程序出错了...");
}
private boolean handleExceptiion(Throwable ex){
if (ex==null){
return false;
}
addCustomInfo();
new Thread(){
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "程序开小差了呢..", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (!handleExceptiion(e)&&uncaughtExceptionHandler!=null){
uncaughtExceptionHandler.uncaughtException(t,e);
}else {
try {
Thread.sleep(3000);
}catch (Exception es){
Log.e(TAG, "error : ", es);
}
}
}
}