Android Service to Activity syncronization

Viewed 15

I'm working on building an Android app that allows the user to press a button which actives a foreground service which subscribes to location updates and then sends them to a backend server. After a period of time the user can press another button to deactivate the service.

The Service communicates with the Activity to show the status, e.g. connected to backend server, and location updates broadcasting etc. When something happens in the Service is uses sendBroadcast and the Activity is listening using a BroadcastReceiver filtered to my actions only (this then updates the UI).

What is the best way to do the dance between deactivating and showing the pending status on the Activity and then finally stopping the service and closing the activity.

The option I'm currently exploring is using a bound service, to communicate from the Activity to the Service - so when the user presses the deactivate button it calls a deactivate method in the Service. This method will need to send an http request to the backend to indicate the user has deactivated, and then unsubscribe the location update callback.

What's the best way to stop the service, should I in the button click handler in the Activity call

Intent stopService = new Intent(this, MyService.class);
stopService(stopService);

and in the onDestroy make the http request to the backend. OR Would it be better to use the bound service to call a method in the service which makes the http request and calls stopSelf and stopForeground on itself.

0 Answers
Related