提交 db5388af 编写于 作者: W wusongqing

updated docs against 4154

Signed-off-by: Nwusongqing <wusongqing@huawei.com>
上级 4192270e
...@@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -5,22 +5,20 @@ A Service ability is used to run tasks in the background, such as playing music
## Available APIs ## Available APIs
**Table 1** Service ability lifecycle callbacks **Table 1** Service ability lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onStart|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| |onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.|
|onCommand|Called every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback.| |onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.|
|onConnect|Called when another ability is connected to the Service ability.| |onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect|Called when another ability is disconnected from the Service ability.| |onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|onStop|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| |onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
## How to Develop ## How to Develop
### Creating a Service Ability ### Creating and Registering a Service Ability
1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability: 1. Override the Service ability-related lifecycle callbacks to implement your own logic for processing interaction requests.
The following code snippet shows how to create a Service ability:
```javascript ```javascript
export default { export default {
...@@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -32,6 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music
}, },
onConnect(want) { onConnect(want) {
console.log('ServiceAbility OnConnect'); console.log('ServiceAbility OnConnect');
return null;
}, },
onDisconnect(want) { onDisconnect(want) {
console.log('ServiceAbility OnDisConnect'); console.log('ServiceAbility OnDisConnect');
...@@ -41,10 +40,10 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -41,10 +40,10 @@ A Service ability is used to run tasks in the background, such as playing music
}, },
} }
``` ```
2. Register a Service ability. 2. Register a Service ability.
You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
```javascript ```javascript
{ {
...@@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l ...@@ -78,12 +77,12 @@ The following code snippet shows how to start a Service ability running on the l
```javascript ```javascript
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let promise = await featureAbility.startAbility( let promise = featureAbility.startAbility(
{ {
want: want:
{ {
bundleName: "com.jstest.serviceability", bundleName: "com.jstest.service",
abilityName: "com.jstest.serviceability.MainAbility", abilityName: "com.jstest.service.ServiceAbility",
}, },
} }
); );
...@@ -93,11 +92,26 @@ After the preceding code is executed, the **startAbility()** API is called to st ...@@ -93,11 +92,26 @@ After the preceding code is executed, the **startAbility()** API is called to st
- If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability.
- If the Service ability is running, the system directly calls **onCommand()** on the Service ability. - If the Service ability is running, the system directly calls **onCommand()** on the Service ability.
The following code snippet shows how to start a Service ability running on the remote device. For details about **getRemoteDeviceId()**, see [Connecting to a Remote Service Ability](#connecting-to-a-remote-service-ability-applying-only-to-system-applications).
```javascript
import featureAbility from '@ohos.ability.featureAbility';
let promise = featureAbility.startAbility(
{
want:
{
deviceId: getRemoteDeviceId(), // Remote device ID
bundleName: "com.jstest.service",
abilityName: "com.jstest.service.ServiceAbility",
},
}
);
```
### Stopping a Service Ability ### Stopping a Service Ability
Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateSelf()** on a Service ability to stop it. Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed.
...@@ -105,124 +119,140 @@ After the preceding code is executed, the **startAbility()** API is called to st ...@@ -105,124 +119,140 @@ After the preceding code is executed, the **startAbility()** API is called to st
If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**.
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks: You can use either of the following methods to connect to a Service ability:
```javascript 1. Using the IDL to automatically generate code
let mRemote;
function onConnectCallback(element, remote){ Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts).
console.log('onConnectLocalService onConnectDone element: ' + element);
console.log('onConnectLocalService onConnectDone remote: ' + remote); 2. Writing code in the corresponding file
mRemote = remote;
if (mRemote == null) { When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
prompt.showToast({
message: "onConnectLocalService not connected yet" The following code snippet shows how to implement the callbacks:
});
return; ```javascript
} import prompt from '@system.prompt'
let option = new rpc.MessageOption();
let data = new rpc.MessageParcel(); let mRemote;
let reply = new rpc.MessageParcel(); function onConnectCallback(element, remote){
data.writeInt(1); console.log('onConnectLocalService onConnectDone element: ' + element);
data.writeInt(99); console.log('onConnectLocalService onConnectDone remote: ' + remote);
mRemote.sendRequest(1, data, reply, option).then((result) => { mRemote = remote;
console.log('sendRequest success'); if (mRemote == null) {
let msg = reply.readInt();
prompt.showToast({ prompt.showToast({
message: "onConnectLocalService connect result: " + msg, message: "onConnectLocalService not connected yet"
duration: 3000 });
return;
}
let option = new rpc.MessageOption();
let data = new rpc.MessageParcel();
let reply = new rpc.MessageParcel();
data.writeInt(1);
data.writeInt(99);
mRemote.sendRequest(1, data, reply, option).then((result) => {
console.log('sendRequest success');
let msg = reply.readInt();
prompt.showToast({
message: "onConnectLocalService connect result: " + msg,
duration: 3000
});
}).catch((e) => {
console.log('sendRequest error:' + e);
}); });
}).catch((e) => {
console.log('sendRequest error:' + e);
});
} }
function onDisconnectCallback(element){ function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback') console.log('ConnectAbility onDisconnect Callback')
} }
function onFailedCallback(code){ function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback') console.log('ConnectAbility onFailed Callback')
} }
``` ```
The following code snippet shows how to connect to a local Service ability: The following code snippet shows how to connect to a local Service ability:
```javascript ```javascript
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let connId = featureAbility.connectAbility( let connId = featureAbility.connectAbility(
{ {
bundleName: "com.jstest.serviceability", bundleName: "com.jstest.service",
abilityName: "com.jstest.serviceability.MainAbility", abilityName: "com.jstest.service.ServiceAbility",
}, },
{ {
onConnect: onConnectCallback, onConnect: onConnectCallback,
onDisconnect: onDisconnectCallback, onDisconnect: onDisconnectCallback,
onFailed: onFailedCallback, onFailed: onFailedCallback,
}, },
); );
``` ```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability: The following code snippet shows how the Service ability instance returns itself to the calling ability:
```javascript ```javascript
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
let mMyStub; let mMyStub;
export default { export default {
onStart() { onStart() {
class MyStub extends rpc.RemoteObject{ class MyStub extends rpc.RemoteObject{
constructor(des) { constructor(des) {
if (typeof des === 'string') { if (typeof des === 'string') {
super(des); super(des);
}
return null;
} }
return null; onRemoteRequest(code, data, reply, option) {
} console.log("ServiceAbility onRemoteRequest called");
onRemoteRequest(code, data, reply, option) { if (code === 1) {
console.log("ServiceAbility onRemoteRequest called"); let op1 = data.readInt();
if (code === 1) { let op2 = data.readInt();
let op1 = data.readInt(); console.log("op1 = " + op1 + ", op2 = " + op2);
let op2 = data.readInt(); reply.writeInt(op1 + op2);
console.log("op1 = " + op1 + ", op2 = " + op2); } else {
reply.writeInt(op1 + op2); console.log("ServiceAbility unknown request code");
} else { }
console.log("ServiceAbility unknown request code"); return true;
} }
return true;
} }
} mMyStub = new MyStub("ServiceAbility-test");
mMyStub = new MyStub("ServiceAbility-test"); },
}, onCommand(want, startId) {
onCommand(want, startId) { console.log('ServiceAbility onCommand');
console.log('ServiceAbility onCommand'); },
}, onConnect(want) {
onConnect(want) { console.log('ServiceAbility OnConnect');
console.log('ServiceAbility OnConnect'); return mMyStub;
return mMyStub; },
}, onDisconnect(want) {
onDisconnect(want) { console.log('ServiceAbility OnDisConnect');
console.log('ServiceAbility OnDisConnect'); },
}, onStop() {
onStop() { console.log('ServiceAbility onStop');
console.log('ServiceAbility onStop'); },
}, }
} ```
```
### Connecting to a Remote Service Ability (Applying only to System Applications)
### Connecting to a Remote Service Ability<a name="section126857614019"></a> (Applying only to System Applications) >**NOTE**
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Service ability startup applies only to system applications. >
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
If you need to connect a Service ability to a Page ability on another device or to a Service ability in another application on another device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows other abilities on another device to connect to it through **connectAbility()**. If you need to connect a Service ability to a Page ability or another Service ability on a remote device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows abilities on another device to connect to it through **connectAbility()**.
When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails.
The following code snippet shows how to implement the callbacks: The following code snippet shows how to implement the callbacks:
```ts ```ts
import prompt from '@system.prompt'
let mRemote; let mRemote;
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
console.log('onConnectRemoteService onConnectDone element: ' + element); console.log('onConnectRemoteService onConnectDone element: ' + element);
...@@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**, ...@@ -264,7 +294,10 @@ The **Want** of the target Service ability must contain the remote **deviceId**,
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
// For details about the implementation of dmClass, see the implementation in Distributed Demo in Samples.
let dmClass; let dmClass;
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) { if (typeof dmClass === 'object' && dmClass != null) {
let list = dmClass.getTrustedDeviceListSync(); let list = dmClass.getTrustedDeviceListSync();
...@@ -327,15 +360,12 @@ async function RequestPermission() { ...@@ -327,15 +360,12 @@ async function RequestPermission() {
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
console.info("data:" + JSON.stringify(data)); console.info("data:" + JSON.stringify(data));
console.info("data requestCode:" + data.requestCode);
console.info("data permissions:" + data.permissions);
console.info("data authResults:" + data.authResults);
}); });
console.info('RequestPermission end'); console.info('RequestPermission end');
} }
``` ```
When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of **IRemoteObject**. You can extend **rpc.RemoteObject** to implement your own class of **IRemoteObject**.
The following code snippet shows how the Service ability instance returns itself to the calling ability: The following code snippet shows how the Service ability instance returns itself to the calling ability:
...@@ -398,5 +428,5 @@ export default { ...@@ -398,5 +428,5 @@ export default {
## Samples ## Samples
The following samples are provided to help you better understand how to develop a Service ability: The following samples are provided to help you better understand how to develop a Service ability:
- [`ServiceAbility`: Service Ability Creation and Use (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) - [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) - [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册