Android 對程式異常崩潰的捕捉,android崩潰捕捉

來源:互聯網
上載者:User

Android 對程式異常崩潰的捕捉,android崩潰捕捉

轉載部落格:http://blog.csdn.net/i_lovefish/article/details/17719081

以下為異常捕捉處理代碼:  
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中註冊(也就是初始化):

import android.app.Application;    public class CrashApplication extends Application {        @Override      public void onCreate() {          super.onCreate();          CrashHandler catchHandler = CrashHandler.getInstance();          catchHandler.init(getApplicationContext());      }  }

現在類比一個null 指標異常:

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>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進行修複。

當我們的的應用由於運行時異常導致Force Close的時候,可以設定主線程的UncaughtExceptionHandler,實現捕獲運行時異常的堆棧資訊。同時使用者可以把堆棧資訊通過發送郵件的方式反饋給我們。下面是實現的代碼:

代碼下載請按此

例子:點擊按鈕後,會觸發一個NullPointerException的運行時異常,這個例子實現了捕獲運行時異常,發送郵件反饋裝置和堆棧資訊的功能。

介面1(觸發運行時異常)

  

介面2(發送堆棧資訊)

  

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> 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.