鸿蒙启动后台服务运行
·
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.xxx.xxx', 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));
}
}更多推荐


所有评论(0)