Notification除了用於後台服務通知,還常用在下面情況:
(1)保持服務存在。當系統記憶體不足時,系統會認為某後台服務佔用記憶體時間太長而中止該服務,以釋放記憶體。對於某些服務,例如播放音樂,如果系統對該服務進行資源釋放,使用者體驗就成了音樂突然沒有聲音。對這類服務,我們希望享有更高的優先順序別,不會被系統幹掉。
(2)使用者隨時與服務進行互動。例如播放音樂的服務,使用者可隨時暫停音樂播放,或選擇其他曲目,甚至中止播放音樂服務。
要實現上述兩點,方法是在Service中宣稱自己是foreground,並維持一個通知來向使用者表明foreground狀態,使用者可以通過下拉通知並點擊通知,進入該服務介面,實施互動操作。
我們將在Android學習筆記(五二):服務Service(中)- 繼承Service類的類比音樂播放例子上進行擴充。
FakePlayer同原例子的用戶端代碼,略過不表。Service的代碼如下
public class FakePlayerService extends Service{
public static final String EXTRA_PLAYLIST="EXTRA_PLAYLIST";
public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
private boolean isPlay = false;
private static final int NOTIFY_FAKEPLAYER_ID=1339;
public IBinder onBind(Intent arg0) {
return null;
}
public void onDestroy() {
stop();
}
public int onStartCommand(Intent intent, int flags, int startId) {
String playlist = intent.getStringExtra(EXTRA_PLAYLIST);
Boolean isShuffle = intent.getBooleanExtra(EXTRA_SHUFFLE, false);
play(playlist,isShuffle);
return START_NOT_STICKY;
}
private void play(String playlist, Boolean isShuffle){
if(!isPlay){
isPlay = true;
//和上一筆記中建立通知的步驟一樣,只是不需要通過通知管理器進行觸發,而是用startForeground(ID,notify)來處理
//步驟1:和上一筆記一樣,通過Notification.Builder( )來建立通知
//FakePlayer就是兩個大button的activity,也即服務的介面,見最左圖
Intent i = new Intent(this,FakePlayer.class);
//注意Intent的flag設定:FLAG_ACTIVITY_CLEAR_TOP: 如果activity已在當前任務中運行,在它前端的activity都會被關閉,它就成了最前端的activity。FLAG_ACTIVITY_SINGLE_TOP: 如果activity已經在最前端運行,則不需要再載入。設定這兩個flag,就是讓一個且唯一的一個activity(服務介面)運行在最前端。
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Notification myNotify = new Notification.Builder(this)
.setSmallIcon(R.drawable.shield)
.setTicker("Fake Player: " + playlist)
.setContentTitle("Test")
.setContentText("Now Playing: \"Ummmm, Nothing\"")
.setContentIntent(pi)
.build();
//設定notification的flag,表明在點擊通知後,通知並不會消失,也在最右圖上仍在通知欄顯示表徵圖。這是確保在activity中退出後,狀態列仍有表徵圖可提下拉、點擊,再次進入activity。
myNotify.flags |= Notification.FLAG_NO_CLEAR;
// 步驟 2:startForeground( int, Notification)將服務設定為foreground狀態,使系統知道該服務是使用者關注,低記憶體情況下不會killed,並提供通知向使用者表明處於foreground狀態。
startForeground(NOTIFY_FAKEPLAYER_ID,myNotify);
}
}
private void stop(){
if(isPlay){
isPlay = false;
//將服務從forefround狀態中移走,使得系統可以在低記憶體的情況下清除它。
stopForeground(true);
}
}
}
相關連結:
我的Android開發相關文章