轉載博客:http://blog.csdn.net/i_lovefish/article/details/17719081html
如下爲異常捕捉處理代碼:
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; 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異常的時候,有該類來接管程序,並記錄發送錯誤報告. * * 須要在Application中註冊,爲了要在程序啓動器就監控整個程序。 */public class CrashHandler implements UncaughtExceptionHandler { public static final String TAG = "CrashHandler"; //系統默認的UncaughtException處理類 private Thread.UncaughtExceptionHandler mDefaultHandler; //CrashHandler實例 private static CrashHandler instance; //程序的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() { if(instance == null) instance = new CrashHandler(); return instance; } /** * 初始化 */public void init(Context context) { mContext = context; //獲取系統默認的UncaughtException處理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); //設置該CrashHandler爲程序的默認處理器 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) { 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; } //收集設備參數信息 collectDeviceInfo(mContext); //使用Toast來顯示異常信息 new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(mContext, "很抱歉,程序出現異常,即將退出.", Toast.LENGTH_SHORT).show(); Looper.loop(); } }.start(); //保存日誌文件 saveCatchInfo2File(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) { 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); } } } /** * 保存錯誤信息到文件中 * * @param ex * @return 返回文件名稱,便於將文件傳送到服務器 */private String saveCatchInfo2File(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); try { 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 = "/mnt/sdcard/crash/"; File dir = new File(path); if (!dir.exists()) { dir.mkdirs(); } FileOutputStream fos = new FileOutputStream(path + fileName); fos.write(sb.toString().getBytes()); //發送給開發人員 sendCrashLog2PM(path+fileName); fos.close(); } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); } return null; } /** * 將捕獲的致使崩潰的錯誤信息發送給開發人員 * * 目前只將log日誌保存在sdcard 和輸出到LogCat中,並未發送給後臺。 */private void sendCrashLog2PM(String fileName){ if(!new File(fileName).exists()){ Toast.makeText(mContext, "日誌文件不存在!", Toast.LENGTH_SHORT).show(); return; } FileInputStream fis = null; BufferedReader reader = null; String s = null; try { fis = new FileInputStream(fileName); reader = new BufferedReader(new InputStreamReader(fis, "GBK")); while(true){ s = reader.readLine(); if(s == null) break; //因爲目前還沒有肯定以何種方式發送,因此先打出log日誌。 Log.i("info", s.toString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ // 關閉流 try { reader.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
針對異常的捕捉要進行全局監控整個項目,因此要將其在Application中註冊(也就是初始化):java
import android.app.Application; public class CrashApplication extends Application { @Override public void onCreate() { super.onCreate(); CrashHandler catchHandler = CrashHandler.getInstance(); catchHandler.init(getApplicationContext()); } }
如今模擬一個空指針異常:android
import android.app.Activity; import android.os.Bundle; public class CatchExceptionLogActivity extends Activity { /** Called when the activity is first created. */private String s; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); System.out.println(s.equals("hello")); // s沒有進行賦值,因此會出現NullPointException異常 } }
別忘了在配置文件中對Application進行註冊:服務器
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.forms.catchlog" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" <span style="color:#ff0000;">android:name=".CrashApplication"></span> <activity android:label="@string/app_name" android:name=".CatchExceptionLogActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
因爲Android設備各異,第三方定製的Android系統也很是多,咱們不可能對全部的設備場景都進行測試,於是開發一款徹底無bug的應用幾乎是不可能的任務,那麼當應用在用戶的設備上Force Close時,咱們是否是能夠捕獲這個錯誤,記錄用戶的設備信息,而後讓用戶選擇是否反饋這些堆棧信息,經過這種bug反饋方式,咱們能夠有針對性地對bug進行修復。app
當咱們的的應用因爲運行時異常致使Force Close的時候,能夠設置主線程的UncaughtExceptionHandler,實現捕獲運行時異常的堆棧信息。同時用戶能夠把堆棧信息經過發送郵件的方式反饋給咱們。下面是實現的代碼:ide
代碼下載請按此函數
例子:點擊按鈕後,會觸發一個NullPointerException的運行時異常,這個例子實現了捕獲運行時異常,發送郵件反饋設備和堆棧信息的功能。oop
界面1(觸發運行時異常)測試
界面2(發送堆棧信息)ui
TestActivity.java
package com.zhuozhuo; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {//給主線程設置一個處理運行時異常的handler @Override public void uncaughtException(Thread thread, final Throwable ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); StringBuilder sb = new StringBuilder(); sb.append("Version code is "); sb.append(Build.VERSION.SDK_INT + "\n");//設備的Android版本號 sb.append("Model is "); sb.append(Build.MODEL+"\n");//設備型號 sb.append(sw.toString()); Intent sendIntent = new Intent(Intent.ACTION_SENDTO); sendIntent.setData(Uri.parse("mailto:csdn@csdn.com"));//發送郵件異常到csdn@csdn.com郵箱 sendIntent.putExtra(Intent.EXTRA_SUBJECT, "bug report");//郵件主題 sendIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());//堆棧信息 startActivity(sendIntent); finish(); } }); findViewById(R.id.button).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Integer a = null; a.toString();//觸發nullpointer運行時錯誤 } }); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:text="點擊按鈕觸發運行時異常" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="top"></EditText> <Button android:text="按鈕" android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></Button> </LinearLayout>
08-01 17:25:10.273 25744-25744/com.errey I/info: SUPPORTED_64_BIT_ABIS=[Ljava.lang.String;@392c43ac 08-01 17:25:10.274 25744-25744/com.errey I/info: versionCode=1 非用戶可見版本號 08-01 17:25:10.274 25744-25744/com.errey I/info: BOARD=m3note 手機型號 08-01 17:25:10.275 25744-25744/com.errey I/info: BOOTLOADER=unknown 引導程序=未知的 08-01 17:25:10.275 25744-25744/com.errey I/info: TYPE=user 類型=用戶 08-01 17:25:10.275 25744-25744/com.errey I/info: ID=LMY47I ID 08-01 17:25:10.275 25744-25744/com.errey I/info: TIME=1466191121000 時間 08-01 17:25:10.275 25744-25744/com.errey I/info: BRAND=Meizu 手機品牌 08-01 17:25:10.276 25744-25744/com.errey I/info: TAG=Build 08-01 17:25:10.276 25744-25744/com.errey I/info: SERIAL=91QECP43FK5Q 手機序列號 08-01 17:25:10.276 25744-25744/com.errey I/info: HARDWARE=mt6755 08-01 17:25:10.276 25744-25744/com.errey I/info: SUPPORTED_ABIS=[Ljava.lang.String;@177f6875 08-01 17:25:10.277 25744-25744/com.errey I/info: CPU_ABI=arm64-v8a 08-01 17:25:10.277 25744-25744/com.errey I/info: RADIO=unknown 08-01 17:25:10.277 25744-25744/com.errey I/info: IS_DEBUGGABLE=false 是否可調試 08-01 17:25:10.277 25744-25744/com.errey I/info: MANUFACTURER=Meizu 製造商 08-01 17:25:10.277 25744-25744/com.errey I/info: SUPPORTED_32_BIT_ABIS=[Ljava.lang.String;@3c593d5f 08-01 17:25:10.277 25744-25744/com.errey I/info: TAGS=release-keys 08-01 17:25:10.277 25744-25744/com.errey I/info: CPU_ABI2= 08-01 17:25:10.277 25744-25744/com.errey I/info: UNKNOWN=unknown 08-01 17:25:10.277 25744-25744/com.errey I/info: USER=flyme 用戶 08-01 17:25:10.277 25744-25744/com.errey I/info: FINGERPRINT=Meizu/meizu_m3note/m3note:5.1/LMY47I/1466190928:user/release-keys 08-01 17:25:10.277 25744-25744/com.errey I/info: HOST=mz-builder-8 08-01 17:25:10.277 25744-25744/com.errey I/info: PRODUCT=m3note 08-01 17:25:10.277 25744-25744/com.errey I/info: versionName=1.0 用戶可見的版本號 08-01 17:25:10.277 25744-25744/com.errey I/info: DISPLAY=Flyme 5.1.3.4A 手機系統版本號 08-01 17:25:10.277 25744-25744/com.errey I/info: MODEL=m3 note 手機型號 08-01 17:25:10.277 25744-25744/com.errey I/info: DEVICE=m3note 設備 08-01 17:25:10.277 25744-25744/com.errey I/info: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button 錯誤日誌 08-01 17:25:10.277 25744-25744/com.errey I/info: at com.errey.Main2Activity.onClick(Main2Activity.java:24) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.view.View.performClick(View.java:4909) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.view.View$PerformClick.run(View.java:20390) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.os.Handler.handleCallback(Handler.java:821) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.os.Handler.dispatchMessage(Handler.java:104) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.os.Looper.loop(Looper.java:194) 08-01 17:25:10.277 25744-25744/com.errey I/info: at android.app.ActivityThread.main(ActivityThread.java:5742) 08-01 17:25:10.277 25744-25744/com.errey I/info: at java.lang.reflect.Method.invoke(Native Method) 08-01 17:25:10.278 25744-25744/com.errey I/info: at java.lang.reflect.Method.invoke(Method.java:372) 08-01 17:25:10.278 25744-25744/com.errey I/info: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1104) 08-01 17:25:10.278 25744-25744/com.errey I/info: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)