I have a Started service called LocationService, which retrieves the location of the device every 3 seconds. I would like these values to be displayed on the UI of the application. To do so I would need to pass values back to the Main Activity.
The communication to the Activity would need to be continuous and be able to run long term.
What is the best way in doing this? I have looked into Bound Services and Local Broadcast but am unsure which is most applicable to continuous communication with the UI.
After a good bit of research and tinkering i found that using a LocalBroadcastManager was suitable for continuous updates to another Activity. The implementation was also straight forward.
Within the Service class when a value is updated the method updateUI()
would be ran:
private void updateUI(String statusValue){
broadcastIntent.putExtra("status", statusValue);
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
This broadcasts the value to be picked up by the Main Activity
Within the Main Activity I added a BroadcastReceiver to pick up these frequent updates:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String brStatus = intent.getStringExtra("status");
if(brStatus != null){
//Do something
}
}
}
};
I'll note that the LocalBroadcastManager can provide continuous updates only whilst the activity is running. When onPause()
is hit, the receiver for the updates is unregistered.