• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Starting a ServiceAbility
2<!--Kit: Ability Kit-->
3<!--Subsystem: Ability-->
4<!--Owner: @xialiangwei-->
5<!--Designer: @jsjzju-->
6<!--Tester: @lixueqing513-->
7<!--Adviser: @huipeizi-->
8<!--deprecated_code_no_check-->
9
10A ServiceAbility is started in the same way other abilities. You can start a ServiceAbility by calling **featureAbility.startAbility()** in the PageAbility or calling **particleAbility.startAbility()** in another ServiceAbility. For details about the startup rules, see [Component Startup Rules](component-startup-rules.md).
11
12
13The following example shows how to use **startAbility()** to start the ServiceAbility whose **bundleName** is **com.example.myapplication** and **abilityName** is **ServiceAbility** in a PageAbility. When starting the ServiceAbility, concatenate the **bundleName** string before **abilityName**.
14
15```ts
16import featureAbility from '@ohos.ability.featureAbility';
17import Want from '@ohos.app.ability.Want';
18import promptAction from '@ohos.promptAction';
19import hilog from '@ohos.hilog';
20
21const TAG: string = 'PageServiceAbility';
22const domain: number = 0xFF00;
23
24@Entry
25@Component
26struct PageServiceAbility {
27  async startServiceAbility(): Promise<void> {
28    try {
29      hilog.info(domain, TAG, 'Begin to start ability');
30      let want: Want = {
31        bundleName: 'com.samples.famodelabilitydevelop',
32        abilityName: 'com.samples.famodelabilitydevelop.ServiceAbility'
33      };
34      await featureAbility.startAbility({ want });
35      promptAction.showToast({
36        message: 'start_service_success_toast'
37      });
38      hilog.info(domain, TAG, `Start ability succeed`);
39    } catch (error) {
40      hilog.error(domain, TAG, 'Start ability failed with ' + error);
41    }
42  }
43  build() {
44    // ...
45  }
46}
47```
48
49
50In the preceding code, [startAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#startability) is used to start the ServiceAbility.
51
52
53- If the ServiceAbility is not running, the system calls **onStart()** to initialize the ServiceAbility, and then calls **onCommand()** on the ServiceAbility.
54
55- If the ServiceAbility is running, the system directly calls **onCommand()** on the ServiceAbility.
56