大家都知道,現在安裝android系統的手機版本和裝置千差萬别,在模拟器上運作良好的程式安裝到某款手機上說不定就出現崩潰的現象,開發者個人不可能購買所有裝置逐個調試,是以在程式釋出出去之後,如果出現了崩潰現象,開發者應該及時擷取在該裝置上導緻崩潰的資訊,這對于下一個版本的bug修複幫助極大,是以今天就來介紹一下如何在程式崩潰的情況下收集相關的裝置參數資訊和具體的異常資訊,并發送這些資訊到伺服器供開發者分析和調試程式。
我們先建立一個crash項目,項目結構如圖:
在mainactivity.java代碼中,代碼是這樣寫的:
package com.scott.crash;
import android.app.activity;
import android.os.bundle;
public class mainactivity extends activity {
private string s;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
system.out.println(s.equals("any string"));
}
}
我們在這裡故意制造了一個潛在的運作期異常,當我們運作程式時就會出現以下界面:
遇到軟體沒有捕獲的異常之後,系統會彈出這個預設的強制關閉對話框。
我們當然不希望使用者看到這種現象,簡直是對使用者心靈上的打擊,而且對我們的bug的修複也是毫無幫助的。我們需要的是軟體有一個全局的異常捕獲器,當出現一個我們沒有發現的異常時,捕獲這個異常,并且将異常資訊記錄下來,上傳到伺服器公開發這分析出現異常的具體原因。
接下來我們就來實作這一機制,不過首先我們還是來了解以下兩個類:android.app.application和java.lang.thread.uncaughtexceptionhandler。
application:用來管理應用程式的全局狀态。在應用程式啟動時application會首先建立,然後才會根據情況(intent)來啟動相應的activity和service。本示例中将在自定義加強版的application中注冊未捕獲異常處理器。
thread.uncaughtexceptionhandler:線程未捕獲異常處理器,用來處理未捕獲異常。如果程式出現了未捕獲異常,預設會彈出系統中強制關閉對話框。我們需要實作此接口,并注冊為程式中預設未捕獲異常處理。這樣當未捕獲異常發生時,就可以做一些個性化的異常處理操作。
大家剛才在項目的結構圖中看到的crashhandler.java實作了thread.uncaughtexceptionhandler,使我們用來處理未捕獲異常的主要成員,代碼如下:
import java.io.file;
import java.io.fileoutputstream;
import java.io.printwriter;
import java.io.stringwriter;
import java.io.writer;
import java.lang.thread.uncaughtexceptionhandler;
import java.lang.reflect.field;
import java.text.dateformat;
import java.text.simpledateformat;
import java.util.date;
import java.util.hashmap;
import java.util.map;
import android.content.context;
import android.content.pm.packageinfo;
import android.content.pm.packagemanager;
import android.content.pm.packagemanager.namenotfoundexception;
import android.os.build;
import android.os.environment;
import android.os.looper;
import android.util.log;
import android.widget.toast;
/**
* uncaughtexception處理類,當程式發生uncaught異常的時候,有該類來接管程式,并記錄發送錯誤報告.
*
* @author user
*/
public class crashhandler implements uncaughtexceptionhandler {
public static final string tag = "crashhandler";
//系統預設的uncaughtexception處理類
private thread.uncaughtexceptionhandler mdefaulthandler;
//crashhandler執行個體
private static crashhandler instance = new crashhandler();
//程式的context對象
private context mcontext;
//用來儲存設備資訊和異常資訊
private map<string, string> infos = new hashmap<string, string>();
//用于格式化日期,作為日志檔案名的一部分
private dateformat formatter = new simpledateformat("yyyy-mm-dd-hh-mm-ss");
/** 保證隻有一個crashhandler執行個體 */
private crashhandler() {
/** 擷取crashhandler執行個體 ,單例模式 */
public static crashhandler getinstance() {
return instance;
/**
* 初始化
*
* @param context
*/
public void init(context context) {
mcontext = context;
//擷取系統預設的uncaughtexception處理器
mdefaulthandler = thread.getdefaultuncaughtexceptionhandler();
//設定該crashhandler為程式的預設處理器
thread.setdefaultuncaughtexceptionhandler(this);
* 當uncaughtexception發生時會轉入該函數來處理
public void uncaughtexception(thread thread, throwable ex) {
if (!handleexception(ex) && mdefaulthandler != null) {
//如果使用者沒有處理則讓系統預設的異常處理器來處理
mdefaulthandler.uncaughtexception(thread, ex);
} else {
try {
thread.sleep(3000);
} catch (interruptedexception e) {
log.e(tag, "error : ", e);
}
//退出程式
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(mcontext, "很抱歉,程式出現異常,即将退出.", toast.length_long).show();
looper.loop();
}.start();
//收集裝置參數資訊
collectdeviceinfo(mcontext);
//儲存日志檔案
savecrashinfo2file(ex);
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) {
log.e(tag, "an error occured when collect package info", e);
field[] fields = build.class.getdeclaredfields();
for (field field : fields) {
field.setaccessible(true);
infos.put(field.getname(), field.get(null).tostring());
log.d(tag, field.getname() + " : " + field.get(null));
} catch (exception e) {
log.e(tag, "an error occured when collect crash info", e);
* 儲存錯誤資訊到檔案中
* @return 傳回檔案名稱,便于将檔案傳送到伺服器
private string savecrashinfo2file(throwable ex) {
stringbuffer sb = new stringbuffer();
for (map.entry<string, string> entry : infos.entryset()) {
string key = entry.getkey();
string value = entry.getvalue();
sb.append(key + "=" + value + "\n");
writer writer = new stringwriter();
printwriter printwriter = new printwriter(writer);
ex.printstacktrace(printwriter);
throwable cause = ex.getcause();
while (cause != null) {
cause.printstacktrace(printwriter);
cause = cause.getcause();
printwriter.close();
string result = writer.tostring();
sb.append(result);
long timestamp = system.currenttimemillis();
string time = formatter.format(new date());
string filename = "crash-" + time + "-" + timestamp + ".log";
if (environment.getexternalstoragestate().equals(environment.media_mounted)) {
string path = "/sdcard/crash/";
file dir = new file(path);
if (!dir.exists()) {
dir.mkdirs();
}
fileoutputstream fos = new fileoutputstream(path + filename);
fos.write(sb.tostring().getbytes());
fos.close();
return filename;
} catch (exception e) {
log.e(tag, "an error occured while writing file...", e);
return null;
在收集異常資訊時,朋友們也可以使用properties,因為properties有一個很便捷的方法properties.store(outputstream out, string comments),用來将properties執行個體中的鍵值對外輸到輸出流中,但是在使用的過程中發現生成的檔案中異常資訊列印在同一行,看起來極為費勁,是以換成map來存放這些資訊,然後生成檔案時稍加了些操作。
完成這個crashhandler後,我們需要在一個application環境中讓其運作,為此,我們繼承android.app.application,添加自己的代碼,crashapplication.java代碼如下:
import android.app.application;
public class crashapplication extends application {
public void oncreate() {
super.oncreate();
crashhandler crashhandler = crashhandler.getinstance();
crashhandler.init(getapplicationcontext());
最後,為了讓我們的crashapplication取代android.app.application的地位,在我們的代碼中生效,我們需要修改androidmanifest.xml:
<application android:name=".crashapplication" ...>
</application>
因為我們上面的crashhandler中,遇到異常後要儲存裝置參數和具體異常資訊到sdcard,是以我們需要在androidmanifest.xml中加入讀寫sdcard權限:
<uses-permission android:name="android.permission.write_external_storage"/>
搞定了上邊的步驟之後,我們來運作一下這個項目:
看以看到,并不會有強制關閉的對話框出現了,取而代之的是我們比較有好的提示資訊。
然後看一下sdcard生成的檔案:
用文本編輯器打開日志檔案,看一段日志資訊:
cpu_abi=armeabi
cpu_abi2=unknown
id=frf91
manufacturer=unknown
brand=generic
type=eng
......
caused by: java.lang.nullpointerexception
at com.scott.crash.mainactivity.oncreate(mainactivity.java:13)
at android.app.instrumentation.callactivityoncreate(instrumentation.java:1047)
at android.app.activitythread.performlaunchactivity(activitythread.java:2627)
... 11 more
不過在使用http服務之前,需要确定網絡暢通,我們可以使用下面的方式判斷網絡是否可用:
* 網絡是否可用
* @return
public static boolean isnetworkavailable(context context) {
connectivitymanager mgr = (connectivitymanager) context.getsystemservice(context.connectivity_service);
networkinfo[] info = mgr.getallnetworkinfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getstate() == networkinfo.state.connected) {
return true;
return false;
}