Non-linear activity flow in an Android app

I have been facing this particular problem in one demo android app I am working on at the moment. The problem is that when the flow of activities in an Android app is linear, then the back button in Android is more than enough to get back to the previous activity. But when the flow is more convoluted, then using “back” or re-launching activities is not the best solution.

For instance:

Android activities linear flow

In this diagram, the flow we want is simple: we can only go from one activity to the next one, and in that particular instance, A launches B, which launches C, etc, and “back” is used to go back to the launching activity.

The situation I’ve had to resolve was slightly more complicated:

Android activities non-linear flow

In this example, we want to go from B to C to D to B as many times as we want, and when done, from B, get back to A by using the Android “back” button. And this is where I faced a problem: pressing “back” from B led me back to D, then C, etc etc.

I didn’t want to implement a cumbersome activities “breadcrumb” system, where each activity that is launched knows the history of its predecessors. So I came up with a simple solution: instead of going from D to B, why not go back from D to C, then C to B?
But in that case, what to do with C, since the user is not supposed to to see it again?

Well, my solution was to remember my Android Activity state machine, and implement an often overlooked method for Activity B; this is what happens (solution highlighted):

Android activities non-linear flow resolved

  1. B creates C
  2. C creates D
  3. D finishes (calls finish())
  4. the Android Activity manager automatically brings back to the front the activity that launched D, i.e. C
  5. C is then resumed, so by calling finish() in C’s onResume() method, C will terminate
  6. the Android Activity manager automatically brings back to the front the activity that launched C, i.e. B

For the user, it will look like we will go directly from D to B, and when in B, using the “back” button will bring us to A.

This might not be the best solution, but it works extremely well in my case, and I hope it will help someone else as well!

Leave a Reply