Communication Between Service and Activity in Android Example easy way

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.

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

thos is Communication Between Service and Activity in Android Example easy way


Create Project: Android Service Example

  1. Create a replacement project with project name: ServiceExample
  2. Fill Application name: ServiceExample
  3. Fill Package Name as: com.techblogon.serviceexample
  4. I even have used SDK version Android 4.0.3 and Eclipse Version Indigo. But you’ll use any version.
  5. Add below code within the (activity_main.xml) enter your project’s res/layout folder. This contains 3 buttons and an easy textview on the GUI.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text_view_header"
		android:layout_width="fill_parent"
        android:layout_height="wrap_content"
  		android:gravity="center_horizontal"
  		android:textColor="#FF0000"
        android:textSize="20sp"
        android:text="Android Simple Service Example" />

     <Button
         android:id="@+id/start_service"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_below="@+id/text_view_header"
         android:layout_marginLeft="50dp"
         android:layout_marginTop="17dp"
         android:onClick="onClickStartServie"
         android:text="Start Service" />

     <Button
         android:id="@+id/stop_service"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignRight="@+id/start_service"
         android:layout_below="@+id/start_service"
         android:gravity="center"
         android:onClick="onClickStopService"
         android:text="Stop Service" />

     <Button
         android:id="@+id/send_message"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignLeft="@+id/stop_service"
         android:layout_below="@+id/stop_service"
         android:gravity="center"
         android:onClick="onClickSendMessage"
         android:text="Send Message" />

</RelativeLayout>

Communication Between Service and Activity in Android Example easy way

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

 <service android:enabled="true" android:name=".MyService" />

AndroidManifestFile

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.techblogon.serviceexample"
    android:versionCode="1"
    android:versionName="1.0" &gt;

    &lt;uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" /&gt;

    &lt;application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" &gt;
        &lt;activity
            android:name="com.techblogon.serviceexample.MainActivity"
            android:label="@string/app_name" &gt;
            &lt;intent-filter&gt;
                &lt;action android:name="android.intent.action.MAIN" /&gt;

                &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
        &lt;service android:enabled="true" android:name=".MyService" /&gt;
    &lt;/application&gt;

&lt;/manifest&gt;

7. Now add a replacement java file (MyService.Java) for your Service Class code to your projects /src folder or simply copy and paste the below content.
Here we’ve created a replacement class called MySercive which is extended from Android inbuilt Service class. Then therein class we’ve @ Override some required virtual functions like ( onBind(), onCreate(), onStart(), onDestroy(), onStartCommand etc).

this is Communication Between Service and Activity in Android Example easy way


MyService.Java

package com.techblogon.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

	private static final String TAG = "MyService";

	//used for getting the handler from other class for sending messages
	public static Handler 		mMyServiceHandler 			= null;
	//used for keep track on Android running status
	public static Boolean 		mIsServiceRunning 			= false;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {

		Toast.makeText(this, "MyService Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart");	
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

	 MyThread myThread = new MyThread();
	 myThread.start();

		try 
		{
			Thread.sleep(1000);
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}

		mIsServiceRunning = true; // set service running status = true

		Toast.makeText(this, "Congrats! My Service Started", Toast.LENGTH_LONG).show();
		// We need to return if we want to handle this service explicitly. 
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");

		mIsServiceRunning = false; // make it false, as the service is already destroyed.
	}

	//Your inner thread class is here to getting response from Activity and processing them
	class MyThread extends Thread
	{
		private static final String INNER_TAG = "MyThread";

    	public void run() 
    	{
    		this.setName(INNER_TAG);

    		// Prepare the looper before creating the handler.
			Looper.prepare();
			mMyServiceHandler = new Handler()
			{
				//here we will receive messages from activity(using sendMessage() from activity)
    			public void handleMessage(Message msg)
    			{
    				Log.i("BackgroundThread","handleMessage(Message msg)" );
    				switch(msg.what)
    				{
    				case 0: // we sent message with what value =0 from the activity. here it is
    						//Reply to the activity from here using same process handle.sendMessage()
    						//So first get the Activity handler then send the message
    					if(null != MainActivity.mUiHandler)
    					{
    						//first build the message and send.
    						//put a integer value here and get it from the Activity handler
    						//For Example: lets use 0 (msg.what = 0;) 
    						//for receiving service running status in the activity
    						Message msgToActivity = new Message();
    						msgToActivity.what = 0; 
    						if(true ==mIsServiceRunning)
    							msgToActivity.obj  = "Request Received. Service is Running"; // you can put extra message here
    						else
    							msgToActivity.obj  = "Request Received. Service is not Running"; // you can put extra message here

    						MainActivity.mUiHandler.sendMessage(msgToActivity);
    					}

    				break;

					default:
						break;
    				}
				}
    		};
    		Looper.loop();
    	}
	}
}

this is Communication Between Service and Activity in Android Example easy way

Note: Code Description for above MyService Clas

• We have @Override Service Class functions () within the above code.
• Once you @Override onStartCommand() function within the code as above. Then once you will call onStartService() function from your activity, the onStartCommand() function are going to be called followed by onCreate() command.


• We have Create a Thread Class and begin the thread from the onStartCommand() function. which can help us to try to to long operations without making the GUI unresponsive.

	//Your inner thread class is here to getting response from Activity and processing them
	class MyThread extends Thread
	{


• In the Thread class we implemented the run() function and therein run() function use the Looper class to urge messages from the Activity at any particular time. you’ll find some code associated with Android Handler functionality. we’ve used Handler functionality within the above code to reply all incoming messages from the Activity.

			mMyServiceHandler = new Handler()
			{
				//here we will receive messages from activity(using sendMessage() from activity)
    			public void handleMessage(Message msg)
    			{


• Sending Message to Activity Class. once we want to send message to an Activity from a service using Android handler, what we’d like is: the handler instance of the activity class. you’ve got to implement the handler code in your Activity class to handle incoming request from other components. we’ve implemented the below code in our MyService Class as above.

if(null != MainActivity.mUiHandler)
    					{
    						//first build the message and send.
    						//put a integer value here and get it from the Activity handler
    						//For Example: lets use 0 (msg.what = 0;) 
    						//for receiving service running status in the activity
    						Message msgToActivity = new Message();
    						msgToActivity.what = 0; 
    						if(true ==mIsServiceRunning)
    							msgToActivity.obj  = "Request Received. Service is Running"; // you can put extra message here
    						else
    							msgToActivity.obj  = "Request Received. Service is not Running"; // you can put extra message here

    						MainActivity.mUiHandler.sendMessage(msgToActivity);
    					}

8. Add below code in your default MainActivity.java file. we’ve 3 buttons for ‘Start Service’, ‘Stop Service’ and ‘Send Message’ within the Activity class. we’ll 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 obtain the Response from the service by Clicking the button ‘Send Message’. Then we’ll show all status by displaying Android Toast message.

this is Communication Between Service and Activity in Android Example easy way


MainActivity.Java

package com.techblogon.serviceexample;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
public static Handler mUiHandler = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mUiHandler = new Handler() // Receive messages from service class 
        {
			public void handleMessage(Message msg)
        	{
          		switch(msg.what)
        		{
	          		case 0:
	          			// add the status which came from service and show on GUI
	          			Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
	          			break;

	        		default:
        			break;
        		}
        	}
        };
	}

	//start the service
	public void onClickStartServie(View V)
	{
		//start the service from here //MyService is your service class name
		startService(new Intent(this, MyService.class));
	}
	//Stop the started service
	public void onClickStopService(View V)
	{
		//Stop the running service from here//MyService is your service class name
		//Service will only stop if it is already running.
		stopService(new Intent(this, MyService.class));
	}
	//send message to service
	public void onClickSendMessage (View v)
	{
		//only we need a handler to send message to any component.
		//here we will get the handler from the service first, then 
		//we will send a message to the service.

		if(null != MyService.mMyServiceHandler)
		{
			//first build the message and send.
			//put a integer value here and get it from the service handler
			//For Example: lets use 0 (msg.what = 0;) for getting service running status from the service
			Message msg = new Message();
			msg.what = 0; 
			msg.obj  = "Add your Extra Meaage Here"; // you can put extra message here
			MyService.mMyServiceHandler.sendMessage(msg);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

this is Communication Between Service and Activity in Android Example easy way


Notes: Code Description for above MainActivity Class


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

mUiHandler = new Handler() // Receive messages from service class 
        {
			public void handleMessage(Message msg)
        	{
          		switch(msg.what)
        		{
	          		case 0:
	          			// add the status which came from service and show on GUI
	          			Toast.makeText(MainActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
	          			break;

	        		default:
        			break;
        		}
        	}
        };
	}


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

public class MainActivity extends Activity {
public static Handler mUiHandler = null;


• 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 want to implement the service handler as public static, in order that other components can access it to send messages.

	if(null != MyService.mMyServiceHandler)
		{
			//first build the message and send.
			//put a integer value here and get it from the service handler
			//For Example: lets use 0 (msg.what = 0;) for getting service running status from the service
			Message msg = new Message();
			msg.what = 0; 
			msg.obj  = "Add your Extra Meaage Here"; // you can put extra message here
			MyService.mMyServiceHandler.sendMessage(msg);
		}


• Start Service. once you click on the ‘Start Service’ button, then the service are going to be start.

//start the service
	public void onClickStartServie(View V)
	{
		//start the service from here //MyService is your service class name
		startService(new Intent(this, MyService.class));
	}


• Stop Service. once you click on the ‘Stop Service’ button, then the running service are going to be stop.

//Stop the started service
	public void onClickStopService(View V)
	{
		//Stop the running service from here//MyService is your service class name
		//Service will only stop if it is already running.
		stopService(new Intent(this, MyService.class));
	}


• Send Message. once you click on the ‘Send Message’ button, then the message are going to be send and obtain the response from the service. Then we’ll show the response using Android Toast message.

//send message to service
	public void onClickSendMessage (View v)
	{
		//only we need a handler to send message to any component.
		//here we will get the handler from the service first, then 
		//we will send a message to the service.

		if(null != MyService.mMyServiceHandler)
		{
			//first build the message and send.
			//put a integer value here and get it from the service handler
			//For Example: lets use 0 (msg.what = 0;) for getting service running status from the service
			Message msg = new Message();
			msg.what = 0; 
			msg.obj  = "Add your Extra Meaage Here"; // you can put extra message here
			MyService.mMyServiceHandler.sendMessage(msg);
		}
	}

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

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

this is Communication Between Service and Activity in Android Example easy way

FOLLOW US ON FACEBOOK INSTAGRAM TWITTER

Steps to Download Android Apps from Google Play Store

Fully Automatic Washing Machine makes washing easy

Communication Between Service and Activity in Android Example

Mozilla Firefox OS – New Competitor in Smartphone Market

Insert New Contact in Android Code Example

Leave a Comment