简体   繁体   中英

How to make background API calls in Android Oreo during Locale change?

I have a scenario where I need to notify the server whenever the device language changes. I need to call an API (even if the app is not running) and update the current language with the server. I have implemented this with the help of a BroadCastReceiver for

  <action android:name="android.intent.action.LOCALE_CHANGED" />

As soon as the broadcast triggered, I'm launching a service and calling the API. But, Since Android Oreo and above has background execution limits, I have to launch a ForegroundService .

Here, during the background API call, a notification is visible in the Notification panel. So, The user can still go to App settings and Force Stop the App, then the API call will be interrupted. But I need a guaranteed execution of this API. Is there any way to execute it in the background other than foreground service? Can it be done with the help of WorkManager or Job Scheduler? What is the best way to handle this use case? Hope my question is clear. Thanks in advance!

The user can always kill your app so this should not be unexpected. But if you do not like foreground service, then queue this information (with timestamp) in DB and send to your API next time your app is running. If you must send immediately then do queue it too and then send immediately. If the user kills your app in mid-operation then you still will be able to resend it from queue next time. WorkManager is a good choice:

Guarantees task execution, even if the app or device restarts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM