定义MyCrashHandler类,该类实现java.lang.Thread.UncaughtExceptionHandler接口。

import java.io.PrintWriter;import java.io.StringWriter;import java.io.Writer;import java.lang.Thread.UncaughtExceptionHandler;import org.json.JSONException;import org.json.JSONObject;import android.content.Context;import android.os.Build;import android.os.Looper;public class MyCrashHandler implements UncaughtExceptionHandler {    private static MyCrashHandler myCrashHandler;    private Context context;       private MyCrashHandler() {    }    public static synchronized MyCrashHandler getInstance() {        if (myCrashHandler != null) {            return myCrashHandler;        } else {            myCrashHandler = new MyCrashHandler();            return myCrashHandler;        }    }    public void init(Context context) {        this.context = context;    }    public void uncaughtException(Thread thread, final Throwable arg1) {                    new Thread() {                @Override                public void run() {                    super.run();                    Looper.prepare();                    String errorinfo = getErrorInfo(arg1);                   //TODO  处理errorinfo                    Looper.loop();                }            }.start();    //Thread.sleep()是为了等待上面处理errorinfo的线程结束。        try {            Thread.sleep(3000);        } catch (InterruptedException e) {            e.printStackTrace();        }        android.os.Process.killProcess(android.os.Process.myPid());            }       private String getErrorInfo(Throwable arg1) {        Writer writer = new StringWriter();        PrintWriter pw = new PrintWriter(writer);        arg1.printStackTrace(pw);        pw.close();        String error = writer.toString();        return error;    }}
使用MyCrashHandler捕获异常

    MyCrashHandler handler = MyCrashHandler.getInstance();    handler.init(context.getApplicationContext());    Thread.setDefaultUncaughtExceptionHandler(handler);//将handler设置为默认



更多相关文章

  1. Android 后台线程调用前台线程的几种方法
  2. Android 创建线程执行任务
  3. android 线程之创建一个子线程,并在UI线程中进行交互
  4. Android studio 多线程网络文件下载
  5. Android 子线程 更新 UI 界面 总结
  6. Android非UI线程访问UI线程的方法总结
  7. FregServer进程,发送BC_TRANSACTION,唤醒ServiceManager进程,返回BR
  8. 在非主线程中不能操作主线程中的View

随机推荐

  1. mysql数据库设置utf-8编码的方法步骤
  2. mysql 8.0.17 winx64(附加navicat)手动配置
  3. mysql-8.0.17-winx64 部署方法
  4. mysql 8.0.17 安装与使用教程图解
  5. 解决Mysql 8.0.17 winx64版本安装过程中
  6. Mysql巧用join优化sql的方法详解
  7. MySQL慢查日志的开启方式与存储格式详析
  8. MySQL 使用DQL命令查询数据的实现方法
  9. MySQL5.6解压版服务无法启动之系统错误10
  10. MySQL InnoDB MRR优化指南