什么是前臺(tái)服務(wù)
前臺(tái)服務(wù)是那些被認(rèn)為用戶知道(用戶認(rèn)可所認(rèn)可)且在系統(tǒng)內(nèi)存不足的時(shí)候不允許系統(tǒng)殺死的服務(wù)。前臺(tái)服務(wù)必須給狀態(tài)欄提供一個(gè)通知,它被放到正在運(yùn)行(Ongoing)標(biāo)題之下——這就意味著通知只有在這個(gè)服務(wù)被終止或從前臺(tái)主動(dòng)移除通知后才能被解除。
通知
Notification支持文字內(nèi)容顯示、震動(dòng)、三色燈、鈴聲等多種提示形式,在默認(rèn)情況下,Notification僅顯示消息標(biāo)題、消息內(nèi)容、送達(dá)時(shí)間這3項(xiàng)內(nèi)容。
-
標(biāo)準(zhǔn)樣式
-
擴(kuò)展樣式
-
自定義樣式
使用notification
Notification:通知信息類,它里面對(duì)應(yīng)了通知欄的各個(gè)屬性。
NotificationManager : 狀態(tài)欄通知的管理類,負(fù)責(zé)發(fā)通知、清除通知等操作。
構(gòu)建通知的步驟:
- 獲取狀態(tài)通知欄管理類實(shí)例
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
- 實(shí)例化通知欄構(gòu)造器NotificationCompat.Builder
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
- 對(duì)Builder進(jìn)行配置
// 設(shè)置通知的基本信息:icon、標(biāo)題、內(nèi)容
mBuilder .setSmallIcon(R.drawable.notification_icon)
mBuilder .setContentTitle("My notification")
mBuilder .setContentText("Hello World!");
- 設(shè)置通知欄PendingIntent(點(diǎn)擊動(dòng)作事件等都包含在這里)
// 設(shè)置通知的點(diǎn)擊行為:這里啟動(dòng)一個(gè) Activity
Intent intent = new Intent(this, ResultActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder .setContentIntent(pendingIntent);
- 發(fā)送通知請(qǐng)求
mNotificationManager.notify(notifyId, mBuilder.build());
更新通知
要想更新通知,需要利用NotificationManager.notify()
的id參數(shù),該id在應(yīng)用內(nèi)需要唯一。要想更新特定id的通知,只需要?jiǎng)?chuàng)建新的Notification,并發(fā)出與之前所用 id 相同的 Notification。如果之前的通知仍然可見,則系統(tǒng)會(huì)根據(jù)新的 Notification 對(duì)象的內(nèi)容更新該通知。相反,如果之前的通知已被清除,系統(tǒng)則會(huì)創(chuàng)建一個(gè)新通知。
刪除通知
刪除通知可以有多種方式:
1.通過NotificationCompat.Builder
設(shè)置setAutoCancel(true)
,這樣當(dāng)用戶點(diǎn)擊通知后,通知自動(dòng)刪除。
2.通過NotificationManager.cancel(id)
方法,刪除指定 id 的通知
3.通過 NotificationManager.cancelAll()
方法,刪除該應(yīng)用的所有通知
關(guān)于前臺(tái)服務(wù)和通知更具體的內(nèi)容可參考紫豪