首页 > 解决方案 > 我想每 1 分钟在后台自动运行一次应用程序(我使用 TaskManager - Expo)

问题描述

我将expo应用程序与android一起使用,我想在后台自动运行我的应用程序,任务后台应该每1分钟运行一次应用程序,我与TaskManager一起使用-Expo 我是expo react native的新手,我需要有关该问题的帮助,因为这对我来说太难了。

我的代码中缺少什么或需要修复什么才能使其正常工作?

我的想法只是在后台自动运行应用程序。
另外,如果我必须在 app.json 中写一些东西,请告诉我(仅在需要时)

我也在 app.js 中调用了“registerFetchTask”:

从 './helpers/registerFetchTask' 导入 { registerFetchTask }

registerFetchTask();

这是代码本身:

import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';

const FETCH_TASKNAME = 'test_task'
const INTERVAL = 60

function test() {
    console.log('function is running')
}

export async function registerFetchTask() {
    TaskManager.defineTask(FETCH_TASKNAME, test);

    const status = await BackgroundFetch.getStatusAsync();
    switch (status) {
        case BackgroundFetch.Status.Restricted:
        case BackgroundFetch.Status.Denied:
            console.log("Background execution is disabled");
            return;

        default: {
            console.debug("Background execution allowed");

            let tasks = await TaskManager.getRegisteredTasksAsync();
            if (tasks.find(f => f.taskName === FETCH_TASKNAME) == null) {
                console.log("Registering task");
                await BackgroundFetch.registerTaskAsync(FETCH_TASKNAME);

                tasks = await TaskManager.getRegisteredTasksAsync();
                console.debug("Registered tasks", tasks);
            } else {
                console.log(`Task ${FETCH_TASKNAME} already registered, skipping`);
            }

            console.log("Setting interval to", INTERVAL);
            await BackgroundFetch.setMinimumIntervalAsync(INTERVAL);
        }
    }

}

标签: javascriptreactjsreact-nativeexpotaskmanager

解决方案


推荐阅读