寫在前面:
Android崩潰是我們開發中不可避免的異常處理,通常崩潰都會觸發系統的強制關閉對話框,用戶點擊后系統會強制關閉當前進程,用戶體驗及其不好。本文就簡單介紹下怎么優雅的處理全局異常并實現簡單的日志保存,日志上送,以及程序重啟。
大神請無視。。
你好,你們程序崩潰了,納尼?
鬼知道發聲了什么...
如果你的項目沒有全局異常處理,沒有實現日志保存和上送那么恭喜你,你中獎了。
接下來等待你的就是無休止的加班找bug,盡快找到還好,如果找不到問題。領導就要考慮換你了。
1. 什么是UncaughtExceptionHandler
UncaughtExceptionHandler是什么鬼?
官網解釋
Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.
大概意思是說:如果一個程序沒有捕獲異常,java虛擬機調用Thread.getUncaughtExceptionHandler()處理,如果一個線程沒有uncaughtexceptionhandler設置,那么它的線程組對象作為其uncaughtexceptionhandler。如果線程組對象具有處理異常的能力,可以在線程組內處理異常,如果沒有處理能力也可以轉發給默認的捕獲異常處理程序。
2. UncaughtExceptionHandler怎么用?
UncaughtExceptionHandler是一個接口,需要創建類來實現這個接口。
- 創建UniException類并實現UncaughtExceptionHandler接口。
- 重寫uncaughtException()方法,當UncaughtException發生時會轉入該函數來處理。
- 單例模式創建靜態getInstance()方法,獲取當前UniException類對象。
- 創建init()方法,獲取系統默認的UncaughtException處理器,設置本類為程序的默認處理器。
- 創建handleException()方法,自定義錯誤處理,收集錯誤日志,上送錯誤日志。
具體實現如下:
public class UniException implements UncaughtExceptionHandler {
public static final String TAG = "UniException";
// 系統默認的UncaughtException處理類
private Thread.UncaughtExceptionHandler mDefaultHandler;
// UniException實例
private static UniException INSTANCE = new UniException();
// 用來存儲設備信息和異常信息
private Map<String, String> infos = new HashMap<String, String>();
/** 保證只有一個實例 */
private UniException() {
}
/** 獲取UniException實例 ,單例模式 */
public static UniException getInstance() {
if (INSTANCE == null) {
INSTANCE = new UniException();
INSTANCE.init();
}
return INSTANCE;
}
/**
* 初始化
*
* @param context
*/
public void init() {
// 獲取系統默認的UncaughtException處理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 設置該本類為程序的默認處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 當UncaughtException發生時會轉入該函數來處理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用戶沒有處理則讓系統默認的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
LogUtil.e("error : " + e.getMessage());
}
// 退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
/**
* 自定義錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成.
*
* @param ex
* @return true:如果處理了該異常信息;否則返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
// 使用Toast來顯示異常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(AppOS.appOS, "很抱歉,程序出現異常,即將退出.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
// 收集設備參數信息
collectDeviceInfo(AppOS.appOS);
// 保存日志文件
try {
File file = new File(INI.INI_BUS_LOG_FLODER);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fout;
fout = new FileOutputStream(new File(INI.INI_BUS_LOG_FLODER + DateUtil.getYourTime("yyyyMMdd") + ".log"),
true);
fout.write((">>>>時間:" + DateUtil.getYourTime(DateUtil.yyyyMMdd_HH_mm_ss) + "\r\n").getBytes("utf-8"));
fout.write(("信息:" + ex.getMessage() + "\r\n").getBytes("utf-8"));
for (int i = 0; i < ex.getStackTrace().length; i++) {
fout.write(("****StackTrace" + i + "\r\n").getBytes("utf-8"));
fout.write(("行數:" + ex.getStackTrace()[i].getLineNumber() + "\r\n").getBytes("utf-8"));
fout.write(("類名:" + ex.getStackTrace()[i].getClassName() + "\r\n").getBytes("utf-8"));
fout.write(("文件:" + ex.getStackTrace()[i].getFileName() + "\r\n").getBytes("utf-8"));
fout.write(("方法:" + ex.getStackTrace()[i].getMethodName() + "\r\n\r\n").getBytes("utf-8"));
}
fout.write(
"--------------------------------\r\n--------------------------------\r\n--------------------------------\r\n"
.getBytes("utf-8"));
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* 收集設備參數信息
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
LogUtil.e("an error occured when collect package info" + e.getMessage());
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
LogUtil.e(field.getName() + " : " + field.get(null));
} catch (Exception e) {
LogUtil.e("an error occured when collect crash info" + e.getMessage());
}
}
}
3.定義完成后續咋用?
- 定義類AppOS extends Application
- 在AndroidManifest.xml中注冊AppOS
- 注冊異常處理UniException.getInstance().init(getApplicationContext());
public class AppOS extends Application {
public static AppOS appOS;
@Override
public void onCreate() {
// TODO
super.onCreate();
appOS = this;
UniException.getInstance().init(getApplicationContext());
}
}