微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。