Android Notification 基礎
在Android中,基本的Notification就是有事件發生的時候在屏幕頂端的Notification bar上顯示一個圖標。然後拉下Notification bar,點擊Notification的項目,會調用相應的程序做處理。比如有新短信,就會出現短信的圖標,拉下Notification bar,點擊圖標會調用短信查看程序。
我們先看一下Notification的Sample Code,然後逐行做解說,大致能了解它的基本構成。
import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; ... private void showNotification(Message msg, int id) { NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.notiicon, msg .getTitle(), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent intent = new Intent(this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putString("info", msg.getInfo()); intent.putExtras(bundle); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); notification.setLatestEventInfo(this, msg.getTitle(), msg.getInfo(), contentIntent); notiManager.notify(id, notification); }
首先導入三個類,Notification,NotificationManager,PendingIntent。 值得一提的是PendingIntent,它可以看做是Intent這封信的一個信封。PendingIntent基本上是Intent的包裝和描述,對象收到PendingIntent後,可以得到其中的Intent再發出去。
NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
上麵這一句,從係統中獲得Notification服務,getSystemService()就是這麼用,來獲得係統服務的。
Notification notification = new Notification(R.drawable.notiicon, msg .getTitle(), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL;
然後是構造一個Notification,包括三個屬性,圖標,圖標後麵的文字,以及Notification時間部分顯示出來的時間,通常使用當前時間。FLAG_AUTO_CANCEL說明Notification點擊一次就消失。
Intent intent = new Intent(this, MainActivity.class); Bundle bundle = new Bundle(); bundle.putString("info", msg.getInfo()); intent.putExtras(bundle); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
上麵這部分Code,構造一個Intent,並且放進去一條信息。 FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_NEW_TASK者兩個FLAG表示優先尋找已經打開的應用,如果應用沒有打開那麼啟動它。
PendingIntent contentIntent = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
這一句代碼把Intent包裝在PendingIntent裏,this是Context,id是PendingIntent的標誌,如果id相同會被認為是一個。FLAG_UPDATE_CURRENT是指後來的PendingIntent會更新前麵的。
notification.setLatestEventInfo(this, msg.getTitle(), msg.getInfo(), contentIntent); notiManager.notify(id, notification);
最後這兩行添加狀態欄的詳細信息,包裝PendingIntent給Notification,最後發送Notification。
最後更新:2017-04-02 06:51:49