歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android程序崩潰統一處理機制

Android程序崩潰統一處理機制

日期:2017/3/1 9:28:38   编辑:Linux編程

在應用發布以後,由於安卓機型的千差萬別 ,可能會出現各種各樣的問題,這時候如果我們可以將這些信息收集起來,並進行修改就很不錯了。下面就來討論一下怎麼處理程序崩潰以後,錯誤信息的手機。

Java中已經提供了一個接口Thread.UncaughtExceptionHandler來對運行時的異常進行處理。只需要實現這個接口,並覆寫 public void uncaughtException(Thread thread, Throwable ex) 方法即可。

由於Application是Android應用啟動的第一個入口,所以我們實現自己的Application,讓他去實現Thread.UncaughtExceptionHandler接口。

使用的時候有一下幾個注意事項

1. 需要在manifest文件中的application節點,添加你自己實現的Application類,例如

<application
android:name=".CrashApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

2.在實現的Application類的onCreate方法中,設置本類為默認的異常處理器,添加如下代碼:

Thread.setDefaultUncaughtExceptionHandler(this);

3.在uncaughtException(Thread thread, Throwable ex) 方法中添加實現。

示例代碼如下,實現了收集發生異常的手機設備信息和異常信息,並將這些信息保存至本地

public class CrashApplication extends Application implements UncaughtExceptionHandler {

// 單例模式
private static CrashApplication INSTANCE;

private Context mContext;
// 用來存儲設備信息和異常信息
private Map<String, String> info = new HashMap<String, String>();
// 用於格式化日期,作為日志文件名的一部分
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

public CrashApplication() {
}

public static CrashApplication getInstance() {

if (INSTANCE == null) {
INSTANCE = new CrashApplication();
}
return INSTANCE;
}

@Override
public void onCreate() {
super.onCreate();
mContext = this;

// 設置該CrashHandler為程序的默認處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}

public void uncaughtException(Thread thread, Throwable ex) {
// TODO,在這裡你可以處理當 程序崩潰時你想做的事情

// 收集設備參數信息
collectDeviceInfo(mContext);
// 保存日志文件
saveCrashInfo2File(ex);
}

/**
* 收集設備參數信息
*
*/
public void collectDeviceInfo(Context context) {
try {
PackageManager pm = context.getPackageManager();// 獲得包管理器
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);// 得到該應用的信息,即主Activity
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
info.put("versionName", versionName);
info.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
e.printStackTrace();
}

Field[] fields = Build.class.getDeclaredFields();// 反射機制
for (Field field : fields) {
try {
field.setAccessible(true);
info.put(field.getName(), field.get("").toString());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

/**
* 將異常信息保存至SD卡crash目錄
*/
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : info.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\r\n");
}
Writer writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
ex.printStackTrace(pw);
Throwable cause = ex.getCause();
// 循環著把所有的異常信息寫入writer中
while (cause != null) {
cause.printStackTrace(pw);
cause = cause.getCause();
}
pw.close();// 記得關閉
String result = writer.toString();
sb.append(result);
// 保存文件
long timetamp = System.currentTimeMillis();
String time = format.format(new Date());
String fileName = "crash-" + time + "-" + timetamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
File dir = new File(Environment.getExternalStorageDirectory(), "crash");
if (!dir.exists())
dir.mkdir();

File file = new File(dir, fileName);

FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved