Foreground Service - make API request and show notification

from the CommonsWare Community archives

At January 29, 2021, 3:22pm, grrigore asked:

Hello,

I’m trying to implement a Foreground Service that has to make a periodic API request and based on the API’s response show a notification. The periodicity might vary from 1 minute to 10 minutes based on the user selection. I am aware of the effect this service might have on the battery but it’s something that the app assumes in order to achieve this functionality.

I had a look over an example on your github @ cw-android-q, ForegroundService.kt but this one extends LifecycleService and uses LiveData. At the moment my implementation is a little bit different. I’m using RxJava and Retrofit for my API requests and I’m not using LiveData.

Let’s say my service is AppService and it extends DaggerService. I’ve followed this tutorial for the implementation of my service.

I was wondering if an Observable.interval(X, TimeUnit.MINUTES) would be a good approach for this. So, AppService should start and the Observable should periodically make that API request, when the API responses I will call a function that will display a notification. As per the tutorial, he is launching a coroutine (see line 89).

We’ve also talked during office hours, you might or might not remember and recommended me ScheduledExecutorService.

Ok, so my question is if I’m on the right path or not and if you have any recommendations regarding this:

Let me know if you have any questions or if I can clarify things for you. And sorry in advance if this is not well redacted.


At January 29, 2021, 7:56pm, mmurphy replied:

That should be fine. I suggested ScheduledExecutorService based on a pure Android SDK solution, without involving RxJava, coroutines, or anything else.

That would be a good idea.

Sorry, but I am uncertain what you mean by this. Observable is oblivious to what sort of Android component uses it, because RxJava is independent of Android. Or, to put it another way, I would expect Observable.timer() to work about as well as ScheduledExecutorService when used from a foreground service.


At January 30, 2021, 11:21am, grrigore replied:

I mean as long as the AppService is running the Observable should do its work. Assuming it is correctly setup.


At January 30, 2021, 12:30pm, mmurphy replied:

I would not expect any problems here.