Search This Blog

Wednesday 20 February 2013

Binding service using iBinder and updating UI in android

Binding service is used when you want to communicate with service either it for updating UI with the work you are doing in service or using values of service's current instance. See binding service using Messanger

You can bind service by multiple ways but here i explain using iBinder method.

Some Fact
You can only bind service with activity not with the BroadcastReceiver

Binding Purpose
To get current instance of Service to interact with its member
When to use iBinder Approach
If your service is private to your own application and runs in the same process as the client (which is common), you should create your interface by extending the Binder class and returning an instance of it from onBind()
Binding service automatically start service so use either bindService() or both methods. UsingiBinder is service class

public void startingService() {
Intent intent = new Intent(this, UsingiBinder.class);
startService(intent);
}

public void bindService() {
Intent intent = new Intent(this, UsingiBinder.class);
bindService(intent, new ConnectService(), 0);
}

ConnectService is ServiceConnection that provide you bridge between Service and activity. It has two method

onServiceConnected(ComponentName name, IBinder service)
onServiceDisconnected(ComponentName name)

Service class has method onBind(Intent arg0) that help to return service instance in the form of iBinder

 import android.app.Service;  
 import android.content.Intent;  
 import android.os.Binder;  
 import android.os.IBinder;  
 public class UsingiBinder extends Service {  
 @Override  
 public IBinder onBind(Intent arg0) {  
 return iBinder;  
 }  
 private IBinder iBinder = new ContainsLocal();  
 public class ContainsLocal extends Binder {  
 UsingiBinder getBinder() {  
 return UsingiBinder.this;  
 }  
 }  
 }  

Download All Service Binding Example

2 comments:

  1. [...] service using Messanger is another way. Here we discussed bounding service using iBinder. This current post address the issue of bounding service using [...]

    ReplyDelete

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code