//使用
//在MainApplication的onCreate中
@Override
public void onCreate() {
super.onCreate();
CrashHandler.getInstance().init(this);
}
public class CrashHandler implements UncaughtExceptionHandler {
private static CrashHandler sInstance = new CrashHandler();
private Context mContext;
private CrashHandler() {
}
public static CrashHandler getInstance() {
return sInstance;
}
public void init(Context context) {
//将当前应用异常处理器改为this
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String msg=sw.toString();
writeLog(msg);
ex.printStackTrace();
restartApp();
}
private void writeLog(String log) {
WriteFileUtil.writeLog("Exception.txt", log, mContext);
}
public void restartApp() {
writeLog("重启APP");
// Intent intent = new Intent(mContext, SplashActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
// mContext.startActivity(intent);
// android.os.Process.killProcess(android.os.Process.myPid());
new Thread(){
@Override
public void run() {
super.run();
try {
L.e("开始睡眠");
Thread.sleep(20*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
L.e("睡眠结束");
Intent intent = new Intent(mContext, SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
mContext.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
}
}.start();
}
}