Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 全局異常捕獲實戰:用 UncaughtExceptionHandler 告別殘酷的閃退

編輯:關於 Android 程式設計

一、前言

當 Android 應用發生 crash 時,系統會跳出「程式異常退出」的提示,接著應用就被關閉,使用者體驗非常糟。為了在應用運行時攔截異常並做出合理處理、給出友善提示,我們可以在開發中繼承 UncaughtExceptionHandler 類來統一接管,顯著提升使用者體驗。

二、使用方法

(1)定義 CrashHandler 處理類。當發生未捕獲異常時,由它接管程式,並將堆疊資訊記錄到本地檔案:

public class CrashHandler implements UncaughtExceptionHandler {
    public static final String TAG = "CrashHandler";
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Map<String, String> infos = new HashMap<String, String>();
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    private CrashHandler() {}

    public static CrashHandler getInstance() {
        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(4000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error:", e);
            }
            // 退出程式
            Global.logoutApplication(mContext);
        }
    }

    /** 自定義錯誤處理:收集錯誤資訊、發送報告等 */
    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;
    }

    /** 收集裝置參數資訊 */
    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);
            }
        }
    }

    /** 將錯誤資訊保存到檔案 */
    private void saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue() + "\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();
        sb.append(writer.toString());
        try {
            String time = formatter.format(new Date());
            String fileName = FileSystemManager.getCrashPath(mContext) + time + ".log";
            FileOutputStream fos = new FileOutputStream(fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
        } catch (Exception e) {
            Log.e(TAG, "an error occured while writing file...", e);
        }
    }
}

可以看到,檔名以時間戳作為關鍵欄位保存在本地,等待後續上傳。收集錯誤資訊、發送報告等都在 handleException 中完成:一旦應用崩潰,便會自動呼叫 uncaughtException,接著透過 handleException 收集手機資訊、保存崩潰堆疊至本地、清理當前 Activity 堆疊,最後自動關閉應用並給出 Toast 提示。

(2)在 Application 中配置是否開啟全局捕獲。

public class CCApplication extends Application {
    public static CCApplication ccApplication = null;
    public static List<Activity> activitys = new ArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        ccApplication = this;
        new SharePref(ccApplication).saveAppOpenOrClose(true);
        loadData(getApplicationContext());
        JPushInterface.setDebugMode(false);
        JPushInterface.init(this);
        // 打開全局異常捕獲
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
    }
    // ... 其餘初始化與 Activity 管理邏輯省略
}

(3)下次啟動後上傳本地保存的崩潰檔案,上傳成功後刪除,避免重複上傳。

/** 上傳崩潰日誌檔案到伺服器 */
private void uploadCrashFile() {
    File root = new File(FileSystemManager.getCrashPath(HomeFragmentActivity.this));
    File[] listFiles = root.listFiles();
    if (listFiles != null && listFiles.length > 0) {
        ArrayList<File> files = new ArrayList<File>();
        for (File file : listFiles) {
            files.add(file);
        }
        Map<String, File> fileParameters = new HashMap<String, File>();
        fileParameters.put("file", files);
        ConnectService.instance().connectServiceUploadCrashFile(
                HomeFragmentActivity.this, null, fileParameters,
                HomeFragmentActivity.this, UploadCrashFileResponse.class,
                URLUtil.UPLOAD_CRASH_FILE);
    }
}

上傳成功後,刪除本地檔案:

else if (ob instanceof UploadCrashFileResponse) {
    UploadCrashFileResponse response = (UploadCrashFileResponse) ob;
    if (GeneralUtils.isNotNullOrZeroLenght(response.getRetcode())
            && Constants.SUCESS_CODE.equals(response.getRetcode())) {
        // 發送成功後刪除本地檔案
        FileUtil.deleteDirectory(FileSystemManager.getCrashPath(HomeFragmentActivity.this));
    }
}

(4)檔案目錄管理類。透過 FileSystemManager 統一管理各類快取目錄,崩潰日誌目錄由 getCrashPath() 提供,上傳成功後即可清空:

public class FileSystemManager {
    private static String cacheFilePath;
    private static String crashPath;

    /** 根目錄快取目錄 */
    public static String getCacheFilePath(Context context) {
        cacheFilePath = FileUtil.getSDPath(context) + File.separator
                + "cloudcentral" + File.separator;
        return cacheFilePath;
    }

    /** 崩潰日誌快取目錄(上傳成功則刪除) */
    public static String getCrashPath(Context context) {
        crashPath = FileUtil.createNewFile(getCacheFilePath(context) + "crash" + File.separator);
        return crashPath;
    }
    // 圖片、頭像、資料庫、語音、發帖、臨時等目錄方法可依需求擴充
}

配套的 FileUtil 則負責取得 SD 卡路徑、建立目錄、複製檔案、遞迴刪除目錄、序列化物件存取與網路下載等底層檔案操作,為日誌落地與上傳提供基礎能力。這樣一整套機制運作下來,即便應用遭遇未預期異常,也能優雅收場並留下可供追蹤的線索。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved