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

成都創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站建設(shè)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的防城港網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
- 創(chuàng)建 Ability 的子類,實(shí)現(xiàn) Service 相關(guān)的生命周期方法。Service 也是一種 Ability,Ability 為 Service 提供了以下生命周期方法,用戶可以重寫這些方法來(lái)添加自己的處理。
- onStart()
該方法在創(chuàng)建 Service 的時(shí)候調(diào)用,用于 Service 的初始化,在 Service 的整個(gè)生命周期只會(huì)調(diào)用一次。
- onCommand()
在 Service 創(chuàng)建完成之后調(diào)用,該方法在客戶端每次啟動(dòng)該 Service 時(shí)都會(huì)調(diào)用,用戶可以在該方法中做一些調(diào)用統(tǒng)計(jì)、初始化類的操作。
- onConnect()
在 Ability 和 Service 連接時(shí)調(diào)用,該方法返回 IRemoteObject 對(duì)象,用戶可以在該回調(diào)函數(shù)中生成對(duì)應(yīng) Service 的 IPC 通信通道,以便 Ability 與 Service 交互。Ability 可以多次連接同一個(gè) Service,系統(tǒng)會(huì)緩存該 Service 的 IPC 通信對(duì)象,只有第一個(gè)客戶端連接 Service 時(shí),系統(tǒng)才會(huì)調(diào)用 Service 的 onConnect 方法來(lái)生成 IRemoteObject 對(duì)象,而后系統(tǒng)會(huì)將同一個(gè) RemoteObject 對(duì)象傳遞至其他連接同一個(gè) Service 的所有客戶端,而無(wú)需再次調(diào)用 onConnect 方法。
- onDisconnect()
在 Ability 與綁定的 Service 斷開連接時(shí)調(diào)用。
- onStop()
在 Service 銷毀時(shí)調(diào)用。Service 應(yīng)通過實(shí)現(xiàn)此方法來(lái)清理任何資源,如關(guān)閉線程、注冊(cè)的偵聽器等。
創(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();
}
}
- 注冊(cè) Service。
Service 也需要在應(yīng)用配置文件中進(jìn)行注冊(cè),注冊(cè)類型 type 需要設(shè)置為 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 ... } ] ... } ...} 新聞名稱:創(chuàng)新互聯(lián)鴻蒙OS教程:鴻蒙OS創(chuàng)建Service
鏈接分享:http://www.5511xx.com/article/dpcihdc.html


咨詢
建站咨詢
