Android Local Bound Service Example with Binder and ServiceConnection

By Arvind Rai, July 17, 2015
On this page we will provide android local bound service example with Binder and ServiceConnection. Bound service is bound with other application and responds to the clients. Service class has onBind() method which is overridden and that returns IBinder. For local bound service where service use will be private and are in same application we can create an inner class in our service class with public methods that can be accessed by clients. To bind and unbind service from main thread of activity we call bindService() and unbindService() respectively. Here we will provide a complete example. In our service we will create a method to get current date that will be called by client. Our service should be configured in AndroidManifest.xml within application tag.
<service android:name=".MyLocalService"/>

Bound Service

A bound service is a service which allows other applications to bind and interact with it. This is the implementation of Service where we have to override onBind() that will return IBinder.
public IBinder onBind(Intent intent) {
     return binder;
} 
To bind and unbind service we use the following methods.

bindService(Intent service, ServiceConnection conn, int flags): Binds the service. We need to pass intent which is instantiated using our service class. Pass the ServiceConnection instance created for service. flag is context value which can be as follows
BIND_ABOVE_CLIENT, BIND_ADJUST_WITH_ACTIVITY, BIND_ALLOW_OOM_MANAGEMENT,
BIND_AUTO_CREATE, BIND_DEBUG_UNBIND, BIND_IMPORTANT, BIND_NOT_FOREGROUND,
BIND_WAIVE_PRIORITY 

unbindService(ServiceConnection conn): Unbinds the bound service from other application for the given connection.

We call the above methods from the main thread of our activity.

Binder

android.os.Binder implements android.os.IBinder. If our client and service are in same application, we can implement our own Binder. To use it we can create public inner class which will extend Binder within our service and finally return the instance of this inner class by onBind() method. Extending Binder works if our service is private to our application that is known as local binding.

ServiceConnection

android.content.ServiceConnection is an interface which is used to monitor the state of service. We need to override following methods.
onServiceConnected(ComponentName name, IBinder service) : This is called when service is connected to the application.
onServiceDisconnected(ComponentName name) : This is called when service is disconnected.

Complete Example


MainActivity.java
package com.concretepage;
import java.util.Date;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Toast;
import com.concretepage.MyLocalService.LocalBinder;
public class MainActivity extends Activity {
    MyLocalService localService;
    private boolean isBound = false; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, MyLocalService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
        	unbindService(connection);
        	isBound = false;
        }
    }
    public void dispalyDate(View v) {
    	if (isBound) {
	    	Date date = localService.getCurrentDate();
	        Toast.makeText(this, String.valueOf(date), Toast.LENGTH_SHORT).show();
    	}
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
	        LocalBinder binder = (LocalBinder) service;
	        localService = binder.getService();
	        isBound = true;
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
        	isBound = false;
        }
    };
} 

MyLocalService.java
package com.concretepage;
import java.util.Calendar;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyLocalService extends Service {
    private final IBinder binder = new LocalBinder();
    public class LocalBinder extends Binder {
        MyLocalService getService() {
            return MyLocalService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
    public Date getCurrentDate() {
    	return Calendar.getInstance().getTime();
    }
 } 

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C98C00"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btn_date"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_msg"
        android:onClick="dispalyDate" />
</LinearLayout> 

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyLocalService"/>
    </application>
</manifest> 

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Concrete Page</string>
    <string name="btn_msg">Show Current Date</string>
</resources>  

Output

Android Local Bound Service Example with Binder and ServiceConnection

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us