Essential Android Exceptions edit forum

Registering own Handler for unexpected exceptions

This is how you can react to exceptions which have not been catched, similar to the system’s standard “Application XYZ has crashed”

import android.app.Application;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Application class writing unexpected exceptions to a crash file before crashing.
 */
public class MyApplication extends Application {

private static final String TAG = “ExceptionHandler”;

@Override public void onCreate() { super.onCreate();

// Setup handler for uncaught exceptions.
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread thread, Throwable e) {
        try {
            handleUncaughtException(e);
            System.exit(1);
        } catch (Throwable e2) {
            Log.e(TAG, "Exception in custom exception handler", e2);
            defaultHandler.uncaughtException(thread, e);
        }
    }
});

}

private void handleUncaughtException(Throwable e) throws IOException { Log.e(TAG, “Uncaught exception logged to local file”, e);

// Create a new unique file
final DateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
String timestamp;
File file = null;
while (file == null || file.exists()) {
    timestamp = dateFormat.format(new Date());
    file = new File(getFilesDir(), "crashLog_" + timestamp + ".txt");
}
Log.i(TAG, "Trying to create log file " + file.getPath());
file.createNewFile();

// Write the stacktrace to the file
FileWriter writer = null;
try {
    writer = new FileWriter(file, true);
    for (StackTraceElement element : e.getStackTrace()) {
        writer.write(element.toString());
    }
} finally {
    if (writer != null) writer.close();
}

// You can (and probably should) also display a dialog to notify the user

}

}

Then register this Application class in your AndroidManifest.xml:

<application android:name="de.ioxp.arkmobile.MyApplication" >

Table Of Contents
11 Exceptions
39 ACRA
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close