ServicesDemo - Using Android Services

Posted on Jan 5, 2010 (4 years ago). Seen 251,863 times. 49 comments. Permalink Feed
Member since Dec 23, 2009
Location: Oakland
Stream Posts: 0
Tagged as: Android Tutorial

To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).

Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service.

context.startService() | ->onCreate() - >onStartCommand() [service running]

Calling the applications stopService() method to stop the service.

context.stopService() | ->onDestroy() [service stops]

Something that we didn't use in this example is bindService() which just calls the services onCreate() method but does not call the onStartCommand(). onBindService() is used to create persistance connection to the service.

context.onBindService() | ->onCreate() [service created]

This Services Demo is simple as it plays a audio file and by listening to click events of the buttons invokes the MyService service.


ServicesDemo.java
Code:
package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}

public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}

To understand the audiomedia player, please review the AudioDemo posted in this form. The custom MyService extends Service class and necessary to override various methods of its lifecycle ie onCreate(), onStartCommand(), or onDestroy()

MyService.java

Code:

package com.example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");

player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}

Necessary to let the AndroidManifest file know about your service <service android:enabled="true" android:name=".MyService" />


AndroidManifest.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServicesDemo" 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:enabled="true" android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>


main.xml

Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Services Demo" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="Start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>



Output

Source
http://thenewcircle.com/static/tutorials/ServicesDemo.zip

Music File
http://thenewcircle.com/static/tutorials/braincandy.m4a

Comments

Posted on Feb 16, 2010
Photo Marc Cohen
Self-Employed
Member since Feb 16, 2010
Thank you for your tutorial.... can you show how to use this with more than one media file?

Thanks,
Marc
Posted on Feb 16, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
What do you mean by multiple media files? Be able to choose what to play? That would be a UI task that is not necessarily appropriate for this example. This example is there just to explain what an Android service is and how to use it. Media is secondary in this case to help illustrate the point.
Posted on Feb 16, 2010
Photo Marc Cohen
Self-Employed
Member since Feb 16, 2010
Thank you for responding. I understand it may be out of scope from this tutorial, but, i was just wondering, because the media file call is within MyService.java, how would it be possible to ever have more than one media file?
Posted on Feb 16, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Well, you can have as many media files as you want. You'd have to build some sort of UI so user can choose the right one. Perhaps, use PreferenceActivity, etc. This is not covered in this example, but I think MyTwitter (part 2, may be) does cover it.

In this example, we store media files in application resources. If you had more files, I'd use MediaStore, or just store them on SDCard file system.

Anyway, lots of IFs.
Posted on Feb 16, 2010
Photo Joyy Joyy
IT Company
Member since Feb 16, 2010
HI.
I am currently working on android application which store Image as a blob data type in sqlite.

but, when i m retriving blob from the database and converted it into Bitmap object using decodeByteArray() my bitmap object return null.
I dont know how thats happen?

please help me.
THNX
Joyy
Posted on Feb 17, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Not sure why that happened. But, I wouldn't put images into database as blobs. I'd put just the file names and store the actual images on SD Card. Even better, I'd use MediaStore which was designed for this purpose.
Posted on Feb 17, 2010
Photo Joyy Joyy
IT Company
Member since Feb 16, 2010
Thanks,
Mark for responding.
Posted on Mar 15, 2010
Photo Nagendra Kumar
V2solutions
Member since Mar 15, 2010
hank you for your tutorial.
Posted on Mar 15, 2010
Photo Nagendra Kumar
V2solutions
Member since Mar 15, 2010
hank you for your tutorial.
Posted on Mar 15, 2010
Photo Joyy Joyy
IT Company
Member since Feb 16, 2010
hey Mark..

I have .chm reader android application.
in which i m trying to decompress .chm files. but i cant.
i don't know how to decompress .chm files in android?
please help me..
Joyy
Posted on Mar 16, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
I have no idea about .chm files. It's got nothing to do with Android, so you are on your own.
Posted on Apr 16, 2010
Photo Narayan Babu
Software Developer
Dexetra Technologies.
Member since Apr 16, 2010
Hi,
I tried exactly shown in your tutorial. But, the problem is the code breaks at the line
MediaPlayer.create(this,R.raw.braincandy);
And, I precisely wanted a solution for this. From within the service, though Service is a derived from Context class, wherever we pass this, it breaks. Can you comment on this?
I am running Android 1.6 SDK.
Posted on Apr 19, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Possible reasons why this breaks:
1) you didn't import MediaPlayer
2) you don't have braincandy song in your res/raw directory
3) you are within an inner class so this referes to the inner class and not service

It would help to know how it break, in other words, what those the logcat tell you. The answer is right there, spelled out.
Posted on Apr 19, 2010
Photo Narayan Babu
Software Developer
Dexetra Technologies.
Member since Apr 16, 2010
Thanks for the response.
By "breaking" I meant the program was crashing (Force close) and getApplicationContext() was null.
But I found the problem. The "context" value is properly available in the onCreate funtion. While I was doing these in the constructor.
Posted on May 9, 2010
Photo Phaneendra Kumar
se
H
Member since May 9, 2010
Hi,

This is very good example. I want to create a service, that service will start when the emulator starts. How can i make my service as demon service.
Posted on May 10, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
See BootReceiver in MyTwitter example. You'll also need to update the Manifest file.
Posted on May 10, 2010
Photo Phaneendra Kumar
se
H
Member since May 9, 2010
Thanks for the response. I need one more help, that is when we delete a contact from the contact list, I need to catch the deleted contact. Is there any listioner for this, to give notification that file has to deleted from the list.
Posted on Aug 27, 2010
Photo Hassan Dibani
home user
Member since Aug 27, 2010
Hi,
I have tried using this example but i found a problem that i couldn't resolve. if i hit play, then go back to the home screen, run some others apps (music keeps playing in the backgroud), if i then rerun this app, the stop button is not able to stop the music, the play button starts a secons mediaplayer and now i have the music playing twice.
any ideas?
Posted on Aug 27, 2010
Photo Marko Gargenta
@MarkoGargenta
Member since Jan 19, 2007
Location: San Francisco
Hard to tell what is going on without the log info.
Posted on Sep 1, 2010
Photo Suppi D
Home
Member since Sep 1, 2010
Hi,

After installing my application on the device or emulator, i would like my Service to start, how can i do that without any UI

Right now i have written code for starting my service on boot of the system, i don't want to do this now, i just want the service to start when the application is installed and continue running even if the emulator is restarted.

thanks alot
Posted on Sep 2, 2010
Photo John Brown
Programmer
LMS, Inc.
Member since Sep 2, 2010
Hello,

This example of Android Service is excellent. Thank you Serete. Thank you markana.com.

I have been trying to understand android Service for some time. Lots of books, tutorials, web searches. This example has been the most useful of all. This example contains one new subject, Services. I seem to learn the best when I learn one thing at a time. Many examples incorporate several new features all at the same time. I like this example's simple, focused approach the best.

Thank you, John Brown
Posted on Nov 4, 2010
Photo Assaf Passal
None
Member since Aug 26, 2010
Your examples are very usefull and simple, thank you very much
Posted on Nov 19, 2010
Photo Sharad Kumar
Student
Collge project
Member since Nov 19, 2010
is there any on who can help me...
i'm doing a project 4 my colge in which i have to do.....i have to read a the some data of xml file which is present on some link like http://google.com/abc.xml..and need to fetch the data and show on some label plzz help me
thanks...
Posted on Nov 25, 2010
Photo Vivek Madhavan
Student
CU
Member since Nov 25, 2010
Hi ,

thanks for this post ,

When i simply try to integrate this with another project
It does not seem to work

I added the required line in the manifest file also .

Any where else that I need to make changes?

Thnaks in advance for ur help

--
Vivek
Posted on Mar 10, 2011
Photo Cathal Coffey
NCG
Member since Mar 10, 2011
How do I pass a parameter to the service when I am starting it?

// I want to do something like.
startService(new Intent(this, MyService.class), params);
Posted on Mar 10, 2011
Photo Cathal Coffey
NCG
Member since Mar 10, 2011
Never mind I figured it out.

Bundle b = new Bundle();
b.putInt("id", 7);
Intent i = new Intent(this, MyService.class)
i.putExtras(b);

startService(i);

.
.
.

@Override
public void onStart(Intent intent, int startid)
{
Bundle b = intent.getExtras();
int id = b.getInt("id");

Toast.makeText(this, "My Service Started with id = " + id, Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
Posted on Mar 10, 2011
Photo Cathal Coffey
NCG
Member since Mar 10, 2011
Okay why can't I do the following?

public class MyService extends Service
{
private TelephonyManager tm;
private LocationManager lm;
private LocationListener ll;

@Override
public void onCreate()
{
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");

tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
ll = new MyLocationListener();
}

@Override
public void onStart(Intent intent, int startid)
{
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);
}
Posted on Mar 31, 2011
Photo Ram Dharan
Vizser
Member since Mar 31, 2011
hii can u explain me how to run a background service for every 24 hours
Posted on Apr 13, 2011
Photo Thomas A.
No
Member since Apr 13, 2011
Thanks for this nice example...
But you should add the following lines to your MyService.java to make it running on API Level 5 (Android 2.0+) and higher. (onStart() is deprecated!)

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
return START_NOT_STICKY;
}

Thomas
Posted on Apr 17, 2011
Photo Cosma Mihai
Student
Member since Apr 6, 2011
Hey I need some help.I want to record a sound(= a word) from the MIC and store it to a database or SD card and add it a name . Also I want to compare it to a new sound (same word) that I say to the MIC and see if they match?

I know it's much but at least can u tell me what to use, what to start with.


Most grateful!

Misu.
Posted on Apr 28, 2011
Photo Terry D'Souza
Terry
Member since Apr 28, 2011
Thanks for this nice article and explaining cycle of Service.
How to get the object of MyService class and access other methods from ServiceDemo activity class ? To obtain a instance of the service do we have to use bindService only ??


Please help me out.

Thanks
Posted on Jul 18, 2011
Photo Jim Pruett
Wikispeedia
Member since Jul 18, 2011
Code works great.
One thing I can't work out.

When I kill the app (hit backarrow on emulator), how do I get it to call stopservice().

I am kinda new at this. Is there an onDestroy or something special?
I tried experimenting around and can't get it to kill the service like the stop-button does...

thanks
jim
Posted on Jul 20, 2011
Photo M. Hossein Amerkashi
Self
Member since Jul 20, 2011
Hi, Thanks for great tutorial. However, I do have a question:
If STOP the ServiceDemo, the service, MyService, also stops. Shouldn't this run in background all the time? I even updated code to include following, but still force-closing the ServiceDemo, also stopped this service. Please help. Very interested in a solution and I can be accesses at kkashi01@gmail.com


@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
Posted on Aug 29, 2011
Photo Han Tran
None
Member since Aug 29, 2011
Great tutorial!
May I ask you a question like this. If in the activity (which call the service) have a TextView, when it call service, the method onStart() of service will change the text of that TextView of activity, how can I do it?
Posted on Nov 11, 2011
Photo Somasundaram S
None
Member since Nov 11, 2011
Hi, Thanks for the Great Post. I have a small questions related to the Andriod App I'm working on now.

Is it Possible to set an Intent Filter for <Sevice> as Launcher, if that is not possible is it to be launched from an Activity and that Activity to be set with Transparent Theme, so that User doesn't see the Blank Screen, before I'm done with some background Check and then launch the actual App.

Kindly Help.

Thanks in Advance.
Posted on Nov 14, 2011
Photo Sidik Edi
Laboratorium Universitas Budi Luhur
Member since Nov 14, 2011
how i can Access a service in multiple activities?
Posted on Jan 25, 2012
Photo Krzysztof Kubacki
Home
Member since Jan 25, 2012
Hi, great example.
I'm trying to use mediaController in this example and doesnt't work. I dont know how to get LinearLayout view from my main.xml
In the MyService class I implement OnPreparedListener and my onPrepared method looks like this ...

Code:
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaController.setMediaPlayer(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, (ViewGroup) findViewById(R.id.main_program_view));
mediaController.setAnchorView(layout);
}


I dont know if it is possible to use MediaController in service.
here is more info about my issue http://stackoverflow.com/questions/9001183/android-how-to-use-mediacontroller-in-service-class

Thanks for your help.
Posted on Feb 20, 2012
Photo Dipali Patel
trainee
Student
Member since Feb 20, 2012
hi...
i don't know ...what is use of raw folder in layout.

where to put the media file in example.?

when i was put that media file in raw folder but it was not been used into jav code.it was

generate error.
Posted on Mar 1, 2012
Photo Daan Dawud
Software
Member since Mar 1, 2012
Fantastic dude. A* ...
Posted on Mar 22, 2012
Photo Keerthi R
Trainee
Member since Mar 22, 2012
Hi...
Iam new to android and still trainee..
Please suggest me to use raw folder in layout which is not present in my res..and where to dump the media file(braincandy as in example). And how to use it...

Thanks
Posted on Mar 24, 2012
Photo Keerthi R
Trainee
Member since Mar 22, 2012
Hi Sir,
I finally did this player but after installing in AVD its going on for Force Close. Please help me out.


Thanks
Posted on May 2, 2012
Photo Deobrat Nayak
Android
Member since May 2, 2012
Thanks Buddy it helped me a lot
Posted on Aug 11, 2012
Photo Sijoy Thomas
Capgemini
Member since Aug 11, 2012
Thank you!
Nice one. Helped me to understand service lifecycle Activity bounded
Posted on Sep 27, 2012
Photo cheng Wei Lee
Android player
Member since Sep 27, 2012
Location: Taipei
Hi Marko Gargenta

I want to used this to be a personal Clock

And your example is useful for me

But when I use " Task Killer " to kill it .
It will not restart
And I want Clock can Auto run in background even
" task kill " or " restart the phone after change the battery "
How can I solve it !?
Posted on Dec 8, 2012
Photo Anuj Devasthali
GIPL
Member since Dec 8, 2012
Hello Sir...
Its really a nice & informative post..
Can you please help me out?
Actually I have a MusicPlayerService. I start it from MusicPlayerActivity But I want to keep service running though MusicPlayerActivity finishes... How can I achieve it?
Thanks.
Posted on Dec 8, 2012
Photo Anuj Devasthali
GIPL
Member since Dec 8, 2012
Please provide a link for Tutorial with e.g. of Multiple music files
Posted on Dec 19, 2012
Photo Pankaj Sp
Android
SP
Member since Dec 17, 2012
Hi Serete Itebete & Marko Gargenta
can we start camera in service? because i want to capture image periodically when my app minimize. so if possible then please help me.
Thanks....
Posted on Jan 27, 2013
Photo Shankar Ramdurg
sdmcet
Sdmcet
Member since Jan 27, 2013
Hi,i am developing application that uses wifi connection and it will connect to wifi then access the pc's data through application but i want to know that how access data between phone and pc by using wifi and code for the same.
Posted on Jun 25, 2013
Photo Wei Ho
Personal
Member since Aug 13, 2012
I`ve meet the same requirement with Pankaj ,too.

recently , I can do the data pass from Service to Activity by BroadcastReceiver. However , I still get Null value(Null height, Null width , Null PreviewFrame) from my camera implemented in my Service.

I`ve setted up the same camera enviroment in my Service with SurfaceHolder.callBack .

and implemented 3 functions onSurfaceCreated, onSurfaceChanged, onSurfaceDestroyed as I had done in my activity and it worked without error.

But now, when I tried to move these functions to service. It seems these functions never work normally as they implemented in Activity.

Does anyone know how this might be happening? or is there something i lost in my Service part or Activity. Thanks