Programming Guide to Android Services

Written by:  • Edited by: Simon Hill
Updated Mar 2, 2011
• Related Guides: Android | Android Market | Android Applications

In Android, we have an interesting tool to work with when we want to run background applications or processes. Let's have a look at it!

How Android Services Work

Sometimes, we would like to have an application running in the background of our device, waiting for any change in the system, or maybe we want to run an application with the usual Activities, and a “piece of code” running, in the background that checks in on the Internet, waiting for incoming SMS messages or other events.

If you'd like to start at the beginning, try this tutorial on developing Google Android Applications.

In those cases Android Services are available. They are classes without UI (Activities are classes with UI), so they can be executed in the background, in a separate thread and you can start and stop them from an Activity.

This could be difficult to understand so to make it more clear we'll put up some examples.

Here's the classic example of when a Service would be used: In an audio player. Imagine, you have an MP3 player (downloaded from Android Market, done by yourself or the default media player in the device), you can then select artist, albums, songs... you start playing a song, and then you want to go back to the home screen to start another activity (in this case I'm not talking about Android Activities, its just the common word “activity”), you go to the home screen, but the song you have selected is still playing...

A less classic example. You have a simple RSS reader, with a list that includes all new posts from a very well known blog. A Service will search for updates via the site, and then it will update the screen with the new info. All while running in the background.

Now that we have a more clear understanding of how a Service works, let's move deeper into the Service construction.

Building a Service

First of all, we need to create the Service in the AndroidManifest.xml file. Remember, that every Activity, Service, Content Provider you create in the code, you need to create a reference for here, in the Manifest, if not, the application will not recognize it.

<service android:name=".subpackagename.ServiceName"/>

In the code, we need to create a class that extends from “Service”

public class ServiceName extends Service {

private Timer timer = new Timer();

protected void onCreate() {

super.onCreate();

startservice();

}

}

This is a way to create Services, there are others ways, or the way I use to work with them. Here, we create a Timer, that every X seconds, calls to a method. This is running until we stop it. This can be used, for example, to check updates in an RSS feed. The “Timer” class is used in the startservice method like this

private void startservice() {

timer.scheduleAtFixedRate( new TimerTask() {

public void run() {

//Do whatever you want to do every “INTERVAL”

}

}, 0, INTERVAL);

; }

Where INTERVAL, is the time, every time the run method is executed.

To stop the service, we can stop the timer, for example, when the application is destroyed (in onDestroy())

private void stopservice() {

if (timer != null){

timer.cancel();

}

}

So, this application will be running in the background... But...How do we bind it with Activities? Or how can we start a Service from an Activity? In the next lesson we will delver deeper into Services.

Short term background process

Sometimes we need to accomplish short background tasks. For this, I recommend using AsyncTasks. Here you will find an article that explains how to work with them:

How to work with AsyncTask in Android.


Comments

Showing all 35 comments
 
Guest Dec 6, 2011 7:31 AM
RE: Programming Guide to Android Services
A completely vacuous post, how about providing som actual detail on how to handle service not found errors for example. All the above does is repeat the millions of other posts on how to do the basics rather than how to do it properly
Paulo Aug 8, 2011 12:07 AM
Broadcast receiver
Use a brodcastreceiver to initiate que service after reboot
Neil Aug 3, 2011 5:18 PM
RE: Programming Guide to Android Services
I was thinking, I have seen people set objects to null to make them GC. Why are you not setting the timer = null in onDestroy after you call timer.cancel() ??
abu_alfouz Apr 12, 2011 4:27 AM
Device Clock?
Nice article, but I have a problem with it.

I try the code above and worked fine, but the problem when I change the device clock -> if I change to older date the schedule won't work, if I change it to newer date the schedule will execute all times that should be executed on the lost period.

What I want is that the timer keep executing with same schedule without depending on device clock.

Thank you.
Jbeerdev Feb 15, 2011 11:06 AM
RE: Programming Guide to Android Services
Ayreon if you use Threads for long background process you have the risk that Android kills an activitiy and with it, the thread and whatever task you are doing in background.

For short background process I recommend Asyntask or Threads

For longs one, I recommend Intent Services.
Ayreon Feb 15, 2011 11:01 AM
Do not follow this guide!
I'd suggest everybody to read the manual instead, using timers in a Services is definitely a misuse! Use threads/handlers instead!
chetan k s Feb 15, 2011 6:49 AM
Java/j2ee openings
we are also continuously HIRING and seek your referrals for:
1) JAVA, J2EE (3-5 years)

5. UI Developer
Strong in Photoshop, HTML, CSS and JavaScript.
Very good in Flash, XML and XHTML
Very good logical & analytical thinking.
Very good communication/client communication
Good to have: ASP.Net, JavaScript libraries and UI standards.
2) Embedded linux (3-5 years)
3) Linux, Kernel development (3 to 5 yrs)
Please send in your updated Resume to chetan.ks@opterna.com
Jin Dec 1, 2010 11:55 PM
here's how to start
//ImplicitlystartaService
IntentmyIntent=newIntent(MyService.ORDER_PIZZA);
myIntent.putExtra("TOPPING","Margherita");
startService(myIntent);
//ExplicitlystartaService
startService(newIntent(this,MyService.class));
Computer Tutorials Nov 22, 2010 11:00 AM
A very useful one
A very well explained and focused one.
Kerric Nov 13, 2010 10:33 PM
Start Service
Hello,

I am viewing your tutorial about services in android and it's pretty interesting.

I am trying to make a service in my app, however the service is not being 'Started' when I start it.

my code is simple:
Intent int = new Intent(this, MyServiceClass.class);
startService(int);

I have in the service "onCreate" overriden method a simple bool which should return true if the service is working correctly but unfortunately it's not.

After checking the references on android.com, do i need to declare methods like:
onServiceConnected
onServiceDisconnected
doBindService
doUnbindService
etc...etc...

or are those methods only used for communication with the service from outsite the current process?

Thank you for the help.
Regards
Amit Goyal Oct 3, 2010 2:37 PM
Want Dialog fom Service
hiiii
I want to create a "yes" or "No" dialog box when my Background service detect a data from udp Socket.But after my action on that dialog box., my current Activty should run from same point when the diolog Box appear .
JN Raju Sep 29, 2010 6:39 AM
Capture Screen as a background service
Hello, i am new for android. I have one requirement that. capture the device screen for every 5second. Can any body please help to me , how to write service for capture the device screen.
George Aug 24, 2010 2:02 PM
can't auto start service
Hi, ur tutorial helps for understand a little about Services, how can i do that services starts from his own or at least start or do something. my code:

package com.example;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MainService extends Service {
@Override
public IBinder onBind(Intent intent) {
Log.e("Service", "onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
Log.e("Service", "onCreate");
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
Log.e("Service", "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.e("Service", "onStart");
}
}


int th manifiest:

<service android:enabled="true" android:name=".MainService" />


i need the service start when android starts and dont know if that's possible.

Hope some1 can help me, because i dont know what im i missing

Thanks
Jbeerdev Aug 17, 2010 4:12 PM
RE: Programming Guide to Android Services
Eh guys. I have written more about background process and multitasking:

http://www.brighthub.com/mobile/google-android/articles/82805.aspx
Narasimha Aug 11, 2010 4:31 AM
android screen capture code implementation
Hi,

I am trying to develop a Remote Test tool application which runs in background under Android 1.5+ SDK Emulator version Environment.

The purpose of this application is to capture the screen shots on Real Physical Device OR Emulator and store in SDCARD, whenever
User browses from one screen to another, using this application during running phase. If you have related info / code package for the same, please send it. Thanks. I appreciate your valuable feedback/support and oblige.

Looking forward to hear from you soon,
Thanks,
Narasimha
mainu Aug 10, 2010 3:26 AM
Regarding the animation
Hi Jbeer,
I am unable to find any article in this site for the animation. please help. I always found this site very active and helpful for me.
Please give me the link if u have any.
I want to know how to rotate a button or image on clicking.
appy Jul 19, 2010 9:45 AM
service can't play media file loger
I used service class. in serivce class i set media file which play on ending of timer.. every thing is fine but sound file for 1-2 second, so how can make it longer & also can i start new activity from service
Bghaak Jun 18, 2010 7:44 PM
Service on start up
Hi
Is it possible to write a service that can be started automatically after the phone has been restarted?
If you have experience in this, could you direct me to some useful links?
Thank you, looking forward yo your next article
Waseem Sarwar May 12, 2010 1:27 PM
Background service
Please anyone can tell me that whenever more than one second Thread.sleep(2000) is used in onStartService method why it throws an exception while running.

i have called "finish()" function in a button just after the service called code is below

startService(new Intent(LBMA.this,SimpleService.class));
LBMA.this.setResult(RESULT_OK);
finish();

Why this LBMA activity does not finish until service class finish its work. what should i do ? i just want to close LBMA activity after calling serviceStart method.
Jbeerdev Apr 6, 2010 5:32 PM
RE: Programming Guide to Android Services
Hi!

Yes, the idea is to continue writing about this. In one hand there is going to be some structural changes in the web and in other hand I have tons of work and not too much time to write. Hope this will change soon :)
John Giotta Apr 6, 2010 5:07 PM
Continue
Any plans to follow-up with the Activity and service tutorial?
Ejder Yurdakul Mar 4, 2010 11:34 AM
take picture in service
Hi,
i've created a service like you describe above but when i take a picture, eveything is correct, size, format, name but the image is black. This is because camera needs preview on surface to setup exposure and focus. Now i have a surface and surface listener which starts the preview. but onsurfacecreated event never fires. i guess because it is not visible so it is not created too. But i want to run as a service and take pictures in background, do you have any suggestion about that? Thanks in advance
Jbeerdev Feb 26, 2010 2:52 AM
RE: Programming Guide to Android Services
Hi Muhammad

You can find examples of services binding in SDK /samples/ApiDemos/ folders.
Muhammad Feb 26, 2010 1:50 AM
.How do we bind service with Activities
hi jbeer

what is required is to bind a Service with an activity
so plz write on it immediately.
Jon Watte Feb 16, 2010 11:33 PM
It's the bindService() that's hard!
Creating a service is very simple.

However, having your activity start the service, and communicate with it through IBinder RPC, is more complex. That's the part that a tutorial on services on Android needs to cover -- without that, you can't actually DO anything with your service!
Jbeerdev Jan 3, 2010 7:25 PM
RE: Programming Guide to Android Services
Hi ambarish

I have been some weeks-months with a very low writting-activity (too much work!!), now I have more time to write about what I do and work (Android developer). In few time I will have more articles, about services and more!

I will put all my aritcles and news in my twtter:

http://twitter.com/jbeerdev

ambarish malpani Jan 3, 2010 6:24 PM
Next lesson?
Hi Jbeer,
Did you ever write your followup article about using services in Android? If so, can you pls send me a pointer?

Thanks,
Ambarish
Prabu Aug 18, 2009 6:42 AM
Thanks a lot for your quick reply, Jbeer
Looking forward for your valuable Lesson.
Jbeerdev Aug 18, 2009 2:22 AM
About Service->Activity comunication
Hi Prabu.

This is done use "Bindings" (you bind the Service to the Activity so they can communicate). It not as easy as 2 lines of code. I have to write something about it. Its an interesting subjet!!
I will notify when the article is ready.
Jbeerdev Aug 18, 2009 2:19 AM
Start Service Lesson
Hi Patrios.

Its something I have to do. Sorry about the confusion. But the idea of starting a service is the same as starting a new Activity: using intents:

Intent int = new Intent( this, MyService.class );
startService(int );

I will write about it anyway.
Prabu Aug 18, 2009 1:41 AM
Start Service from Android Activity
Can you let me know how to start Service from Android Activity, also how to shuffle the application between service and activity(Activity-->Service-->Activity)?
Patrios Aug 12, 2009 6:24 AM
Start Service from Android Activity
Hello, I didn't find the lesson about starting Service from Android Activity.
Jbeerdev Jul 15, 2009 3:24 AM
RE: Programming Guide to Android Services
Arun, could you explain a bit more the situation? You want to call a Service fron an OnRecieve method?

Pablo, un saludo a ti también desde Santiago de Compostela.
Arun Jul 7, 2009 4:58 AM
Regarding startService method
I want to do a background process in onRecieve method .It is in a class which extends Broadcast receiver > how do i do it from there.???,,can u help me
Pablo Jul 3, 2009 7:26 AM
Thanks/Gracias
Qué pequeño es el mundo en internet.
Gracias por el tutorial. Espero el próximo.

Un saludo desde Alicante
 
blog comments powered by Disqus
Email to a friend