Communication Between Service and Activity in Android Example

Communication Between Service and Activity in Android (2 Way communication)

After posted a complete tutorial on simple Android service with example. Now it is time to learn the real usage of Android service in  an Android application. So here we will discuss on the communication between service and activity in Android (startService, stopService onStartCommand etc). So lets going to the coding part e.g , how to communicate between Android Service and Android Activity. If you are new to Android services then first you should look into my article on Simple Android service example code with description’

  • What we will learn here using Android Service Example Code

  1. How to call an Android service from an Activity.

  2. How to communicate between android service and activity.

  3. How to manage Android service lifecycle

  4. How to use a thread in side Android service

  5. Create an Android Handler for communicating with an Activity.

android service example start service android service example send message

As we know the lifecycle of an Android Service is different from an Android Activity. If you are interested to know about the life cycle of an Android Service, then click here. Here will create a service, then start it from an activity. After that we will sending and getting messages between the service and activity.

 Create Project: Android Service Example

1. Create a new project with project name: ServiceExample

2. Fill Application name: ServiceExample

3. Fill Package Name as: com.techblogon.serviceexample

4. I have used SDK version Android 4.0.3 and Eclipse Version Indigo. But you can use any version.

 5. Add below code in the (activity_main.xml) file in your project’s res/layout folder. This contains 3 buttons and a simple textview on the GUI.

 6. Register your service class in the Manifest file(AndroidManifest)

AndroidManifestFile

7. Now add a new java file (MyService.Java) for your  Service Class code to your projects /src folder or just copy and paste the below content.

Here We have created a new class called MySercive which is extended from Android inbuilt Service class. Then in that class we have @ Override some required virtual functions like ( onBind(), onCreate(), onStart(), onDestroy(),  onStartCommand etc).

MyService.Java

 Note: Code Description for above MyService Class

  • We have @Override Service Class functions () in the above code.
  • Once you @Override onStartCommand() function in the code as above. Then when you will call onStartService() function from your activity, the onStartCommand() function will be called followed by onCreate() command. 
  • We have Create a Thread Class and start the thread from the onStartCommand() function. Which will help us to do long operations without making the GUI unresponsive.

  • In the Thread class we implemented the run() function and in that run() function use the Looper class to get messages from the Activity at any particular time. You can find some code related to Android Handler functionality. We have used Handler functionality in the above code to respond all incoming messages from the Activity.

  • Sending Message to Activity Class. When we want to send message to an Activity from a service using Android handler, what we need is:  the handler instance of the activity class. You have to implement the handler code in your Activity class to handle incoming request from other components. We have implemented the below code in our MyService Class as above.

 8. Add below code in your default MainActivity.java file.  We have 3 buttons for ‘Start Service’, ‘Stop Service’ and ‘Send Message’ in the Activity class. We will start the service by clicking the button ‘Start Service’, stop the service by clicking the button ‘Stop Service’ and Send Message to the Service and get the Response from the service by Clicking the button ‘Send Message’. Then we will show all status by displaying Android Toast message.

MainActivity.Java

Notes: Code Description for above MainActivity Class

  • Adding handler code for processing incoming messages from the service class. We have added handler code inside the onCreate() method of the MainActivity class as below. then show the message in a Android Toast message.

  •  Make the handler instance as public static, so that other components (service in our case) can access to send messages to Activity.

  •  Sending Message to Service Class. We just retrieve the Service class handler class’s Handle instance. then send message using sendMessage() function as below. You must implement the service handler as public static, so that other components can access it to send messages. 

  •  Start Service.  When you click on the ‘Start Service’ button, then the service will be start.

  • Stop Service. When you click on the ‘Stop Service’ button, then the running service will be stop.

  • Send Message. When you click on the ‘Send Message’ button, then the message will be send and get the response from the service. Then we will show the response using Android Toast message.

 9. Build and Run the project. Watch the behavior of your Android service Example.

downloadDownload Complete Source code for Communication Between Service and Activity in Android from Here.

I hope this small tutorial on Android Service Example Code Description (Complete Tutorial) will help you at it’s best.

 

Post By SmrutiRanjan (57 Posts)

Working @ Samsung as a Project Lead for Android Smartphones. I have been blogging since 2008. Previously I was writing articles for other bloggers, but finally I have started my own blog-"Techblogon".I am also an active contributor for the blog-"Gadgets n Gizmos World". Job is my necessity, but blogging is my passion.

Website: → Techblogon

Connect

3 Responses to Communication Between Service and Activity in Android Example

  1. Carlos says:

    Hi, could you show an example of how to make a widget? At least a Information Widget !!
    Thank You , excelent tutorial !!

  2. Willi says:

    It is possible to put an UDP Server, and UDP Client into that service. I’ve an Application for remote control so the communication between the Android device and the Equipment should be bedirectional. The UDP Server is wating vor status and the UDP Client is sending the Command to the equipment. At the moment I’m not aple to solve that in a Service. I thought the service will be easy to start and stop an so the udp server and the udp client will be stopt as well. (my motherlanguage is german)
    regards willi

  3. jetti says:

    Hi, Thanks for the tutorial..
    could you please post where to use service/intentService/AsyncTask/Thread,..

    Thanks,
    Jetti.

Leave a Reply

Your email address will not be published. Required fields are marked *


1 × = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">