Thursday, January 27, 2011

Android app life cycle and the HOME and BACK keys

As I'm working on adding the option in Net Ping that allows continuous pinging, I've had to take a closer look at the Android app life cycle. Or, I should more accurately say, the Android activity life cycle. Android apps are a stack of Activities.

Here is the diagram from the Android developer documentation:

Activity life cycle, from
I had observed different behaviors from when I used the BACK key to return to the home screen versus the HOME key. I'm testing on Android 2.2.

If the user presses HOME, the activity is paused, and then stopped. If the user presses BACK, the app is paused, stopped, and destroyed. As an Android user, the distinction was never obvious to me. That's probably because most apps get it right.

Net Ping starts the ping in the background in order to keep its main activity responsive. Now that the unpublished, development version of the app can ping forever, stopping the ping when the app is paused has become important. If I don't stop pinging, the user can lose control of the operation, and ping will continue to run and drain the battery until the phone is restarted. The biggest surprise was that Force Closing Net Ping didn't kill the ping operation.

For all situations I've observed, the activity is paused and resumed. Net Ping has to be able to pause and resume the ping operation in these events. Once I finish proper pause/resume handling, I'll publish an update to Net Ping.

In my testing, I noticed two other cases of importance. When the Settings screen is activated by the user, the user is presented with the Settings activity, and the main activity is paused. This is the same behavior as if the user pressed the HOME key. Secondly, when the device orientation changes, the main activity is destroyed and recreated in the new orientation, much like pressing BACK and starting the app again.

To summarize, the scenarios that any app that performs background processing should gracefully handle are as follows:

All situations:

  • Pause/Resume/Create.

Activity is stopped, but not destroyed upon:

  • HOME key press.
  • Transitioning to a different activity, like Settings.

Activity is stopped and destroyed upon:

  • BACK key press.
  • Orientation changes.

No comments:

Post a Comment