🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
#### **应用发生Crash在所难免** Android 应用不可避免地会发生crash,也称之为崩溃,无论你的程序写得多么完美,总是无法完全避免crash 的发生,可能是由于Android 系统底层的bug,也可能是由于不充分的机型适配或者是槽糕的网络状况。当crash 发生时,系统会kill 掉正在执行的程序,现象就是闪退或者提示用户程序已停止运行,这对用户来说是很不友好的,也是开发者所不愿意看到的。更糟糕的是,当用户发生了crash,开发者却无法得知程序为何crash ,即使开发人员想去解决这个crash ,但是由于无法知道用户当时的crash 信息,所以往往也无能为力。 #### **如何采集crash信息以供后续开发处理这类问题呢?** 利用Thread类的setDefaultUncaughtExceptionHandler方法!defaultUncaughtHandler是Thread类的静态成员变量,所以如果我们将自定义的UncaughtExceptionHandler设置给Thread的话,那么当前进程内的所有线程都能使用这个UncaughtExceptionHandler来处理异常了。 ~~~ /** * Sets the default uncaught exception handler. This handler is invoked in * case any Thread dies due to an unhandled exception. * * @param handler * The handler to set or null. */ public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { Thread.defaultUncaughtHandler = handler; } ~~~ 当crash 发生的时候,系统就会回调UncaughtExceptionHandler 的uncaughtException }j法,在uncaughtException 方法中就可以获取到异常信息,可以选择把异常信息存储到SD卡中,然后在合适的时机通过网络将crash信息上传到服务器上,这样开发人员就可以分析用户crash 的场景从而在后面的版本中修复此类crash 。我们还可以在crash 发生时,弹出一个对话框告诉用户程序crash 了,然后再退出,这样做比闪退要温和一点。 UncaughtExceptionHandler是Thread类的一个接口 **Thread:UncaughtExceptionHandler** ~~~ /** * Implemented by objects that want to handle cases where a thread is being * terminated by an uncaught exception. Upon such termination, the handler * is notified of the terminating thread and causal exception. If there is * no explicit handler set then the thread's group is the default handler. */ public static interface UncaughtExceptionHandler { /** * The thread is being terminated by an uncaught exception. Further * exceptions thrown in this method are prevent the remainder of the * method from executing, but are otherwise ignored. * * @param thread the thread that has an uncaught exception * @param ex the exception that was thrown */ void uncaughtException(Thread thread, Throwable ex); } ~~~ #### **获取应用crash 信息的方式了** 首先需要实现一个UncaughtExceptionHandler 对象,在它的uncaughtException 方法中获取异常信息并将其存储在SD 卡中或者上传到服务器供开发人员分析,然后调用Thread 的setDefaultUncaughtExceptionHandler方法将它设置为线程默认的异常处理器,由于默认异常处理器是Thread类的静态成员,因此它的作用对象是当前进程的所有线程。 **示例**: 作者实现了一个简易版本的UncaughtExceptionHandler类的子类CrashHandler,[源码传送门](https://gitee.com/Alexwsc/androiddevelopartistic/tree/master/Chapter_13),本示例中并没有实现将异常信息上传到服务器,但是在实际开发中一般都需要将异常信息上传到服务器。 **CrashHandler** ~~~ package com.ryg.crashtest; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Environment; import android.os.Process; import android.util.Log; 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,我们就可以得到异常信息。 * * 这个方法的回调,该方法运行在发生crash的那个线程。如果UI线程crash,就运行在UI线程 * 如果发生在子线程,就运行在子线程;因此不可以在这个方法中弹出toast或者dialog(因为这个线程的消息循环已经被破坏了) * 但是可以跳转到一个Activity,在这个Acitivty中弹dialog或者toast */ @Override public void uncaughtException(Thread thread, Throwable ex) { try { //导出异常信息到SD卡中 dumpExceptionToSDCard(ex); uploadExceptionToServer(); //这里可以通过网络上传异常信息到服务器(完成下面的方法uploadExceptionToServer),便于开发人员分析日志从而解决bug } catch (IOException e) { e.printStackTrace(); } ex.printStackTrace(); // 发生crash之后,需要将进程杀掉,因为此时程序不能继续往下运行,程序状态已不对 //如果系统提供了默认的异常处理器,则交给系统去结束我们的程序,否则就由我们自己结束自己 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 } } ~~~ 从上面的代码可以看出,当应用崩溃时, CrashHandler 会将异常信息以及设备信息写入SD 卡,接着将异常交给系统处理,系统会帮我们中止程序,如果系统没有默认的异常处理机制,那么就自行中止CrashHandler的使用方式就是在Application的onCreate方法中设置一下即可。 如何使用上面的CrashHandler 呢?也很简单,可以在Application 初始化的时候为线程设置CrashHandler,如下所示。 **MyApplication** ~~~ package com.ryg.crashtest; import android.app.Application; public class MyApplication extends Application { private static MyApplication sInstance; @Override public void onCreate() { super.onCreate(); sInstance = this; //在这里为应用设置异常处理程序,然后我们的程序才能捕获未处理的异常 CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(this); } public static MyApplication getInstance() { return sInstance; } } ~~~ **CrashActivity** ~~~ package com.ryg.crashtest; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.app.Activity; /** * @author wsc */ public class CrashActivity extends Activity implements OnClickListener { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_crash); initView(); } private void initView() { mButton = (Button) findViewById(R.id.button1); mButton.setOnClickListener(this); } @Override public void onClick(View v) { if (v == mButton) { // 在这里模拟异常抛出情况,人为抛出一个运行时异常 throw new RuntimeException("自定义异常:这是自己抛出的异常"); } } } ~~~ 在上面的测试代码中,给按钮加一个单击事件,在onClick 中人为抛出一个运行时异常,这个时候程序就crash 了,看看异常处理器为在们做了什么。从图2中可以看出,异常处理器为我们创建了一个日志文件,打开日志文件图3,可以看到手机的信息以及异常发生时的调用枝, 有了这些内容,开发人员就很容易定位问题了。 如下图1所示 ![](https://box.kancloud.cn/f4bc02de815b742e6103ae9bd9d78d98_427x625.png) 点击按钮,就会崩溃crash 下图2、图3是采集到的crash信息 ![](https://box.kancloud.cn/4e723c8e65e87977420729e5c750cf16_424x624.png) 图2 存储崩溃信息文件的位置 ![](https://box.kancloud.cn/a25f36d2cfb53675b2191b92061c42e1_422x626.png) 图3 采集到的崩溃信息