在 Android 开发中,谁都不想自己的 APP 出现异常,哪怕代码写得再好,也免不了出现异常的情况。而当出现异常后,要做的就是全局捕获异常以及将异常收集起来并且回传给服务端,方便对异常的解决。
CrashHandler 类:
package cn.zzw.crashdemo; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import java.util.HashMap; import java.util.Map; /** * @author 鹭岛猥琐男 * @create 2019/10/2 21:23 */ public class CrashHandler implements Thread.UncaughtExceptionHandler { /** * 采用饿汉式来创建单例实例. */ private static CrashHandler instance = new CrashHandler(); private Context mContext; /** * 系统默认的UncaughtException处理类. */ private Thread.UncaughtExceptionHandler mDefaultHandler; /** * 用来存储设备信息和异常信息. */ private Map<String, String> infos = new HashMap<String, String>(); /** * 保证只有一个CrashHandler实例. */ private CrashHandler() { } /** * 获取CrashHandler实例 ,单例模式. */ public static CrashHandler getInstance() { return instance; } /** * 初始化. */ public void init(Context context) { mContext = context; // 获取系统默认的UncaughtException处理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); // 设置该CrashHandler为程序的默认处理器 Thread.setDefaultUncaughtExceptionHandler(this); } @Override public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) { //TODO 收集Log Log.e("zzw", "CrashHandler uncaughtException(): "+throwable.getMessage().toString()); //干掉当前的程序 android.os.Process.killProcess(android.os.Process.myPid()); } }在自定义的 Application 类中进行调用 :
package cn.zzw.crashdemo; import android.app.Application; /** * @author 鹭岛猥琐男 * @create 2019/10/2 21:13 */ public class CrashApplication extends Application { @Override public void onCreate() { super.onCreate(); CrashHandler.getInstance().init(this); } }在 AndroidManifest.xml 中的修改:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.zzw.crashdemo"> <application android:name=".CrashApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>测试结果:
2019-10-02 21:59:24.257 10397-10397/cn.zzw.crashdemo E/zzw: CrashHandler uncaughtException(): divide by zero