鴻蒙OS 前臺(tái)Service

2020-09-18 10:05 更新

一般情況下,Service 都是在后臺(tái)運(yùn)行的,后臺(tái) Service 的優(yōu)先級(jí)都是比較低的,當(dāng)資源不足時(shí),系統(tǒng)有可能回收正在運(yùn)行的后臺(tái) Service。

在一些場(chǎng)景下(如播放音樂(lè)),用戶(hù)希望應(yīng)用能夠一直保持運(yùn)行,此時(shí)就需要使用前臺(tái) Service。前臺(tái) Service 會(huì)始終保持正在運(yùn)行的圖標(biāo)在系統(tǒng)狀態(tài)欄顯示。

使用前臺(tái) Service 并不復(fù)雜,開(kāi)發(fā)者只需在 Service 創(chuàng)建的方法里,調(diào)用 keepBackgroundRunning()將 Service 與通知綁定。調(diào)用 keepBackgroundRunning() 方法前需要在配置文件中聲明 ohos.permission.KEEP_BACKGROUND_RUNNING 權(quán)限,該權(quán)限是 normal 級(jí)別,同時(shí)還需要在配置文件中添加對(duì)應(yīng)的 backgroundModes 參數(shù)。在 onStop() 方法中調(diào)用 cancelBackgroundRunning() 方法可停止前臺(tái) Service。

使用前臺(tái) Service 的 onStart() 代碼示例如下:

// 創(chuàng)建通知,其中1005為notificationId
NotificationRequest request = new NotificationRequest(1005);
NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
content.setTitle("title").setText("text");
NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
request.setContent(notificationContent);

 
// 綁定通知,1005為創(chuàng)建通知時(shí)傳入的notificationId
keepBackgroundRunning(1005, request);

在配置文件中配置如下:

{    
    "name": ".ServiceAbility",
    "type": "service",
    "visible": true,
    "backgroundModes": ["dataTransfer","location"]
}
以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)