SlideShare a Scribd company logo
Implementation of a State machine for a long
running background task in an Android service
by
Somenath Mukhopadhyay
som.mukhopadhyay@gmail.com

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
import
import
import

android.app.Activity;
android.content.Context;
android.content.Intent;
android.os.Bundle;
import
import
import
import
import
import
import
import

android.os.Handler;
android.os.Message;
android.os.Messenger;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
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(),
Toast.LENGTH_LONG).show();
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
case DOWNLOADSTARTED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
case DOWNLOADFINISHED:
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
break;
default:
super.handleMessage(msg);

"Connecting",

"Connected",

"Download Started",

"Download Finished",
}
}
}
@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 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
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
// 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
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void 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
import
import
import
import
import
import
import
import

android.app.Service;
android.content.Intent;
android.os.Handler;
android.os.HandlerThread;
android.os.IBinder;
android.os.Looper;
android.os.Message;
android.os.Messenger;
android.os.RemoteException;
import android.widget.Toast;
public class LongRunningService extends Service {
private
private
private
private

static
static
static
static

final
final
final
final

int
int
int
int

CONNECTING = 1;
CONNECTED = 2;
DOWNLOADSTARTED = 3;
DOWNLOADFINISHED = 4;

private Looper mServiceLooper;
private ServiceHandler mServiceHandler; // Handler that receives messages from
the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void 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
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
// 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
public int 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
return null;
}
@Override
public void 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.

More Related Content

What's hot

Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodb
ikailan
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
Ilya Grigorik
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachine
Christopher Spring
 
Tornado web
Tornado webTornado web
Tornado web
kurtiss
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
biyu
 
Domains!
Domains!Domains!
Mule esb json_to_object
Mule esb json_to_objectMule esb json_to_object
Mule esb json_to_object
Davide Rapacciuolo
 
A guide to EPiServer CMS Scheduled Job
A guide to EPiServer CMS Scheduled JobA guide to EPiServer CMS Scheduled Job
A guide to EPiServer CMS Scheduled Job
Paul Graham
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Nuxeo5 - Continuous Integration
Nuxeo5 - Continuous IntegrationNuxeo5 - Continuous Integration
Nuxeo5 - Continuous IntegrationPASCAL Jean Marie
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
moret1979
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
All about CFThread - CFUnited 2008
All about CFThread - CFUnited 2008All about CFThread - CFUnited 2008
All about CFThread - CFUnited 2008
Rupesh Kumar
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Yet another node vs php
Yet another node vs phpYet another node vs php
Yet another node vs php
Anirban Bhattacharya
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Framework
jfarcand
 
Netty - anfix tech&beers
Netty - anfix tech&beersNetty - anfix tech&beers
Netty - anfix tech&beersjorgecarabias
 
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
GeeksLab Odessa
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
 

What's hot (20)

Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodb
 
No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010No Callbacks, No Threads - RailsConf 2010
No Callbacks, No Threads - RailsConf 2010
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachine
 
Tornado web
Tornado webTornado web
Tornado web
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Domains!
Domains!Domains!
Domains!
 
Mule esb json_to_object
Mule esb json_to_objectMule esb json_to_object
Mule esb json_to_object
 
A guide to EPiServer CMS Scheduled Job
A guide to EPiServer CMS Scheduled JobA guide to EPiServer CMS Scheduled Job
A guide to EPiServer CMS Scheduled Job
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Nuxeo5 - Continuous Integration
Nuxeo5 - Continuous IntegrationNuxeo5 - Continuous Integration
Nuxeo5 - Continuous Integration
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
All about CFThread - CFUnited 2008
All about CFThread - CFUnited 2008All about CFThread - CFUnited 2008
All about CFThread - CFUnited 2008
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Yet another node vs php
Yet another node vs phpYet another node vs php
Yet another node vs php
 
The Atmosphere Framework
The Atmosphere FrameworkThe Atmosphere Framework
The Atmosphere Framework
 
Netty - anfix tech&beers
Netty - anfix tech&beersNetty - anfix tech&beers
Netty - anfix tech&beers
 
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
 

Similar to Implementation of a state machine for a longrunning background task in android service

Build your own secure mail server on the cloud using Amazon Web Services
Build your own secure mail server on the cloud using Amazon Web ServicesBuild your own secure mail server on the cloud using Amazon Web Services
Build your own secure mail server on the cloud using Amazon Web Servicesponukumatla joel nishanth
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machen
André Goliath
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
deepfountainconsulting
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
Max Kleiner
 
DEF CON 23: Stick That In Your (root)Pipe & Smoke It
DEF CON 23: Stick That In Your (root)Pipe & Smoke ItDEF CON 23: Stick That In Your (root)Pipe & Smoke It
DEF CON 23: Stick That In Your (root)Pipe & Smoke It
Synack
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
Aravindharamanan S
 
Embedded systems
Embedded systems Embedded systems
Embedded systems
Katy Anton
 
Mail
MailMail
Mail
Md Shihab
 
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps   sumit sidharthNew and improved hacking oracle from web apps   sumit sidharth
New and improved hacking oracle from web apps sumit sidharth
owaspindia
 
C++ course start
C++ course startC++ course start
C++ course startNet3lem
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraumpatricklee
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
Su Zin Kyaw
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
John Congdon
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
Somenath Mukhopadhyay
 
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesBuild Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Robert Li
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
Containers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific TrioContainers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific Trio
Jérôme Petazzoni
 
Celery with python
Celery with pythonCelery with python
Celery with python
Alexandre González Rodríguez
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
Stacy Devino
 

Similar to Implementation of a state machine for a longrunning background task in android service (20)

Build your own secure mail server on the cloud using Amazon Web Services
Build your own secure mail server on the cloud using Amazon Web ServicesBuild your own secure mail server on the cloud using Amazon Web Services
Build your own secure mail server on the cloud using Amazon Web Services
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Das kannste schon so machen
Das kannste schon so machenDas kannste schon so machen
Das kannste schon so machen
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
 
DEF CON 23: Stick That In Your (root)Pipe & Smoke It
DEF CON 23: Stick That In Your (root)Pipe & Smoke ItDEF CON 23: Stick That In Your (root)Pipe & Smoke It
DEF CON 23: Stick That In Your (root)Pipe & Smoke It
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
Embedded systems
Embedded systems Embedded systems
Embedded systems
 
Mail
MailMail
Mail
 
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps   sumit sidharthNew and improved hacking oracle from web apps   sumit sidharth
New and improved hacking oracle from web apps sumit sidharth
 
C++ course start
C++ course startC++ course start
C++ course start
 
JavaScript Sprachraum
JavaScript SprachraumJavaScript Sprachraum
JavaScript Sprachraum
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
Active object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architectureActive object of Symbian in the lights of client server architecture
Active object of Symbian in the lights of client server architecture
 
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesBuild Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Containers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific TrioContainers, Docker, and Microservices: the Terrific Trio
Containers, Docker, and Microservices: the Terrific Trio
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
 

More from Somenath Mukhopadhyay

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
Somenath Mukhopadhyay
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
Somenath Mukhopadhyay
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
Somenath Mukhopadhyay
 
Copy on write
Copy on writeCopy on write
Copy on write
Somenath Mukhopadhyay
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
Somenath Mukhopadhyay
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
Somenath Mukhopadhyay
 
Observer pattern
Observer patternObserver pattern
Observer pattern
Somenath Mukhopadhyay
 
Uml training
Uml trainingUml training
Uml training
Somenath Mukhopadhyay
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
Somenath Mukhopadhyay
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
Somenath Mukhopadhyay
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
Somenath Mukhopadhyay
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
Somenath Mukhopadhyay
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
Somenath Mukhopadhyay
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
Somenath Mukhopadhyay
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
Somenath Mukhopadhyay
 
Android services internals
Android services internalsAndroid services internals
Android services internals
Somenath Mukhopadhyay
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Somenath Mukhopadhyay
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
Somenath Mukhopadhyay
 

More from Somenath Mukhopadhyay (20)

Significance of private inheritance in C++...
Significance of private inheritance in C++...Significance of private inheritance in C++...
Significance of private inheritance in C++...
 
Arranging the words of a text lexicographically trie
Arranging the words of a text lexicographically   trieArranging the words of a text lexicographically   trie
Arranging the words of a text lexicographically trie
 
Generic asynchronous HTTP utility for android
Generic asynchronous HTTP utility for androidGeneric asynchronous HTTP utility for android
Generic asynchronous HTTP utility for android
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Memory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bitsMemory layout in C++ vis a-vis polymorphism and padding bits
Memory layout in C++ vis a-vis polymorphism and padding bits
 
Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...Developing an Android REST client to determine POI using asynctask and integr...
Developing an Android REST client to determine POI using asynctask and integr...
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Uml training
Uml trainingUml training
Uml training
 
How to create your own background for google docs
How to create your own background for google docsHow to create your own background for google docs
How to create your own background for google docs
 
The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...The Designing of a Software System from scratch with the help of OOAD & UML -...
The Designing of a Software System from scratch with the help of OOAD & UML -...
 
Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...Structural Relationship between Content Resolver and Content Provider of Andr...
Structural Relationship between Content Resolver and Content Provider of Andr...
 
Flow of events during Media Player creation in Android
Flow of events during Media Player creation in AndroidFlow of events during Media Player creation in Android
Flow of events during Media Player creation in Android
 
Tackling circular dependency in Java
Tackling circular dependency in JavaTackling circular dependency in Java
Tackling circular dependency in Java
 
Implementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgetsImplementation of composite design pattern in android view and widgets
Implementation of composite design pattern in android view and widgets
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Android services internals
Android services internalsAndroid services internals
Android services internals
 
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design patternAndroid Asynctask Internals vis-a-vis half-sync half-async design pattern
Android Asynctask Internals vis-a-vis half-sync half-async design pattern
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Bridge Pattern
Bridge PatternBridge Pattern
Bridge Pattern
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

Implementation of a state machine for a longrunning background task in android service

  • 1. Implementation of a State machine for a long running background task in an Android service by Somenath Mukhopadhyay som.mukhopadhyay@gmail.com 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 import import import android.app.Activity; android.content.Context; android.content.Intent; android.os.Bundle;
  • 2. import import import import import import import import android.os.Handler; android.os.Message; android.os.Messenger; android.view.Menu; android.view.View; android.view.View.OnClickListener; android.widget.Button; 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(), Toast.LENGTH_LONG).show(); break; case CONNECTED: Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); break; case DOWNLOADSTARTED: Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); break; case DOWNLOADFINISHED: Toast.makeText(getApplicationContext(), Toast.LENGTH_LONG).show(); break; default: super.handleMessage(msg); "Connecting", "Connected", "Download Started", "Download Finished",
  • 3. } } } @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 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 public void onCreate() { // Start up the thread running the service. Note that we create a
  • 4. // 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 private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void 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,
  • 5. 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 import import import import import import import import android.app.Service; android.content.Intent; android.os.Handler; android.os.HandlerThread; android.os.IBinder; android.os.Looper; android.os.Message; android.os.Messenger; android.os.RemoteException;
  • 6. import android.widget.Toast; public class LongRunningService extends Service { private private private private static static static static final final final final int int int int CONNECTING = 1; CONNECTED = 2; DOWNLOADSTARTED = 3; DOWNLOADFINISHED = 4; private Looper mServiceLooper; private ServiceHandler mServiceHandler; // Handler that receives messages from the thread private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void 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);
  • 7. 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 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 // 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 public int 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; }
  • 8. @Override public IBinder onBind(Intent intent) { // We don't provide binding, so return null return null; } @Override public void 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" />
  • 9. <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.