鴻蒙OS 創(chuàng)建Service

2020-09-18 10:00 更新

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

  1. 創(chuàng)建 Ability 的子類,實(shí)現(xiàn) Service 相關(guān)的生命周期方法。Service 也是一種 Ability,Ability 為 Service 提供了以下生命周期方法,用戶可以重寫這些方法來添加自己的處理。

  • 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 對象,用戶可以在該回調(diào)函數(shù)中生成對應(yīng) Service 的 IPC 通信通道,以便 Ability 與 Service 交互。Ability 可以多次連接同一個(gè) Service,系統(tǒng)會(huì)緩存該 Service 的 IPC 通信對象,只有第一個(gè)客戶端連接 Service 時(shí),系統(tǒng)才會(huì)調(diào)用 Service 的 onConnect 方法來生成 IRemoteObject 對象,而后系統(tǒng)會(huì)將同一個(gè) RemoteObject 對象傳遞至其他連接同一個(gè) Service 的所有客戶端,而無需再次調(diào)用 onConnect 方法。

  • onDisconnect()

在 Ability 與綁定的 Service 斷開連接時(shí)調(diào)用。

  • onStop()

在 Service 銷毀時(shí)調(diào)用。Service 應(yīng)通過實(shí)現(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();
       }
   }

  1. 注冊 Service。

Service 也需要在應(yīng)用配置文件中進(jìn)行注冊,注冊類型 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 ? ? ? ? ? ? ?  ... ? ? ? ? ?  } ? ? ?  ] ? ? ?  ... ?  } ?  ...}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)