zoukankan      html  css  js  c++  java
  • Android中使用UncaughtExceptionHandler来处理未捕获的异常

    原文在sparkyuan.me上。转载注明出处:http://sparkyuan.github.io/2016/03/28/使用UncaughtExceptionHandler来处理未捕获的异常/

    全部的App都会发生crash。本文解说的是怎样採集crash信息以供兴许开发处理这类问题。

    基本思路

    当crash发生时,系统会调用UncaughtExceptionHandler的uncaughtException方法,我们能够在这种方法中捕获异常信息,把异常信息存到SD卡中。在合适的时候通过网络把crash信息传回server,这样就能够分析crash原因,在兴许的版本号中解决。
    先看一下Thread类中的一个方法,setDefaultUncaughtExceptionHandler

    public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) {
        Thread.defaultUncaughtHandler = handler;
    }

    defaultUncaughtHandler是Thread类的静态成员变量。所以假设我们将自己定义的UncaughtExceptionHandler设置给Thread的话,那么当前进程内的全部线程都能使用这个UncaughtExceptionHandler来处理异常了。

    CrashHandler

    public class CrashHandler implements UncaughtExceptionHandler {
        private static final String TAG = "CrashHandler";
        private static final boolean DEBUG = true;
    
        private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/CrashTest/log/";
        private static final String FILE_NAME = "crash";
        private static final String FILE_NAME_SUFFIX = ".trace";
    
        private static CrashHandler sInstance = new CrashHandler();
        private UncaughtExceptionHandler mDefaultCrashHandler;
        private Context mContext;
    
        private CrashHandler() {
        }
    
        public static CrashHandler getInstance() {
            return sInstance;
        }
    
        //须要初始化的单例
        public void init(Context context) {
            mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
            Thread.setDefaultUncaughtExceptionHandler(this);
            mContext = context.getApplicationContext();
        }
    
        /**
         * 这个是最关键的函数。当程序中有未被捕获的异常,系统将会自己主动调用#uncaughtException方法
         * thread为出现未捕获异常的线程,ex为未捕获的异常,有了这个ex,我们就能够得到异常信息。
         */
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            try {
                //导出异常信息到SD卡中
                dumpExceptionToSDCard(ex);
                uploadExceptionToServer();
                //这里能够通过网络上传异常信息到server。便于开发者分析日志从而解决bug
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            ex.printStackTrace();
    
            //假设系统提供了默认的异常处理器。则交给系统去结束我们的程序,否则就由我们自己结束自己
            if (mDefaultCrashHandler != null) {
                mDefaultCrashHandler.uncaughtException(thread, ex);
            } else {
                Process.killProcess(Process.myPid());
            }
    
        }
    
        private void dumpExceptionToSDCard(Throwable ex) throws IOException {
            //假设SD卡不存在或无法使用。则无法把异常信息写入SD卡
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                if (DEBUG) {
                    Log.w(TAG, "sdcard unmounted,skip dump exception");
                    return;
                }
            }
    
            File dir = new File(PATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            long current = System.currentTimeMillis();
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
            File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
    
            try {
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
                pw.println(time);
                dumpPhoneInfo(pw);
                pw.println();
                ex.printStackTrace(pw);
                pw.close();
            } catch (Exception e) {
                Log.e(TAG, "dump crash info failed");
            }
        }
    
        private void dumpPhoneInfo(PrintWriter pw) throws NameNotFoundException {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            pw.print("App Version: ");
            pw.print(pi.versionName);
            pw.print('_');
            pw.println(pi.versionCode);
    
            //android版本号号
            pw.print("OS Version: ");
            pw.print(Build.VERSION.RELEASE);
            pw.print("_");
            pw.println(Build.VERSION.SDK_INT);
    
            //手机制造商
            pw.print("Vendor: ");
            pw.println(Build.MANUFACTURER);
    
            //手机型号
            pw.print("Model: ");
            pw.println(Build.MODEL);
    
            //cpu架构
            pw.print("CPU ABI: ");
            pw.println(Build.CPU_ABI);
        }
    
        private void uploadExceptionToServer() {
          //TODO Upload Exception Message To Your Web Server
        }
    
    }

    用法

    在Application的onCreate方法中配置一下就能够

    public class TestApp extends Application {
    
        private static TestApp sInstance;
    
        @Override
        public void onCreate() {
            super.onCreate();
            sInstance = this;
    
            //在这里为应用设置异常处理程序,然后我们的程序才干捕获未处理的异常
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(this);
        }
    
        public static TestApp getInstance() {
            return sInstance;
        }
    
    }
    

    原文在sparkyuan.me上,转载注明出处:http://sparkyuan.github.io/2016/03/28/使用UncaughtExceptionHandler来处理未捕获的异常/

  • 相关阅读:
    Crazypony四轴飞行器代码框架
    Python中 sys.argv[]的用法简明解释
    详解STM32的PWM输出及频率和脉宽(占空比)的计算——寄存器配置六步曲!(转)
    jquery——所有版本下载
    jsop跨域请求方式--及中文乱码解决方案
    js ---任何浏览器关闭当前网页的代码
    jquery ajax跨域请求 IE9及以下不支持---调试
    poi---Excel导入数据-ClassNotFoundException
    ajax获取json数据为undefined--原因解析
    可变参数 / 枚举--详解
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/7301417.html
Copyright © 2011-2022 走看看