user9582784
user9582784

Reputation: 185

Run service frequently also after app was closed

For my app I want to fetch data from a server in the background. When the user wants to be notified about specific changes, I want my app to keep fetching data even when the app was closed. I was researching about this topic and found out that the possibilities of running services continuously also after the app is closed changed with Android Oreo. What I don‘t see are the alternatives to handle running services in background with newer versions of android. The most proposed solution I saw is using a Foreground Service. But since I don‘t have any user interaction, I don‘t think this solution fits perfectly. Also I read about the WorkManager but unfortunately it has a minimum time interval of 15 minutes. Are there other alternatives to process data in the background continuously than a Foreground service and a WorkManager?

Upvotes: 1

Views: 154

Answers (1)

Martin Marconcini
Martin Marconcini

Reputation: 27236

You don't need "user interaction" to have a Foreground Service, what you need is a Notification that cannot be removed while the service is in foreground.

If your notification Context is the service itself, tapping on the notification will take the user to the "settings" where he/she can force close the service for example).

You can start your FG service in a BOOT_COMPLETED broadcast receiver. You have to quickly (5 seconds or less) send it to Foreground or android will throw an exception. Unfortunately, there's a bug which Google thinks it's ok and closed as "won't fix" but you'll still need to work around.

Long story short, have an onCreate in your service:


    @Override
    public void onCreate() {
        super.onCreate();

        final Notification notification = createNotification();
        startForeground("SOME_UNIQUE_ID", notification);
    }

You get the idea (the createNotification() is whatever you want to create a Channel (if O+) + Notification.

HOWEVER, all this is nice, but it will have a service running all the time, which is probably not what you should do.

You can use an Alarm a trigger a more efficient (in terms of scope) Intent Service to do the job, schedule another alarm in, say 5 minutes, and do it again.

Or -as commented- you could use Firebase, and Notifications to react to a change.

All in all, those are the options.

I'd say that unless you truly need "real time" updating, the 15 ~ of WorkManager is usually fine, if you can deal with the fact that you have to design your code to be very independent, because WorkManager cannot receive much information and it's a pain to use for some things...

Upvotes: 1

Related Questions