-1

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.

Basmatti
  • 27
  • 8
  • You can use Handler to pass data in activity. – Abhay Koradiya Jun 08 '18 at 09:45
  • The question is way too broad, there's lots of ways to do this and there's not 1 way which is best for everyone. LiveData, Broadcasts and RxJava are all good solutions in general. – Sander Jun 08 '18 at 10:01
  • @Sander There are many ways to do this and that's why i asked the question, as I am getting confused with what is the best solution. I am happy to make my question more specific – Basmatti Jun 08 '18 at 10:25
  • There is no single best way to do it, it really depends on your needs and the structure of you app. E.g. I'm getting location updates in a repository which sends location updates through LiveData to the ViewModel which exposes this LiveData to the Fragment, but that wouldn't make sense if you're not using an MVVM architecture in your app. – Sander Jun 08 '18 at 10:31

1 Answers1

0

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.

Basmatti
  • 27
  • 8