
Serete Itebete
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
Sourcehttp://marakana.com/static/tutorials/ServicesDemo.zipMusic Filehttp://marakana.com/static/tutorials/braincandy.m4a
Edited 5 times. Last edit by John Brown on Sep 2, 2010 at 11:40:50 AM (about 11 weeks ago).

Marc Cohen
Self-Employed
Thank you for your tutorial.... can you show how to use this with more than one media file?
Thanks,
Marc

Marko Gargenta
Marakana, Inc.
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.

Marc Cohen
Self-Employed
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?

Marko Gargenta
Marakana, Inc.
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.
Edited one time. Last edit by Marko Gargenta on Feb 16, 2010 at 1:05:25 PM (about 11 weeks ago).

Joyy Joyy
IT Company
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

Marko Gargenta
Marakana, Inc.
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.

Joyy Joyy
IT Company
Thanks,
Mark for responding.

Nagendra Kumar
V2solutions
hank you for your tutorial.

Nagendra Kumar
V2solutions
hank you for your tutorial.

Joyy Joyy
IT Company
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

Marko Gargenta
Marakana, Inc.
I have no idea about .chm files. It's got nothing to do with Android, so you are on your own.

Narayan Babu
Software Developer
Dexetra Technologies.
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.

Marko Gargenta
Marakana, Inc.
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.

Narayan Babu
Software Developer
Dexetra Technologies.
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.

Phaneendra Kumar
se
H
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.

Marko Gargenta
Marakana, Inc.

Phaneendra Kumar
se
H
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.

Hassan Dibani
home user
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?

Marko Gargenta
Marakana, Inc.
Hard to tell what is going on without the log info.

Suppi D
Home
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

John Brown
Programmer
LMS, Inc.
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