天天看點

Android開發之全局異常捕獲前言源碼分析實作代碼

前言

大家都知道,現在安裝Android系統的手機版本和裝置千差萬别,在模拟器上運作良好的程式安裝到某款手機上說不定就出現崩潰的現象,開發者個人不可能購買所有裝置逐個調試,是以在程式釋出出去之後,如果出現了崩潰現象,開發者應該及時擷取在該裝置上導緻崩潰的資訊,這對于下一個版本的bug修複幫助極大,是以今天就來介紹一下如何在程式崩潰的情況下收集相關的裝置參數資訊和具體的異常資訊,并發送這些資訊到伺服器供開發者分析和調試程式。

源碼分析

/**
     * Interface for handlers invoked when a <tt>Thread</tt> abruptly
     * terminates due to an uncaught exception.
     * <p>When a thread is about to terminate due to an uncaught exception
     * the Java Virtual Machine will query the thread for its
     * <tt>UncaughtExceptionHandler</tt> using
     * {@link #getUncaughtExceptionHandler} and will invoke the handler's
     * <tt>uncaughtException</tt> method, passing the thread and the
     * exception as arguments.
     * If a thread has not had its <tt>UncaughtExceptionHandler</tt>
     * explicitly set, then its <tt>ThreadGroup</tt> object acts as its
     * <tt>UncaughtExceptionHandler</tt>. If the <tt>ThreadGroup</tt> object
     * has no
     * special requirements for dealing with the exception, it can forward
     * the invocation to the {@linkplain #getDefaultUncaughtExceptionHandler
     * default uncaught exception handler}.
     *
     * @see #setDefaultUncaughtExceptionHandler
     * @see #setUncaughtExceptionHandler
     * @see ThreadGroup#uncaughtException
     * @since 1.5
     */
    @FunctionalInterface
    public interface UncaughtExceptionHandler {
        /**
         * Method invoked when the given thread terminates due to the
         * given uncaught exception.
         * <p>Any exception thrown by this method will be ignored by the
         * Java Virtual Machine.
         * @param t the thread
         * @param e the exception
         */
        void uncaughtException(Thread t, Throwable e);
    }
           

源碼并不難,通過源碼可以知道:

Thread.UncaughtExceptionHandler是一個當線程由于未捕獲的異常突然終止而調用處理程式的接口.

當線程由于未捕獲的異常即将終止時,Java虛拟機将使用它來查詢其UncaughtExceptionHandler的線程Thread.getUncaughtExceptionHandler(),并将調用處理程式的 uncaughtException方法,将線程和異常作為參數傳遞。如果一個線程沒有顯示它的UncaughtExceptionHandler,那麼它的ThreadGroup對象充當它的 UncaughtExceptionHandler。如果ThreadGroup對象沒有處理異常的特殊要求,它可以将調用轉發到預設的未捕獲的異常處理程式。

是以我們可以自定一個類去實作該接口,該類主要用于收集錯誤資訊和儲存錯誤資訊.

實作代碼

自己先寫一個錯誤的、會導緻崩潰的代碼:

public class MainActivity extends Activity {  

    private String s;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        System.out.println(s.equals("any string"));  
    }  
}  
           

我們在這裡故意制造了一個潛在的運作期異常,當我們運作程式時就會出現以下界面:

Android開發之全局異常捕獲前言源碼分析實作代碼

遇到軟體沒有捕獲的異常之後,系統會彈出這個預設的強制關閉對話框。

我們當然不希望使用者看到這種現象,簡直是對使用者心靈上的打擊,而且對我們的bug的修複也是毫無幫助的。我們需要的是軟體有一個全局的異常捕獲器,當出現一個我們沒有發現的異常時,捕獲這個異常,并且将異常資訊記錄下來,上傳到伺服器公開發這分析出現異常的具體原因。

剛才在項目的結構圖中看到的CrashHandler.java實作了Thread.UncaughtExceptionHandler,使我們用來處理未捕獲異常的主要成員,代碼如下:

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發生時會轉入該函數來處理 
     */  
    @Override  
    public void uncaughtException(Thread thread, Throwable ex) {  
        if (!handleException(ex) && mDefaultHandler != null) {  
            //如果使用者沒有處理則讓系統預設的異常處理器來處理  
            mDefaultHandler.uncaughtException(thread, ex);  
        } else {  
            try {  
                Thread.sleep();  
            } catch (InterruptedException e) {  
                Log.e(TAG, "error : ", e);  
            }  
            //退出程式  
            android.os.Process.killProcess(android.os.Process.myPid());  
            System.exit();  
        }  
    }  

    /** 
     * 自定義錯誤處理,收集錯誤資訊 發送錯誤報告等操作均在此完成. 
     *  
     * @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) {  
            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 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);  
        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 = "/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代碼如下:

public class CrashApplication extends Application {  
    @Override  
    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"/>  
           

搞定了上邊的步驟之後,我們來運作一下這個項目:

Android開發之全局異常捕獲前言源碼分析實作代碼

會發現,在我們的sdcard中生成了一個Log檔案

用文本編輯器打開日志檔案,看一段日志資訊:

Caused by: java.lang.NullPointerException  
    at com.scott.crash.MainActivity.onCreate(MainActivity.java:)  
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:)  
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:)  
    ...  more 
           

這些資訊對于開發者來說幫助極大,是以我們需要将此日志檔案上傳到伺服器。

這樣就達到了線上如果使用者出問題,就可以抓到對應的log問題了。