Android Force Close和ANR等異常處理方法

來源:互聯網
上載者:User

Android Force Close和ANR等異常處理方法

對android應用而言最常出現的異常是Force close和ANR(Application is not response).

對於這兩類錯誤而言,應用是可以進行相關處理的。

一 Forceclose這類問題主要通過Thread.UncaughtExceptionHandler這個類來捕獲異常。通過實作類別裡面的方法uncaughtException來實現應用在捕獲到異常後進行相關的處理。一般這裡處理基本放在應用的Application類中。為了方便大家進行相關處理,我這裡寫了個類,大家直接在Application回調即可。

 

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();            }        });

 

同樣的對於ANR問題,應用也可以做相關處理。對ANR,我們可以這樣處理。通過一個看門狗來即時的檢測主線程,一旦主線程發生阻塞,則通知Application 做相關處理。

主要方法是線上程中每隔一段時間(Activity一般是5S,廣播一般是10S),向主線程發送一個messager,使計數器加1,如果到點沒有加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 ;            }        }    }
 private final Runnable tickerRunnable = new Runnable() {        @Override public void run() {            mTick = (mTick + 1) % 10;        }    };
 

聯繫我們

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