Android App崩潰上傳日誌到伺服器並且重啟!
阿新 • • 發佈:2019-02-06
我們寫程式的時候都希望能寫出一個沒有任何Bug的程式,期望在任何情況下都不會發生程式崩潰。但沒有一個程式設計師能保證自己寫的程式絕對不會出現異常崩潰。特別是當你使用者數達到一定數量級後,你也更容易發現應用不同情況下的崩潰。
對於還沒釋出的應用程式,我們可以通過測試、分析Log的方法來收集崩潰資訊。但對已經發布的程式,我們不可能讓使用者去檢視崩潰資訊然後再反饋給開發者。所以,設計一個對於小白使用者都可以輕鬆實現反饋的應用就顯得很重要了。我這裡結合我自己寫的一個Demo,來分析從崩潰開始到崩潰資訊反饋到我們伺服器,我們程式都需要做什麼。
當我們的程式因未捕獲的異常而突然終止時,系統會呼叫處理程式的介面UncaughtExceptionHandler
綜上,我對異常處理方式的思路是這樣的:
1.我們需要首先收集產生崩潰的手機資訊,因為Android的樣機種類繁多,很可能某些特定機型下會產生莫名的bug。
2.將手機的資訊和崩潰資訊寫入檔案系統中。這樣方便後續處理。3.崩潰的應用需要可以自動重啟。重啟的頁面設定成反饋頁面,詢問 使用者是否需要上傳崩潰報告。
4.使用者同意後,即將2中寫入的崩潰資訊檔案傳送到自己的伺服器。
通過上面的步驟,我們就可以寫出大概的虛擬碼:
handleException(){
collectDeviceInfo(context);//手機手機資訊
writeCrashInfoToFile(ex);//寫入崩潰檔案
restart();//應用重啟
}
最後,在重啟頁面通過AsyncTask將崩潰資訊上傳伺服器。
有了以上思路,我們一步一步的寫出每個偽函式的具體程式碼。
1.收集手機的資訊:
/**
*
* @param ctx
* 手機裝置相關資訊
*/
publicvoid 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);
infos.put("crashTime", formatter.format(newDate()));
}
}catch(NameNotFoundException e){
Log.e(TAG,"an error occured when collect package info", e);
}
Field[] fields =Build.class.getDeclaredFields();
for(Field field: fields){
try{
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);
}
}
}
2.崩潰和手機資訊寫入檔案:
/**
*
* @param ex
* 將崩潰寫入檔案系統
*/
privatevoid writeCrashInfoToFile(Throwable ex){
StringBuffer sb =newStringBuffer();
for(Map.Entry<String,String> entry: infos.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
sb.append(key +"="+ value +"\n");
}
Writer writer =newStringWriter();
PrintWriter printWriter =newPrintWriter(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);
//這裡把剛才異常堆疊資訊寫入SD卡的Log日誌裡面
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
String sdcardPath =Environment.getExternalStorageDirectory().getPath();
String filePath = sdcardPath +"/cym/crash/";
localFileUrl = writeLog(sb.toString(), filePath);
}
}
/**
*
* @param log
* @param name
* @return 返回寫入的檔案路徑
* 寫入Log資訊的方法,寫入到SD卡里面
*/
privateString writeLog(String log,String name)
{
CharSequence timestamp =newDate().toString().replace(" ","");
timestamp ="crash";
String filename = name + timestamp +".log";
File file =newFile(filename);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try
{
Log.d("TAG","寫入到SD卡里面");
// FileOutputStream stream = new FileOutputStream(new File(filename));
// OutputStreamWriter output = new OutputStreamWriter(stream);
file.createNewFile();
FileWriter fw=newFileWriter(file,true);
BufferedWriter bw =newBufferedWriter(fw);
//寫入相關Log到檔案
bw.write(log);
bw.newLine();
bw.close();
fw.close();
return filename;
}
catch(IOException e)
{
Log.e(TAG,"an error occured while writing file...", e);
e.printStackTrace();
returnnull;
}
}
3.重啟應用:
注:我嘗試過好多種應用重啟的方法,最終選擇採用PendingIntent的方式。
privatevoid restart(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
Log.e(TAG,"error : ", e);
}
Intent intent =newIntent(context.getApplicationContext(),SendCrashActivity.class);
PendingIntent restartIntent =PendingIntent.getActivity(
context.getApplicationContext(),0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
//退出程式
AlarmManager mgr =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC,System.currentTimeMillis()+1000,
restartIntent);// 1秒鐘後重啟應用
}
4.上傳崩潰
應用重啟後來到的是SendCrashActivity介面,在這裡我設定了一個簡單的按鈕,點選後即可上傳崩潰資訊。程式碼比較多,這裡列一個比較有用的上傳方法吧:
publicstaticString uploadFile(File file,String requestUrl){
String result =null;
String BOUNDARY = UUID.randomUUID().toString();//邊界標識 隨機生成
String PREFIX ="--";