W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
一般情況下,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"]
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: