I have ju开发者_如何学Gost started using services in Android and I have a made a simple service that is polling a server every 20 seconds.
Now how can I get this data from my main activity (when it is active)?
Alternatively the service could send it back do my main activity (but only if its active). I don't want to wake up my activity.
I have read SDK examples of "Binding" but I can't find an example how to actually get something from the service. Just how to start and stop the Binding.
From the example. If I have the "mBoundService" object in my activity how do I get my data from the service method called eg. "pollingData()"?
My suggestion would be to send out a broadcast using sendBroadcast()
from the service and then use a BroadcastReceiver
as an inner class in your main activity. Depending on your service you can just attach the data to the intent using putExtras()
and getExtras()
Hope this helps!
A practical example:
public class x extends Service {
//Code for your service goes here
public talk() {
Intent i = new Intent();
i.putExtras("Extra data name", "Super secret data");
i.setAction("FILTER");
sendBroadcast(i);
}
}
Then in the class the service is talking to:
public class y extends Activity {
//Code for your activity goes here
BroadcastReceiver br = new BroadcastReceiver() {
public void onReceive(Intent i) {
String str = (String) i.getExtras().get("Extra data name").toString();
}
OnResume() {
super.OnResume();
IntentFilter filt = new IntentFilter("FILTER");
this.registerReceiver(br, filt);
//Do your other stuff
}
OnPause() {
super.OnPause();
unregisterReceiver(br);
}
Hope this example is about what you are looking for, let me know if you need any more details.
精彩评论