您的位置:首页 > 其它

02.捕获未知异常

2016-03-13 15:46 246 查看

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class UnCeHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
public static final String TAG = "CatchExcep";
PdaApplication application;
public static MainActivity mainAct;

public UnCeHandler(PdaApplication application) {
//获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
this.application = application;
}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(2000);

} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
if (mainAct != null) {
mainAct.finish();
}
Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
PendingIntent restartIntent = PendingIntent.getActivity(
application.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);  //第四个参数据改变了
//退出程序
AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200,
restartIntent); // 重启应用

android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}

/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//使用Toast来显示异常信息
Log.e("Evaluator", "崩溃啦\n" + ex.toString() + "\n");
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(application.getApplicationContext(), "很抱歉,程序出现异常,即将重启。",
Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
}
import android.app.Application;

//在程序启动时,启动捕获异常
public class PdaApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//设置异常捕获
UnCeHandler catchExcep = new UnCeHandler(this);
Thread.setDefaultUncaughtExceptionHandler(catchExcep);
}
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: