Android捕獲崩潰異常,Android捕獲崩潰

來源:互聯網
上載者:User

Android捕獲崩潰異常,Android捕獲崩潰

開發中最讓人頭疼的是應用突然爆炸,然後跳回到案頭。而且我們常常不知道這種狀況會何時出現,在應用調試階段還好,還可以通過調試工具的日誌查看錯誤出現在哪裡。但平時使用的時候給你鬧崩潰,那你就欲哭無淚了。

那麼今天主要講一下如何去捕捉系統出現的Unchecked異常。何為Unchecked異常呢,換句話說就是指非受檢異常,它不能用try-catch來顯示捕捉。

我們先從Exception講起。Exception分為兩類:一種是CheckedException,一種是UncheckedException。這兩種Exception的區別主要是CheckedException需要用try...catch...顯示的捕獲,而UncheckedException不需要捕獲。通常UncheckedException又叫做RuntimeException。《effective java》指出:對於可恢複的條件使用被檢查的異常(CheckedException),對於程式錯誤(言外之意不可恢複,大錯已經釀成)使用運行時異常(RuntimeException)。我們常見的RuntimeExcepiton有IllegalArgumentException、IllegalStateException、NullPointerException、IndexOutOfBoundsException等等。對於那些CheckedException就不勝枚舉了,我們在編寫程式過程中try...catch...捕捉的異常都是CheckedException。io包中的IOException及其子類,這些都是CheckedException。

一、使用UncaughtExceptionHandler來捕獲unchecked異常

UncaughtException處理類,當程式發生Uncaught異常的時候,由該類來接管程式,並記錄發送錯誤報表。

直接上代碼吧

  1 import java.io.File;  2 import java.io.FileOutputStream;  3 import java.io.PrintWriter;  4 import java.io.StringWriter;  5 import java.io.Writer;  6 import java.lang.Thread.UncaughtExceptionHandler;  7 import java.lang.reflect.Field;  8 import java.text.DateFormat;  9 import java.text.SimpleDateFormat; 10 import java.util.Date; 11 import java.util.HashMap; 12 import java.util.Locale; 13 import java.util.Map; 14 import java.util.Map.Entry; 15 import java.util.regex.Matcher; 16 import java.util.regex.Pattern; 17  18 import android.annotation.SuppressLint; 19 import android.content.Context; 20 import android.content.pm.PackageInfo; 21 import android.content.pm.PackageManager; 22 import android.content.pm.PackageManager.NameNotFoundException; 23 import android.os.Build; 24 import android.os.Environment; 25 import android.os.Looper; 26 import android.util.Log; 27 import android.widget.Toast; 28  29 /** 30  * UncaughtException處理類,當程式發生Uncaught異常的時候,有該類來接管程式,並記錄發送錯誤報表. 31  *  32  * @author user 33  *  34  */ 35 @SuppressLint("SdCardPath") 36 public class CrashHandler implements UncaughtExceptionHandler { 37  38     public static final String TAG = "TEST"; 39  40     // CrashHandler 執行個體 41     private static CrashHandler INSTANCE = new CrashHandler(); 42  43     // 程式的 Context 對象 44     private Context mContext; 45  46     // 系統預設的 UncaughtException 處理類 47     private Thread.UncaughtExceptionHandler mDefaultHandler; 48  49     // 用來存放裝置資訊和異常資訊 50     private Map<String, String> infos = new HashMap<String, String>(); 51  52     // 用來顯示Toast中的資訊 53     private static String error = "程式錯誤,額,不對,我應該說,伺服器正在維護中,請稍後再試"; 54  55     private static final Map<String, String> regexMap = new HashMap<String, String>(); 56  57     // 用于格式化日期,作為記錄檔名的一部分 58     private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", 59             Locale.CHINA); 60  61     /** 保證只有一個 CrashHandler 執行個體 */ 62     private CrashHandler() { 63         // 64     } 65  66     /** 擷取 CrashHandler 執行個體 ,單例模式 */ 67     public static CrashHandler getInstance() { 68         initMap(); 69         return INSTANCE; 70     } 71  72     /** 73      * 初始化 74      *  75      * @param context 76      */ 77     public void init(Context context) { 78         mContext = context; 79  80         // 擷取系統預設的 UncaughtException 處理器 81         mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); 82  83         // 設定該 CrashHandler 為程式的預設處理器 84         Thread.setDefaultUncaughtExceptionHandler(this); 85         Log.d("TEST", "Crash:init"); 86     } 87  88     /** 89      * 當 UncaughtException 發生時會轉入該函數來處理 90      */ 91     @Override 92     public void uncaughtException(Thread thread, Throwable ex) { 93         if (!handleException(ex) && mDefaultHandler != null) { 94             // 如果使用者沒有處理則讓系統預設的異常處理器來處理 95             mDefaultHandler.uncaughtException(thread, ex); 96             Log.d("TEST", "defalut"); 97         } else { 98             try { 99                 Thread.sleep(3000);100             } catch (InterruptedException e) {101                 Log.e(TAG, "error : ", e);102             }103             // 退出程式104             android.os.Process.killProcess(android.os.Process.myPid());105             // mDefaultHandler.uncaughtException(thread, ex);106             System.exit(1);107         }108     }109 110     /**111      * 自訂錯誤處理,收集錯誤資訊,發送錯誤報表等操作均在此完成112      * 113      * @param ex114      * @return true:如果處理了該異常資訊;否則返回 false115      */116     private boolean handleException(Throwable ex) {117         if (ex == null) {118             return false;119         }120 121         // 收集裝置參數資訊122         // collectDeviceInfo(mContext);123         // 儲存記錄檔124         saveCrashInfo2File(ex);125         // 使用 Toast 來顯示異常資訊126         new Thread() {127             @Override128             public void run() {129                 Looper.prepare();130                 Toast.makeText(mContext, error, Toast.LENGTH_LONG).show();131                 Looper.loop();132             }133         }.start();134         return true;135     }136 137     /**138      * 收集裝置參數資訊139      * 140      * @param ctx141      */142     public void collectDeviceInfo(Context ctx) {143         try {144             PackageManager pm = ctx.getPackageManager();145             PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(),146                     PackageManager.GET_ACTIVITIES);147 148             if (pi != null) {149                 String versionName = pi.versionName == null ? "null"150                         : pi.versionName;151                 String versionCode = pi.versionCode + "";152                 infos.put("versionName", versionName);153                 infos.put("versionCode", versionCode);154             }155         } catch (NameNotFoundException e) {156             Log.e(TAG, "an error occured when collect package info", e);157         }158 159         Field[] fields = Build.class.getDeclaredFields();160         for (Field field : fields) {161             try {162                 field.setAccessible(true);163                 infos.put(field.getName(), field.get(null).toString());164                 Log.d(TAG, field.getName() + " : " + field.get(null));165             } catch (Exception e) {166                 Log.e(TAG, "an error occured when collect crash info", e);167             }168         }169     }170 171     /**172      * 儲存錯誤資訊到檔案中 *173      * 174      * @param ex175      * @return 返迴文件名稱,便於將檔案傳送到伺服器176      */177     private String saveCrashInfo2File(Throwable ex) {178         StringBuffer sb = getTraceInfo(ex);179         Writer writer = new StringWriter();180         PrintWriter printWriter = new PrintWriter(writer);181         ex.printStackTrace(printWriter);182         Throwable cause = ex.getCause();183         while (cause != null) {184             cause.printStackTrace(printWriter);185             cause = cause.getCause();186         }187         printWriter.close();188 189         String result = writer.toString();190         sb.append(result);191         try {192             long timestamp = System.currentTimeMillis();193             String time = formatter.format(new Date());194             String fileName = "crash-" + time + "-" + timestamp + ".log";195 196             if (Environment.getExternalStorageState().equals(197                     Environment.MEDIA_MOUNTED)) {198                 String path = Environment.getExternalStorageDirectory()199                         + "/crash/";200                 File dir = new File(path);201                 if (!dir.exists()) {202                     dir.mkdirs();203                 }204                 FileOutputStream fos = new FileOutputStream(path + fileName);205                 fos.write(sb.toString().getBytes());206                 fos.close();207             }208 209             return fileName;210         } catch (Exception e) {211             Log.e(TAG, "an error occured while writing file...", e);212         }213 214         return null;215     }216 217     /**218      * 整理異常資訊219      * @param e220      * @return221      */222     public static StringBuffer getTraceInfo(Throwable e) {223         StringBuffer sb = new StringBuffer();224 225         Throwable ex = e.getCause() == null ? e : e.getCause();226         StackTraceElement[] stacks = ex.getStackTrace();227         for (int i = 0; i < stacks.length; i++) {228             if (i == 0) {229                 setError(ex.toString());230             }231             sb.append("class: ").append(stacks[i].getClassName())232                     .append("; method: ").append(stacks[i].getMethodName())233                     .append("; line: ").append(stacks[i].getLineNumber())234                     .append(";  Exception: ").append(ex.toString() + "\n");235         }236         Log.d(TAG, sb.toString());237         return sb;238     }239 240     /**241      * 設定錯誤的提示242      * @param e243      */244     public static void setError(String e) {245         Pattern pattern;246         Matcher matcher;247         for (Entry<String, String> m : regexMap.entrySet()) {248             Log.d(TAG, e+"key:" + m.getKey() + "; value:" + m.getValue());249             pattern = Pattern.compile(m.getKey());250             matcher = pattern.matcher(e);251             if(matcher.matches()){252                 error = m.getValue();253                 break;254             }255         }256     }257 258     /**259      * 初始化錯誤的提示260      */261     private static void initMap() {262         // Java.lang.NullPointerException263         // java.lang.ClassNotFoundException264         // java.lang.ArithmeticException265         // java.lang.ArrayIndexOutOfBoundsException266         // java.lang.IllegalArgumentException267         // java.lang.IllegalAccessException268         // SecturityException269         // NumberFormatException270         // OutOfMemoryError 271         // StackOverflowError 272         // RuntimeException 273         regexMap.put(".*NullPointerException.*", "嘿,無中生有~Boom!");274         regexMap.put(".*ClassNotFoundException.*", "你確定你能找得到它?");275         regexMap.put(".*ArithmeticException.*", "我猜你的數學是體育老師教的,對吧?");276         regexMap.put(".*ArrayIndexOutOfBoundsException.*", "恩,無下限=無節操,請不要跟我搭話");277         regexMap.put(".*IllegalArgumentException.*", "你的出生就是一場錯誤。");278         regexMap.put(".*IllegalAccessException.*", "很遺憾,你的信用卡帳號被凍結了,無權支付");279         regexMap.put(".*SecturityException.*", "死神馬上降臨");280         regexMap.put(".*NumberFormatException.*", "想要改變一下自己形象?去泰國吧,包你滿意");281         regexMap.put(".*OutOfMemoryError.*", "或許你該減減肥了");282         regexMap.put(".*StackOverflowError.*", "啊,啊,憋不住了!");283         regexMap.put(".*RuntimeException.*", "你的人生走錯了方向,重來吧");284 285     }286 287 }

 

二、建立一個Application來全域監控

 

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

 

最後在設定檔中加入註冊資訊

 

<application android:name=".CrashApplication" ... />

 

和許可權

    <!--uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /-->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

提交錯誤記錄檔到網路伺服器這一塊還沒有添加。如果添加了這一塊功能,就能夠即時的得要使用者使用時的錯誤記錄檔,能夠及時反饋不同機型不同時候發生的錯誤,能對我們開發人員的後期維護帶來極大的方便。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.