Passing Data From Activity To Service Through Interface
I am trying to pass data from an Android Activity to a Service. I am attempting to do so by calling a method within another class which contains an interface,this interface is impl
Solution 1:
You can pass data from Android activity to service as intent extras while starting service.
Intent i = newIntent(this, MyService.class);
i.putExtra("key", value);
startService(i);
Inside onHandleIntent() method of your service:
@OverrideprotectedvoidonHandleIntent(Intent intent) {
String data = intent.getStringExtra(key);
...
}
Solution 2:
Passing data from activity to service through interface
For getting data from Activity to service using interface we need to get interface object in Actvity which we are implementing in Service.
For example just for testing:
1. Create a static reference in Service:
publicstatic SubscribeHandler subscribeHandler;
2. In onStartCommand()
method of Service assign this to subscribeHandler:
subscribeHandler=this;
Now after starting Service access subscribeHandler
in Activity from Service for sending data:
subscribeHandler.handleSubscribe("Message");
But not good approach use static objects for sending data between to components of application
So for communicating between Service and Activity use LocalBroadcastManager
Post a Comment for "Passing Data From Activity To Service Through Interface"