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); } }
相关文章推荐
- hdoj 三角形 2039 (判断)
- Unity 5.3 Assetbundle热更资源
- Android开发之在代码中给控件设置颜色不起作用的解决办法
- glove入门实战
- 课堂所讲整理:输入输出流(I/O)
- 反应器类型的操作
- 国内某电商大佬面试题(二)
- Linux基础入门实战(1)
- MySQL基础知识总结
- move and forward
- 第三周项目4穷举法解决组合问题
- 【Web前端】AJAX之我见
- 课堂所讲整理:异常
- JAVA操作Redis增删改查
- Qt-----发布应用程序
- mybatis注解详解
- 蓝桥杯 算法提高 排列数
- 第3周项目1 个人所得税计算器
- 第二周学习进度
- Linux笔记(32)——SSH协议