简体   繁体   English

如何在Locale更改期间在Android Oreo中进行后台API调用?

[英]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. 我需要调用一个API(即使应用程序没有运行)并使用服务器更新当前语言。 I have implemented this with the help of a BroadCastReceiver for 我已经在BroadCastReceiver的帮助下实现了这一点

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

As soon as the broadcast triggered, I'm launching a service and calling the API. 广播触发后,我即启动服务并调用API。 But, Since Android Oreo and above has background execution limits, I have to launch a ForegroundService . 但是,由于Android Oreo及以上版本具有后台执行限制,因此我必须启动ForegroundService

Here, during the background API call, a notification is visible in the Notification panel. 此处,在后台API调用期间,通知面板中会显示通知。 So, The user can still go to App settings and Force Stop the App, then the API call will be interrupted. 因此,用户仍然可以转到应用程序设置并强制停止应用程序,然后API调用将被中断。 But I need a guaranteed execution of this API. 但我需要保证执行此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? 可以在WorkManager或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. 但是如果你不喜欢前台服务,那么在数据库中排队这些信息(带时间戳),并在你的应用程序运行时发送到你的API。 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: WorkManager是一个不错的选择:

Guarantees task execution, even if the app or device restarts 即使应用程序或设备重新启动,也可以保证任务执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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