ServicesDemo - Using Android Services

ServicesDemo - Using Android Services

Member since Dec 23, 2009
Stream Posts: 14
Posted on Jan 05, 2010 (5 years ago)
Seen 274588 times.
Tagged As:

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="https://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="https://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
https://newcircle.com/static/tutorials/ServicesDemo.zip

Music File
https://newcircle.com/static/tutorials/braincandy.m4a

Comments

You have to login to post a comment.
Posted on Mar 31, 2015 (2 months ago)
Member since Mar 31, 2015
@Marko Gargenta Hi Marko Would you please tell me how to build an app that runs automatically when the user receives an SMS .
Posted on Jul 30, 2014 (10 months ago)
Photo Munir Sheikh
Student
Nil
Member since Jul 30, 2014
Nice service tuts
Posted on Jun 25, 2013 (2 years ago)
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
Posted on Jan 27, 2013 (2 years ago)
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 Dec 19, 2012 (2 years ago)
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 Dec 08, 2012 (2 years ago)
Member since Dec 8, 2012
Please provide a link for Tutorial with e.g. of Multiple music files
Posted on Dec 08, 2012 (2 years ago)
Member since Dec 8, 2012
Hello Sir... Its really a nice & informative post.. Can you please help me out? Actually I have a [b]MusicPlayerService[/b]. I start it from [b]MusicPlayerActivity [/b]But I want to keep service running though [b]MusicPlayerActivity [/b]finishes... How can I achieve it? Thanks.
Posted on Sep 27, 2012 (3 years ago)
Photo cheng Wei Lee
Android player
Member since Sep 27, 2012
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[b] Auto run [/b]in background even " [b]task kill[/b] " or " [code]restart the phone after change the battery[/code] " How can I solve it !?
Posted on Aug 11, 2012 (3 years ago)
Photo Sijoy Thomas
Capgemini
Member since Aug 11, 2012
Thank you! Nice one. Helped me to understand service lifecycle Activity bounded
Posted on May 02, 2012 (3 years ago)
Photo Deobrat Nayak
Android
Member since May 2, 2012
Thanks Buddy it helped me a lot
Posted on Mar 24, 2012 (3 years ago)
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 Mar 22, 2012 (3 years ago)
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 01, 2012 (3 years ago)
Photo Daan Dawud
Software
Member since Mar 1, 2012
Fantastic dude. A* ...
Posted on Feb 20, 2012 (3 years ago)
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 Jan 25, 2012 (3 years ago)
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); }[/code] I dont know if it is possible to use MediaController in service. here is more info about my issue [url]http://stackoverflow.com/questions/9001183/android-how-to-use-mediacontroller-in-service-class[/url] Thanks for your help.
Posted on Nov 14, 2011 (4 years ago)
Photo Sidik Edi
Laboratorium Universitas Budi Luhur
Member since Nov 14, 2011
how i can Access a service in multiple activities?
Posted on Nov 11, 2011 (4 years ago)
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 Aug 29, 2011 (4 years ago)
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 Jul 20, 2011 (4 years ago)
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 Jul 18, 2011 (4 years ago)
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 Apr 28, 2011 (4 years ago)
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 Apr 17, 2011 (4 years ago)
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 13, 2011 (4 years ago)
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 Mar 31, 2011 (4 years ago)
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 Mar 10, 2011 (4 years ago)
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); }