首页 > 解决方案 > 无法在博览会中启动背景任务

问题描述

我想观察location应用程序在后台运行的时间。我有这个代码:

import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';

import { locationTaskName } from '../../constants/app-constants';

export async function isTracking() {
  return await Location.hasStartedLocationUpdatesAsync(locationTaskName);
}

export async function startTracking() {
  await Location.startLocationUpdatesAsync(locationTaskName, {
    accuracy: Location.Accuracy.BestForNavigation,
    timeInterval: 60 * 1000,
    distanceInterval: 100,
    accuracy: Location.Accuracy.Balanced,
    // android behavior
    mayShowUserSettingsDialog: false,
    foregroundService: {
      notificationTitle: '...',
      notificationBody: '...',
      notificationColor: 'red',
    },
    // ios behavior
    activityType: Location.ActivityType.Fitness,
    showsBackgroundLocationIndicator: true,
    pausesUpdatesAutomatically: true,
  });
  console.log(`[Tracking]: Started background location task ${locationTaskName}`);
}

export async function stopTracking() {
  await Location.stopLocationUpdatesAsync(locationTaskName);
  console.log(`[Tracking]: Stopped background location task ${locationTaskName}`);
}

TaskManager.defineTask(locationTaskName, async event => {
  if (event.error) {
    return console.error(`[Tracking]: Something went wrong within the background location task ${locationTaskName}. Error: `, event.error);
  }
  const location = event.data.locations[0]
  console.log('Track: ', location)
});

这给了我这个错误

可能的未处理承诺拒绝(id:1):错误:找不到应用程序 ID 'mainApplication' 的任务'track-user-location'。

track-user-location是 中的字符串locationTaskName。这是为什么?

标签: javascriptreact-nativeexpo

解决方案


推荐阅读