Service call backs to activity in android
android, callback, service
Solution
Here is the flow Create your intent to call a service. You can either `startService()` or `BindService()` with `BIND_AUTO_CREATE`
Once the service is bond, it will create a tunnel to talk with it clients which is the `IBinder` Interface. This is used by your AIDL Interface implementation and return the `IBinder` in
private final MyServiceInterface.Stub mBinder = new MyServiceInterface.Stub() {
public int getNumber() {
return new Random().nextInt(100);
}
};
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
return mBinder;
}
Once it returns the `mBinder`, `ServiceConnection` that you created in the client will be called back and you will get the service interface by using this
mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = MyServiceInterface.Stub.asInterface(service);
};
Now you got the `mService` interface to call and retreive any service from that
Problem
I have a background service running and a client which interacts with the service. When the client requests for some operation, the service performs it and it should send the result back to the activity (client). I know how to invoke the service methods in activity and using call backs we can achieve what I want to do. But I am not able to understand the call back mechanism and code example provided in Api demos (remoteservice). Could someone explain how this service callback works; or anything which is achievable using simpler mechanism.