Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

Bound Service Example in Android

|| 0

Bound Service Example in Android
Stechies

What is a bound service?

A bound service is like a server in a client-server interface. A bound server allows components, such as activities, to bind to the service, send requests, receive responses and even perform IPC or Inter-Process Communication.

There are three ways of creating bound services:

  1. First is by extending the binder class
  2. Second is by using a messenger
  3. Third, is by using AIDL or Android Interface Definition Language.

Read Next Creating Started Service

In this tutorial, we are going to create bind service or a bound service by extending a binder class.

Please follow the steps below for creating a bound service by extending the binder class:

Step 1) First of all in a blank bare born project we will create a service as we always do for creating a service.

So right click your package->create new->go to services->click service.

Now please name the service class finish it.

Step 2) Now it will create a class which extends from service class. As we know if you want to create a service we need to extend from service class.

And this is the onBind method which we implement when we create our bound service.

Now in which scenarios we want to create a bound service by extending the Binder class. And why or how we can do it lets see.

So if your service is private to your own application and runs in the same process as the client (which is the most common case) then should create your interface by extending the Binder class and returning an instance of it from 'onBind' method which will be automatically generated for us.

Step 3) Now let's create the bound service by extending the binder class.

So, first of all, we will create a class inside our my service class which will be a public class and I will name it as LocalBinder. And this class will extend from the binder class.

Step 4) Now inside the 'LocalBinder'class which we created what we want to do is to create a method which returns MyService and the method name is GetService. And what this is going to do is it is going to return an instance of MyService.this.

Step 5) Now as the definition says that "We need to create our interface by extending from the binder class and returning an instance of it from onBind method". So we are going to do the same.

Therefore, first of all, we are going to create our binder interface, give any name to your binder class for example 'IBinder' and initialize this using our local binder class.

And as it says that we need to return this instance from onBind method. So just take this instance of interface and just return it from here.

Step 6) Now, for example, we want to create a random number generator for our bound service.

So what we can do is we can create a variable called 'mGenerator' and which uses the class called 'Random' which is used to generate the random numbers and we are going to initialize it by new Random.

Step 7) Now we have to create a method which is going to return an integer value. And in here we want to return the generated random number. So just write 'mGenerator .nextInt' and in the argument of nextInt just give the range in which you want to create the random number. For example, under 200 you want to create this random number then you just need to give 200.

So it's going to create the random number between 0 to 200.

This is how we can create a bound service using the extension or which extends from the binder class.

Step 8) Now in our interface or in our activity what we are going to do is we are going to take a button and a large text on which we are going to display the number.

Now go to your activity and go to your text and in the button here add an element called 'onClick' and we can give any method name. for example GetRandomNumber and this is the method which we are going to implement

Step 9) Now go to your main activity.java file and in here, first of all create this method, and inside this we are going through return this random number.

Now at the top we are going to define two variables. One is the object or instance of my service class, so MyService object and second is a variable for checking our services bound or not. So this will be our Boolean variable and we are going to name it as isBound. And we are going to initialize it as false.

Step 10) Now we need to create an object of a class called service connection at the bottom. So inside the class go at the bottom and in here create an instance of a class called service connection and we will name it as service connection and we will press alt+enter to import service connection class and when you press enter for the first method here it will create two methods automatically.

Now in these methods you need to write some code and in the first line you need to create our lower binder object and cast it lower binder with the service instance. And in the 'onservice disconnected' method we want to make our isbounder variable as false.

Step 11) Now as we always do we need to create intent for creating our service. So go to on create method here and create an intent oject.

And now we are going to create a bound service and the first argument of it will be your intent, second will your instance of your service connection instance and the third argument will be context.BIND_AUTO_CREATE.

Step 12) Now one thing, which is remaining now, is to display our random number in our added text view. So we will create an object of a text view and we are going to cast it with (textview)findViewById(R.Id.textView).

And then you just need to take your textView.setText and inside this use object of my service class and using this we can call our getRandom function here.

This will not work as this to returning an integer because we need to pass the 'setText' to string variable. So what we can do is we can cast this cast this integer to string.

Now everything is done. So let's run our program.

Now our app is running now and when we click this get random number button it gives me a random number which is 142.So in this way you can create a bound service in Android.

Complete Code:

import android.app.Service;
import android.cintent.Intent;
import android.os.IBinder;

public class MyService extends Service{
	public MyService(){
		
	}
}

@Override
public IBinder onBind(Intent intent){
	//TODO: Return the communication channel to the service.
	throw new UnsupportedOperationException("Not yet implemented");
}

public class MyService extends Service{
	public class LocalBinder extends Binder{
		MyService getService(){
			return MyService.this;
		}
	}
}

public class MyService extends Service{
	private final IBinder iBinder = new LocalBinder();
}

@Override
public IBinder OnBind(Intent intent){
	return iBinder;
}

Public class MyService extends Service{
	private final IBinder iBinder = new LocalBinder();
	private final Random mGenerator = new Random();
}

public int gerRamdom(){
	return mGenerator.nexInt(200);
}

Public void gerRamdomNumber(View view){
	TextView textView = (TextView)findViewById(R.id.textView);
	textView.setText(Integer.toString(myService.gerRamdom()));
}

public class MainActivity extends ActionBarActivity{
	MyService myService;
	boolean isBound = false;
}

private ServiceConnection serviceConnection = new ServiceConnection(){
	@Override
	public void onServiceConnected(ComponentName name, IBinder service){
		MyService.LocalBinder binder = (MyService.LocalBinder) service;
		myService = binder.getService();
		isBound = true;		
	}
	@Override
	public void onServiceDisconnected(componentName name){
		isBound = false;
	}
};

@Override
protected void onCreate(bundle saveInstanceState){
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	Intent intent = new Intent(this,MyService.class);
	bindService(intent,serviceConnection, Context.BIND_AUTO_CREATE);
}

XML

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get random Number"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="91dp"
android:layout_marginStart="91dp"
android:layout_marginTop="45dp"
android:onClick="getRandomNumber"/>

 


Advertisement
Advertisement
Advertisement