views:

52

answers:

1

I have just 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()"?

+2  A: 

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.

Andrew Guenther
Thanks Do you know if there is any practical examples of this?
droidgren
I just added one for you! Hope it helps. Broadcasts are often used by android to let other programs or other parts of itself what is going on. Things like an incoming text message or outgoing call all produce broadcasts.
Andrew Guenther
Thank you, I really appreciate your help. Your example worked fine although it was: public void onReceive(Context c, Intent i) and then a ";" after .toString();
droidgren
All fixed. My bad.
Andrew Guenther