前言
通知Notification也是Android中很重要的一環。在API11以後,Notification類中的許多方法都被棄用了,因爲現在大多數應用都最低支持API15了。所以,我們直接學習新的發送通知的方法就可以了。
代碼
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//獲取的是v4包中的兼容構造器,如果不需要,也可以使用Notification.Builder
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
//配置點擊的意圖
Intent intent = new Intent(getApplicationContext(), TargetActivity.class);
intent.addCategory(Intent.CATEGORY_DEFAULT);//在Activity中也要配置,否則不能啓動Activity
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//如果通知是在沒有Activity棧的情況下發送的,就要配置這個Flags
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder.setContentTitle("測試標題")//設置通知欄標題
.setContentText("測試內容")//設置通知欄顯示內容
.setContentIntent(pendingIntent)//設置通知欄點擊意圖
//.setNumber(number);
.setTicker("測試通知來啦")//通知欄首次出現在通知欄,帶上動畫效果
.setWhen(System.currentTimeMillis())//通知欄時間,一般是直接用系統的
.setPriority(Notification.DEFAULT_ALL)//設置通知欄優先級
// .setAutoCancel(true)//用戶單擊面板後消失
.setOngoing(false)//true,設置他爲一個正在進行的通知。他們通常是用來表示一個後臺任務,用戶積極參與(如播放音樂)或以某種方式正在等待,因此
//佔用設備(如一個文件下載,同步操作,主動網絡連接)
.setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加聲音、閃燈和振動效果的最簡單、最一致的方式是使用當前的用戶默認設置,
//使用default屬性,可以組合
//Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加聲音 // requires VIBRATE permission
.setSmallIcon(R.mipmap.ic_launcher);
//生成通知
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags = Notification.FLAG_NO_CLEAR;//點擊清除的時候不清除
mNotificationManager.notify(0,notification);//第一個參數是notification的id,可以用於後來的清除
如何自定義通知
RemoteViews remoteView = new RemoteViews(getPackageName(), R.layout.remoteview);
// remoteView.setOnClickPendingIntent(R.id.btn_two, pendingIntent);//爲單個按鈕設置點擊事件
mBuilder.setContent(remoteView).setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentIntent(pendingIntent);
不知道爲什麼,自定義通知的時候一定要設置setSmallIcon(),雖然它並不顯示,但是不設置就會報錯。