HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第59天,创建,启动,连接ServiceAbility。
HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第59天,创建,启动,连接ServiceAbility。 1、创建ServiceAbility
创建ServiceAbility。
重写ServiceAbility的生命周期方法,添加其他Ability请求与ServiceAbility交互时的处理方法。
import rpc from "@ohos.rpc"
class FirstServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
if (typeof des === 'string') {
super(des)
} else {
return
}
}
}
export default {
onStart() {
console.info('ServiceAbility onStart')
},
onStop() {
console.info('ServiceAbility onStop')
},
onCommand(want, startId) {
console.info('ServiceAbility onCommand')
},
onConnect(want) {
console.info('ServiceAbility onConnect' + want)
return new FirstServiceAbilityStub('test')
},
onDisconnect(want) {
console.info('ServiceAbility onDisconnect' + want)
}
}
2.注册ServiceAbility。
ServiceAbility需要在应用配置文件config.json中进行注册,注册类型type需要设置为service。"visible"属性表示ServiceAbility是否可以被其他应用调用,true表示可以被其他应用调用,false表示不能被其他应用调用(仅应用内可以调用)。若ServiceAbility需要被其他应用调用,注册ServiceAbility时需要设置"visible"为true,同时需要设置支持关联启动。
{
"module": {
"abilities": [
{
"name": ".ServiceAbility",
"srcLanguage": "ets",
"srcPath": "ServiceAbility",
"icon": "$media:icon",
"description": "hap sample empty service",
"type": "service",
"visible": true
}
]
}
}
2、启动ServiceAbility
ServiceAbility的启动与其他Ability并无区别,应用开发者可以在PageAbility中通过featureAbility的startAbility接口拉起ServiceAbility,在ServiceAbility中通过particleAbility的startAbility接口拉起ServiceAbility。
如下示例展示了在PageAbility中通过startAbility启动bundleName为"com.example.myapplication",abilityName为"ServiceAbility"的ServiceAbility的方法。启动FA模型的ServiceAbility时,需要在abilityName前拼接bundleName字符串。
import featureAbility from '@ohos.ability.featureAbility'
async function startServiceAbility() {
try {
console.info('Begin to start ability')
let param = {
want: {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.ServiceAbility"
}
}
await featureAbility.startAbility(param)
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。
3、连接ServiceAbility
如果ServiceAbility需要与PageAbility或其他应用的ServiceAbility进行交互,则须创建用于连接的Connection。ServiceAbility支持其他Ability通过connectAbility()方法与其进行连接。PageAbility的connectAbility方法定义在featureAbility中,ServiceAbility的connectAbility方法定义在particleAbility中。在使用connectAbility()处理回调时,需要传入目标Service的Want与IAbilityConnection的实例。IAbilityConnection提供了以下方法供开发者实现。
接口名 | 描述 |
---|---|
onConnect() | 用于处理连接Service成功的回调。 |
onDisconnect() | 用来处理Service异常死亡的回调。 |
onFailed() | 用来处理连接Service失败的回调。 |
PageAbility创建连接本地ServiceAbility回调实例的代码以及连接本地ServiceAbility的示例代码如下:
import rpc from "@ohos.rpc"
import prompt from '@system.prompt'
import featureAbility from '@ohos.ability.featureAbility'
let option = {
onConnect: function onConnectCallback(element, proxy) {
console.info(`onConnectLocalService onConnectDone`)
if (proxy === null) {
prompt.showToast({
message: "Connect service failed"
})
return
}
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
let option = new rpc.MessageOption()
data.writeInterfaceToken("connect.test.token")
proxy.sendRequest(0, data, reply, option)
prompt.showToast({
message: "Connect service success"
})
},
onDisconnect: function onDisconnectCallback(element) {
console.info(`onConnectLocalService onDisconnectDone element:${element}`)
prompt.showToast({
message: "Disconnect service success"
})
},
onFailed: function onFailedCallback(code) {
console.info(`onConnectLocalService onFailed errCode:${code}`)
prompt.showToast({
message: "Connect local service onFailed"
})
}
}
let request = {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.ServiceAbility",
}
let connId = featureAbility.connectAbility(request, option)
同时,Service侧也需要在onConnect()时返回IRemoteObject,从而定义与Service进行通信的接口。onConnect()需要返回一个IRemoteObject对象。HarmonyOS提供了IRemoteObject的默认实现,开发者可以通过继承rpc.RemoteObject来创建自定义的实现类。
Service侧把自身的实例返回给调用侧的示例代码如下:
import rpc from "@ohos.rpc"
class FirstServiceAbilityStub extends rpc.RemoteObject {
constructor(des: any) {
if (typeof des === 'string') {
super(des)
} else {
return
}
}
onRemoteRequest(code: number, data: any, reply: any, option: any) {
console.info(`onRemoteRequest called`)
if (code === 1) {
let string = data.readString()
console.info(`string=${string}`)
let result = Array.from(string).sort().join('')
console.info(`result=${result}`)
reply.writeString(result)
} else {
console.info(`unknown request code`)
}
return true
}
}
更多关于HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第59天,创建,启动,连接ServiceAbility。的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS中,ServiceAbility是一种后台服务组件,用于执行长时间运行的任务。使用ArkTS语言创建、启动和连接ServiceAbility的步骤如下:
-
创建ServiceAbility:
- 在
ets
目录下新建一个ServiceAbility文件,例如MyServiceAbility.ets
。 - 在文件中定义ServiceAbility类,继承自
ServiceAbility
基类,并实现onStart
、onCommand
等方法。
import ServiceAbility from '[@ohos](/user/ohos).app.ability.ServiceAbility'; export default class MyServiceAbility extends ServiceAbility { onStart(want) { console.log('ServiceAbility onStart'); } onCommand(want, startId) { console.log('ServiceAbility onCommand'); } onConnect(want) { console.log('ServiceAbility onConnect'); return null; } onDisconnect(want) { console.log('ServiceAbility onDisconnect'); } onStop() { console.log('ServiceAbility onStop'); } }
- 在
-
启动ServiceAbility:
- 在需要启动ServiceAbility的地方,使用
startAbility
方法,传入want
对象指定要启动的ServiceAbility。
import featureAbility from '[@ohos](/user/ohos).ability.featureAbility'; let want = { bundleName: 'com.example.myapp', abilityName: 'MyServiceAbility' }; featureAbility.startAbility(want) .then(() => { console.log('ServiceAbility started'); }) .catch((error) => { console.error('Failed to start ServiceAbility', error); });
- 在需要启动ServiceAbility的地方,使用
-
连接ServiceAbility:
- 使用
connectAbility
方法连接ServiceAbility,并实现IAbilityConnection
接口处理连接成功或失败的回调。
import featureAbility from '[@ohos](/user/ohos).ability.featureAbility'; let want = { bundleName: 'com.example.myapp', abilityName: 'MyServiceAbility' }; let connection = { onConnect: (elementName, remote) => { console.log('ServiceAbility connected'); }, onDisconnect: (elementName) => { console.log('ServiceAbility disconnected'); }, onFailed: (code) => { console.error('Failed to connect ServiceAbility', code); } }; featureAbility.connectAbility(want, connection);
- 使用
通过以上步骤,你可以在HarmonyOS中使用ArkTS语言创建、启动和连接ServiceAbility。
更多关于HarmonyOS 鸿蒙Next ArkTS语言教程入门学习第59天,创建,启动,连接ServiceAbility。的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html