Android Force Close, ANR, and other Exception Handling Methods
The most common exceptions for android applications are Force close and ANR (Application is not response ).
Applications can handle these two types of errors.
Forceclose mainly uses the Thread. UncaughtExceptionHandler class to capture exceptions. By implementing the method uncaughtException in the class, the application can handle exceptions after capturing them. Generally, the processing is basically in the Application class of the Application. In order to facilitate relevant processing, I have written a class here, and you can directly call back in the 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(); } });
Applications can also handle ANR problems. For ANR, we can do this. A watchdog is used to detect the main thread in real time. Once the main thread is blocked, the Application is notified to perform relevant processing.
The main method is to send a messager to the main thread at intervals of time (Activity is generally 5 S, broadcast is generally 10 S) in the thread to add 1 to the counter. If 1 is not added to the thread, indicates that the main thread is blocked.
@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; } };