Android 在后台获取任务中的异步获取之前断开 Wi-Fi

问题描述

我正在使用 expo-background-fetch 安排后台提取任务。在该任务中,我想请求地理定位,对我的服务器进行 HTTP 调用以检索一些数据,并且我还想发送通知

问题在于地理位置请求、获取通知计划功能是异步的。当我使用 .then 或调用 async 函数时,主任务函数已经返回,因此 Android 在 fetch 发生之前切断了 Wi-Fi 连接。 (这不会发生在移动数据上,因此后台提取任务完全完成。在 iOS 上提取也失败,但可能不是因为这个,我还不知道。)

示例代码

import * as TaskManager from 'expo-task-manager';
import * as BackgroundFetch from 'expo-background-fetch';
import * as Location from 'expo-location';
import * as Notifications from 'expo-notifications';

const BG_TASK_NAME = "me.mogery.dummybgf"

export async function init() {
    TaskManager.defineTask(BG_TASK_NAME,function backgroundFetch() {
        console.log("[BGF] Called.");
        
        (async function() {
            var location = await Location.getCurrentPositionAsync({
                accuracy: Location.LocationAccuracy.Balanced
            });
            console.log("[BGF] User location:",location);
            
            var poll = await (await fetch("https://myapihere")).json();
            console.log("[BGF] Poll complete.");

            if (poll.notify) {
                var res = await Notifications.scheduleNotificationAsync({
                    content: {
                        title: "Test notification",body: "Yay!"
                    },trigger: null
                });
                console.log("[BGF] Scheduled notification.",res);
            }
        })();

        return BackgroundFetch.Result.NewData;
    });

    await BackgroundFetch.registerTaskAsync(BG_TASK_NAME,{
        minimumInterval: 15*60,stopOnTerminate: false,startOnBoot: false
    });

    var status = await BackgroundFetch.getStatusAsync();
    console.log("[BGF] Status",status);
}

我尝试使用 while 循环在返回之前等待异步,但最终只是冻结了事件循环。我也尝试过使用 Atomics.wait,但它在 Android 上不可用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)