Android-通知欄Notification學習

https://blog.csdn.net/vipzjyno1/article/details/25248021

一、使用步驟

1)創建一個通知欄的Builder構造類 (Create a Notification Builder)

2)定義通知欄的Action (Define the Notification’s Action)

定義通知欄的Action (Define the Notification’s Action)

3)設置通知欄點擊事件 (Set the Notification’s Click Behavior)

設置通知欄點擊事件 (Set the Notification’s Click Behavior)

4)通知 (Issue the Notification)

二、代碼實現

1)獲取狀態通知欄管理

NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

2)實例化通知欄構造器

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

3)對builder設置

mBuilder.setContentTitle("測試標題")//設置通知欄標題
	.setContentText("測試內容") //設置通知欄顯示內容
	.setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //設置通知欄點擊意圖
//	.setNumber(number) //設置通知集合的數量
	.setTicker("測試通知來啦") //通知首次出現在通知欄,帶上升動畫效果的
	.setWhen(System.currentTimeMillis())//通知產生的時間,會在通知信息裏顯示,一般是系統獲取到的時間
	.setPriority(Notification.PRIORITY_DEFAULT) //設置該通知優先級
//	.setAutoCancel(true)//設置這個標誌當用戶單擊面板就可以讓通知將自動取消  
	.setOngoing(false)//ture,設置他爲一個正在進行的通知。他們通常是用來表示一個後臺任務,用戶積極參與(如播放音樂)或以某種方式正在等待,因此佔用設備(如一個文件下載,同步操作,主動網絡連接)
	.setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加聲音、閃燈和振動效果的最簡單、最一致的方式是使用當前的用戶默認設置,使用defaults屬性,可以組合
	//Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加聲音 // requires VIBRATE permission
	.setSmallIcon(R.drawable.ic_launcher);//設置通知小ICON

4)設置通知欄PendingIntent(點擊動作事件等)

  • 屬性
FLAG_ONE_SHOT   表示返回的PendingIntent僅能執行一次,執行完後自動取消

FLAG_NO_CREATE     表示如果描述的PendingIntent不存在,並不創建相應的PendingIntent,而是返回NULL

FLAG_CANCEL_CURRENT      表示相應的PendingIntent已經存在,則取消前者,然後創建新的PendingIntent,這個有利於數據保持爲最新的,可以用於即時通信的通信場景

FLAG_UPDATE_CURRENT     表示更新的PendingIntent
  • 在各種情況下情況下它還會根據各種情況出發效果:

    contentIntent:在通知窗口區域,Notification被單擊時的響應事件由該intent觸發;

    deleteIntent:當用戶點擊全部清除按鈕時,響應該清除事件的Intent;

    fullScreenIntent:響應緊急狀態的全屏事件(例如來電事件),也就是說通知來的時候,跳過在通知區域點擊通知這一步,直接執行fullScreenIntent代表的事件。

Intent intent = new Intent(context,XXX.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
mBuilder.setContentIntent(pendingIntent)

5)發通知

mNotificationManager.notify(notifyId, mBuilder.build());

三、自定義通知欄

https://juejin.im/entry/578ef709c4c971005e0b3251

這裏要用到RemoteViews這個類。注意RemoteViews類,在自定義視圖佈局文件中,僅支持FrameLayout、LinearLayout、RelativeLayout三種佈局控件和AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper這些顯示控件,不支持這些類的子類或Android提供的其他控件。否則會引起ClassNotFoundException異常

步驟如下:

1)創建自定義視圖

2)獲取遠程視圖對象(注:Notification的contentView不能爲空)

3)設置PendingIntent(來響應各種事件)

4)發起Notification

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章