Support free tutorials









vogella training Training Books



Android Background Processing with Handlers and AsyncTask and Loaders - Tutorial

Lars Vogel

Version 2.7

12.06.2013

Revision History
Revision 0.1 21.10.2010 Lars
Vogel
Created
Revision 0.2 - 2.7 21.12.2010 - 12.06.2013 Lars
Vogel
bug fixes and updates

Android Threads, Handlers AsyncTask

This tutorial describes the usage of Threads, Handlers and AsyncTask in your application. It also covers how to handle the application lifecycle together with threads. It is based on Eclipse 4.2, Java 1.6 and Android 4.2.


Table of Contents

1. Android's user interface thread
1.1. Main thread
1.2. Why using concurrency?
2. Android Basics
3. Using Java threads in Android
3.1. Using Java threading in Android
3.2. Disadvantages of using Java threads in Android
4. Concurrency constructs in Android
5. Handler
5.1. Purpose of the Handler class
5.2. Creating and reusing instances of Handlers
5.3. Example
6. AsyncTask
6.1. Purpose of the AsyncTask class
6.2. Using the AsyncTask class
6.3. Parallel execution of several AsyncTasks
6.4. Disadvantages of using AsyncTasks
6.5. Example: AsyncTask
7. Background processing and lifecycle handling
7.1. Retaining state during configuration changes
7.2. Using the application object to store objects
8. Fragments and background processing
8.1. Retain instance during configuration changes
8.2. Headless fragments
9. Learn about Fragments
10. Loader
10.1. Purpose of the Loader class
10.2. Implementing a Loader
10.3. SQLite database and CursorLoader
11. Exercise: Custom loader for preferences
11.1. Implementation
11.2. Test
12. Usage of services
13. Learn about services
14. Exercise: activity lifecycle and threads
15. Memory optimizations
15.1. Using caches
15.2. Using memory efficient memory structures
15.3. Cleaning up memory usage
16. StrictMode
17. Feedback via dialog
18. Support this website
18.1. Thank you
18.2. Questions and Discussion
19. Links and Literature
19.1. Source Code
19.2. Concurrency Resources
19.3. Android Resources
19.4. vogella Resources

1. Android's user interface thread

1.1. Main thread

Android modifies the user interface and handles input events from one single user interface thread. This thread is also called the main thread.

Android collects all events in a queue and processed an instance of the Looper class.

Message Queue in Android with Looper

1.2. Why using concurrency?

If the programmer does not use any concurrency constructs, all code of an Android application runs in the main thread and every statement is executed after each other.

If you perform a long lasting operation, for example accessing data from the Internet, the application blocks until the corresponding operation has finished.

To provide a good user experience all potentially slow running operations in an Android application should run asynchronously, e.g. via some way of concurrency constructs of the Java language or the Android framework. This includes all potential slow operations, like network, file and database access and complex calculations.

Note

Android enforces a worst case reaction time of applications. If an activity does not react within 5 seconds to user input, the Android system displays an Application not responding (ANR) dialog. From this dialog the user can choose to stop the application.

2. Android Basics

The following description assumes that you have already basic knowledge in Android development.

Please check the Android development tutorial to learn the basics. Also see Android development tutorials for more information about Android development.

3. Using Java threads in Android

3.1. Using Java threading in Android

Android supports the usage of the Thread class to perform asynchronous processing.

Android also supplies the java.util.concurrent package to perform something in the background, e.g. using the ThreadPools and Executor classes.

If you need to update the user interface from a new Thread, you need to synchronize with the user interface thread.

3.2. Disadvantages of using Java threads in Android

If you use Java threads you have to handle the following requirements in your own code:

  • Synchronization with the main thread if you post back results to the user interface

  • No default for canceling the thread

  • No default thread pooling

  • No default for handling configuration changes in Android

4. Concurrency constructs in Android

Android provides additional constructs to handle concurrently in comparison with standard Java. You can use the android.os.Handler class or the AsyncTasks classes. More sophisticated approach are based on the Loader class, retained Fragments and services.

5. Handler

5.1. Purpose of the Handler class

The Handler class can be used to register to a thread and provides a simple channel to send data to this thread.

A Handler object registers itself with the thread in which it is created. For example, if you create a new instance of the Handler class in the onCreate() method of your activity, the resulting Handler object can be used to post data to the main thread.

The data which can be posted via the Handler class can be an instance of the Message or the Runnable class.

Tip

A Handler is particular useful if you have want to post multiple times data to the main thread.

5.2. Creating and reusing instances of Handlers

To use a handler you have to subclass it and override the handleMessage() method to process messages.

Your thread can post messages via the sendMessage(Message) method or via the sendEmptyMessage() method to the Handler object.

To process a Runnable you can use the post() method.

To avoid object creation you can also reuse the existing Handler object of your activity.

// Reuse existing handler if you don't 
// have to override the message processing
handler = getWindow().getDecorView().getHandler(); 

The View class allows you to post objects of type Runnable via the post() method.

5.3. Example

The following code demonstrates the usage of a Handler via a View.

Assume your activity uses the following layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>
    
   <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" >
      </TextView>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startProgress"
        android:text="Start Progress" >
    </Button>

</LinearLayout> 

With the following the ProgressBar get updated once the users presses the Button.

package de.vogella.android.handler;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ProgressTestActivity extends Activity {
  private ProgressBar progress;
  private TextView text;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    progress = (ProgressBar) findViewById(R.id.progressBar1);
    text = (TextView) findViewById(R.id.textView1);

  }

  public void startProgress(View view) {
    // do something long
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i <= 10; i++) {
          final int value = i;
           doFakeWork();
          progress.post(new Runnable() {
            @Override
            public void run() {
              text.setText("Updating");
              progress.setProgress(value);
            }
          });
        }
      }
    };
    new Thread(runnable).start();
  }

  // Simulating something timeconsuming
  private void doFakeWork() {
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

} 

6. AsyncTask

6.1. Purpose of the AsyncTask class

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

6.2. Using the AsyncTask class

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .

An AsyncTask is started via the execute() method.

The execute() method calls the doInBackground() and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input, ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method and is passed to onPostExecute() as a parameter.

The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.

The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

6.3. Parallel execution of several AsyncTasks

Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence by default.

You can tell Android to run it in parallel with the usage of the executeOnExecutor() method, specifying AsyncTask.THREAD_POOL_EXECUTOR as first parameter.

The following code snippet demonstrates that.

// ImageLoader extends AsyncTask
ImageLoader imageLoader = new ImageLoader(imageView);

// Execute in parallel
imageLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png"); 

6.4. Disadvantages of using AsyncTasks

The AsyncTask does not handle configuration changes automatically, i.e. if the activity is recreated, the programmer has to handle that in his coding.

A common solution to this is to declare the AsyncTask in a retained headless fragment.

6.5. Example: AsyncTask

The following code demonstrates how to use the AsyncTask class to download the content of a webpage.

Create a new Android project called de.vogella.android.asynctask with an activity called ReadWebpageAsyncTask. Add the android.permission.INTERNET permission to your AndroidManifest.xml file.

Create the following layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/readWebpage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Load Webpage" >
    </Button>

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Placeholder" >
    </TextView>

</LinearLayout> 

Change your activity to the following:

package de.vogella.android.asynctask;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import de.vogella.android.asyntask.R;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class ReadWebpageAsyncTask extends Activity {
  private TextView textView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (TextView) findViewById(R.id.TextView01);
  }

  private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      String response = "";
      for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
          HttpResponse execute = client.execute(httpGet);
          InputStream content = execute.getEntity().getContent();

          BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
          String s = "";
          while ((s = buffer.readLine()) != null) {
            response += s;
          }

        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return response;
    }

    @Override
    protected void onPostExecute(String result) {
      textView.setText(result);
    }
  }

  public void onClick(View view) {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute(new String[] { "http://www.vogella.com" });

  }
} 

If you run your application and press your button then the content of the defined webpage is read in the background. Once this process is done your TextView is updated.

7. Background processing and lifecycle handling

7.1. Retaining state during configuration changes

One challenge in using threads is to consider the lifecycle of the application. The Android system may kill your activity or trigger a configuration change which will also restart your activity.

You also need to handle open dialogs, as dialogs are always connected to the activity which created them. In case the activity gets restarted and you access an existing dialog you receive a View not attached to window manager exception.

To save an object you can use the method onRetainNonConfigurationInstance() method. This method allows you to save one object if the activity will be soon restarted.

To retrieve this object you can use the getLastNonConfigurationInstance() method. This way can you can save an object, e.g. a running thread, even if the activity is restarted.

getLastNonConfigurationInstance() returns null if the activity is started the first time or if it has been finished via the finish() method.

onRetainNonConfigurationInstance() is deprecated as of API 13, it is recommended that you use fragments and the setRetainInstance() method to retain data over configuration changes.

7.2. Using the application object to store objects

If more than one object should be stored across activities and configuration changes, you can implement an Application class for your Android application.

To use your application class assign the classname to the android:name attribute of your application.

<application android:icon="@drawable/icon" android:label="@string/app_name"
  android:name="MyApplicationClass">
   <activity android:name=".ThreadsLifecycleActivity"
    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> 

The application class is automatically created by the Android runtime and is available unless the whole application process is terminated.

This class can be used to access objects which should be cross activities or available for the whole application lifecycle. In the onCreate() method you can create objects and make them available via public fields or getter methods.

The onTerminate() method in the application class is only used for testing. If Android terminates the process in which your application is running all allocated resources are automatically released.

You can access the Application via the getApplication() method in your activity.

8. Fragments and background processing

8.1. Retain instance during configuration changes

You can use fragments without user interface and retain them between configuration changes via a call to their setRetainInstance() method.

This way your Thread or AsyncTask is retained during configuration changes. This allows you to perform background processing without explicitly considering the lifecycle of your activity.

8.2. Headless fragments

If you perform background processing you can dynamically attached a headless fragment to your application and call setRetainInstance() to true. This fragment is retained during configuration changes and you can perform asynchronous processing in it.

9. Learn about Fragments

You can use the following Fragments Tutorial to learn how to use fragments .

10. Loader

10.1. Purpose of the Loader class

The Loader class allow you to load data asynchronously in an activity or fragment. They can monitor the source of the data and deliver new results when the content changes. They also persist data between configuration changes.

If the result is retrieved by the Loader after the object has been disconnected from its parent (activity or fragment), it can cache the data.

Loaders have been introduced in Android 3.0 and are part of the compatibility layer for Android versions as of 1.6.

10.2. Implementing a Loader

You can use the abstract AsyncTaskLoader class as the basis for your own Loader implementations.

The LoaderManager of an activity or fragment manages one or more Loader instances. The creation of a Loader is done via the following method call.

# start a new loader or re-connect to existing one
getLoaderManager().initLoader(0, null, this); 

The first parameter is a unique ID which can be used by the callback class to identify that Loader later. The second parameter is a bundle which can be given to the callback class for more information.

The third parameter of initLoader() is the class which is called once the initialization has been started (callback class). This class must implement the LoaderManager.LoaderCallbacks interface. It is good practice that an activity or the fragment which uses a Loader implements the LoaderManager.LoaderCallbacks interface.

The Loader is not directly created by the getLoaderManager().initLoader() method call, but must be created by the callback class in the onCreateLoader() method.

Once the Loader has finished reading data asynchronously, the onLoadFinished() method of the callback class is called. Here you can update your user interface.

10.3. SQLite database and CursorLoader

Android provides a Loader default implementation to handle SQlite database connections, the CursorLoader class.

For a ContentProvider based on an SQLite database you would typically use the CursorLoader class. This Loader performs the database query in a background thread so that the application is not blocked.

The CursorLoader class is the replacement for Activity-managed cursors which are deprecated now.

If the Cursor becomes invalid, the onLoaderReset() method is called on the callback class.

11. Exercise: Custom loader for preferences

11.1. Implementation

In the following your create a custom loader implementation for managing preferences. On every load the value of the preference is increased.

Create a project called com.vogella.android.loader.preferences with an activity called MainActivity.

Create the following class as custom AsyncTaskLoader implementation for managing shared preferences.

package com.vogella.android.loader.preferences;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class SharedPreferencesLoader extends AsyncTaskLoader<SharedPreferences>
    implements SharedPreferences.OnSharedPreferenceChangeListener {
  private SharedPreferences prefs = null;

  public static void persist(final SharedPreferences.Editor editor) {
    editor.apply();
  }

  public SharedPreferencesLoader(Context context) {
    super(context);
  }

  // Load the data asynchronously
  @Override
  public SharedPreferences loadInBackground() {
    prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
    prefs.registerOnSharedPreferenceChangeListener(this);
    return (prefs);
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
      String key) {
    // notify loader that content has changed
    onContentChanged();
  }

  
/** * starts the loading of the data * once result is ready the onLoadFinished method is called * in the main thread. It loader was started earlier the result * is return directly * method must be called from main thread. */
@Override protected void onStartLoading() { if (prefs != null) { deliverResult(prefs); } if (takeContentChanged() || prefs == null) { forceLoad(); } } }

The following example code demonstrates the usage of this loader in an activity.

package com.vogella.android.loader.preferences;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Loader;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity implements
    LoaderManager.LoaderCallbacks<SharedPreferences> {
  private static final String KEY = "prefs";
  private TextView textView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.prefs);
    getLoaderManager().initLoader(0, null, this);

  }

  @Override
  public Loader<SharedPreferences> onCreateLoader(int id, Bundle args) {
    return (new SharedPreferencesLoader(this));
  }

  @SuppressLint("CommitPrefEdits")
  @Override
  public void onLoadFinished(Loader<SharedPreferences> loader,
      SharedPreferences prefs) {
    int value = prefs.getInt(KEY, 0);
    value += 1;
    textView.setText(String.valueOf(value));
    // update value
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(KEY, value);
    SharedPreferencesLoader.persist(editor);
  }

  @Override
  public void onLoaderReset(Loader<SharedPreferences> loader) {
    // NOT used
  }
} 

11.2. Test

The LoaderManager call onLoadFinished() in your activity automatically after a configuration change. Run the application and ensure that the value stored in the shared preferences is increased at every configuration change.

12. Usage of services

You can also use Android services to perform background tasks. See Android service tutorial for details.

13. Learn about services

You can use the following Android service tutorial to learn how to use services.

14. Exercise: activity lifecycle and threads

The following example will download an image from the Internet in a thread and displays a dialog until the download is done. We will make sure that the thread is preserved even if the activity is restarted and that the dialog is correctly displayed and closed.

For this example create a new Android project called de.vogella.android.threadslifecycle with the Activity called ThreadsLifecycleActivity. Also add the permission to use the Internet to your AndroidManifest.xml file.

Your AndroidManifest.xml file should look like the following.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.threadslifecycle"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET" >
    </uses-permission>

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ThreadsLifecycleActivity"
            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> 

Change the layout main.xml to the following.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="downloadPicture"
            android:text="Click to start download" >
        </Button>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="resetPicture"
            android:text="Reset Picture" >
        </Button>
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/icon" >
    </ImageView>

</LinearLayout> 

Now adjust your activity. In this activity the thread is saved and the dialog is closed if the activity is destroyed.

package de.vogella.android.threadslifecycle;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

public class ThreadsLifecycleActivity extends Activity {
  // Static so that the thread access the latest attribute
  private static ProgressDialog dialog;
  private static Bitmap downloadBitmap;
  private static Handler handler;
  private ImageView imageView;
  private Thread downloadThread;

  
/** Called when the activity is first created. */
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // create a handler to update the UI handler = new Handler() { @Override public void handleMessage(Message msg) { imageView.setImageBitmap(downloadBitmap); dialog.dismiss(); } }; // get the latest imageView after restart of the application imageView = (ImageView) findViewById(R.id.imageView1); Context context = imageView.getContext(); System.out.println(context); // Did we already download the image? if (downloadBitmap != null) { imageView.setImageBitmap(downloadBitmap); } // check if the thread is already running downloadThread = (Thread) getLastNonConfigurationInstance(); if (downloadThread != null && downloadThread.isAlive()) { dialog = ProgressDialog.show(this, "Download", "downloading"); } } public void resetPicture(View view) { if (downloadBitmap != null) { downloadBitmap = null; } imageView.setImageResource(R.drawable.icon); } public void downloadPicture(View view) { dialog = ProgressDialog.show(this, "Download", "downloading"); downloadThread = new MyThread(); downloadThread.start(); } // save the thread @Override public Object onRetainNonConfigurationInstance() { return downloadThread; } // dismiss dialog if activity is destroyed @Override protected void onDestroy() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); dialog = null; } super.onDestroy(); } // Utiliy method to download image from the internet static private Bitmap downloadBitmap(String url) throws IOException { HttpUriRequest request = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { throw new IOException("Download failed, HTTP response code " + statusCode + " - " + statusLine.getReasonPhrase()); } } static public class MyThread extends Thread { @Override public void run() { try { // Simulate a slow network try { new Thread().sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } downloadBitmap = downloadBitmap("http://www.devoxx.com/download/attachments/4751369/DV11"); // Updates the user interface handler.sendEmptyMessage(0); } catch (IOException e) { e.printStackTrace(); } finally { } } } }

Run your application and press the button to start a download. You can test the correct lifecycle behavior by changing the orientation in the emulator via the Ctrl+F11 shortcut.

It is important to note that the Thread is a static inner class. It is important to use a static inner class for your background process because otherwise the inner class will contain a reference to the class in which is was created. As the thread is passed to the new instance of your activity this would create a memory leak as the old activity would still be referred to by the Thread.

15. Memory optimizations

15.1. Using caches

Another way of avoiding bad performance is to cache expensive objects. For example if you downloading images from the Internet to display them in a ListView you should hold them in a cache to avoid that you download them several times.

A Least Recently Used (LRU) cache keep track of the usage of its members. It has a given size and if this size is exceed, it removes the items which have not be accessed the longest. This behavior is depicted in the following graphic.

LRU cache in general

The Android platform provides the LruCache class, as of API 12 (or in the support-v4 library). The LruCache class provides an Least Recently Used cache implementation.

The following example code demonstrates a possible implementation of the LruCache class for caching images.

public class ImageCache extends LruCache<String, Bitmap> {
 
  public ImageCache(int maxSize) {
    super(maxSize);
  }
 
  @Override
  protected int sizeOf(String key, Bitmap value) {
    return value.getByteCount();
  }
 
  @Override
  protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
    oldValue.recycle();
  }
 
} 

For determining the initial size of the cache you can use the MemoryClass and use a fraction of the total available memory as demonstrated in the following code.

int memClass = ((ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
int cacheSize = 1024 * 1024 * memClass / 8;
LruCache cache = new LruCache<String, Bitmap>(cacheSize); 

15.2. Using memory efficient memory structures

Android provides data structures which are more efficient for mapping values to other objects. If possible use these objects, they avoid object creation as in the case of using HashMap. Object creation can be expensive and should be avoided to reduce the number of times the garbage collector needs to run.

The table give examples for SparseArrays.

Table 1. Efficient memory structures

Memory structure Description
SparseArray<E> Maps integers to Objects, avoid the creation of Integer objects.
SparseBooleanArray Maps integers to booleans.
SparseIntArray Maps integers to integers


15.3. Cleaning up memory usage

As of API 14 you can override the onTrimMemory() method in Android components. This method is called by the Android system asking you to cleanup your memory in case the Android system requires resources for foreground processes.

16. StrictMode

Android allows you to instruct the system to report any long running processes which are performed in the user interface thread. See Using StrictMode in Android for details.

17. Feedback via dialog

If you are performing a long running operation it is good practice to provide feedback to the user about the running operation.

You can provide progress feedback via the action bar for example via an action view. Alternatively you can use a ProgressBar in your layout which you set to visible and update it during a long running operation. This approach is called providing inline feedback as it leave the user interface responsive.

To block the user interface during the operation you can use the ProgressBar dialog, which allows the display of progress to the user. The Javadoc of ProgressBar gives a nice example of its usage.

Tip

Avoid using the ProgressBar dialog or similar approaches if possible. Prefer providing inline feedback to that your user interface stays responsive.

18. Support this website

This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this tutorial is distributed under the Eclipse Public License. See the vogella License page for details on the terms of reuse.

Writing and updating these tutorials is a lot of work. If this free community service was helpful, you can support the cause by giving a tip as well as reporting typos and factual errors.

18.1. Thank you

Please consider a contribution if this article helped you. It will help to maintain our content and our Open Source activities.

18.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

19. Links and Literature

19.1. Source Code

Source Code of Examples

19.4. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java, compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put all your files in a distributed version control system