Android capture program exits unexpectedly
Today, I saw a CrashHandler class in Thunder animation. I guess it is a crash processing class. Let's take a look. By the way.
The Android system "abnormal exit of the program" has a negative impact on the user experience of the application. You can inherit the UncaughtExceptionHandler class to capture exceptions during application running and give friendly prompts. Use the Thread. setDefaultUncaughtExceptionHandler () method to set the exception handling class to the Thread.
Code:
public class CrashHandler implements UncaughtExceptionHandler { private static final Logger LOG = Logger.getLogger(CrashHandler.class); private final Application mApplication; private Handler mUIHandler; private Thread mUiThread; public CrashHandler(Application app) { mApplication = app; mUIHandler = new Handler(); mUiThread = Thread.currentThread(); } @Override public void uncaughtException(Thread thread, Throwable e) { LOG.error(e); Throwable cause = e.getCause(); while (cause != null) { LOG.error(cause); cause = cause.getCause(); } writeCrashInfoToFile(e); if (Thread.currentThread() != mUiThread) { mUIHandler.post(new Runnable() { @Override public void run() { mApplication.onTerminate(); } }); } else { mApplication.onTerminate(); } } private void writeCrashInfoToFile(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); Throwable cause = t.getCause(); while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } String crashInfo = sw.toString(); pw.close(); try { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File file = mApplication.getApplicationContext().getExternalCacheDir(); if (file != null) { file = FileUtils.getFile(file, crash); file.mkdirs(); FileUtils.writeStringToFile(FileUtils.getFile(file, crash.log), crashInfo); } } } catch (IOException e) { LOG.warn(e); } }}