As I developed my new Android application, Vault 3 for Android, I found it very convenient to catch and log uncaught exceptions. Here's how you can catch them in your app.
Step 1: Create a class inherited from UncaughtExceptionHandler, and implement the uncaughtException method:
public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler { @Override public void uncaughtException(Thread thread, Throwable tr) { String logMessage = String.format("CustomUncaughtExceptionHandler.uncaughtException: Thread %d Message %s", thread.getId(), tr.getMessage()); Log.e(StringLiterals.LogTag, logMessage); tr.printStackTrace(); if (VaultPreferenceActivity.isUncaughtExceptionLoggingEnabled()) { PrintWriter printWriter = null; try { printWriter = new PrintWriter(new FileWriter("/sdcard/Vault3Log.txt", true)); logMessage = String.format("%s\r\n\r\nThread: %d\r\n\r\nMessage:\r\n\r\n%s\r\n\r\nStack Trace:\r\n\r\n%s", new Date(), thread.getId(), tr.getMessage(), Log.getStackTraceString(tr)); printWriter.print(logMessage); printWriter.print("\n\n---------------------------------------------------------------------------\n\n"); } catch (Throwable tr2) { } finally { if (printWriter != null) { printWriter.close(); } } } }
Step 2: Call Thread.setDefaultUncaughtExceptionHandler with your UncaughtExceptionHandler-derived object early in the application lifespan.
Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
Since I want to start catching uncaught exceptions as early as possible in my app's lifespan, I implemented a custom Application class for Vault 3 for Android:
public class VaultApplication extends Application { @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler()); Log.i(StringLiterals.LogTag, "VaultApplication.onCreate"); } ...
This application class is specified in my AndroidManifest.xml file:
... <application android:name="com.ericbt.Vault3.VaultApplication" ...
If you need to keep track of important notes, with optional strong encryption, check out Vault 3 for Android. Thanks!
Title | Date |
EBTCalc (Android) Version 1.53 is now available | May 19, 2024 |
Vault 3 Security Enhancements | October 24, 2023 |
Vault 3 is now available for Apple OSX M2 Mac Computers! | September 18, 2023 |
Vault (for Desktop) Version 0.77 Released | March 26, 2023 |
EBTCalc (Android) Version 1.44 is now available | October 12, 2021 |
Vault (Desktop) Version 0.72 Released | October 6, 2021 |
EBT Compass is Now Available for Android Devices | June 2, 2021 |