这里主要是针对崩溃异常捕获(runtimeException)
思路就是整个程序都在自己写的application监控下,然后在application里面去监控异常的情况,以及在捕获异常的时候把当前机型和异常的情况提交给服务端。
直接上代码:
public class MyApplication extends Application {
public static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
// 全局闪退异常记录
CrashUtils crashUtils = CrashUtils.getInstance();
crashUtils.init();
}
/** 获取全局上下文 **/
public static Context getContext() {
return context;
}
}
帮助类:
/**
* Created by Frank on 2016/12/22.
* 崩溃相关工具类
*/
public class CrashUtils implements Thread.UncaughtExceptionHandler {
private volatile static CrashUtils mInstance;
privateThread.UncaughtExceptionHandler mHandler;
private boolean mInitialized;
privateCrashUtils() {
}
/**单例**/
public static CrashUtils getInstance() {
if(mInstance==null) {
synchronized(CrashUtils.class) {
if(mInstance==null) {
mInstance=new CrashUtils();
}
}
}
return mInstance;
}
/*** 初始化{true: 成功;false: 失败}**/
public boolean init() {
if(mInitialized)return true;
mHandler= Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
return mInitialized=true;
}
@Override
public void uncaughtException(Thread thread, finalThrowable throwable) {
newThread(newRunnable() {
@Override
public void run() {
CrashModel crashModel =new CrashModel();
crashModel.setDateNow(new SimpleDateFormat("yy-MM-dd HH:mm:ss",Locale.getDefault()).format(newDate()));
crashModel.setDeviceManufacturer(Build.MANUFACTURER);
crashModel.setDeviceModel(Build.MODEL);
crashModel.setAndroidVersion(Build.VERSION.RELEASE);
crashModel.setAndroidSDK(Build.VERSION.SDK_INT);
crashModel.setMessage(throwable.getMessage());
// 接下来就是调用服务端的接口去保存闪退的信息
}
}).start();
if(mHandler!=null) {
mHandler.uncaughtException(thread,throwable);
}
}
}
model类:
/**
* Created by Frank on 2016/12/23.
* 全局异常捕获
*/
public class CrashModel {
/*
************* Crash Log Head ****************
Device Manufacturer: Meizu
Device Model : m3 note
Android Version : 5.1
Android SDK : 22
App VersionName : null
App VersionCode : 0
************* Crash Log Head ****************
*/
privateStringDeviceManufacturer;
privateStringDeviceModel;
privateStringAndroidVersion;
private intAndroidSDK;
privateStringAppVersionName;
private intAppVersionCode;
privateStringMessage;
privateStringDateNow;
// get,set 方法
}
加入注册信息-->配置文件(AndroidManifest.xml)中
android:name=".MyApplication"
就加在<application 后面
记得给权限(获取数据,SD卡写入什么的)
小知识点源码
网友评论