Detecting whether an Android app is stopping (or starting)

I am writing an Android app (called Rabbit Escape), and I want it to start playing music when the user enters the app, and stop when the user leaves.

Not as easy as it sounds because Android largely doesn’t think in apps, but Activities.

Update: real-life code for this is here: Code for detecting when you leave an Android app.

In my previous post Order of Android Activity lifecycle events I tracked the methods that get called on activities on my two test devices when the user does various actions. There was some variation between devices, but we can determine some useful rules.

First, let’s enumerate what we need to detect.

The user leaves by:

  • pressing “home” at any time
  • pressing the power button when the app is running
  • pressing “back” when in the first activity
  • launching an external activity (e.g. web browser)

The user enters by:

  • starting the app (e.g. from the home page, or the “running apps” panel)
  • pressing the power button when the app has been suspended
  • pressing “back” when in an external activity launched by us

From the previous post we can work out these rules:

  • When the user is entering, onResume is always called (on the activity that will be current)
  • When the user is leaving, onStop is always called (on the current activity), except when pressing the power button (to turn off) where you may only see an onPause call.
  • When the user is moving between activities, onResume is always called on the new activity, and onStop is always called on the old one. The onResume call is always before onStop

Thus, if we are OK with leaving ourselves running when the power button is pressed, we can detect leaving and entering the app using the code below.

If we need to stop something when the power button is pressed too, it seems we must be prepared to stop it when we receive onPause, and immediately restart it if we receive onResume, hoping that doesn’t cause a problem (e.g. a break in the music).

// All activities have these two methods:
@Override
public void onResume()
{
    super.onResume();
    LeavingOrEntering.activityResumed( this );
}

@Override
public void onStop()
{
    super.onStop();
    LeavingOrEntering.activityStopped( this );
}

// And we detect leaving and entering like this:
class LeavingOrEntering
{
    private static Activity currentActivity = null;

    public static void activityResumed( Activity activity )
    {
        if ( currentActivity == null )
        {
            // We were resumed and no-one else was running.
            notifyEntering() // Start the music!
        }
        currentActivity = activity;
    }

    public static void activityStopped( Activity activity )
    {
        assert currentActivity != null;

        if ( currentActivity == activity )  
        {
            // We were stopped and no-one else has been started.
            notifyLeaving(); // Stop the music!
        }
        currentActivity == null;
    }
}

Order of Android Activity lifecycle events

I noticed some variation between devices so I tested various user actions on various devices and recorded the Android Activity lifecycle methods (e.g. onResume, onPause, onCreate, onStop) that got called. My results are below.

[Why? I want to detect whether the user is leaving the app or just transitioning from one activity to another. See my next blog posts Detecting whether an Android app is stopping (or starting) and Code for detecting when you leave an Android app for how to do it.]

Press the home button

  • Ensure the app process is stopped.
  • Start the app. It starts an Activity.
  • Start recording events.
  • Press “home” on the device.
HTC Wildfire S
Android 2.3.5 (API 10)
onSaveInstanceState
onPause
onStop
  
Nexus One Emulator (x86)
Android L (API 20)
onPause
onSaveInstanceState
onStop
  

When home was pressed, onPause and onStop were called in that order, and onSaveInstanceState was always called before onStop. The app was still running after the test.

Note that onSaveInstanceState can happen either before or after onPause.

This is consistent with the information given on the Android Activity API docs:

Starting with Honeycomb, an application is not in the killable state until its onStop() has returned. This impacts when onSaveInstanceState(Bundle) may be called (it may be safely called after onPause() and allows and application to safely wait until onStop() to save persistent state.

Press the home button in a second activity

  • Ensure the app process is stopped.
  • Start the app. It starts Activity1.
  • Press a button in the activity that launches Activity2.
  • Start recording events.
  • Press “home” on the device.

Results are identical to “Press the home button” above, with Activity2 receiving all the calls, and Activity1 not receiving any.

Press the back button to exit

  • Ensure the app process is stopped.
  • Start the app. It starts an Activity.
  • Start recording events.
  • Press “back” on the device.
HTC Wildfire S
Android 2.3.5 (API 10)
onPause
onStop
onDestroy
  
Nexus One Emulator (x86)
Android L (API 20)
(same as above)

When back was pressed, onPause, onStop and onDestroy were called. The app process was still running after the test.

onSaveInstanceState was not called, because there is no current state to resume – when you re-enter you will be back at the beginning.

Start the app

  • Ensure the app process is stopped.
  • Start recording events.
  • Start the app.
HTC Wildfire S
Android 2.3.5 (API 10)
onCreate
onStart
onResume
  
Nexus One Emulator (x86)
Android L (API 20)
(same as above)

When the app was started, onCreate, onStart and onResume were called in that order.

Turn off with the power button

  • Start the app.
  • Start recording events.
  • Press the power button (turn off).
HTC Wildfire S
Android 2.3.5 (API 10)
onSaveInstanceState
onPause
  
Nexus One Emulator (x86)
Android L (API 20)
onPause
onSaveInstanceState
onStop

When the phone was suspended, onSaveInstanceState and onPause were called in different orders, and onStop was called in some cases.

Turn on with the power button

  • Start the app.
  • Press the power button (turn off).
  • Start recording events.
  • Press the power button (turn on).
  • Unlock the device.
HTC Wildfire S
Android 2.3.5 (API 10)
onResume
  
Nexus One Emulator (x86)
Android L (API 20)
onRestart
onStart
onResume
  

When the phone was resumed, onResume was always called, and onRestart and onStart were sometimes called.

Restart the app after pressing home

  • Ensure the app process is stopped.
  • Start the app.
  • Press “home” on the device.
  • Start recording events.
  • Start the app.
HTC Wildfire S
Android 2.3.5 (API 10)
onRestart
onStart
onResume
  
Nexus One Emulator (x86)
Android L (API 20)
(same as above)

When the app was restarted after pressing home, onCreate was not called, but onRestart, onStart and onResume were (in that order).

Restart the app after pressing back

  • Ensure the app process is stopped.
  • Start the app.
  • Press “back” on the device.
  • Start recording events.
  • Start the app.
HTC Wildfire S
Android 2.3.5 (API 10)
onCreate
onStart
onResume
  
Nexus One Emulator (x86)
Android L (API 20)
(same as above)

When the app was restarted after pressing back, onRestart was not called, but onCreate, onStart and onResume were (in that order).

This is consistent with the idea that pressing back effectively ends the app, but pressing home effectively pauses it.

Launch a second activity

  • Ensure the app process is stopped.
  • Start the app. It starts Activity1.
  • Start recording events.
  • Press a button in the activity that launches Activity2.
HTC Wildfire S
Android 2.3.5 (API 10)
Activity1.onSaveInstanceState
Activity1.onPause
Activity2.onCreate
Activity2.onStart
Activity2.onResume
Activity1.onStop
  
Nexus One Emulator (x86)
Android L (API 20)
Activity1.onPause
Activity2.onCreate
Activity2.onStart
Activity2.onResume
Activity1.onSaveInstanceState
Activity1.onStop
  

The later version of Android called onSaveInstanceState much later in the process. This is consistent with the documentation for the Activity Lifecycle.

In both cases Activity1’s onPause was called before any methods were called on Activity2.

In both cases Activity1’s onStop was called after all methods were called on Activity2.

Activity2’s methods were called just as if it were the starting activity of a freshly-launched app (see “Start the app” above).

Activity1’s methods were called just as if the home button had been pressed.

Launch an external activity

  • Ensure the app process is stopped.
  • Start the app. It starts an Activity.
  • Start recording events (in our activity only).
  • Press a button in the activity that launches the Android web browser.

Results are identical to “Press the home button” above.

Go back from one activity to another

  • Ensure the app process is stopped.
  • Start the app. It starts Activity1.
  • Press a button in the activity that launches Activity2.
  • Start recording events.
  • Press “back” on the device.
HTC Wildfire S
Android 2.3.5 (API 10)
Activity2.onPause
Activity1.onRestart
Activity1.onStart
Activity1.onResume
Activity2.onStop
Activity2.onDestroy
  
Nexus One Emulator (x86)
Android L (API 20)
(same as above)

Activity2 sees the same calls as in “Press the back button to exit” (i.e. it is destroyed).

Activity1 see the same calls as in “Restart the app after pressing home” (i.e. it is resumed).

Go back from an external activity to ours

  • Ensure the app process is stopped.
  • Start the app. It starts an Activity.
  • Press a button in the activity that launches the Android web browser.
  • Start recording events (in our activity only).
  • Press “back” on the device.

Results are identical to “Restart the app after pressing home” above.

See my next blog post for how to detect whether we are leaving the app, or just transitioning between activities: Detecting whether an Android app is stopping (or starting).

Rabbit Escape 0.3.1 – now with zoom!

I’ve just release the latest version of Rabbit Escape, which makes things look a lot nicer because you can zoom in, getting you much closer to your rabbits:

rabbitescape-android-zoomed

There are still 60 levels of Lemmings and Pingus -like gameplay, all downloadable for free artificialworlds.net/rabbit-escape/.

I’ve also improved performance significantly, so you should notice things get smoother on older devices.

All those zoomed images increase the download size to 9MB, which is a pity, but that’s still pretty small.