W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
介紹如何創(chuàng)建一個(gè)Service。
該方法在創(chuàng)建 Service 的時(shí)候調(diào)用,用于 Service 的初始化,在 Service 的整個(gè)生命周期只會(huì)調(diào)用一次。
在 Service 創(chuàng)建完成之后調(diào)用,該方法在客戶端每次啟動(dòng)該 Service 時(shí)都會(huì)調(diào)用,用戶可以在該方法中做一些調(diào)用統(tǒng)計(jì)、初始化類的操作。
在 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 方法來生成 IRemoteObject 對(duì)象,而后系統(tǒng)會(huì)將同一個(gè) RemoteObject 對(duì)象傳遞至其他連接同一個(gè) Service 的所有客戶端,而無需再次調(diào)用 onConnect 方法。
在 Ability 與綁定的 Service 斷開連接時(shí)調(diào)用。
在 Service 銷毀時(shí)調(diào)用。Service 應(yīng)通過實(shí)現(xiàn)此方法來清理任何資源,如關(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();
}
}
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 ? ? ? ? ? ? ? ... ? ? ? ? ? } ? ? ? ] ? ? ? ... ? } ? ...}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: