HarmonyOS 在应用开启屏幕共享时,如果应用退到后台,如何防止应用被后台移除呢?

在应用开启屏幕共享时,未防止应用处于后台被杀,准备绑定长时任务,但是长时任务中没有对应场景的绑定选项。

阅读 673
1 个回答

需要开启长时任务防止进程被后台关掉。

示例参考:

startContinuousTask() {
  let wantAgentInfo: wantAgent.WantAgentInfo = {
    // 点击通知后,将要执行的动作列表
    // 添加需要被拉起应用的bundleName和abilityName
    wants: [
      {
        bundleName: "com.xxxx",
        abilityName: "com.xxxAbility"
      }
    ],
    // 指定点击通知栏消息后的动作是拉起ability
    actionType: wantAgent.OperationType.START_ABILITY,
    // 使用者自定义的一个私有值
    requestCode: 0,
    // 点击通知后,动作执行属性
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
  };

  // 通过wantAgent模块下getWantAgent方法获取WantAgent对象
  wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
    backgroundTaskManager.startBackgroundRunning(this.context,
      backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
      console.info(`Succeeded in operationing startBackgroundRunning.`);
    }).catch((err: BusinessError) => {
      console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
    });
  });
}
stopContinuousTask() {
  backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
    console.info(`Succeeded in operationing stopBackgroundRunning.`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
  });
}

onForeground(): void {
  // Ability has brought to foreground
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  this.stopContinuousTask()
}

onBackground(): void {
  // Ability has back to background
  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  this.startContinuousTask()
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进