編輯:關於Android編程
在Android開發中在所難免的會出現程序crash,俗稱崩潰。用戶的隨意性訪問出現測試時未知的Bug導致我們的程序crash,此時我們是無法直接獲取的錯誤log的,也就無法修復Bug。這就會極大的影響用戶體驗,此時我們需要注冊一個功能來捕獲全局的異常信息,當程序出現crash信息,我們把錯誤log記錄下來,上傳到服務器,以便於我們能及時修復bug。實現這個功能我們需要依賴於UncaughtExceptionHandler這個類,UncaughtExceptionHandler是一個接口,在Thread中。裡面只有一個方法uncaughtException。當我們注冊一個UncaughtExceptionHandler之後,當我們的程序crash時就會回調uncaughtException方法,而uncaughtException方法帶有兩個參數,參數中就存放這crash信息。接下來只看寫代碼
package hi.xiaoyu.crashhandler;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
public class CrashHandler implements UncaughtExceptionHandler {
private static CrashHandler instance;
public static CrashHandler getInstance() {
if (instance == null) {
instance = new CrashHandler();
}
return instance;
}
public void init(Context ctx) {
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 核心方法,當程序crash 會回調此方法, Throwable中存放這錯誤日志
*/
@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
String logPath;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
logPath = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator
+ File.separator
+ "log";
File file = new File(logPath);
if (!file.exists()) {
file.mkdirs();
}
try {
FileWriter fw = new FileWriter(logPath + File.separator
+ "errorlog.log", true);
fw.write(new Date() + "\n");
// 錯誤信息
// 這裡還可以加上當前的系統版本,機型型號 等等信息
StackTraceElement[] stackTrace = arg1.getStackTrace();
fw.write(arg1.getMessage() + "\n");
for (int i = 0; i < stackTrace.length; i++) {
fw.write("file:" + stackTrace[i].getFileName() + " class:"
+ stackTrace[i].getClassName() + " method:"
+ stackTrace[i].getMethodName() + " line:"
+ stackTrace[i].getLineNumber() + "\n");
}
fw.write("\n");
fw.close();
// 上傳錯誤信息到服務器
// uploadToServer();
} catch (IOException e) {
Log.e("crash handler", "load file failed...", e.getCause());
}
}
arg1.printStackTrace();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
在Activity或者Application中注冊一下即可
CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(getApplicationContext());
這樣就實現了Android全局異常的捕獲處理,實現過程也比較簡單,希望對大家學習Android軟件編程有所幫助。
Android SwipeMenuListView框架詳解分析
周末 特地把Android SwipeMenuListView(滑動菜單)的知識資料整理一番,以下是整理內容:SwipeMenuListView(滑動菜單)A swipe
Android中常見Intent習慣用法-上篇(附源碼下載)
發送短信 發送短信的時候,我們要使用的action是Intent.ACTION_SENDTO,並且要指定其URI是smsto:協議,這樣能保證是短信應用接
android實現圖片驗證碼方法解析(自繪控件)
自繪控件的內容都是自己繪制出來的 大致流程如下:1.定義一個類繼承view 1.使用TypedArray初始化屬性集合 在
Android學習筆記之Menu的ShowAsAction屬性的設置
(1)在res--menu目錄下的main.xml文件