解决方案主要分两步走:以下是我自己实现的,也可以Application实现此接口。
1:全局捕获异常借助Application入口实现UncaughtExceptionHandler接口,并将其加入到对应Thread中:以下是自己处理:
public class
MyApplication extends
Application {
@Override
public void
onCreate() {
super.onCreate();
init();
}
public void
init() {
//设置该CrashHandler为程序的默认处理器
MyUncaughtExceptionHandler catchException =
new MyUncaughtExceptionHandler(this);
Thread.setDefaultUncaughtExceptionHandler(catchException);
}
2:处理异常需要
实现uncaughException方法;在此方法中处理重启自己的app
重启注意点; 1:需要用到PendingIntent打开 2:重启之后需要将原先的进程杀掉不能出现两个进程,否则出现卡顿ANR现象
public class
MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
private
MyApplication myApplication;
private Thread.UncaughtExceptionHandler
mUncaughtExceptionHandler;
public MyUncaughtExceptionHandler(MyApplication myApplication) {
this.myApplication
= myApplication;
mUncaughtExceptionHandler
= Thread.getDefaultUncaughtExceptionHandler();//
获取系统默认的异常处理器
}
@Override
public void
uncaughtException(Thread thread,
Throwable ex) {
if
(!handleException(ex) && mUncaughtExceptionHandler
!= null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mUncaughtExceptionHandler.uncaughtException(thread,
ex);
}
else {
try
{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new
Intent(myApplication.getApplicationContext(),
MainActivity.class);
//重启应用,得使用PendingIntent
PendingIntent restartIntent = PendingIntent.getActivity(
myApplication.getApplicationContext(),
0,
intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
//退出程序
AlarmManager mAlarmManager = (AlarmManager)
myApplication.getSystemService(Context.ALARM_SERVICE);
mAlarmManager.set(AlarmManager.RTC,
System.currentTimeMillis() +1000,
restartIntent);
// 1秒钟后重启应用
//需要杀掉进程此也可以对Activity的管理
android.os.Process.killProcess(android.os.Process.myPid());
}
}
/**
* 自定义错误处理,收集错误信息
发送错误报告等操作均在此完成.
*
* @param
ex
*
@return true:如果处理了该异常信息;否则返回false.
*/
private boolean
handleException(final
Throwable ex) {
if
(ex == null) {
return false;
}
new
Thread() {
@Override
public void
run() {
Looper.prepare();
Toast.makeText(myApplication.getApplicationContext(),
""+ex,
Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
}