標籤:
Notification
可以用來在狀態列上顯示表徵圖和資訊、使LED燈閃爍、震動手機、鈴聲或者音樂提醒、顯示額外的資訊、使用可互動的控制手段。
Notification Manager是用來管理Notification,包括觸發一個新的Notification、修改存在的、取消Notifications。NotificationManager常用方法介紹:顯示方法public void notify(int id, Notification notification) 將通知加入狀態列,標記為idpublic void notify(String tag ,int id, Notification notification) 將通知加入狀態列,標籤為tag,標記為id清除方法public void cancel(int id) 移除標記為id的通知 (只是針對當前Context下的所有Notification)public void cancelAll() 移除所有通知(只是針對當前Context下的Notification)
核心代碼:
// 建立一個NotificationManager的引用 NotificationManager notificationManager = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE); // 定義Notification的各種屬性 Notification notification =new Notification(R.drawable.icon_luncher, "通知", System.currentTimeMillis()); //FLAG_AUTO_CANCEL 該通知能被狀態列的清除按鈕給清除掉 //FLAG_NO_CLEAR 該通知不能被狀態列的清除按鈕給清除掉 //FLAG_ONGOING_EVENT 通知放置在正在運行 //FLAG_INSISTENT 是否一直進行,比如音樂一直播放,知道使用者響應 notification.flags |= Notification.FLAG_ONGOING_EVENT; // 將此通知放到通知欄的"Ongoing"即"正在運行"組中 notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在點擊了通知欄中的"清除通知"後,此通知不清除,經常與FLAG_ONGOING_EVENT一起使用 notification.flags |= Notification.FLAG_SHOW_LIGHTS; //DEFAULT_ALL 使用所有預設值,比如聲音,震動,閃屏等等 //DEFAULT_LIGHTS 使用預設閃光提示 //DEFAULT_SOUNDS 使用預設提示聲音 //DEFAULT_VIBRATE 使用預設手機震動,需加上<uses-permission android:name="android.permission.VIBRATE" />許可權 notification.defaults = Notification.DEFAULT_LIGHTS; //疊加效果常量 //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND; notification.ledARGB = Color.BLUE; notification.ledOnMS =5000; //閃光時間,毫秒 // 設定通知的事件訊息 CharSequence contentTitle ="我是標題"; // 通知欄標題 CharSequence contentText ="我是內容"; // 通知欄內容 Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class); // 點擊該通知後要跳轉的Activity PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, contentTitle, contentText, contentItent); // 把Notification傳遞給NotificationManager notificationManager.notify(0, notification);
清除通知:
// 清除NotificationNotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);nm.cancel(0);//數字0是清除的標識符與顯示的標識符相同
注:清除動作一般在進入指定頁面前清除掉,可以在onResume()或者onStart()裡面執行。
學友資料:http://my.oschina.net/wangjunhe/blog/113855
android notification通知學習一二三