I seem to have a classic task, yet I can't find any examples on how to do it.
I want to download something. Well I call a web service and get a response... but it's pretty much the same.
In order to do this I have an activity that starts a service that spawns a thread that does the job.
Now i would like to use the data I got in the activity that started the service.
(I assume that starting another activity to handle the job of displaying the result would be simple)
My problem is how does the service notify an activity (the one that started it or another one) of something?
Any pointers to examples are much appreciated.
Regards
we have two method. 1, you can use BROADCAST. you can send BROADCAST in service and use BroadcastReceiver in activity. 2, you also can use bindService to communicate activity.
You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
You need to create a BroadcastReceiver in your activity (be sure to register it in onResume() and unregister it in onPause() ) and notify it via a broadcast, providing an Intent .
According to Google documentation, if your Activity
and Service
are within the same app, using a LocalBroadcastManager is preferable over sendBroadcast (intent) because the information sent does not go through the system which eliminates the risk of interception.
It's quite easy to use.
In your activity, create a BroadcastReceiver
and dynamically add a listener in the onResume() method :
private BroadcastReceiver bReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { //put here whaterver you want your activity to do with the intent received } }; protected void onResume(){ super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message")); } protected void onPause (){ super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver); }
And in your service, you get an instance of LocalBroadcastManager and use it to send an intent. I usually put it in its own method like this :
private void sendBroadcast (boolean success){ Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver intent.putExtra("success", success); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With