Android Threading: All You Need to Know


Every Android developer, at one point or another, needs to deal with threads in their application.

When an application is launched in Android, it creates the first thread of execution, known as the “main” thread. The main thread is responsible for dispatching events to the appropriate user interface widgets as well as communicating with components from the Android UI toolkit.


To keep your application responsive, it is essential to avoid using the main thread to perform any operation that may end up keeping it blocked.


Network operations and database calls, as well as loading of certain components, are common examples of operations that one should avoid in the main thread. When they are called in the main thread, they are called synchronously, which means that the UI will remain completely unresponsive until the operation completes. For this reason, they are usually performed in separate threads, which thereby avoids blocking the UI while they are being performed (i.e., they are performed asynchronously from the UI).


Android provides many ways of creating and managing threads, and many third-party libraries exist that make thread management a lot more pleasant. However, with so many different approaches at hand, choosing the right one can be quite confusing.


In this article, you will learn about some common scenarios in Android development where threading becomes essential and some simple solutions that can be applied to those scenarios and more.

Threading in Android

In Android, you can categorize all threading components into two basic categories:

  1. Threads that are attached to an activity/fragment: These threads are tied to the lifecycle of the activity/fragment and are terminated as soon as the activity/fragment is destroyed.
  2. Threads that are not attached to any activity/fragment: These threads can continue to run beyond the lifetime of the activity/fragment (if any) from which they were spawned.

Threading Components that Attach to an Activity/Fragment

AsyncTask

AsyncTask is the most basic Android component for threading. It’s simple to use and can be good for basic scenarios.

Sample usage:


public class ExampleActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new MyTask().execute(url); } private class MyTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String url = params[0]; return doSomeWork(url); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // do something with result } } }

AsyncTask, however, falls short if you need your deferred task to run beyond the lifetime of the activity/fragment. It is worth noting that even something as simple as screen rotation can cause the activity to be destroyed.


Loaders

Loaders are the solution for the problem mentioned above. Loaders can automatically stop when the activity is destroyed, and can also restart themselves after the activity is recreated.


There are mainly two types of loaders: AsyncTaskLoader and CursorLoader. You will learn more about CursorLoader later in this article.


AsyncTaskLoader is similar to AsyncTask, but a bit more complicated.

Sample usage:
public class ExampleActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLoaderManager().initLoader(1, null, new MyLoaderCallbacks());
    }
    
    private class MyLoaderCallbacks implements LoaderManager.LoaderCallbacks {

        @Override
        public Loader onCreateLoader(int id, Bundle args) {
            return new MyLoader(ExampleActivity.this);
        }

        @Override
        public void onLoadFinished(Loader loader, Object data) {

        }

        @Override
        public void onLoaderReset(Loader loader) {

        }
    }

    private class MyLoader extends AsyncTaskLoader {

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

        @Override
        public Object loadInBackground() {
            return someWorkToDo();
        }
        
    }
}
Threading Components that Don’t Attach to an Activity/Fragment

Service

Service is a component that is useful for performing long (or potentially long) operations without any UI.

Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

Sample usage:

public class ExampleService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        doSomeLongProccesingWork();
        stopSelf();

        return START_NOT_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
With Service, it is your responsibility to stop it when its work is complete by calling either the stopSelf()or the stopService() method.

IntentService

Like ServiceIntentService runs on a separate thread, and stops itself automatically after it completes its work.

IntentService is usually used for short tasks that don’t need to be attached to any UI.

Sample usage:

public class ExampleService extends IntentService {
    
    public ExampleService() {
        super("ExampleService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        doSomeShortWork();
    }
}
Seven Threading Patterns in Android

Use Case No. 1: Making a request over network without requiring a response from the server

Sometimes you may want to send an API request to a server without needing to worry about its response. For example, you may be sending a push registration token to your application’s back-end.


Since this involves making a request over the network, you should do it from a thread other than the main thread.


Option 1: AsyncTask or loaders

You can use AsyncTask or loaders for making the call, and it will work.


However, AsyncTask and loaders are both dependent on the lifecycle of the activity. This means you will either need to wait for the call to execute and try to prevent the user from leaving the activity, or hope that it will execute before the activity is destroyed.


Option 2: Service

Service may be a better fit for this use case since it isn’t attached to any activity. It will therefore be able to continue with the network call even after the activity is destroyed. Plus, since the response from the server is not needed, a service wouldn’t be limiting here, either.


However, since a service will begin running on the UI thread, you will still need to manage threading yourself. You will also need to make sure that the service is stopped once the network call is complete.

This would require more effort than should be necessary for such a simple action.

Option 3: IntentService

This, in my opinion, would be the best option.

Since IntentService doesn’t attach to any activity and it runs on a non-UI thread, it serves our needs perfectly here. Moreover, IntentService stops itself automatically, so there is no need to manually manage it, either.


Use Case No. 2: Making a network call, and getting the response from the server

This use case is probably a bit more common. For example, you may want to invoke an API in the back-end and use its response to populate fields on the screen.


Option 1: Service or IntentService

Although a Service or an IntentService fared well for the previous use case, using them here wouldn’t be a good idea. Trying to get data out of a Service or an IntentService into the main UI thread would make things very complex.


Option 2: AsyncTask or loaders

At first blush, AsyncTask or loaders would appear to be the obvious solution here. They are easy to use—simple and straightforward.


However, when using AsyncTask or loaders, you’ll notice that there is a need to write some boilerplate code. Moreover, error handling becomes a major chore with these components. Even with a simple networking call, you need to be aware of potential exceptions, catch them, and act accordingly. This forces us to wrap our response in a custom class containing the data, with possible error information, and a flag indicates if the action was successful or not.


That’s quite a lot of work to do for every single call. Fortunately, there is now a much better and simpler solution available: RxJava.


Option 3: RxJava

You may heard about RxJava, the library developed by Netflix. It’s almost magic in Java.


RxAndroid lets you use RxJava in Android, and makes dealing with asynchronous tasks a breeze. You can learn more about RxJava on Android here.


RxJava provides two components: Observer and Subscriber.


An observer is a component that contains some action. It performs that action and returns the result if it succeeds or an error if it fails.


A subscriber, on the other hand, is a component that can receive the result (or error) from an observable, by subscribing to it.


With RxJava, you first create an observable:

Observable.create((ObservableOnSubscribe<Data>) e -> {
    Data data = mRestApi.getData();
    e.onNext(data);
})
Once the observable has been created, you can subscribe to it.


With the RxAndroid library, you can control the thread in which you want to execute the action in the observable, and the thread in which you want to get the response (i.e., the result or error).


You chain on the observable with these two functions:

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()
Schedulers are components that execute the action in a certain thread. AndroidSchedulers.mainThread() is the scheduler associated with the main thread.


Given that our API call is mRestApi.getData() and it returns a Data object, the basic call can look like this:

Observable.create((ObservableOnSubscribe<Data>) e -> {
            try { 
                        Data data = mRestApi.getData();
                        e.onNext(data);
            } catch (Exception ex) {
                        e.onError(ex);
            }
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(match -> Log.i(“rest api, "success"),
            throwable -> Log.e(“rest api, "error: %s" + throwable.getMessage()));
Without even going into other benefits of using RxJava, you can already see how RxJava allows us to write more mature code by abstracting away the complexity of threading.


Use Case No. 3: Chaining network calls

For network calls that need to be performed in sequence (i.e., where each operation depends upon the response/result of the previous operation), you need to be particularly careful about generating spaghetti code.


For example, you may have to make an API call with a token that you need to fetch first through another API call.


Option 1: AsyncTask or loaders

Using AsyncTask or loaders will almost definitely lead to spaghetti code. The overall functionality will be difficult to get right and will require a tremendous amount of redundant boilerplate code throughout your project.


Option 2: RxJava using flatMap

In RxJava, the flatMap operator takes an emitted value from the source observable and returns another observable. You can create an observable, and then create another observable using the emitted value from the first one, which will basically chain them.

Step 1. Create the observable that fetches the token:

public Observable<String> getTokenObservable() {
    return Observable.create(subscriber -> {
        try {
            String token = mRestApi.getToken();
            subscriber.onNext(token);

        } catch (IOException e) {
            subscriber.onError(e);
        }
    });
}
Step 2. Create the observable that gets the data using the token:

public Observable<String> getDataObservable(String token) {
    return Observable.create(subscriber -> {
        try {
            Data data = mRestApi.getData(token);
            subscriber.onNext(data);

        } catch (IOException e) {
            subscriber.onError(e);
        }
    });
}
Step 3. Chain the two observables together and subscribe:

getTokenObservable()
.flatMap(new Function<String, Observable<Data>>() {
    @Override
    public Observable<Data> apply(String token) throws Exception {
        return getDataObservable(token);
    }
})
.subscribe(data -> {
    doSomethingWithData(data)
}, error -> handleError(e));
Note that use of this approach is not limited to network calls; it can work with any set of actions that needs to be run in a sequence but on separate threads.


All of the use cases above are quite simple. Switching between threads only happened after each finished its task. More advanced scenarios—for example, where two or more threads need to actively communicate with each other—can be supported by this approach as well.


Use Case No. 4: Communicate with the UI thread from another thread

Consider a scenario where you would like to upload a file and update the user interface once it is complete.


Since uploading a file can take a long time, there is no need to keep the user waiting. You could use a service, and probably IntentService, for implementing the functionality here.


In this case, however, the bigger challenge is being able to invoke a method on the UI thread after the file upload (which was performed in a separate thread) is complete.


Option 1: RxJava inside the service

RxJava, either on its own or inside an IntentService, may not be ideal. You will need to use a callback-based mechanism when subscribing to an Observable, and IntentService is built to do simple synchronous calls, not callbacks.


On the other hand, with a Service, you will need to manually stop the service, which requires more work.


Option 2: BroadcastReceiver

Android provides this component, which can listen to global events (e.g., battery events, network events, etc.) as well as custom events. You can use this component to create a custom event that is triggered when the upload is complete.


To do this, you need to create a custom class that extends BroadcastReceiver, register it in the manifest, and use Intent and IntentFilter to create the custom event. To trigger the event, you will need the sendBroadcast method.

Manifest:

<receiver android:name="UploadReceiver">
   
    <intent-filter>
        <action android:name="com.example.upload">
        </action>
    </intent-filter>
   
</receiver>
Receiver:

public class UploadReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getBoolean(“success”, false) {
            Activity activity = (Activity)context;
            activity.updateUI();
    }

}
Sender:

Intent intent = new Intent();
intent.setAction("com.example.upload"); 
sendBroadcast(intent);
This approach is a viable option. But as you have noticed, it involves some work, and too many broadcasts can slow things down.


Option 3: Using Handler

Handler is a component that can be attached to a thread and then made to perform some action on that thread via simple messages or Runnable tasks. It works in conjunction with another component, Looper, which is in charge of message processing in a particular thread.


When a Handler is created, it can get a Looper object in the constructor, which indicates which thread the handler is attached to. If you want to use a handler attached to the main thread, you need to use the looper associated with the main thread by calling Looper.getMainLooper().


In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable:

Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {
            // update the ui from here                
        }
    });
This approach is a lot better than the first one, but there is an even simpler way to do this…


Option 3: Using EventBus

EventBus, a popular library by GreenRobot, enables components to safely communicate with one another. Since our use case is one where we only want to update the UI, this can be the simplest and safest choice.

Step 1. Create an event class. e.g., UIEvent.

Step 2. Subscribe to the event.

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onUIEvent(UIEvent event) {/* Do something */};

 register and unregister eventbus : 

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}
Step 3. Post the event: EventBus.getDefault().post(new UIEvent());

With the ThreadMode parameter in the annotation, you are specifying the thread on which you would like to subscribe for this event. In our example here, we are choosing the main thread, since we will want the receiver of the event to be able to update the UI.


You can structure your UIEvent class to contain additional information as necessary.

In the service:

class UploadFileService extends IntentService {
    // …
    Boolean success = uploadFile(File file);
    EventBus.getDefault().post(new UIEvent(success));
    // ...
}
In the activity/fragment:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onUIEvent(UIEvent event) {//show message according to the action success};
Using the EventBus library, communicating between threads becomes much simpler.


Use Case No. 5: Two-way communication between threads based on user actions

Suppose you are building a media player and you want it to be able to continue playing music even when the application screen is closed. In this scenario, you will want the UI to be able to communicate with the media thread (e.g., play, pause, and other actions) and will also want the media thread to update the UI based on certain events (e.g. error, buffering status, etc).


A full media player example is beyond the scope of this article. You can, however, find good tutorials here and here.


Option 1: Using EventBus

You could use EventBus here. However, it is generally unsafe to post an event from the UI thread and receive it in a service. This is because you have no way of knowing whether the service is running when you have sent the message.


Option 2: Using BoundService

BoundService is a Service that is bound to an activity/fragment. This means that the activity/fragment always knows if the service is running or not and, in addition, it gets access to the service’s public methods.

To implement it, you need to create a custom Binder inside the service and create a method that returns the service.

public class MediaService extends Service {

    private final IBinder mBinder = new MediaBinder();

    public class MediaBinder extends Binder {
        MediaService getService() {
            // Return this instance of LocalService so clients can call public methods
            return MediaService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

}
To bind the activity to the service, you need to implement ServiceConnection, which is the class monitoring the service status, and use the method bindService to make the binding:

// in the activity
MediaService mService;
// flag indicates the bound status
boolean mBound;

@Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, MediaService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {

            MediaBinder binder = (MediaBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };
You can find a full implementation example here.

To communicate with the service when the user taps on the Play or Pause button, you can bind to the service and then call the relevant public method on the service.


When there is a media event and you want to communicate that back to the activity/fragment, you can use one of the earlier techniques (e.g., BroadcastReceiverHandler, or EventBus).


Use Case No. 6: Executing actions in parallel and getting results

Let’s say you are building a tourist app and you want to show attractions on a map fetched from multiple sources (different data providers). Since not all of the sources may be reliable, you may want to ignore the ones that have failed and continue to render the map anyway.


To parallelize the process, each API call must take place in a different thread.


Option 1: Using RxJava

In RxJava, you can combine multiple observables into one using the merge() or concat() operators. You can then subscribe on the “merged” observable and wait for all results.

This approach, however, won’t work as expected. If one API call fails, the merged observable will report an overall failure.


Option 2: Using native Java components

The ExecutorService in Java creates a fixed (configurable) number of threads and executes tasks on them concurrently. The service returns a Future object that eventually returns all results via the invokeAll() method.


Each task you send to the ExecutorService should be contained in Callable interface, which is an interface for creating a task that can throw an exception.


Once you get the results from invokeAll(), you can check every result and proceed accordingly.

Let’s say, for example, that you have three attraction types coming in from three different endpoints and you want to make three parallel calls:

ExecutorService pool = Executors.newFixedThreadPool(3);
    List<Callable<Object>> tasks = new ArrayList<>();
    tasks.add(new Callable<Object>() {
        @Override
        public Integer call() throws Exception {
            return mRest.getAttractionType1();
        }
    });

    // ...

    try {
        List<Future<Object>> results = pool.invokeAll(tasks);
        for (Future result : results) {
        try {
            Object response = result.get();
            if (response instance of AttractionType1... {}
            if (response instance of AttractionType2... {}
                ...
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
This way, you are running all of the actions in parallel. You can, therefore, check for errors in each action separately and ignore individual failures as appropriate.

This approach is easier than using RxJava. It is simpler, shorter, and doesn’t fail all actions because of one exception.


Use Case #7: Querying local SQLite database

When dealing with a local SQLite database, it is recommended that the database be used from a background thread, since database calls (especially with large databases or complex queries) can be time consuming, resulting in the UI freezing.

When querying for SQLite data, you get a Cursor object that can then be used to fetch the actual data.

Cursor cursor = getData();
String name = cursor.getString(<colum_number>);

Option 1: Using RxJava

You can use RxJava and get the data from the database, just as we’re getting data from our back-end:

public Observable<Cursor> getLocalDataObservable() {
    return Observable.create(subscriber -> {
        Cursor cursor = mDbHandler.getData();
        subscriber.onNext(cursor);
    });
}
You can use the observable returned by getLocalDataObservable() as follows:

getLocalDataObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
 .subscribe(cursor -> String name = cursor.getString(0),
                   throwable -> Log.e(“db, "error: %s" + throwable.getMessage()));
While this is certainly a good approach, there is one that is even better, since there is a component that is built just for this very scenario.


Option 2: Using CursorLoader + ContentProvider

Android provides CursorLoader, a native component for loading SQLite data and managing the corresponding thread. It’s a Loader that returns a Cursor, which we can use to get the data by calling simple methods such as getString()getLong(), etc.

public class SimpleCursorLoader extends FragmentActivity implements
LoaderManager.LoaderCallbacks<Cursor> {

  public static final String TAG = SimpleCursorLoader.class.getSimpleName();
  private static final int LOADER_ID = 0x01;
  private TextView textView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_cursor_loader);
    textView = (TextView) findViewById(R.id.text_view);
    getSupportLoaderManager().initLoader(LOADER_ID, null, this);

  }

  public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

    return new CursorLoader(this,
      Uri.parse("content://com.github.browep.cursorloader.data")
      , new String[]{"col1"}, null, null, null);
    }

    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
      if (cursor != null && cursor.moveToFirst()) {
        String text =  textView.getText().toString();
        while (cursor.moveToNext()) {
          text += "<br />" + cursor.getString(1);
          cursor.moveToNext();
        }
        textView.setText(Html.fromHtml(text) );
      }
    }

    public void onLoaderReset(Loader<Cursor> cursorLoader) {
      
    }

}
CursorLoader works with the ContentProvider component. This component provides a plethora of real-time database features (e.g., change notifications, triggers, etc.) that enables developers to implement a better user experience much more easily.


There’s no Silver Bullet Solution to Threading in Android

Android provides many ways to handle and manage threads, but none of them are silver bullets.

Choosing the right threading approach, depending on your use case, can make all the difference in making the overall solution easy to implement and understand. The native components fit well for some cases, but not for all. The same applies for fancy third-party solutions.


I hope you will find this article useful when working on your next Android project. Share with us your experience of threading in Android or any use case where the above solutions work well—or don’t, for that matter—in the comments below.

About the author

Eliran Goshen, Israel

Source: toptal.com
Share on Google Plus
    Blogger Comment

1 comments: