1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 17import common from '@ohos.app.ability.common'; 18import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 19import { BusinessError } from '@ohos.base'; 20import geolocation from '@ohos.geoLocationManager'; 21import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; 22import notificationManager from '@ohos.notificationManager'; 23 24const TAG: string = 'BackgroundLocation'; 25 26@Component 27export struct LongTermTaskView { 28 @State latitude: number = 0; 29 @State longitude: number = 0; 30 31 aboutToAppear() { 32 notificationManager.requestEnableNotification().then(() => { 33 console.info(`requestEnableNotification success`); 34 let atManager = abilityAccessCtrl.createAtManager(); 35 try { 36 // 定位需要先单独申请APPROXIMATELY_LOCATION权限 37 atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.APPROXIMATELY_LOCATION']) 38 .then((data) => { 39 console.info(`data: ${JSON.stringify(data)}`); 40 atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.INTERNET', 41 'ohos.permission.LOCATION', 42 'ohos.permission.LOCATION_IN_BACKGROUND']) 43 .then((data) => { 44 console.info(`data: ${JSON.stringify(data)}`); 45 }) 46 .catch((err: BusinessError) => { 47 console.info(`err: ${JSON.stringify(err)}`); 48 }) 49 }) 50 .catch((err: BusinessError) => { 51 console.info(`err: ${JSON.stringify(err)}`); 52 }) 53 } catch (err) { 54 console.info(`catch err->${JSON.stringify(err)}`); 55 } 56 }).catch((err: BusinessError) => { 57 console.error(`requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); 58 }); 59 } 60 61 // 位置变化回调 62 locationChange = async (location: geolocation.Location) => { 63 console.info(TAG, `locationChange location =${JSON.stringify(location)}`); 64 this.latitude = location.latitude; 65 this.longitude = location.longitude; 66 } 67 68 // 获取定位 69 async getLocation() { 70 console.info(TAG, `enter getLocation`); 71 let requestInfo: geolocation.LocationRequest = { 72 priority: geolocation.LocationRequestPriority.FIRST_FIX, // 快速获取位置优先 73 scenario: geolocation.LocationRequestScenario.UNSET, // 未设置场景信息 74 timeInterval: 1, // 上报位置信息的时间间隔 75 distanceInterval: 0, // 上报位置信息的距离间隔 76 maxAccuracy: 100 // 精度信息 77 }; 78 console.info(TAG, `on locationChange before`); 79 geolocation.on('locationChange', requestInfo, this.locationChange); 80 console.info(TAG, `on locationChange end`); 81 } 82 83 // 开始长时任务 84 startContinuousTask() { 85 let context: Context = getContext(this); 86 // 通知参数,指定点击长时任务通知后跳转的应用 87 let wantAgentInfo: wantAgent.WantAgentInfo = { 88 wants: [ 89 { 90 bundleName: (context as common.UIAbilityContext).abilityInfo.bundleName, 91 abilityName: (context as common.UIAbilityContext).abilityInfo.name 92 } 93 ], 94 operationType: wantAgent.OperationType.START_ABILITY, 95 requestCode: 0, 96 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 97 }; 98 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 99 backgroundTaskManager.startBackgroundRunning(context, 100 backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 101 console.info(`Succeeded in operationing startBackgroundRunning.`); 102 }).catch((err: BusinessError) => { 103 console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 104 }); 105 }); 106 } 107 108 // 停止长时任务 109 stopContinuousTask() { 110 backgroundTaskManager.stopBackgroundRunning(getContext()).then(() => { 111 console.info(`Succeeded in operationing stopBackgroundRunning.`); 112 }).catch((err: BusinessError) => { 113 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 114 }); 115 } 116 117 build() { 118 Column() { 119 Column() { 120 Text(this.latitude.toString()) 121 Text(this.longitude.toString()) 122 } 123 .width('100%') 124 125 Column() { 126 Button('开启定位服务') 127 .onClick(() => { 128 this.startContinuousTask(); 129 this.getLocation(); 130 }) 131 Button('关闭定位服务') 132 .onClick(async () => { 133 await geolocation.off('locationChange'); 134 this.stopContinuousTask(); 135 }) 136 .margin({ top: 10 }) 137 } 138 .width('100%') 139 } 140 .width('100%') 141 .height('100%') 142 .justifyContent(FlexAlign.Center) 143 } 144} 145 146