HarmonyOS 鸿蒙Next应用切后台后怎么实现后台定位

HarmonyOS 鸿蒙Next应用切后台后怎么实现后台定位 后台定位,已经申请了长时任务。应用切后台后 定位就停止了。麻烦问一下怎么才能做到应用进程还在的情况下 后台就一直能定位。

4 回复

需要申请长任务,和定位权限到始终允许才能后台定位

更多关于HarmonyOS 鸿蒙Next应用切后台后怎么实现后台定位的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


不会后台定位

HarmonyOS 鸿蒙Next后台定位代码如下:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-backgroundtaskmanager

配置后台长任务权限

"module": {

   "abilities": [

      {

         "backgroundModes": [

         "dataTransfer",

         "location"

         ], // 后台模式类型

      }

   ],

   "requestPermissions": [

      {

         "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"  // 长时任务权限

      },
      {
        "name": "ohos.permission.LOCATION_IN_BACKGROUND",
        "reason": "$string:get_location_description",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "inuse"
        }
      }

   ]

}

backgroundTaskManager申请配置后台任务

  // 申请长时任务
  async startBackgroundRunning() {
    const context = getContext()
    // 获取 bundle 应用信息
    const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)

    let wantAgentInfo : wantAgent.WantAgentInfo = {
      wants: [
        {
          bundleName: bundleInfo.name,
          abilityName: "EntryAbility"
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };

    // 重点: 创建后台定位任务
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => {
      backgroundTaskManager.startBackgroundRunning(context,
        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, (err: BusinessError, data: void)=> {
        if (err) {
          console.error("Operation startBackgroundRunning failed Cause: " + JSON.stringify(err));
        } else {
          console.info("Operation startBackgroundRunning succeeded");
        }
      })
    });

  }

  stopBackgroundRunningTask() {
    const context = getContext()
    backgroundTaskManager.stopBackgroundRunning(context).then(() => {
      console.info(`Succeeded in operationing stopBackgroundRunning.`);
    }).catch((err:BusinessError) => {
      console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
    });
  }

在HarmonyOS(鸿蒙Next)中,应用切后台后实现后台定位,可以通过使用LocationManagerBackgroundTask来实现。首先,应用需要在config.json中声明ohos.permission.LOCATIONohos.permission.LOCATION_IN_BACKGROUND权限。然后,使用LocationManager获取位置信息,并通过BackgroundTask在应用切后台后继续执行定位任务。具体步骤如下:

  1. 声明权限:在config.json中添加以下权限声明:
"reqPermissions": [
    {
        "name": "ohos.permission.LOCATION"
    },
    {
        "name": "ohos.permission.LOCATION_IN_BACKGROUND"
    }
]
  1. 初始化LocationManager:在应用代码中初始化LocationManager并设置定位参数:
import geoLocationManager from '@ohos.geoLocationManager';

let locationManager = geoLocationManager.getLocationManager();
let requestInfo = {
    priority: geoLocationManager.LocationRequestPriority.FIRST_FIX,
    scenario: geoLocationManager.LocationRequestScenario.NAVIGATION,
    timeInterval: 1,
    distanceInterval: 0,
    maxAccuracy: 0
};
  1. 请求位置更新:使用LocationManager请求位置更新:
locationManager.requestLocationUpdates(requestInfo, (location) => {
    console.log('Location updated:', location);
});
  1. 使用BackgroundTask:在应用切后台时,通过BackgroundTask继续执行定位任务:
import backgroundTask from '@ohos.backgroundTask';

let backgroundTaskId = backgroundTask.startBackgroundTask(() => {
    // 在这里继续执行定位任务
    locationManager.requestLocationUpdates(requestInfo, (location) => {
        console.log('Background location updated:', location);
    });
});

通过以上步骤,应用在切后台后仍可以继续获取位置信息。

回到顶部