参考示例如下:// Datatransfer.ets文件 import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import { BusinessError } from '@ohos.base'; import router from '@ohos.router'; import http from '@ohos.net.http'; import { notificationManager } from '@kit.NotificationKit'; const TAG = "[DATA_TRANSFER_PAGE]" const START_DATA_TRANSFER_BGMODE = 1 const STOP_DATA_TRANSFER_BGMODE = 2 const START_LOCATING1 = 3; const STOP_LOCATING1 = 4; const START_LOCATING2 = 5; const STOP_LOCATING2 = 6; @Entry @Component struct Datatransfer { @State message: string = '下载测试' private context: Context = getContext(this) private info: backgroundTaskManager.ContinuousTaskNotification = { slotType: 0, contentType: 0, notificationId: 0 }; private numlist: number[] = [10, 90] private index: number = 0 callback(err: BusinessError, data: void) { if (err) { // hilog.error(CommonConstant.DOMAIN, CommonConstant.TAG, "Operation failed") } else { // hilog.info(CommonConstant.DOMAIN, CommonConstant.TAG, "Operation succeed"); } } Http_request_custom() { let httpRequest = http.createHttp(); try { httpRequest.on("dataReceive", (data: ArrayBuffer) => { console.info("Rcv data"); }); httpRequest.requestInStream("资源地址", { readTimeout: 0, connectTimeout: 0, }).then((data: number) => { console.log("lpf request2 OK! RespondCode is " + data); httpRequest.off("dataReceive") httpRequest.destroy() }).catch((err: BusinessError) => { console.log("lpf request2 ERROR : " + JSON.stringify(err)); }); } catch (error) { console.log("lpf request2 catch ERROR : " + JSON.stringify(error)); console.log('ccj: 下载大文件异常捕获') } } startContinuousTask() { let wantAgentInfo: wantAgent.WantAgentInfo = { // 点击通知后,将要执行的动作列表 // 添加需要被拉起应用的bundleName和abilityName wants: [ { bundleName: 'com.example.myapplication', abilityName: "DataTransferAbility", } ], // 指定点击通知栏消息后的动作是拉起ability operationType: wantAgent.OperationType.START_ABILITY, // 使用者自定义的一个私有值 requestCode: 0, // 点击通知后,动作执行属性 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { let list: Array<string> = [ "dataTransfer" ]; backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj) .then((res: backgroundTaskManager.ContinuousTaskNotification) => { console.info(`Succeeded in operationing startBackgroundRunning. id = ` + res.notificationId); this.info = res }) .catch((err: BusinessError) => { console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); }); }); } stopContinuousTask() { // hilog.info(CommonConstant.DOMAIN, CommonConstant.TAG, 'stopBackgroundRunning begin'); backgroundTaskManager.stopBackgroundRunning(this.context) } updateProcess(process: Number) { let downLoadTemplate: notificationManager.NotificationTemplate = { name: 'downloadTemplate', // 当前只支持downloadTemplate,后续根据需要支持录音 data: { title: '文件下载:music.mp4', // 必填 fileName: 'senTemplate', // 必填 progressValue: process, } }; let request: notificationManager.NotificationRequest = { content: { notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW, systemLiveView: { typeCode: 8, title: "111", text: "111", } }, id: this.info.notificationId, notificationSlotType: notificationManager.SlotType.LIVE_VIEW, template: downLoadTemplate }; try { notificationManager.publish(request).then(() => { console.info("publish success, id= " + this.info.notificationId); }).catch((err: BusinessError) => { console.error(`publish fail: ${JSON.stringify(err)}`); }); } catch (err) { console.error(`publish fail: ${JSON.stringify(err)}`); } } build() { Row() { Column() { // back Column() { Image($r('app.media.startIcon')) .width(100) .height(200) .margin(50) .onClick(() => { router.back(); }) } .width("100%") .height(250) .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Start) Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) Button() { Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 10 }) .backgroundColor('#0D9FFB') .width(250) .height(40) .onClick(() => { console.log('tag: 长时任务') this.startContinuousTask(); }) Button() { Text('下载大文件').fontSize(25).fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 10 }) .backgroundColor('#0D9FFB') .width(250) .height(40) .onClick(() => { console.log('tag: 下载大文件') this.Http_request_custom(); }) Button() { Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 10 }) .backgroundColor('#0D9FFB') .width(250) .height(40) .onClick(() => { console.log('tag: 取消长时任务') this.stopContinuousTask(); }) Button() { Text('更新进度').fontSize(25).fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .margin({ top: 10 }) .backgroundColor('#0D9FFB') .width(250) .height(40) .onClick(() => { console.log('tag: 更新进度') this.updateProcess(this.numlist[this.index % this.numlist.length]); this.index++; }) } .width('100%') } .height('100%') } }module.json5文件配置{ "module": { "name": "entry", "type": "entry", "description": "$string:module_desc", "mainElement": "EntryAbility", "deviceTypes": [ "phone", "tablet", "2in1" ], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", "requestPermissions":[ { "name": "ohos.permission.CAMERA", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.MICROPHONE", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.MEDIA_LOCATION", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.WRITE_MEDIA", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.READ_MEDIA", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, {"name": 'ohos.permission.READ_CALENDAR', "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, {"name": 'ohos.permission.WRITE_CALENDAR', "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.APPROXIMATELY_LOCATION", // 允许应用获取设备模糊位置信息,此权限必须放在前面,否则可能会有问题 "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.LOCATION", // 允许应用获取设备位置信息 "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.INTERNET" }, { "name": "ohos.permission.GET_NETWORK_INFO" }, { "name": "ohos.permission.PUBLISH_AGENT_REMINDER" }, { "name" : "ohos.permission.READ_AUDIO", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.USE_BLUETOOTH" }, { "name" : "ohos.permission.LOCATION_IN_BACKGROUND", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } }, { "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" }, { "name" : "ohos.permission.WRITE_AUDIO", "reason": "$string:EntryAbility_desc", "usedScene": { "abilities": [ "EntryAbility" ], "when":"always" } } ], "abilities": [ { "name": "EntryAbility", "srcEntry": "./ets/entryability/EntryAbility.ets", "description": "$string:EntryAbility_desc", "icon": "$media:app_icon", "label": "$string:EntryAbility_label", "startWindowIcon": "$media:startIcon", "startWindowBackground": "$color:start_window_background", "exported": true, "backgroundModes": [ "audioPlayback", "location", "dataTransfer", "audioRecording" ], "skills": [ { "entities": [ "entity.system.home" ], "actions": [ "action.system.home" ] }, { "uris": [ { "scheme": "yymobile" } ] } ], "orientation": "auto_rotation" } ] } }
参考示例如下:
module.json5文件配置