應用程序能夠使用Notifications來通知用戶某個事件發生了(如收到短信)。類NotificationManager 用來處理Notification, NotificationManager能夠:windows
對於一些沒有UI的應用程序組件(如Broadcast Receiver, Services)或是非活動狀態的Activity,Notification是推薦使用的能夠提醒用戶注意的方法。app
Notification一般是在Status Bar上顯示圖標或是文字,此時用戶若是想了解Notification的詳細內容,能夠按住Status Bar下拉顯示Expanded Status bar 窗口,在Expanded Status bar窗口顯示該Notification詳情並能夠啓動對應的Activity。dom
IncomingMessage 示例介紹了Notification的通常用法:this
1. 首先是取得NotificationManager 對象:spa
// look up the notification manager service NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
2. 而後建立Notification,建立Notification時指定顯示在Status bar的圖標,文字以及顯示Notification的時間:code
// construct the Notification object. Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis());
3. 而後定義當用戶打開Extented status windows窗口時的標題及詳情。Notification經常表明了一個請求或者須要引發注意的事件,所以能夠指定一個PendingIntent來響應用戶點擊這個Notification。orm
// The details of our fake message CharSequence from = "Joe"; CharSequence message; switch ((new Random().nextInt()) % 3) { case 0: message = "r u hungry? i am starved"; break; case 1: message = "im nearby u"; break; default: message = "kthx. meet u for dinner. cul8r"; break; } // The PendingIntent to launch our activity if the user selects this // notification. Note the use of FLAG_CANCEL_CURRENT so that, if there // is already an active matching pending intent, cancel it and replace // it with the new array of Intents. PendingIntent contentIntent = PendingIntent.getActivities(this, 0, makeMessageIntentStack(this, from, message), PendingIntent.FLAG_CANCEL_CURRENT); // The ticker text, this uses a formatted string so our message could be localized String tickerText = getString(R.string.imcoming_message_ticker_text, message); // construct the Notification object. Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis()); // Set the info for the views that show in the notification panel. notif.setLatestEventInfo(this, from, message, contentIntent); // We'll have this notification do the default sound, vibration, and led. // Note that if you want any of these behaviors, you should always have // a preference for the user to turn them off. notif.defaults = Notification.DEFAULT_ALL;
4. 最後是觸發這個Notification:對象
// Note that we use R.layout.incoming_message_panel as the ID for // the notification. It could be any integer you want, but we use // the convention of using a resource id for a string related to // the notification. It will always be a unique number within your // application. nm.notify(R.string.imcoming_message_ticker_text, notif);
通常來講對應同一個事件能夠使用同一個Notification來通知用戶,nm.notify的第一個參數爲Notification 的ID,類型爲整數。 能夠使用同一個ID來表示同一個Notification,也能夠使用這個ID來取消這個Notification,在IncomingMessage 中當用戶點擊顯示了這個IncomingMessage詳情後,會取消這個Notification(類IncomingMessageView中)。blog
nm.cancel(R.string.imcoming_message_ticker_text);