Quantcast
Channel: SCN : Blog List - SMP Developer Center
Viewing all articles
Browse latest Browse all 370

Implementation of State Machine for a Long Running Background Task in an Android Service

$
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 delay of 1000 ms). This background task has been splitted 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 from a background service to the frontend UI through Android messenger framework.


So lets 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;

publicclassMainActivityextends Activity implements OnClickListener{
 
privatestaticfinalint CONNECTING = 1;
 
privatestaticfinalint CONNECTED = 2;
 
privatestaticfinalint DOWNLOADSTARTED = 3;
 
privatestaticfinalint DOWNLOADFINISHED = 4;
 
  Button startButton;
 
private MessageHandler handler;
 
privatestatic MainActivity mMainActivity;
 
 
public Messenger mMessenger = new Messenger(new MessageHandler(this));
 
privateclassMessageHandlerextends Handler{
 
private Context c;
 
  MessageHandler(Context c){
  
this.c = c;
  }
  @Override
       
publicvoid 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
   
protectedvoid onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMainActivity =
this;
        startButton = (Button)findViewById(R.id.button1);
       
        startButton.setOnClickListener(
this);
    }


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


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





Now lets 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
  
publicvoid 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
    
// background priority so CPU-intensive work will not disrupt our UI.
     HandlerThread thread =
new HandlerThread("ServiceStartArguments",
             Thread.NORM_PRIORITY);
     thread.start();

    
// Get the HandlerThread's Looper and use it for our Handler
     mServiceLooper = thread.getLooper();
     mServiceHandler =
new ServiceHandler(mServiceLooper);
   }

The service class also has a Handler class called ServiceHandler through which we send messages from the service to the thread’s message loop. Inside the message loop, we actually accomplish the long running task. Lets have a look at this ServiceHandler class


privatefinalclassServiceHandlerextends Handler {
      
public ServiceHandler(Looper looper) {
          
super(looper);
       }
       @Override
      
publicvoid handleMessage(Message msg) {
          
     
       Messenger messenger= MainActivity.getMainActivity().mMessenger;
  
         
try {
          
          
          messenger.send(Message.obtain(
null, CONNECTING, "Connecting"));
         
// Normally we would do some work here, like download a file.
          
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
// Normally we would do some work here, like download a file.
          
// For our sample, we just sleep for 10 seconds.
 
  messenger.send(Message.obtain(
null, CONNECTED, "Connected"));
 
// Normally we would do some work here, like download a file.
        
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
 
  messenger.send(Message.obtain(
null, DOWNLOADSTARTED, "Download Started"));
 
// Normally we would do some work here, like download a file.
        
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
 
  messenger.send(Message.obtain(
null, DOWNLOADFINISHED, "Download Finished"));
 
 
  }
catch (InterruptedException e) {
 
// TODO Auto-generated catch block
  e.printStackTrace();
  }
catch (RemoteException e) {
 
// TODO Auto-generated catch block
  e.printStackTrace();
  }
          
// Stop the service using the startId, so that we don't stop
          
// the service in the middle of handling another job
           stopSelf(msg.arg1);
       }
   }

As it becomes clear from the above code that in this overridden HandleMessage function of the service handler, we acquire a reference to the messenger of the main activity and it falls through different states like “Connecting”, “Connected”, “Start Downloading” and “Finish Downloading”. In each state a different integer constant is being passed to the UI thread through the messenger.


In the main UI thread the handler function of the messenger handles these messages from the service and displays the status of the each state.


After that the service stops itself.


package com.somitsolutions.android.example.statepatterninservice;


import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

publicclassLongRunningServiceextends Service {
 
 
privatestaticfinalint CONNECTING = 1;
 
privatestaticfinalint CONNECTED = 2;
 
privatestaticfinalint DOWNLOADSTARTED = 3;
 
privatestaticfinalint DOWNLOADFINISHED = 4;
 
 
private Looper mServiceLooper;
 
private ServiceHandler mServiceHandler; // Handler that receives messages from the thread
 
privatefinalclassServiceHandlerextends Handler {
      
public ServiceHandler(Looper looper) {
          
super(looper);
       }
       @Override
      
publicvoid handleMessage(Message msg) {
          
     
       Messenger messenger= MainActivity.getMainActivity().mMessenger;
  
         
try {
          
          
          messenger.send(Message.obtain(
null, CONNECTING, "Connecting"));
         
// Normally we would do some work here, like download a file.
          
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
// Normally we would do some work here, like download a file.
          
// For our sample, we just sleep for 10 seconds.
 
  messenger.send(Message.obtain(
null, CONNECTED, "Connected"));
 
// Normally we would do some work here, like download a file.
        
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
 
  messenger.send(Message.obtain(
null, DOWNLOADSTARTED, "Download Started"));
 
// Normally we would do some work here, like download a file.
        
// For our sample, we just sleep for 10 seconds.
  Thread.sleep(1000);
 
 
  messenger.send(Message.obtain(
null, DOWNLOADFINISHED, "Download Finished"));
 
 
  }
catch (InterruptedException e) {
 
// TODO Auto-generated catch block
  e.printStackTrace();
  }
catch (RemoteException e) {
 
// TODO Auto-generated catch block
  e.printStackTrace();
  }
          
// Stop the service using the startId, so that we don't stop
          
// the service in the middle of handling another job
           stopSelf(msg.arg1);
       }
   }
 
  @Override
  
publicvoid 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
    
// background priority so CPU-intensive work will not disrupt our UI.
     HandlerThread thread =
new HandlerThread("ServiceStartArguments",
             Thread.NORM_PRIORITY);
     thread.start();

    
// Get the HandlerThread's Looper and use it for our Handler
     mServiceLooper = thread.getLooper();
     mServiceHandler =
new ServiceHandler(mServiceLooper);
   }

   @Override
  
publicint onStartCommand(Intent intent, int flags, int startId) {
       Toast.makeText(
this, "download service starting", Toast.LENGTH_SHORT).show();

      
// For each start request, send a message to start a job and deliver the
      
// start ID so we know which request we're stopping when we finish the job
       Message msg = mServiceHandler.obtainMessage();
       msg.arg1 = startId;
       mServiceHandler.sendMessage(msg);
       
      
// If we get killed, after returning from here, restart
      
return START_STICKY;
   }

   @Override
  
public IBinder onBind(Intent intent) {
      
// We don't provide binding, so return null
      
returnnull;
   }

   @Override
  
publicvoid onDestroy() {
     Toast.makeText(
this, "service done", Toast.LENGTH_SHORT).show();
   }
  }


The main.xml layout file looks like the following:



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools=
"http://schemas.android.com/tools"
    android:layout_width=
"match_parent"
    android:layout_height=
"match_parent"
    android:paddingBottom=
"@dimen/activity_vertical_margin"
    android:paddingLeft=
"@dimen/activity_horizontal_margin"
    android:paddingRight=
"@dimen/activity_horizontal_margin"
    android:paddingTop=
"@dimen/activity_vertical_margin"
    tools:context=
".MainActivity">

    <Button
        android:id=
"@+id/button1"
        android:layout_width=
"wrap_content"
        android:layout_height=
"wrap_content"
        android:layout_alignParentTop=
"true"
        android:layout_centerHorizontal=
"true"
        android:layout_marginTop=
"165dp"
        android:text=
"Start Service" />

</RelativeLayout>


And the manifest file of this application is as follows:


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

    <uses-sdk
        android:minSdkVersion=
"8"
        android:targetSdkVersion=
"17" />

    <application
        android:allowBackup=
"true"
        android:icon=
"@drawable/ic_launcher"
        android:label=
"@string/app_name"
        android:theme=
"@style/AppTheme">
        <activity
            android:name=
"com.somitsolutions.android.example.statepatterninservice.MainActivity"
            android:label=
"@string/app_name">
            <intent-filter>
                <action android:name=
"android.intent.action.MAIN" />

                <category android:name=
"android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=
".LongRunningService"></service>
    </application>
   
</manifest>


Hope it clears some of the ideas behind Android messenger and how we can use it for notification from a background service to the frontend UI.



Viewing all articles
Browse latest Browse all 370

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>