新聞中心
介紹如何創(chuàng)建一個Service。

成都創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務領域包括:網(wǎng)站建設、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的防城港網(wǎng)站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡建設合作伙伴!
- 創(chuàng)建 Ability 的子類,實現(xiàn) Service 相關(guān)的生命周期方法。Service 也是一種 Ability,Ability 為 Service 提供了以下生命周期方法,用戶可以重寫這些方法來添加自己的處理。
- onStart()
該方法在創(chuàng)建 Service 的時候調(diào)用,用于 Service 的初始化,在 Service 的整個生命周期只會調(diào)用一次。
- onCommand()
在 Service 創(chuàng)建完成之后調(diào)用,該方法在客戶端每次啟動該 Service 時都會調(diào)用,用戶可以在該方法中做一些調(diào)用統(tǒng)計、初始化類的操作。
- onConnect()
在 Ability 和 Service 連接時調(diào)用,該方法返回 IRemoteObject 對象,用戶可以在該回調(diào)函數(shù)中生成對應 Service 的 IPC 通信通道,以便 Ability 與 Service 交互。Ability 可以多次連接同一個 Service,系統(tǒng)會緩存該 Service 的 IPC 通信對象,只有第一個客戶端連接 Service 時,系統(tǒng)才會調(diào)用 Service 的 onConnect 方法來生成 IRemoteObject 對象,而后系統(tǒng)會將同一個 RemoteObject 對象傳遞至其他連接同一個 Service 的所有客戶端,而無需再次調(diào)用 onConnect 方法。
- onDisconnect()
在 Ability 與綁定的 Service 斷開連接時調(diào)用。
- onStop()
在 Service 銷毀時調(diào)用。Service 應通過實現(xiàn)此方法來清理任何資源,如關(guān)閉線程、注冊的偵聽器等。
創(chuàng)建 Service 的代碼示例如下:
public class ServiceAbility extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
}
@Override
public void onCommand(Intent intent, boolean restart, int startId) {
super.onCommand(intent, restart, startId);
}
@Override
public IRemoteObject onConnect(Intent intent) {
super.onConnect(intent);
return null;
}
@Override
public void onDisconnect(Intent intent) {
super.onDisconnect(intent);
}
@Override
public void onStop() {
super.onStop();
}
}
- 注冊 Service。
Service 也需要在應用配置文件中進行注冊,注冊類型 type 需要設置為 service。
{
"module": {
"abilities": [
{
"name": ".ServiceAbility",
"type": "service",
"visible": true
...
}
]
...
}
...
}xxxxxxxxxx { "module": { "abilities": [ { "name": ".ServiceAbility", "type": "service", "visible": true ... } ] ... } ...}{ "module": { "abilities": [ { "name": ".ServiceAbility", "type": "service", "visible": true ... } ] ... } ...} 網(wǎng)站名稱:創(chuàng)新互聯(lián)鴻蒙OS教程:鴻蒙OS創(chuàng)建Service
當前URL:http://m.fisionsoft.com.cn/article/dpcihdc.html


咨詢
建站咨詢
