简体   繁体   English

如何在后台使用应用程序在Android上进行网络通话

[英]How to make network calls on Android with an app in the background

I am building a react-native app that launches a series of network requests (both UDP, HTTP) when it receives a special kind of notification, or based on a delayed execution. 我正在构建一个本机应用程序,该应用程序在收到特殊类型的通知时或基于延迟执行时会启动一系列网络请求(UDP,HTTP)。

However it turns out that after the first or second call, it enqueues the calls, without making them. 但是事实证明,在第一个或第二个呼叫之后,它将使呼叫排队,而不进行呼叫。 If I open the applications, the remaining network calls are made, and the process continues. 如果我打开应用程序,则会进行其余的网络调用,然后继续进行该过程。

It's a normal issue given that there is a specific doc page inside Android documentation targeting this behaviour: 考虑到Android文档中有一个针对此行为的特定文档页面,这是一个正常问题:

I have read and research over SO: Best place to make network calls , How to make network call from Background service? 我已经阅读并研究了SO: 进行网络通话的最佳位置如何从后台服务进行网络通话? but those methods did not work to bypass the obstacle. 但是这些方法无法绕过障碍。 I can require the user to deactivate "battery optimisation" if required, but that did not work either. 如果需要的话,我可以要求用户停用“电池优化”功能,但这也不起作用。

I should mention that I am using React Native in order to handle the lifecycle and trigger the network calls, so they are running inside an Activity that is not in the background or when the phone is locked. 我应该提到,我正在使用React Native来处理生命周期并触发网络调用,因此它们正在不在后台或电话被锁定的Activity中运行。 I believe there should be ways moving things to a) a background thread or b) an Android service. 我相信应该有办法将内容移至a)后台线程或b)Android服务。

I really appreciate any response, experience or links that would help me address this problem. 我非常感谢任何能够帮助我解决此问题的回复,经验或链接。

Ideally, you would want to trigger these calls in a HeadlessJS setup. 理想情况下,您希望在HeadlessJS设置中触发这些调用。 To ensure to subsequent calls are made, either try reducing all the responses to a single API call, or use Promise.all to resolve it. 为了确保进行后续调用,请尝试将所有响应减少到单个API调用,或者使用Promise.all来解决它。 Multiple calls might fail due to how battery optimisations are designed. 由于电池优化设计的方式,多次通话可能会失败。

To work around such battery optimisations, you will have to promote the HeadlessJs task into a foreground service (Android 7+), which you can do with native code, or calling it from NativeModules from the JS side. 要解决这种电池优化问题,您必须将HeadlessJs任务升级为前台服务 (Android 7+),可以使用本机代码执行此操作,也可以从JS端从NativeModules调用它。

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

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