NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Friday, 4 September 2009

Local Service | Android Tutorial for Beginners – (Part 7)


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.


Service Example (code downloadable here)


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.

75 comments:

  1. Thanks a lot for this. It is very well explained. Cheers

    ReplyDelete
  2. This application is not getting listed in my emulator....
    How to launch this application in the emulator....

    ReplyDelete
  3. Anand,
    Is 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.

    ReplyDelete
  4. 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.

    ReplyDelete
  5. Hi! 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?
    Meaning, 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.

    ReplyDelete
  6. Hi
    "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 :(

    ReplyDelete
  7. hello maam,
    I 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.

    ReplyDelete
  8. Hi,
    I 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.

    ReplyDelete
  9. Good Example. This example should be entry point for any new one who wants to work with Service. Simple and Good Example.

    ReplyDelete
  10. I really enjoyed very much this Tutorial. It is actually written for beginners.

    The 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

    ReplyDelete
  11. hi Sai Geetha,

    I 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.

    ReplyDelete
  12. Hi geetha,

    I 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.

    ReplyDelete
  13. Hello Geeta,

    Your 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

    ReplyDelete
  14. 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..

    ReplyDelete
  15. Thank you! All very nice and affordable!

    ReplyDelete
  16. Hi..
    I make a service like this. But I want to call this service from my own other application. Can you help me ..

    ReplyDelete
  17. Hi Shivaprasad,

    If 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

    ReplyDelete
  18. Hello all,
    how to get notification before the application data cleared on change.
    i wanna notification or log before my apps uninstall.please help me.

    ReplyDelete
  19. Hi Sai Geeta,
    mam 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.

    ReplyDelete
  20. Thank you for that fantastic tutorial. You are great!

    ReplyDelete
  21. hi geetha am looking for how json integration is done in android can you please help me??

    ReplyDelete
  22. And along with that how to access soap web services using json integration in android.

    ReplyDelete
  23. Great tutorial!

    How 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.

    ReplyDelete
  24. Hi Geetha,
    awesome 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..

    ReplyDelete
  25. sorry the code in the for loop above is wrong
    here is the right code:
    for(int j=0; j<pixels.length; j++)

    ReplyDelete
  26. and inside for loop is this code
    ib.put(pixels[j] << 8 | pixels[j] >>> 24)

    ReplyDelete
  27. Hey geetha,

    Can you please suggest me something to overcome the above issue.
    Please, i am helpless and being stuck with this issue for nearly 2 weeks.

    ReplyDelete
  28. Hi Geetha

    Nice Tutorials

    i am waiting for some more examples

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. Hi Geetha

    Let 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 )

    ReplyDelete
  31. Thanx a lot.it works great....

    ReplyDelete
  32. Very nice tutorial the best I´ve found .Thanks..

    ReplyDelete
  33. Thanks for all the articles on Android!
    Your lessons are simple, crisp, and easy to understand.

    ReplyDelete
  34. hi geetha

    thankx a lot. it is realy very helpfull for me to understand service. and also thanx for another article on this blog.

    ReplyDelete
  35. hi,
    geetha
    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.........

    ReplyDelete
  36. hi mam,
    I Muralidhar, from bangalore. Could you please help to create daemon process. I have to disable camera when the mobile is switched on(android).

    ReplyDelete
  37. Hi geetha.. Nice tutorial.
    I 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.

    ReplyDelete
  38. Hi mam,
    Can you please give the example of how to bind the activity with local service?
    Thanks.

    ReplyDelete
  39. chetan@kratin.co.in24 February 2012 at 16:35

    Hi Mam,
    thank 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.

    ReplyDelete
  40. Hai madam,

    Iam 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

    ReplyDelete
  41. Hai madam, how to invoke a 3rd party apk into my activity

    ReplyDelete
  42. Hi Mam.... Nice tutorial.

    thankx a lot. it is realy very helpfull for me to understand service. and also thanx for another article on this blog.

    ReplyDelete
  43. Hi Madam,

    I 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.

    ReplyDelete
  44. I studied lots of article for getting services concept but i got from this article

    ReplyDelete
  45. Hi mam
    i need a service example which extracts the data from database and show it in list view.
    please help me mam

    ReplyDelete
  46. Really nice because of its simplicity, thanks for this example!

    ReplyDelete
  47. Thank 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.

    ReplyDelete
  48. Hi,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.

    Thanks,
    Aarti

    ReplyDelete
  49. This was exactly what I needed. Thank you so much. Great tutorial.

    ReplyDelete
  50. Simply Explained for the beginners

    ReplyDelete
  51. Thank you! Bless you!

    ReplyDelete
  52. Thanks.............

    ReplyDelete
  53. Mam can you tell me service has any method that called every time during running
    service in background .bcz onstart() and oncreate() called always one's during life of the service.

    ReplyDelete
  54. Thank u very much.
    u r tutorial is very much useful to every android learner & developers also.
    please publish up to date changes in android & java technology.

    ReplyDelete
  55. Mam, thanks for the easy explanation.

    ReplyDelete
  56. Hi,
    I want the steps to create Remote service and Local service

    ReplyDelete
  57. C# is easier and more clear

    ReplyDelete
  58. Very good coder and you really explain very very well !!! thanks a lot for dis wonderful blog ...

    ReplyDelete
  59. am so happy for coloring code i noticed this since first tutorial coloring is more attractive :)

    ReplyDelete
  60. Hi geetha, it was the nice tutorial for the beginners......thanks for the concepts...

    ReplyDelete
  61. I need to get the key events in the service.. How can i do it..

    ReplyDelete
  62. Hi Friends ,

    I 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

    ReplyDelete
  63. Nice Tutorial :)

    ReplyDelete
  64. Really, this is most well explain example of simple service. Binding service to change user interface

    ReplyDelete
  65. Hello mam,
    I 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?

    ReplyDelete
  66. hi the code which u had given is not working & getting errors could u provide the other code which would be useful for us

    ReplyDelete
  67. public void onCreate(Bundle savedInstanceState) {
    super.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

    ReplyDelete
  68. sir,
    am 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..

    ReplyDelete
  69. good geetha...thnkzz alot............... :D

    ReplyDelete
  70. Thanks for this tutorial. Very interesting and simple.

    ReplyDelete
  71. Hey Geetha thanx for explaining the Services Beautifully...........I clearly understood..........keep it up!!

    ReplyDelete
  72. Great article. Thanks

    ReplyDelete
  73. Nice Tutorial and Great Explanation Geetha Mam

    ReplyDelete