3

Is there a way to ask Android to return to a previous Activity within my application in the event that another Activity causes an unhandled exception to be thrown?

Tyler
  • 19,113
  • 19
  • 94
  • 151

2 Answers2

4

You can try to use Thread.setDefaultUncaughtExceptionHandler to receive notification when any thread has died due to an unhandled exception. But I'm not sure about Dalvik implementation of that mechanism. It could be possible you would not be able to start another activity from the UncaughtExceptionHandler as the documentation says nothing about thread/process resurrection.

Update

Ok. I tested it and now I'm sure you will NOT be able to return to a previous Activity using the above technique if your application thrown an exception in the UI thread. This happens because that exception would cause application main looper to exit and thus your application would not be able to process any further UI messages.

The only possible way I've found to achieve what you want is the following dirty-hack:

public class MyApplication extends Application {

  @Override
  public void onCreate() {
    super.onCreate();
    while (true) {
      try {
        Log.i("MyLooper", "Starting my looper");
        Looper.loop();
      } catch (Exception e) {
        Log.e("MyLooper", "Caught the exception in UI thread, e:", e);
        showPreviousActivity();
      }
    }
  }

  private void showPreviousActivity() {
    // your implementation of showing the previous activity
  }   
}

And register MyApplication in your AndroidManifest.xml:

<application android:name=".MyApplication">
…

The implementation of the showPreviousActivity() method is up to you. One of the possible solution would be to keep track of the currently Activity instance in some ActivityTracker class and to call current activity finish() method from the showPreviousActivity code.

Volo
  • 28,673
  • 12
  • 97
  • 125
  • If the application has more than 1 `Activity` running, `getApplicationContext()` will still provide a valid `Context`. You can then call `startActivity()` from inside a registered `UncaughtExceptionHandler` ;) – Tyler Oct 07 '11 at 19:59
  • If you use `UncaughtExceptionHandler` and exception happens in the UI thread then `startActivity()` won't help since main looper would be already dead. – Volo Oct 07 '11 at 23:03
0

Use a try-catch block to catch the exception and startActivity there. You can not go to another activity without catching it.

mikera
  • 105,238
  • 25
  • 256
  • 415
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63