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 ApproachBinding service automatically start service so use either bindService() or both methods. UsingiBinder is service class
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()
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;
}
}
}
[...] service using Messanger is another way. Here we discussed bounding service using iBinder. This current post address the issue of bounding service using [...]
ReplyDelete[...] Binding service using iBinder and updating UI in android [...]
ReplyDelete