设置一个类继承下列所需类
public class Cast_Handler implements Thread.UncaughtExceptionHandler {
private static final String TAG="Cast_Handler" ;
private Thread.UncaughtExceptionHandler dhandler;
public static Cast_Handler cast_handler;
private Context mContext;
public static synchronized Cast_Handler getInstance(){
if(null==cast_handler){
cast_handler = new Cast_Handler();
}
return cast_handler;
}
public void init(Context context){
this.mContext=context;
dhandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if(handleException(e)&&dhandler!=null){
dhandler.uncaughtException(t,e);
}else{
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
Log.e(TAG, "uncaughtException: error",e1 );
}
}
}
private boolean handleException(Throwable throwable){
if(throwable==null){
return false;
}
addCast();
new Thread(){
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "run: 程序开小差了呢.......",Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
public void addCast(){
Log.i(TAG,"addCast:程序出错了...");
}
}
在app配置文件中配置
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Cast_Handler.getInstance().init(this);
}
}