本文原创发布在华为开发者社区。
介绍
本示例演示的是申请定位权限之后,可以在后台持续进行上传定位及位置信息。
效果预览
使用说明
点击申请权限,点击申请长时任务可以在控制栏看到持续进行定位。
实现思路
startContinuousTask() {
let wantAgentInfo: wantAgent.WantAgentInfo = {
// 点击通知后,将要执行的动作列表
// 添加需要被拉起应用的bundleName和abilityName
wants: [
{
bundleName: "com.example.BackgroundTaskDemo",
abilityName: "EntryAbility"
}
],
// 指定点击通知栏消息后的动作是拉起ability
actionType: wantAgent.OperationType.START_ABILITY,
// 使用者自定义的一个私有值
requestCode: 0,
// 点击通知后,动作执行属性
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// 后台持续定位配置
let request: geoLocationManager.ContinuousLocationRequest =
{ 'interval': 5, 'locationScenario': geoLocationManager.UserActivityScenario.NAVIGATION };
// 通过wantAgent模块下getWantAgent方法获取WantAgent对象
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
let list: Array<string> = ["location"];
backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj)
.then((res: backgroundTaskManager.ContinuousTaskNotification) => {
hilog.info(0x0000, 'testTag',"Operation startBackgroundRunning succeeded");
// 开启后台持续定位
try {
geoLocationManager.on('locationChange', request, this.locationCallback);
} catch (err) {
hilog.error(0x0000, 'testTag',"errCode:" + JSON.stringify(err));
}
})
.catch((error: BusinessError) => {
hilog.error(0x0000, 'testTag',`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
});
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。