How to send data from the service to my activity?

I have two actions A and B I need to start a service from A The service will perform some actions. I need to use some data from the service in step B How can i do this. Please explain this with sample code.

+4
source share
3 answers

You can send data using intent in the StartService method.

This code is from my service (StartService method)

 Intent updater = new Intent(); updater.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updater.putExtra("betHour", pref.getInt("Hr", exampleHour)); updater.putExtra("betMin", pref.getInt("Mn", exampleMinute)); PendingIntent pen = PendingIntent.getBroadcast(getApplicationContext(), 0, updater, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, 60000, pen); 
+1
source

One way is to use ResultReceiver to send data from the service to the action using the Bundle. For example, you can see my blog post here . Another way is to use BroadCastReceiver. You can register your BroadCast and launch BroadCast when you want to receive data in your activity.

+1
source

Well, there are many ways to do this.

Here is one simple way: You can use Broadcast to send these messages:

 Intent i = new Intent(); i.setAction("broadcastName"); //You can put extras here. context.sendBroadcast(i); 

And what do you need the broadcast recipient in your activity:

 private static class UpdateReceiver extends BroadcastReceiver { ListSmartsActivity reference; @Override public void onReceive(Context context, Intent intent) { //You do here like usual using intent intent.getExtras(); // } } 

- change - Sorry, forgot to mention that you need to register your brochure just by doing this:

 updateReceiver = new UpdateReceiver(); registerReceiver(updateReceiver, new IntentFilter("broadcastName")); 

You can send as many transmissions as you need and register as many receivers as possible.

+1
source

All Articles