美文网首页
Android UncaughtExceptionHandler

Android UncaughtExceptionHandler

作者: 皮皮铭 | 来源:发表于2019-09-26 15:33 被阅读0次

UncaughtExceptionHandler是一个Thread的接口,当应用发生异常时,就会走uncaughtException()方法,所以在uncaughtException()里面做处理。

创建一个异常管理类CrashHandler.java实现UncaughtExceptionHandler接口

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    //系统默认UncaughtExceptionHandler
    private Thread.UncaughtExceptionHandler mDefaultHandler;  
    private Context mContext;  
    private static CrashHandler mInstance;
    private String DeviceUrl = "xxx";//上传错误网址
    //空的构造方法
    private CrashHandler() {

    }

    //单例,获取CrashHandler实例
    public static synchronized CrashHandler getInstance() {
        if (null == mInstance) {
            mInstance = new CrashHandler();
        }
        return mInstance;
    }

    public void init(Context context) {
        mContext = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为系统默认的
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    //uncaughtException 回调函数
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果自己没处理交给系统处理
            mDefaultHandler.uncaughtException(thread, ex);
        }
    }

    //收集错误信息.发送到服务器, 处理了该异常返回true, 否则false  
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //获取错误信息
        final Writer result = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(result);
        ex.printStackTrace(printWriter);
        String errorReport = result.toString();
        //上传错误信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                MyDatas.SNNum = getSN();
                Map<String, String> map = new ConcurrentHashMap<>();
                map.put("deviceNo", MyDatas.SNNum);
                map.put("errorData", errorReport);
                map.put("versionNo", packageName(mContext));
                //1.创建OkHttpClient对象
                OkHttpClient okHttpClient = new OkHttpClient();
                //2.创建Request对象,设置一个url地址,设置请求方式。
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.mapToJson(map));
                Request request = new Request.Builder()
                        .url(MyDatas.path + DeviceUrl)
                        .post(requestBody)
                        .build();
                //3.创建一个call对象,参数就是Request请求对象
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    Log.e(TAG, "run: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(mContext, "程序异常崩溃,正在重新打开", Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //重新打开应用
                        Intent intent = new Intent(mContext, LunchActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mContext.startActivity(intent);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 4000);
                Looper.loop();
            }
        }.start();
        return true;
    }

    //获取SN号
    @SuppressLint("MissingPermission")
    public static String getSN() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Build.getSerial();
        } else
            return Build.SERIAL;
    }

    //获取版本号
    public static String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }
}
 CrashHandler.getInstance().init(this);

相关文章

网友评论

      本文标题:Android UncaughtExceptionHandler

      本文链接:https://www.haomeiwen.com/subject/ixqnuctx.html