Solving an Android Threading Problem

Similar documents
Android Beginners Workshop

Lab 1: Getting Started With Android Programming

Embedded Systems Programming - PA8001

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Android Workshop: Model View Controller ( MVC):

Real-Time Embedded Systems

Manifest.xml. Activity.java

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

EMBEDDED SYSTEMS PROGRAMMING Application Basics

Applications. Marco Ronchetti Università degli Studi di Trento

Vienos veiklos būsena. Theory

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

App Development for Android. Prabhaker Matet

Developed and taught by well-known Contact author and developer. At public for details venues or onsite at your location.

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Android Development Tutorial. Yi Huang

LifeStreet Media Android Publisher SDK Integration Guide

8/30/15 MOBILE COMPUTING. CSE 40814/60814 Fall How many of you. have implemented a command-line user interface?

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Security model. Marco Ronchetti Università degli Studi di Trento

INTRODUCTION TO ANDROID

Agenda. Overview of Xamarin and Xamarin.Android Xamarin.Android fundamentals Creating a detail screen

Notification mechanism

Mobile Programming Lecture 1. Getting Started

Android Exam AND-401 Android Application Development Version: 7.0 [ Total Questions: 129 ]

Android Application Development

Services. Marco Ronchetti Università degli Studi di Trento

Programming in Android. Nick Bopp

CS 4330/5390: Mobile Application Development Exam 1

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time

Android HelloWorld - Example. Tushar B. Kute,

CS 234/334 Lab 1: Android Jump Start

MODULE 2: GETTING STARTED WITH ANDROID PROGRAMMING

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH

UNDERSTANDING ACTIVITIES

ELET4133: Embedded Systems. Topic 15 Sensors

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

Introduction to Android

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

Group B: Assignment No 8. Title of Assignment: To verify the operating system name and version of Mobile devices.

Lecture 1 Introduction to Android. App Development for Mobile Devices. App Development for Mobile Devices. Announcement.

Embedded Systems Programming - PA8001

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

Mobila applikationer och trådlösa nät, HI1033, HT2012

EMBEDDED SYSTEMS PROGRAMMING Android NDK

Orientation & Localization

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Java & Android. Java Fundamentals. Madis Pink 2016 Tartu

Agenda. The Android GUI Framework Introduction Anatomy A real word example Life cycle Findings

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

CMSC436: Fall 2013 Week 3 Lab

Learn about Android Content Providers and SQLite

Wireless Vehicle Bus Adapter (WVA) Android Library Tutorial

Introduction To Android

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

EMBEDDED SYSTEMS PROGRAMMING Android Services

Questions and Answers. Q.1) Which of the following is the most ^aeuroeresource hungry ^aeuroepart of dealing with activities on android?

Mobile Programming Lecture 2. Layouts, Widgets, Toasts, and Event Handling

Computer Science E-76 Building Mobile Applications

Comp 595MC/L: Mobile Computing CSUN Computer Science Department Fall 2013 Midterm

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android Application Model I

Android Services. Victor Matos Cleveland State University. Services

Android Programming (5 Days)

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

Simple Currency Converter

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Android App Development

Basic UI elements: Android Buttons (Basics) Marco Ronchetti Università degli Studi di Trento

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

Android & iphone. Amir Eibagi. Localization

Android framework overview Activity lifecycle and states

Basic GUI elements - exercises

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

App Development for Smart Devices. Lec #18: Advanced Topics

Android Basics. Android UI Architecture. Android UI 1

Our First Android Application

Produced by. Mobile Application Development. Eamonn de Leastar

Minds-on: Android. Session 2

Tutorial: Setup for Android Development

Theme 2 Program Design. MVC and MVP

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

Android Application Development. By : Shibaji Debnath

PROGRAMMING APPLICATIONS DECLARATIVE GUIS

Mobila applikationer och trådlösa nät, HI1033, HT2013

Android Ecosystem and. Revised v4presenter. What s New

MVC Apps Basic Widget Lifecycle Logging Debugging Dialogs

Intents. Your first app assignment

Android Activities. Akhilesh Tyagi

Meniu. Create a project:

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle

Software Practice 3 Before we start Today s lecture Today s Task Team organization

Lecture 6: Android XML, Inversion of Control, Timers (Handlers), Activity

Android Overview. Most of the material in this section comes from

Android UI Development

Answers to Exercises

Transcription:

Home Java News Brief Archive OCI Educational Services Solving an Android Threading Problem Introduction by Eric M. Burke, Principal Software Engineer Object Computing, Inc. (OCI) 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. If you are new to Android development, start with Google's Notepad Tutorial. Rather than repeat that material, this article looks at a particular threading problem in more detail. If you are completely new to Android, you may want to work through the 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: Android fails fast when background threads update GUI components. Rather than silently ignoring this kind of threading bug, Android throws CalledFromWrongThreadException and immediately terminates the activity. Page 1 of 14

If a long-running process locks up the UI, Android intervenes and displays this dialog to the user: 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.) Page 2 of 14

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: Page 3 of 14

When the thread completes, the button becomes enabled again and the status label shows Finished. Now let's review the source code. XML Files Our application contains three XML files, larger applications will have many more. Although Android utilizes XML during application development, all of these XML files are compiled into a highly 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. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ociweb.demo" android:versioncode="1" android:versionname="1.0.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".homeactivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> </manifest> Although this XML is verbose, editing is easy thanks to the graphical editors in the Android Eclipse plugin. Page 4 of 14

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. <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">thread Demo</string> <string name="start_background_thread">start Background Thread</string> <string name="thread_running">running</string> <string name="thread_finished">finished</string> <string name="thread_status">thread Status:</string> <string name="thread_not_started">not Started</string> </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 files, layout files are compiled to a more efficient form before they are ever installed on a phone. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/start_background_thread_btn" android:text="@string/start_background_thread" android:layout_gravity="center"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/thread_status" android:textsize="20dp" android:paddingright="5dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/thread_status_label" android:text="@string/thread_not_started" android:freezestext="true" android:textsize="20dp"/> </LinearLayout> </LinearLayout> Android includes a variety of layout classes, such as LinearLayout, FrameLayout, RelativeLayout, and more. Like Swing layout managers, these help your UI adjust to varying screen resolutions with minimum hardcoding. Page 5 of 14

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 change screen orientation. 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. /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.ociweb.demo; public final class R { public static final class attr { public static final class drawable { public static final int icon=0x7f020000; public static final class id { public static final int start_background_thread_btn=0x7f050000; public static final int thread_status_label=0x7f050001; public static final class layout { public static final int home=0x7f030000; public static final class string { public static final int app_name=0x7f040000; public static final int start_background_thread=0x7f040001; public static final int thread_finished=0x7f040003; public static final int thread_not_started=0x7f040005; public static final int thread_running=0x7f040002; public static final int thread_status=0x7f040004; Finally, using integer constants is more efficient than looking up strings from XML. 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 Page 6 of 14

heavy use of the Template Method pattern, in which base classes like Activity define numerous methods you must override. public class HomeActivity extends Activity implements OnClickListener { private Button mstartbutton; private TextView mstatuslabel; private static final String ENABLED_KEY = "com.ociweb.buttonenabled"; // background threads use this Handler to post messages to // the main application thread private final Handler mhandler = new Handler(); // post this to the Handler when the background thread completes private final Runnable mcompleterunnable = new Runnable() { public void run() { onthreadcompleted(); ; We'll see how to initialize Button and TextView shortly. The ENABLED_KEY let's 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. @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.home); mstartbutton = (Button) findviewbyid(r.id.start_background_thread_btn); mstatuslabel = (TextView) findviewbyid(r.id.thread_status_label); mstartbutton.setonclicklistener(this); if (savedinstancestate!= null) { if (savedinstancestate.containskey(enabled_key)) { mstartbutton.setenabled(savedinstancestate.getboolean(enabled_key)); 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.java constants. 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. Page 7 of 14

The enabled flag is saved here in the onsaveinstancestate(...) method: @Override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putboolean(enabled_key, mstartbutton.isenabled()); Next, our Activity implements onclick(view v) from the OnClickListener interface. This is how we react to button clicks. public void onclick(view v) { if (v == mstartbutton) { mstartbutton.setenabled(false); mstatuslabel.settext(r.string.thread_running); // show a brief popup alert Toast.makeText(this, R.string.thread_running, Toast.LENGTH_SHORT).show(); Thread t = new Thread() { public void run() { // perform expensive tasks in a background thread expensiveoperation(); // let the UI know the task is complete mhandler.post(mcompleterunnable); ; t.start(); 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. /** * Call this method on the main application thread once the background thread * completes. */ private void onthreadcompleted() { mstartbutton.setenabled(true); mstatuslabel.settext(r.string.thread_finished); Toast.makeText(this, R.string.thread_finished, Toast.LENGTH_SHORT).show(); /** * This method runs in a background thread. In a real app, it would do * something useful, such as getting data from a web service. */ private void expensiveoperation() { try { TimeUnit.SECONDS.sleep(4); catch (InterruptedException e) { Thread.currentThread().interrupt(); Those calls to Toast.makeText(...) trigger a brief popup alert. When the thread is complete, we enable the button again and change the status label back Page 8 of 14

to "Finished". 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: 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: 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 Page 9 of 14

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: Override Activity.onPause() and stop the thread. When the activity resumes, simply start another thread. While this would work, it is inefficient. So long as we started a thread, we may as well try to utilize the data it just fetched. Override Activity.onRetainNonConfigurationInstance() and return a reference to the running Thread. When Android creates the new HomeActivity instance, you can obtain the thread via getlastnonconfigurationinstance(). This is only a partial solution because our inner class thread still has a reference to the old HomeActivity. We'd need to make a static or top-level Thread class, and explicitly set a reference to the new HomeActivity instance after the rotation. This is possible, but tricky to get right. Use an Android Service along with BroadcastReceiver, but that's a pretty expensive solution. BroadcastReceiver is more appropriate when sending messages to other applications, and is overkill when sending messages within a single Activity. Our Solution Let's start by creating a data model that keeps track of the HomeActivity state. HomeModel.java /** * Data model for the HomeActivity. Fires events when the data * fetch thread begins and ends. */ public class HomeModel implements Serializable { private static final long serialversionuid = 1L; public enum State { NOT_STARTED, RUNNING, FINISHED private State state = State.NOT_STARTED; private HomeModelListener homemodellistener; public synchronized void sethomemodellistener(homemodellistener l) { homemodellistener = l; public void setstate(state state) { // copy to a local variable inside the synchronized block // to avoid synchronization while calling homemodelchanged() HomeModelListener hml = null; synchronized (this) { if (this.state == state) { return; // no change this.state = state; hml = this.homemodellistener; Page 10 of 14

// notify the listener here, not synchronized if (hml!= null) { hml.homemodelchanged(this); public synchronized State getstate() { return state; HomeModelListener.java The HomeModelListener interface is trivial. public interface HomeModelListener { void homemodelchanged(homemodel hm); 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. public class DataFetcherThread extends Thread { private final HomeModel homemodel; public DataFetcherThread(HomeModel homemodel) { this.homemodel = homemodel; public void start() { homemodel.setstate(homemodel.state.running); super.start(); public void run() { try { TimeUnit.SECONDS.sleep(3); catch (InterruptedException e) { finally { homemodel.setstate(homemodel.state.finished); Class Diagram Here is a diagram that shows how these pieces fit together. Page 11 of 14

HomeActivity creates DataFetcherThread, but does not retain a reference to it. HomeActivity implements HomeModelListener, updating the button and label display whenever the data model changes. The thread is no longer an inner class, so it retains no reference back to HomeActivity. 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: HomeActivity, Final Version Here is HomeActivity.java in its entirety, using all of the changes mentioned above. Page 12 of 14

public class HomeActivity extends Activity implements OnClickListener, HomeModelListener { private Button mstartbutton; private TextView mstatuslabel; private static final String ENABLED_KEY = "com.ociweb.buttonenabled"; private static final String HOME_MODEL_KEY = "com.ociweb.homemodel"; // background threads use this Handler to post messages to // the main application thread private final Handler mhandler = new Handler(); // this data model knows when a thread is fetching data private HomeModel mhomemodel; // post this to the Handler when the background thread completes private final Runnable mupdatedisplayrunnable = new Runnable() { public void run() { updatedisplay(); ; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.home); mstartbutton = (Button) findviewbyid(r.id.start_background_thread_btn); mstatuslabel = (TextView) findviewbyid(r.id.thread_status_label); mstartbutton.setonclicklistener(this); if (savedinstancestate!= null) { if (savedinstancestate.containskey(enabled_key)) { mstartbutton.setenabled(savedinstancestate.getboolean(enabled_key)); if (savedinstancestate.containskey(home_model_key)) { mhomemodel = (HomeModel) savedinstancestate.getserializable(home_model_key); if (mhomemodel == null) { // the first time in, create a new model mhomemodel = new HomeModel(); @Override protected void onpause() { super.onpause(); // detach from the model mhomemodel.sethomemodellistener(null); @Override protected void onresume() { super.onresume(); // attach to the model mhomemodel.sethomemodellistener(this); // synchronize the display, in case the thread completed // while this activity was not visible. For example, if // a phone call occurred while the thread was running. updatedisplay(); public void homemodelchanged(homemodel hm) { Page 13 of 14

// this may be called from a background thread, so post // to the handler mhandler.post(mupdatedisplayrunnable); @Override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); outstate.putboolean(enabled_key, mstartbutton.isenabled()); outstate.putserializable(home_model_key, mhomemodel); public void onclick(view v) { if (v == mstartbutton) { new DataFetcherThread(mHomeModel).start(); private void updatedisplay() { mstartbutton.setenabled(mhomemodel.getstate()!= HomeModel.State.RUNNING); switch (mhomemodel.getstate()) { case RUNNING: mstatuslabel.settext(r.string.thread_running); Toast.makeText(this, R.string.thread_running, Toast.LENGTH_SHORT); break; case NOT_STARTED: mstatuslabel.settext(r.string.thread_not_started); break; case FINISHED: mstatuslabel.settext(r.string.thread_finished); Toast.makeText(this, R.string.thread_finished, Toast.LENGTH_SHORT); break; 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. Recommended Reading Hello, Android by Ed Burnette is probably the best book for programmers new to Android. Android Official Site - http://www.android.com Android Developer site on Google Code (SDK, documentation, and tutorials) - http://code.google.com/android/ Android Open Source Project (source code for the OS, SDK, and Dalvik VM) - http://source.android.com/ Page 14 of 14