Android Bound Service

In the previous tutorial we have seen unbounded android service and it's life cycle , here in this tutorial we will discuss on android bounded service with example  .

Android bound service offer's a kind of client server interface , in which service component act as server and the component with which it is  going to binded (lets say activity) act as client . bounded service allows to send requests, receive responses, and even perform interprocess communication (IPC). a bound service lives until it serves to the component with which it is binded and does not run indefinitely.



Bound Service Life Cycle



bindService()
To client component must call bindService() method to bind to a service component by passing intent , service connection object and bound flag as parameter to it.

unbindService()
To unbind from service component client component must call unbindService() by passing service connection object as paramter to it.

Bound Service Methods


onCreate()
 The onCreate() method of the service is called only once during the creation of service object.

onBind()
 The onBind() returns an IBinder object that defines the programming interface that clients can use to interact with the service.
 
onUnbind()
 This method is used to disconnect service component , the return type of this method is boolean value , if the return value is true you can
 make a call to onRebind() , so that the client bind to service instead of receiving a call to onBind().

onRebind()

 This method is used for rebinding the unbinded service component without making a call to onBind() again.

onDestroy()
 Call to this method destroys the service component.


ServiceConnection


Android API Provides a Interface Called ServiceConnection for monitoring the state of an application service ,this interface provides two methods .

onServiceConnected() :
This method is called when a connection to the Service has been established , This method provides the IBinder object which you can use to make a call to methods in service call .

onServiceDisconnected() :
This Method is called when a connection to the Service has been lost .

XML Layout


file : activity_main.xml
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="38dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="50sp" />

    <Button

        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:onClick="showRandomNumber"
        android:text="Random Number"
        android:textSize="30sp" />

</LinearLayout>

Creating Bound Service

  1. Create an Inner Class LocalBinder Inside the MyService class and extend the LocalBinder to IBinder class.
  2. Inside the MyService Class Create an object for LocalBinder class.
  3. Override the onBind() method inside the MyService class which returns IBinder object.
  4. Inside the LocalBinder class create a method getService() which returns the IBinder object.

file : MyService.java
package com.example.binderservicedemo;

import java.util.Random;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {

    private IBinder mBinder = new LocalBinder();

    // Random number generator
    private final
Random mGenerator = new Random();

    @Override
    public
IBinder onBind(Intent intent) {
        return mBinder;
    }

    /** method for clients */
    public
int getRandomNumber() {
        return mGenerator.nextInt(100);
    }

    class LocalBinder extends Binder {

        public MyService getService() {
            return MyService.this;
        }
    }

}


MainActivity

  1. Inside the onResume() method make a call to bindService() method by passing intent ,service connection object and Bind Flag as paramter to it .
  2. Inside the onStop() method make a call to unbindService() by passing service connection object as parameter to it.
  3. Inside the MainActivity Class Create a Service Connection object and inside the onServiceConnection() method hold the reference to IBinder object which you can  later call to the methods defined inside the service class .

file : MainActivity.java
package com.example.binderservicedemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
import com.example.binderservicedemo.MyService.LocalBinder;

public class MainActivity extends Activity {

    TextView tv;

    MyService mService;
    boolean mBound;

    ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void
onServiceDisconnected(ComponentName name) {
            mBound = false;
            mService = null;
        }

        @Override
        public void
onServiceConnected(ComponentName name, IBinder service) {
            mBound = true;
            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();
        }
    };

    @Override
    protected void
onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.textView1);

    }

    public void showRandomNumber(View view) {

        int randomNum = mService.getRandomNumber();
        tv.setText(randomNum + "");

    }

    @Override
    protected void
onResume() {
        super.onStart();

        Intent i = new Intent(this, MyService.class);
        bindService(i, mConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected
void onStop() {
        super.onStop();

        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }

    }

}


AndroidManifest


Declare the Service Class inside the manifest file

file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest 
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.binderservicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk

        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application

        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity

            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action
android:name="android.intent.action.MAIN" />

                <category
android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
android:name=".MyService"></service>
    </application>

</manifest>



3 comments:

vydyabhushana siddhu said...

pavan i need background service example

Pavan Deshpande said...

Service Component is used to run in background , you can configure your service with android platform how it should behave when it gets killed check this link http://www.tutorialsbuzz.com/2015/01/android-service-life-cycle.html

Arif Ishaq said...

Greate Tutorial

Post a comment