January 2009: A Simple Android App and a Threading Bug

A Simple Android App and a Threading Bug

By Eric M. Burke, OCI Principal Software Engineer

January 2009


Introduction

By now, you probably know what Google Android is: an open source operating system, virtual machine, and SDK for mobile devices. In 2008, T-Mobile released the first Android phone, the G1. 2009 will bring many different phones from a variety of carriers.

Android presents an exciting opportunity for programmers. Millions of people will purchase Android phones in 2009, each including a link to the Android Market. For a nominal $25 registration fee, any programmer can distribute free Android applications on the Market. Beginning in January, you'll be able to sell commercial applications, as well.

This article shows a simple Android application created with the freely-available Android SDK using Eclipse. You can use any IDE you like, but Eclipse currently offers the best Android support since Google provides an Android development plugin. After showing this simple app, we tackle a common threading bug and show how to fix it.

If you are new to Android development, you may want to work through Google's Notepad Tutorial before proceeding.

Threading Rules

Like other GUI toolkits, the Android user interface is single-threaded. To avoid locking up the GUI, long running operations must run in background threads. This should sound familiar to Swing programmers, although Android differs in two notable ways:

Called From Wrong Thread Exception
Not Responding


These are welcome improvements because they encourage correct code and help programmers locate bugs early in the development process. They also prevent poorly written applications from locking up your entire phone.

The Example

Our sample application looks like this when running in the Android emulator. (The emulator is included in the free SDK.)

Sample App 1

When you click Start Background Thread, a few things happen:

  1. The button is disabled
  2. The status label changes to Running
  3. A background thread simulates a long operation

While running, the UI looks like this:
 

Sample App Running


When the thread completes, the button becomes enabled again and the status label shows Finished.
 

Sample App Finished


Now let's review the source code.

XML Files

Our application contains three XML files; larger applications have many more. Although Android utilizes XML during application development, tools included in the SDK compile the XML into a efficient binary form.

AndroidManifest.xml

Every Android application has a manifest in its root folder. The Android Eclipse plugin generates ours, specifying HomeActivity as the application entry point.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.ociweb.demo"
  4. android:versionCode="1"
  5. android:versionName="1.0.0">
  6. <application android:icon="@drawable/icon"
  7. android:label="@string/app_name">
  8. <activity android:name=".HomeActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <action android:name="android.intent.action.MAIN" ></action>
  12. <category android:name="android.intent.category.LAUNCHER" ></category>
  13. </intent-filter>
  14. </activity>
  15. </application>
  16. </manifest>

Although this XML is verbose, editing is easy thanks to the graphical editors in the Android Eclipse plugin.

strings.xml

The next XML file, strings.xml, defines labels for the entire application. As you can see, the app_name used in AndroidManifest.xml is defined here in strings.xml.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="app_name">Thread Demo</string>
  4. <string name="start_background_thread">Start Background Thread</string>
  5. <string name="thread_running">Running</string>
  6. <string name="thread_finished">Finished</string>
  7. <string name="thread_status">Thread Status:</string>
  8. <string name="thread_not_started">Not Started</string>
  9. </resources>

As you add new values to this (and other) XML files, the Eclipse plugin automatically generates a file named R.java with constants for each string. The Android SDK also includes command line tools that generate R.java if you don't use Eclipse.

home.xml

This is the GUI layout file for the home screen shown earlier. Android lets you define screen layout in XML files or programmatically, although XML is generally preferred. Like other XML in Android, tools compile the layout files to a more efficient form before they are ever installed on a phone.

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7.  
  8. <Button android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:id="@+id/start_background_thread_btn"
  11. android:text="@string/start_background_thread"
  12. android:layout_gravity="center"></Button>
  13.  
  14. <LinearLayout android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"
  16. android:orientation="horizontal"
  17. android:layout_gravity="center">
  18.  
  19. <TextView android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:text="@string/thread_status"
  22. android:textSize="20dp"
  23. android:paddingRight="5dp"></TextView>
  24.  
  25. <TextView android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:id="@+id/thread_status_label"
  28. android:text="@string/thread_not_started"
  29. android:freezesText="true"
  30. android:textSize="20dp"></TextView>
  31. </LinearLayout>
  32. </LinearLayout>

Android includes a variety of layout classes, such as LinearLayoutFrameLayoutRelativeLayout, and more. Like Swing layout managers, these help your UI adjust to varying screen resolutions with minimum hardcoding.

Rather than include labels in the layout XML files, we choose to reference values in strings.xml using this syntax: @string/thread_status.

You may also notice these identifiers: @+id/thread_status_label. The @+id tells the Android tools to generate a constant in R.java. Your application code always uses R.java constants to ensure a degree of compile-time safety.

Finally notice the android:freezesText="true" attribute on the status label. This ensures the label remembers its value when you toggle screen orientation between portrait and landscape.

Java Source

R.java

The Android SDK includes a command-line tool named aapt that generates R.java from the XML files. If you use Eclipse, the plugin instantly updates R.java whenever you save changes to one of the XML files. This is very useful when you rename constants because you get compile-time errors until you also update the code.

  1. /* AUTO-GENERATED FILE. DO NOT MODIFY.
  2.  *
  3.  * This class was automatically generated by the
  4.  * aapt tool from the resource data it found. It
  5.  * should not be modified by hand.
  6.  */
  7.  
  8. package com.ociweb.demo;
  9.  
  10. public final class R {
  11. public static final class attr {
  12. }
  13. public static final class drawable {
  14. public static final int icon=0x7f020000;
  15. }
  16. public static final class id {
  17. public static final int start_background_thread_btn=0x7f050000;
  18. public static final int thread_status_label=0x7f050001;
  19. }
  20. public static final class layout {
  21. public static final int home=0x7f030000;
  22. }
  23. public static final class string {
  24. public static final int app_name=0x7f040000;
  25. public static final int start_background_thread=0x7f040001;
  26. public static final int thread_finished=0x7f040003;
  27. public static final int thread_not_started=0x7f040005;
  28. public static final int thread_running=0x7f040002;
  29. public static final int thread_status=0x7f040004;
  30. }
  31. }

As you see above, R.java replaces the XML strings with highly efficient integer constants.

HomeActivity.java

Other than the home.xml layout file, most of what we've seen so far is either generated by command line tools or edited via graphical tools in Eclipse. The actual home screen, however, is Java source code. In Android, an Activity is something the user can do. In most cases, Activities are screens in the user interface.

HomeActivity extends Android's Activity base class. The Android APIs make heavy use of the Template Method pattern, in which base classes like Activity define numerous methods you must override.

  1. public class HomeActivity extends Activity implements OnClickListener {
  2.  
  3. private Button mStartButton;
  4. private TextView mStatusLabel;
  5.  
  6. private static final String ENABLED_KEY = "com.ociweb.buttonEnabled";
  7.  
  8. // background threads use this Handler to post messages to
  9. // the main application thread
  10. private final Handler mHandler = new Handler();
  11.  
  12. // post this to the Handler when the background thread completes
  13. private final Runnable mCompleteRunnable = new Runnable() {
  14. public void run() {
  15. onThreadCompleted();
  16. }
  17. };

We'll see how to initialize Button and TextView shortly. The ENABLED_KEY flag lets us remember if the button is enabled when the user changes the screen orientation. On the G1 phone, the screen rotates from portrait to landscape mode when the user slides out the keyboard. This key comes into play in the onCreate(...) and onSaveInstanceState(...) methods.

The Handler shown above allows background threads to send messages or Runnable objects back to the main application thread. This is the same concept as SwingUtilities.invokeLater(Runnable r) and SwingUtilities.invokeAndWait(Runnable r). When the background thread completes, it passes the mCompleteRunnable to the Handler for execution on the main thread.

Next we see the onCreate(...) method.

  1. @Override
  2. public void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.home);
  5.  
  6. mStartButton = (Button) findViewById(R.id.start_background_thread_btn);
  7. mStatusLabel = (TextView) findViewById(R.id.thread_status_label);
  8.  
  9. mStartButton.setOnClickListener(this);
  10.  
  11.  
  12. if (savedInstanceState != null) {
  13. if (savedInstanceState.containsKey(ENABLED_KEY)) {
  14. mStartButton.setEnabled(savedInstanceState.getBoolean(ENABLED_KEY));
  15. }
  16. }
  17. }

onCreate(...) is one of several Activity Lifecycle methods, called at appropriate times as Activites come and go. Android always calls onCreate(...), so this is a good place to locate GUI components and register event listeners. The code also shows how we use the generated R.javaconstants.

This is also where we re-establish the enabled flag on mStartButton, using the ENABLED_KEY defined earlier. Android uses savedInstanceState for short-term data storage, such as when activities are temporarily paused or when screen rotation happens.

The enabled flag is saved here in the onSaveInstanceState(...) method:

  1. @Override
  2. protected void onSaveInstanceState(Bundle outState) {
  3. super.onSaveInstanceState(outState);
  4. outState.putBoolean(ENABLED_KEY, mStartButton.isEnabled());
  5. }

Next, our Activity implements onClick(View v) from the OnClickListener interface. This is how we react to button clicks.

  1. public void onClick(View v) {
  2. if (v == mStartButton) {
  3.  
  4. mStartButton.setEnabled(false);
  5. mStatusLabel.setText(R.string.thread_running);
  6. // show a brief popup alert
  7. Toast.makeText(this, R.string.thread_running, Toast.LENGTH_SHORT).show();
  8.  
  9. Thread t = new Thread() {
  10. public void run() {
  11. // perform expensive tasks in a background thread
  12. expensiveOperation();
  13.  
  14. // let the UI know the task is complete
  15. mHandler.post(mCompleteRunnable);
  16. }
  17. };
  18. t.start();
  19. }
  20. }

On a phone like the G1, users click buttons by tapping on the screen or hitting a physical button on the phone. Our code changes the status label, disables the button, and launches a background thread. Using this thread avoids locking up the main application thread.

Once the thread completes, it posts the mCompleteRunnable to the mHandler. Our Runnable, in turn, calls the onThreadComplete() method, shown next.

  1. /**
  2.   * Call this method on the main application thread once the background thread
  3.   * completes.
  4.   */
  5. private void onThreadCompleted() {
  6. mStartButton.setEnabled(true);
  7. mStatusLabel.setText(R.string.thread_finished);
  8. // show a brief popup alert
  9. Toast.makeText(this, R.string.thread_finished, Toast.LENGTH_SHORT).show();
  10. }
  11.  
  12. /**
  13.   * This method runs in a background thread. In a real app, it would do
  14.   * something useful, such as getting data from a web service.
  15.   */
  16. private void expensiveOperation() {
  17. try {
  18. TimeUnit.SECONDS.sleep(4);
  19. } catch (InterruptedException e) {
  20. Thread.currentThread().interrupt();
  21. }
  22. }
  23. }

Our example uses Toast as a quick-and-dirty alert mechanism to visually indicate when events occur within the application. Those calls to Toast.makeText(...) trigger a brief popup alert. When the thread completes, we enable the button again and change the status label back to "Finished".

As you jump from screen-to-screen, you may notice that Toast popups sometimes stick around a bit too long, or popup on top of the next ActivityToast alerts don't really tie in with Android's excellent notification area, either. For more robust event notification, you may want to investigate Android's Notification APIs instead of Toast.

The Threading Bug

The example handles threads just like most of the examples shown online, but it suffers from a critical bug. If you change the screen orientation while the thread is active, the UI fails to receive notification when the thread completes. Here is what you see:

Stuck GUI


At this point the user has to exit and re-start the app, because the button will never again become enabled.

When the screen orientation changes, Android destroys the existing Activity instance and creates a completely new Activity as a replacement. This is all part of the Activity lifecycle mentioned before. This diagram shows what happens:
 

Rotate Thread Bug


Although Android creates a new instance of HomeActivity, our background thread does not stop automatically. Even worse, our thread is an inner class with an implicit reference back to the HomeActivity instance. If the thread never stops, this causes a memory leak. But in our case, it means when the thread completes, it notifies the old HomeActivity instance instead of the new one. If you rotate the screen while our thread is running, the GUI shows incorrect values.

These kinds of state management problems are not limited to screen rotation. When an incoming phone call arrives, Android pauses the HomeActivity to display the phone call. The user might also bring up the dialer or navigate to some other Activity. You need to test all of these scenarios to ensure the background thread completes successfully.

Fixing the Bug

There are a variety of things we can do to fix this bug. Some options include:

Regardless of how you use threads, keep in mind that once the system calls onPause(), your entire process may be killed if the OS needs to reclaim resources. If your threads contain important data, make sure your Activity informs them when onPause() occurs, giving them a chance to checkpoint their state.

Our Solution

Let's start by creating a data model that keeps track of the HomeActivity state.

HomeModel.java

  1. /**
  2.  * Data model for the HomeActivity. Fires events when the data
  3.  * fetch thread begins and ends.
  4.  */
  5. public class HomeModel implements Serializable {
  6. private static final long serialVersionUID = 1L;
  7.  
  8. public enum State { NOT_STARTED, RUNNING, FINISHED }
  9.  
  10. private State state = State.NOT_STARTED;
  11. private HomeModelListener homeModelListener;
  12.  
  13. public synchronized void setHomeModelListener(HomeModelListener l) {
  14. homeModelListener = l;
  15. }
  16.  
  17. public void setState(State state) {
  18. // copy to a local variable inside the synchronized block
  19. // to avoid synchronization while calling homeModelChanged()
  20. HomeModelListener hml = null;
  21. synchronized (this) {
  22. if (this.state == state) {
  23. return; // no change
  24. }
  25. this.state = state;
  26. hml = this.homeModelListener;
  27. }
  28.  
  29. // notify the listener here, not synchronized
  30. if (hml != null) {
  31. hml.homeModelChanged(this);
  32. }
  33. }
  34.  
  35. public synchronized State getState() {
  36. return state;
  37. }
  38. }

HomeModelListener.java

The HomeModelListener interface is trivial.

  1. public interface HomeModelListener {
  2. void homeModelChanged(HomeModel hm);
  3. }

DataFetcherThread.java

Next, we'll break out the thread into a standalone class. This eliminates the problem with our inner class holding an implicit reference to the enclosing HomeActivity instance.

  1. public class DataFetcherThread extends Thread {
  2. private final HomeModel homeModel;
  3.  
  4. public DataFetcherThread(HomeModel homeModel) {
  5. this.homeModel = homeModel;
  6. }
  7.  
  8. public void start() {
  9. homeModel.setState(HomeModel.State.RUNNING);
  10. super.start();
  11. }
  12.  
  13. public void run() {
  14. try {
  15. TimeUnit.SECONDS.sleep(3);
  16. } catch (InterruptedException e) {
  17. } finally {
  18. homeModel.setState(HomeModel.State.FINISHED);
  19. }
  20. }
  21. }

Class Diagram

Here is a diagram that shows how these pieces fit together.

Class Diagram

Improved Rotation

What happens when the user rotates the screen? When Android destroys the first HomeActivity instance, the activity saves the HomeModel reference in its saved instance state. It also detaches itself as a listener. When Android creates the second HomeActivity, it obtains the saved HomeModel instance from the saved instance state. Hopefully this diagram clarifies a bit:

Improved Rotation

HomeActivity, Final Version

Here is HomeActivity.java in its entirety, using all of the changes mentioned above.

  1. public class HomeActivity extends Activity implements OnClickListener, HomeModelListener {
  2.  
  3. private Button mStartButton;
  4. private TextView mStatusLabel;
  5.  
  6. private static final String ENABLED_KEY = "com.ociweb.buttonEnabled";
  7. private static final String HOME_MODEL_KEY = "com.ociweb.homeModel";
  8.  
  9. // background threads use this Handler to post messages to
  10. // the main application thread
  11. private final Handler mHandler = new Handler();
  12.  
  13. // this data model knows when a thread is fetching data
  14. private HomeModel mHomeModel;
  15.  
  16. // post this to the Handler when the background thread completes
  17. private final Runnable mUpdateDisplayRunnable = new Runnable() {
  18. public void run() {
  19. updateDisplay();
  20. }
  21. };
  22.  
  23. @Override
  24. public void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.home);
  27.  
  28. mStartButton = (Button) findViewById(R.id.start_background_thread_btn);
  29. mStatusLabel = (TextView) findViewById(R.id.thread_status_label);
  30.  
  31. mStartButton.setOnClickListener(this);
  32.  
  33. if (savedInstanceState != null) {
  34. if (savedInstanceState.containsKey(ENABLED_KEY)) {
  35. mStartButton.setEnabled(savedInstanceState.getBoolean(ENABLED_KEY));
  36. }
  37. if (savedInstanceState.containsKey(HOME_MODEL_KEY)) {
  38. mHomeModel = (HomeModel) savedInstanceState.getSerializable(HOME_MODEL_KEY);
  39. }
  40. }
  41. if (mHomeModel == null) {
  42. // the first time in, create a new model
  43. mHomeModel = new HomeModel();
  44. }
  45. }
  46.  
  47. @Override
  48. protected void onPause() {
  49. super.onPause();
  50. // detach from the model
  51. mHomeModel.setHomeModelListener(null);
  52. }
  53.  
  54. @Override
  55. protected void onResume() {
  56. super.onResume();
  57. // attach to the model
  58. mHomeModel.setHomeModelListener(this);
  59.  
  60. // synchronize the display, in case the thread completed
  61. // while this activity was not visible. For example, if
  62. // a phone call occurred while the thread was running.
  63. updateDisplay();
  64. }
  65.  
  66. public void homeModelChanged(HomeModel hm) {
  67. // this may be called from a background thread, so post
  68. // to the handler
  69. mHandler.post(mUpdateDisplayRunnable);
  70. }
  71.  
  72. @Override
  73. protected void onSaveInstanceState(Bundle outState) {
  74. super.onSaveInstanceState(outState);
  75. outState.putBoolean(ENABLED_KEY, mStartButton.isEnabled());
  76. outState.putSerializable(HOME_MODEL_KEY, mHomeModel);
  77. }
  78.  
  79. public void onClick(View v) {
  80. if (v == mStartButton) {
  81. new DataFetcherThread(mHomeModel).start();
  82. }
  83. }
  84.  
  85. private void updateDisplay() {
  86. mStartButton.setEnabled(mHomeModel.getState() != HomeModel.State.RUNNING);
  87.  
  88. switch (mHomeModel.getState()) {
  89. case RUNNING:
  90. mStatusLabel.setText(R.string.thread_running);
  91. // show the user what's happening
  92. Toast.makeText(this, R.string.thread_running, Toast.LENGTH_SHORT);
  93. break;
  94. case NOT_STARTED:
  95. mStatusLabel.setText(R.string.thread_not_started);
  96. break;
  97. case FINISHED:
  98. mStatusLabel.setText(R.string.thread_finished);
  99. // show the user what's happening
  100. Toast.makeText(this, R.string.thread_finished, Toast.LENGTH_SHORT);
  101. break;
  102. }
  103. }
  104. }

Summary

Understanding the Activity Lifecycle is critical to success with Android. Since mobile devices have limited resources, activities are constantly paused, resumed, initialized, and destroyed. Your application code has to handle these transitions with grace, which is probably the most challenging aspect of Android development.

Credits

Dan Morrill and Lance Finney were kind enough to review this article and provided several suggestions for improvement. Thank you!

References

 

The Software Engineering Tech Trends is a monthly newsletter featuring emerging trends in software engineering.

Subscribe

© Copyright Object Computing, Inc. 1993, 2016. All rights reserved

secret