對android應(yīng)用而言最常出現(xiàn)的異常是Force close和ANR(Application is not response).
對于這兩類錯(cuò)誤而言,應(yīng)用是可以進(jìn)行相關(guān)處理的。 一 Forceclose這類問題主要通過Thread.UncaughtExceptionHandler這個(gè)類來捕獲異常。通過實(shí)現(xiàn)類里面的方法uncaughtException來實(shí)現(xiàn)應(yīng)用在捕獲到異常后進(jìn)行相關(guān)的處理。一般這里處理基本放在應(yīng)用的Application類中。為了方便大家進(jìn)行相關(guān)處理,我這里寫了個(gè)類,大家直接在Application回調(diào)即可。
- new ExceptionHandler(mContext).setFCListener(new ExceptionHandler.FCListener() {
-
- @Override
- public void onFCDispose(Throwable paramThrowable) {
- Log.d(TAG, onFCListerner enter!!!);
- new Thread(){
- public void run(){
- Looper.prepare();
- Toast.makeText(mContext, APP is Force Close do what you want!, Toast.LENGTH_LONG).show();
- Looper.loop();
- }
- }.start();
- }
- });
復(fù)制代碼
同樣的對于ANR問題,應(yīng)用也可以做相關(guān)處理。對ANR,我們可以這樣處理。通過一個(gè)看門狗來實(shí)時(shí)的檢測主線程,一旦主線程發(fā)生阻塞,則通知Application 做相關(guān)處理。 主要方法是在線程中每隔一段時(shí)間(Activity一般是5S,廣播一般是10S),向主線程發(fā)送一個(gè)messager,使計(jì)數(shù)器加1,如果到點(diǎn)沒有加1,則表明主線程阻塞。
- @Override
- public void run() {
- setName(|ANR-WatchDog|);
-
- int lastTick;
- while (!isInterrupted()) {
- lastTick = mTick;
- mUIHandler.post(tickerRunnable);
- try {
- Thread.sleep(mTimeoutInterval);
- }
- catch (InterruptedException e) {
- mInterruptionListener.onInterrupted(e);
- return ;
- }
-
- // If the main thread has not handled _ticker, it is blocked. ANR.
- if (mTick == lastTick) {
- ANRError error;
- if (mNamePrefix != null)
- error = ANRError.New(mNamePrefix, mLogThreadsWithoutStackTrace);
- else
- error = ANRError.NewMainOnly();
- mAnrListener.onAppNotResponding(error);
- return ;
- }
- }
- }
復(fù)制代碼- private final Runnable tickerRunnable = new Runnable() {
- @Override public void run() {
- mTick = (mTick + 1) % 10;
- }
- };
復(fù)制代碼
|