UrbanPro
true

Learn Mobile App Development from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Implementation of a state machine for a long running background task in Android

Somenath Mukhopadhyay
03/04/2017 0 0

In the below example I will show how we can break a long-running background task running in a service into different states of a state machine and notify the front end UI about each and every stage as they occur in the service. Here I have used a service called LongRunningService which actually (theoretically) does the task of downloading a big file from a network server (however, for simplicity I have just stubbed out the actual download code with a thread having a delay of 1000 ms). This background task has been split into different states according to the state machine like “Start Connection”, “Connection Completed”, “Start Downloading” and “Stop Downloading”. This application also showcases the concept of communicating with a background service to the frontend UI through Android messenger framework.

So let's start digging into the source code of the application.

First of all the main Activity class. 

As it is clear from the code that the main activity has a messenger whose message handling part has been defined by a class called MessageHandler (derived from Handler). This is the messenger object through which the background service notifies the UI thread.

The UI has a button. Upon clicking it, it starts the service and as soon as it starts the service the service starts notifying about the different states of the Service through the messenger.

This is pretty simple. Right!!!

The class MainActivity.Java

package com.somitsolutions.android.example.statepatterninservice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
private static final int CONNECTING = 1;
private static final int CONNECTED = 2;
private static final int DOWNLOADSTARTED = 3;
private static final int DOWNLOADFINISHED = 4;

Button startButton;
private MessageHandler handler;
private static MainActivity mMainActivity;

public Messenger mMessenger = new Messenger(new MessageHandler(this));
private class MessageHandler extends Handler{
private Context c;

MessageHandler(Context c){
this.c = c;
}
@Override
       public void handleMessage(Message msg) {
switch(msg.what){
case CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_LONG).show();
break;
case CONNECTED:
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
break;
case DOWNLOADSTARTED:
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
break;
case DOWNLOADFINISHED:
Toast.makeText(getApplicationContext(), "Download Finished", Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);

}
}
}
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       mMainActivity = this;
       startButton = (Button)findViewById(R.id.button1);
       
       startButton.setOnClickListener(this);
   }


   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.main, menu);
       return true;
   }
   public static MainActivity getMainActivity(){
    return mMainActivity;
   }


@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent serv = new Intent(MainActivity.this, LongRunningService.class);
       startService(serv);
}
}

Now, let's start digging the LongrunningServivce class.

As we know that a service usually runs in the main thread. Hence the UI thread may seem to be frozen in case of a long background service. To overcome that a background thread is being created the moment one starts the service and the task is executed in that thread. This is clear from the following piece of code.

 

@Override
 public void onCreate() {
   // Start up the thread running the service.  Note that we create a
   // separate thread because the service normally runs in the process's
   // main thread, which we don't want to block.  We also make it
   

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

10 Ways My Life Changed When I Learned To Code
1. I have freedom to make my own schedule. 2. I earn more, but work fewer hours. 3. I can say “no” to job offers. 4. People come to me asking if I can work for them. 5. I never have to...

Broadcast Receiver in Android
How you ever wonder how all your app detects OS events like when the internet is turned ON, the incoming call is coming, battery low etc. like that? Yes, it is because of Android OS build in Event, "Broadcast...

Microsoft Cognitive Face API (iOS) - Identifying Faces From an Image and Extracting Facial Features Like Age, Gender, Emotions.
Microsoft Cognitive Services is a set of APIs, SDKs and services available to developers to make their applications more intelligent, engaging and discoverable. You can basically do a lot of cool stuffs...

Xamarin Evolve 2016
Xamarin is one of the best cross-platform frameworks I have ever seen in my life. That is the biggest sell, you can write 1 mobile app and then “tailor” it for 3 different platforms. Great....

What Would Be Life Cycle Of A Fresher After Campus In An IT Company?
1. Basic Technical Training: Since freshers are not subject matter experts so gone through 3 - 6 months basic technical training within Organization. 2. Technical Assessment: HR sends freshers to various...
X

Looking for Mobile App Development Classes?

The best tutors for Mobile App Development Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Mobile App Development with the Best Tutors

The best Tutors for Mobile App Development Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more