安開發卓之Notification(一)代碼直接能用
來自: http://www.cnblogs.com/sunzan/p/5242799.html
Notification是Android中很理想的一種顯示提示信息的方法,它可以將應用程序的信息傳遞到我們的Android桌面狀態欄,采用這種消息傳遞方式不會影響到用戶對手機的正常使用。而且Notification不僅僅可以傳遞文字信息,還可以傳遞圖片信息,甚至可以將我們的控件追加到上面,只要用戶不對其進行清空,那么消息將一直保存在用戶桌面的狀態欄當中。
Notification通常用來進行對用戶的更新提醒等消息的傳遞。
Notification需要使用到NotificationManager(消息通知管理類)對消息進行管理,其創建需要五個步驟:
(1)通過getSystemService獲取Notification對象
(2)創建一個Notification,每一個notification對應一個notification對象。
(3)創建一個PendingIntent對象
(4)使用notification類的setLatestEventInfo方法設置Notification對象的詳細信息
(5)使用NotificationManager對象的notify方法顯示消息
在第二步時應當注意需要設置顯示在屏幕上方狀態欄的通知消息、通知消息前方的圖像資源ID和放出通知的時間,一般為當前時間
(3)創建PendingIntent對象:
由于notification可以與應用程序脫離,也就是說你的應用程序已經關閉,消息仍然顯示在狀態欄之中,當應用程序再次啟動后,又可以重新控制這些notification,如清除、替換等工作。因此需要PendingIntent對象,該對象由安卓系統維護,因此,應用程序關閉后,消息仍然不會被釋放。
(4)在使用notify方法時需要指定Notification對象的唯一ID,這個ID必須相對于一個Notificationmanager對象來說是唯一的,否則就會覆蓋相同ID的
Notification
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
String notice = "您有短消息了!";
Notification notification = new Notification(R.drawable. ic_launcher, notice,System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity
(getApplicationContext(), 0, getIntent(), 0);
notification. setLatestEventInfo
(getApplicationContext(), "小搬運工又變帥了 ", " 華中軟件龍頭企業 ", contentIntent);
notification.defaults = Notification.DEFAULT_SOUND;
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.defaults = Notification.DEFAULT_VIBRATE;
notification.defaults = Notification.DEFAULT_ALL;
manager.notify(R.drawable.ic_launcher,notification);
1、如果要調取聲音,需用使用到:android:name=“android.permission.VIBRATE”權限
NotificationManager.cancel(resId)清除某個數據 NotificationManager.cancelAll()清除某個NotificationManager對象中的所有消息。在清除完消息后,需要做一些善后工作,需要通過notification,deleteIntent來完成,deleteIntent也需要一個pendingIntent類型的變量,用于在清除所用的notification對象時調用。這個動作可以與Activity、Service、Broadcast關聯。
如果想永久保存推送的通知,需要增加代碼:
?notification.flags = Notification.FLAG_NO_CLEAR;
</div>