Android Service詳解(八)---前臺服務詳解
這是第八篇文章主要講的是如何實現一個前臺服務
回顧可以到第一篇文章從頭瞭解Service:
一、首先我們要知道什麼是前臺服務
前臺服務被認爲是用戶主動意識到的一種服務,因此在內存不足時,系統也不會考慮將其終止。 前臺服務必須爲狀態欄提供通知,放在“正在進行”標題下方,這意味着除非服務停止或從前臺移除,否則不能清除通知。
二、什麼時候使用前臺服務?
例如,應該將通過服務播放音樂的音樂播放器設置爲在前臺運行,這是因爲用戶明確意識到其操作。 狀態欄中的通知可能表示正在播放的歌曲,並允許用戶啓動 Activity 來與音樂播放器進行交互。
三。實現前臺服務的步驟
其實很簡單就是將服務創建後創建一個Notification就好,利用提供好的方法進行顯示和移除就好
1.創建一個Service,在這個Service的onCreate方法中創建一個Notification
@Override
public void onCreate() {
Notification.Builder builder = new Notification.Builder(this);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setTicker("Foreground Service Start");
builder.setContentTitle("Foreground Service");
builder.setContentText("Make this service run in the foreground.");
Notification notification = builder.build();
startForeground(1, notification);
}
要請求讓服務運行於前臺,請調用 startForeground()。此方法採用兩個參數:唯一標識通知的整型數和狀態欄的 Notification。注意:提供給 startForeground() 的整型 ID 不得爲 0。
2.使用綁定服務的Messenger,進行通信來實現前臺移除通知的操作。
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SAY_HELLO:
stopForeground(true);
break;
default:
super.handleMessage(msg);
}
}
}
至於如何使用Messenger請參考這篇文章Android Service詳解(七)---綁定服務BoundService詳解之Messenger雙向通信的實現3.如何移除前臺服務呢?
要從前臺移除服務,請調用 stopForeground()。此方法採用一個布爾值,指示是否也移除狀態欄通知。 此方法不會停止服務。 但是,如果您在服務正在前臺運行時將其停止,則通知也會被移除。
4.在前臺調用方法進行通信告知服務移除通知
public void removeClick(View vie){
Message msg = Message.obtain(null, MyService.MSG_SAY_HELLO, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
附上源碼:源碼