I need to implement accelerometer running on background service on Android. The thread has to communicate both way and fire event based on accelerometer data. The service has to run indefinitely and in case that OS kills service, it restarts from previous state. I did some research and I am not sure whether to use Bound Service or Out of process Service. Is it possible to implement this task? Which type of service works for this problem?
Asked
Active
Viewed 1,105 times
1
-
Foreground Service: https://developer.xamarin.com/guides/android/application_fundamentals/services/part_1_-_started_services/#Foreground_Services – SushiHangover Nov 15 '17 at 19:14
-
Does this foreground service run even if the phone is locked? – Jan Nepraš Nov 15 '17 at 19:23
-
1Yes, think of it like your mp3 player that sits in the notification bar. As a foreground service it has a higher priority so the OS will consider it last to be killed, it avoids the automatic dozing of your services to save battery in later APIs , etc... The "downside" is the user must be made aware that it is running, thus the requirement to be placed in the notification bar, personally I do not see that as a problem and wish it was a hard requirement for all services.., – SushiHangover Nov 15 '17 at 19:47
-
You might not get any accelerometer updates when the screen is off. With a wake lock you can keep the screen on, but that might not be feasible. – Markus Kauppinen Nov 15 '17 at 19:51
-
Could you explain me why this might not be feasible? – Jan Nepraš Nov 15 '17 at 22:23
-
@SushiHangover I implemented everything and it works well. When an event in Foreground Service is fired I use MessagingCenter to call some code in different class. Is there any other way to substitute MessagingCenter. I don't want to be dependant on Xamarin.Forms. – Jan Nepraš Nov 24 '17 at 09:37
-
1@JanNepraš You can create a `BroadcastReceiver` subclass to receive the "events" from your service (publish-subscribe model). You would call `SendBroadcast` in your service, these calls already asynchronous, so your service become a broadcast pump and your receiver(s) could update a database, update screen, perform https posts, etc... https://developer.xamarin.com/guides/android/application_fundamentals/broadcast-receivers/ – SushiHangover Nov 24 '17 at 09:49
-
@SushiHangover thank you. That worked really well. – Jan Nepraš Nov 24 '17 at 14:16
1 Answers
2
Is it possible to implement this task? Which type of service works for this problem?
You will need partial wake lock to prevent the service from being stopped.
Then you can use certain service like Foreground Service as @SushiHangover suggested to track accelerometer data and fire event when necessary.

Elvis Xia - MSFT
- 10,801
- 1
- 13
- 24