Android Basics : Learn how to use a Handler with IntentService to update the Main Thread

In the last Article you saw how to call an IntentService. Then you printed a Log statement in the background thread, once the service completed.

If you want to display a message in the Main Thread then you can use a Handler. A Handler allows you to access the Main Thread once the service is complete.

Here is the sample source code to achieve this.

    protected void onHandleIntent(Intent intent) {
        Log.v(TAG, "In onHandleIntent. Message will be printed after 10sec");
        if (intent != null) {
            synchronized (this){
                try {
                } catch (InterruptedException e) {
                Log.v(TAG, "Service started");
       Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Service Completed" , Toast.LENGTH_SHORT).show();

Complete source code is available here.

Android Basics – Using Handler and Runnable to Schedule Code

You will Learn about

  • Handler
  • post method
  • postDelayed method
  • Main Thread

Android runs every App in a separate Process for Security and Scalability.

So when you Run your App Android starts a Thread for the same.

A New Thread

Now if you want to run code which needs to run in the background then its recommended to use a separate thread for doing that.

This will not only improve user experience but also prevent delays and crashes.

Continue reading “Android Basics – Using Handler and Runnable to Schedule Code”