0%

鸿蒙启动后台服务运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
1.在module.json5中
"requestPermissions": [
{"name": "ohos.permission.INTERNET"},
{"name": "ohos.permission.GET_BUNDLE_INFO"},
{"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"}
],

"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"backgroundModes": [
"dataTransfer" // 对应 BackgroundMode.DATA_TRANSFER
],



2.在EntryAblility中
async onForeground(): Promise<void> {
// Ability has brought to foreground
hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
try {
const wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [{ bundleName: 'com.ht.cotton', abilityName: 'EntryAbility' }],
actionType: wantAgent.OperationType.START_ABILITY,
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};

const wantAgentObj = await wantAgent.getWantAgent(wantAgentInfo);
const taskTypes = ['dataTransfer']; // 或 ['audioPlayback'], ['audioRecording'] 等
const res = await backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj);
// console.info('后台长时任务已申请, notificationId:', res.notificationId);
} catch (e) {
console.error('申请后台长时任务失败:', JSON.stringify(e));
}
}