harmony 鸿蒙启动ServiceAbility

  • 2022-12-13
  • 浏览 (781)

启动ServiceAbility

ServiceAbility的启动与其他Ability并无区别,应用开发者可以在PageAbility中通过featureAbility的startAbility接口拉起ServiceAbility,在ServiceAbility中通过particleAbility的startAbility接口拉起ServiceAbility。ServiceAbility的启动规则详见组件启动规则章节。

如下示例展示了在PageAbility中通过startAbility启动bundleName为”com.example.myapplication”,abilityName为”ServiceAbility”的ServiceAbility的方法。启动FA模型的ServiceAbility时,需要在abilityName前拼接bundleName字符串。

import featureAbility from '@ohos.ability.featureAbility'
import Want from '@ohos.app.ability.Want';

async function startServiceAbility() {
  try {
    console.info('Begin to start ability')
    let want: Want = {
      bundleName: "com.example.myapplication",
      abilityName: "com.example.myapplication.ServiceAbility"
    }
    await featureAbility.startAbility({want})
    console.info(`Start ability succeed`)
  } catch (error) {
    console.error('Start ability failed with ' + error)
  }
}

执行上述代码后,Ability将通过startAbility()方法来启动ServiceAbility。

  • 如果ServiceAbility尚未运行,则系统会先调用onStart()来初始化ServiceAbility,再回调Service的onCommand()方法来启动ServiceAbility。

  • 如果ServiceAbility正在运行,则系统会直接回调ServiceAbility的onCommand()方法来启动ServiceAbility。

你可能感兴趣的鸿蒙文章

harmony 鸿蒙应用模型

harmony 鸿蒙使用显式Want启动应用组件

harmony 鸿蒙使用隐式Want打开网址

harmony 鸿蒙AbilityStage组件容器

harmony 鸿蒙访问DataAbility

harmony 鸿蒙FA模型访问Stage模型DataShareExtensionAbility

harmony 鸿蒙AccessibilityExtensionAbility

harmony 鸿蒙常见action与entities

harmony 鸿蒙API切换概述

harmony 鸿蒙app和deviceConfig的切换

0  赞