Service is a
fundamental component in android. Many a time, applications will need to run
processes for a long time without any intervention from the user, or very rare
interventions. These background processes need to keep running even when the
phone is being used for other activities / tasks.
To accommodate
for such a requirement, android has introduced the “Service” component. It is a
long lived component and does not implement any user interface of its own.
Typically a
user interacts with a service through an activity that has a UI. The service by
itself “notifies” the user in case of any need for user intervention.
In this
article, I would like to introduce you to a very simple service which runs in
the background but does not have any notification features.
In order to
start and stop the service, I have created an activity called the service
controller.
In my example,
when the service starts, it toasts a message that the service has started. When
the service ends, it toasts a message that the service has ended. This is not
of much use in the real sense of services. However, it simplifies the
introduction of service creation and destruction.
Ideally, one of
the ways could be: a service that is running should notify itself as running by
putting up a status bar notification as discussed in the previous article. And when the service has completed
running the notification can be removed. Through the notification, the service
can give a user interface for binding to the service or viewing the status of
the service or any other similar interaction with the service. The combination
of service with notification will be an example I will give in the next part.
Before we jump
into the example, a little more about services.
Binding to a service:
Once a service
has begun and is running in the background, any number of activities can “bind”
to the service. In fact, if we want to bind to a service that has not started,
calling to bind could initiate the service. Such a service would shut down as
soon as the last user detaches from the service.
Remote service
The services
defined above are those that run in the same process as the application that
started it. However, we can have services that run in its own process. This is
particularly useful when the service has to run for a long time, typical
example being a background music player. For two processes to communicate, the
object being passed needs to be marshaled.
For this, Android
provides a AIDL tool (Android Interface Definition Language) to handle all
marshalling and communication. The remote service example will be taken up in a
subsequent article.
Step 1:
Let us start
with creating a service class that extends android.app.Service.
This service just
displays a message when started and again displays a message when stopped.
Hence the onStart()
and onDestroy() methods are implemented. Here is the code.
public class SimpleService extends Service {
@Override
public IBinder
onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Service
created ...", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service
destroyed ...", Toast.LENGTH_LONG).show();
}
}
Step 2:
An entry for
this service needs to be made in the AndroidManifest.xml file. Here it is:
<service android:name=".SimpleService">
</service>
Step 3:
Now, we need to
be able to invoke this service. i.e. start the service and stop the service. I
choose to write an activity that can start and stop the service. This activity
is called SimpleServiceController.
Here is what it
does:
To start the
service –
Button start =
(Button)findViewById(R.id.serviceButton);
…
start.setOnClickListener(startListener);
…
private OnClickListener
startListener = new OnClickListener()
{
public void onClick(View
v){
startService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
Similarly
to stop the service –
Button stop =
(Button)findViewById(R.id.cancelButton);
…
stop.setOnClickListener(stopListener);
…
private OnClickListener
stopListener = new
OnClickListener() {
public void onClick(View
v){
stopService(new Intent(SimpleServiceController.this,SimpleService.class));
}
};
Step
4:
The
entry for this class in the AndroidManifest.xml file is as usual:
<activity android:name=".SimpleServiceController"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"
/>
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
Now we can
launch this application and we can start and stop a service.
Thanks a lot for this. It is very well explained. Cheers
ReplyDeleteThis application is not getting listed in my emulator....
ReplyDeleteHow to launch this application in the emulator....
Anand,
ReplyDeleteIs it not launching for the first time when you start the application from the eclipse IDE on the emulator? That should be launching without problems...
However, if you are saying that you are unable to view an icon for the application on the top level menu / launcher... here is my explanation:
Have you installed other applications from my blog and executed them successfully on your emulator? If yes, I can tell you why this is happening...
Many of my examples are written under the package com.collabera.labs.sai
All of these get packaged as one apk file in the emulator. And since many applications have the "category" android.intent.category.LAUNCHER, the emulator is unable to list them in the main top-level launch screen.
If we were to separately package them into different apk files, then it would work.
Any one else has any other explanations, most welcome.
Hi! Geetha. Your explanation about services is excellent.But when i tried the code just the lay out had displayed without any functioning.Then i had imported and i had run the code,its working.I did not understand where the problem had occurred.
ReplyDeleteHi! Geetha, thanks a lot for your tutorial. Still I have a question. How can I pass data from the service to the the activity that started it?
ReplyDeleteMeaning, instead of "toasting" a message like "service started..." I want to generate the String in the service, pass it to the controller Activity and display it on a TextView.
Hi
ReplyDelete"In this article, I would like to introduce you to a very simple service which runs in the background but does not have any notification features. "
How do you explain why Thread.sleep(1000000) in onStart() service method make the entire app sleep ?
Does it share the same thread than the UI ? So it does not run in background... i don't understand :(
hello maam,
ReplyDeleteI have never thanked you b4 ne where on web,
but since dec 2009,
If ne topic in Android I was feeling uncomfortable with, I would come to ur blog,through google and read, ur blog makes those tough concepts for freshers look real simple.
thnx a lot.
I want to make a suggestion,
you have a gr8 android beginner stuff disbursed all over ur whole blog, and other android sites too.if possible pls keeep a table of content on the home page.
It will be a quick link to a great resource on the web for othr newbies :)
again thnqqqqqq.
Hi,
ReplyDeleteI want to implement a service which captures the Keyboard and mouse events of the parent activity. Can anyone please suggest me, what I have to do. How I have to approach.
Thanks,
Vamsi.
Good Example. This example should be entry point for any new one who wants to work with Service. Simple and Good Example.
ReplyDeleteI really enjoyed very much this Tutorial. It is actually written for beginners.
ReplyDeleteThe way you explained the matter is the way I needed to read it in order to understand services.
I am looking forward to the next tutorial on services.
Thanks
hi Sai Geetha,
ReplyDeleteI am working on background Key event handling and screen capture application.
I am not able to handle the key events in background .
I am attaching the code along this,please do needful.
public boolean onKeyDown(int keyCode, KeyEvent event) {
try {
out.write("" + keyCode);
out.flush();
Toast.makeText(getApplicationContext(), "" + keyCode,
Toast.LENGTH_LONG).show();
}
catch (Exception e) {}
return true;
}
In the above code i stored all key events in a file . wher out is outputstreamwriter object.
Hi geetha,
ReplyDeleteI need to handle the key events in the background.
In the foreground wat ever the keys i am pressing that keys should be captured by a background application.i used onKey(),onKeyDown() but, both are handling keyevents of the application only, but if i send the application in background its not capturing any keys. please suggest me the solution it ill be more helpful.
Hello Geeta,
ReplyDeleteYour articles are really nice and enthusiastic! With simple and rich texts and neat explanation, it makes really interesting to read through your blogs and especially its a boon for android beginners for having come across such thought-provoking articles! Please continue with the same and inspire us.
Coming to the point, 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
I make a service like this. but my service got hanged after some time. It stop responding after some time..plz give me a solution..
ReplyDeleteThank you! All very nice and affordable!
ReplyDeleteHi..
ReplyDeleteI make a service like this. But I want to call this service from my own other application. Can you help me ..
Hi Shivaprasad,
ReplyDeleteIf you would want to invoke your service from another application, then it would no more be created as a local service. Please see my remote service tutorial for how you can do a service call from another application
Hello all,
ReplyDeletehow to get notification before the application data cleared on change.
i wanna notification or log before my apps uninstall.please help me.
Hi Sai Geeta,
ReplyDeletemam i want to create service which will listen phone event like phone call connected, call disconnected, missed call like that
kindly let me know how to do that.
Thank you for that fantastic tutorial. You are great!
ReplyDeletehi geetha am looking for how json integration is done in android can you please help me??
ReplyDeleteAnd along with that how to access soap web services using json integration in android.
ReplyDeleteGreat tutorial!
ReplyDeleteHow might this service be started when the Android is started? For example, I am thinking of making a chime program that will chime every hour. For my application this service should be started when the Android starts.
Thanks again for the tutorial.
Hi Geetha,
ReplyDeleteawesome tutorial and thanx for sharing the same.
I have been developing a game which requires nearly 100 textures to load in openGL ES. Basically building textures from a loaded bitmap takes too much time.
here is my code snippet...
int[] pixels = new int[bitmap[i].getWidth() * bitmap[i].getHeight()];
bitmap[i].getPixels(pixels, 0, bitmap[i].getWidth(), 0, 0, bitmap[i].getWidth(), bitmap[i].getHeight());
for(int j=0;j>> 24);
i runs from 0 to 100.
Is there any way to speed up the same.because it takes nearly 65 seconds to GLSurfaceView to completely render on the screen..
Any help in this regard is appreciated
Thanx in advance.
Hope to get an early reply from you..
sorry the code in the for loop above is wrong
ReplyDeletehere is the right code:
for(int j=0; j<pixels.length; j++)
and inside for loop is this code
ReplyDeleteib.put(pixels[j] << 8 | pixels[j] >>> 24)
Hey geetha,
ReplyDeleteCan you please suggest me something to overcome the above issue.
Please, i am helpless and being stuck with this issue for nearly 2 weeks.
Hi Geetha
ReplyDeleteNice Tutorials
i am waiting for some more examples
This comment has been removed by the author.
ReplyDeleteHi Geetha
ReplyDeleteLet me know how to pass the josn object to servlet through HttpClint . it going fine but where as in servlet i am unable get data Properly from servelt. (i mean in request object how to get the data in to servlet )
Thanx a lot.it works great....
ReplyDeleteVery nice tutorial the best I´ve found .Thanks..
ReplyDeleteThanks for all the articles on Android!
ReplyDeleteYour lessons are simple, crisp, and easy to understand.
hi geetha
ReplyDeletethankx a lot. it is realy very helpfull for me to understand service. and also thanx for another article on this blog.
hi,
ReplyDeletegeetha
i am trying to retrieving data from one url....that have to be done by service with out interrupting main thread ....shall i use thread handlers or the class which have super class as a asynchronous task..... what is difference between them.........
hi mam,
ReplyDeleteI Muralidhar, from bangalore. Could you please help to create daemon process. I have to disable camera when the mobile is switched on(android).
Hi geetha.. Nice tutorial.
ReplyDeleteI have a question. I want to begin service as android app's main action.
It is possible ? if yes or no give some suitable suggestions.
Hi mam,
ReplyDeleteCan you please give the example of how to bind the activity with local service?
Thanks.
Hi Mam,
ReplyDeletethank you for this nice tutorial , One thing that I want to add in this tutorial is , in step 2 : as you mention
An entry for this service needs to be made in the AndroidManifest.xml file. Here it is:
in adding that include this android:enabled="true" so that this service get start otherwise it could not be statr.
thank you once again.
Hai madam,
ReplyDeleteIam a fresher to Android i came to understand nicely ,but i want to implement three activities running simultaneously without any intervention ,if i install first activity then automatically the rest 2 ativities it should run ,can u please help me
Hai madam, how to invoke a 3rd party apk into my activity
ReplyDeleteHi Mam.... Nice tutorial.
ReplyDeletethankx a lot. it is realy very helpfull for me to understand service. and also thanx for another article on this blog.
Hi Madam,
ReplyDeleteI am fresher to Android ,the above tutorial was really appreciated.
I was trying to pass a String from ServiceController to SimpleService which could be triggered in Toast.Can you help me in sorting out this issue.
Thanks in Advance.
I studied lots of article for getting services concept but i got from this article
ReplyDeleteHi mam
ReplyDeletei need a service example which extracts the data from database and show it in list view.
please help me mam
Really nice because of its simplicity, thanks for this example!
ReplyDeleteThank you very much. I have been desperately searching for a android service tutorial, everywhere its too complicated. But you did it in a simple and understandable manner. once again thank you very much mam.
ReplyDeleteHi,I dont think this in the Toast would display a toast.The service running wouldnt have a application context .So,i guess getApplicationContext() needs to be called instead of this.
ReplyDeleteThanks,
Aarti
This was exactly what I needed. Thank you so much. Great tutorial.
ReplyDeleteSimply Explained for the beginners
ReplyDeleteThank you! Bless you!
ReplyDeleteThanks.............
ReplyDeleteMam can you tell me service has any method that called every time during running
ReplyDeleteservice in background .bcz onstart() and oncreate() called always one's during life of the service.
Thank u very much.
ReplyDeleteu r tutorial is very much useful to every android learner & developers also.
please publish up to date changes in android & java technology.
Mam, thanks for the easy explanation.
ReplyDeleteHi,
ReplyDeleteI want the steps to create Remote service and Local service
C# is easier and more clear
ReplyDeleteeven x8 faster
ReplyDeleteVery good coder and you really explain very very well !!! thanks a lot for dis wonderful blog ...
ReplyDeleteam so happy for coloring code i noticed this since first tutorial coloring is more attractive :)
ReplyDeleteHi geetha, it was the nice tutorial for the beginners......thanks for the concepts...
ReplyDeleteI need to get the key events in the service.. How can i do it..
ReplyDeleteHi Friends ,
ReplyDeleteI am new in Android and i want to create service for running application in background and get latitude and longitude and display toast with latitude and longitude at regular time interval . I have created and its running well but after sometimes application is closed automatically where is problem or how can it will be resolved , please help me .
Thanxx and advanced
Niraj
Nice Tutorial :)
ReplyDeleteReally, this is most well explain example of simple service. Binding service to change user interface
ReplyDeleteHello mam,
ReplyDeleteI followed each step that you have described ,but i am not able to get the output.It doesn't show any error.On clicking the buttons no actions are carried out. Where will the toast messages be displayed?
hi the code which u had given is not working & getting errors could u provide the other code which would be useful for us
ReplyDeletepublic void onCreate(Bundle savedInstanceState) {
ReplyDeletesuper.onCreate(savedInstanceState);
setContentView(R.layout.simple_service);
un hadn't written dis code without designing of service how can u run local service now i was getting local service
sir,
ReplyDeleteam a beginner and i want to create an app which could take some data and send that data to mysql database in between i used php page to send that data through insert query to mysql, but i dont know why it is not connecting,and if am sending direct data through browser using php page so its working but why not with Android App plz tell me sir i have to complete my major project soon..
good geetha...thnkzz alot............... :D
ReplyDeleteThanks for this tutorial. Very interesting and simple.
ReplyDeleteHey Geetha thanx for explaining the Services Beautifully...........I clearly understood..........keep it up!!
ReplyDeleteGreat article. Thanks
ReplyDeleteNice tutorial Geetha Mam
ReplyDeleteNice Tutorial and Great Explanation Geetha Mam
ReplyDelete