Android之Notification初識
阿新 • • 發佈:2019-02-09
1.Notification建立
首先,介紹一下,建立一個通知所需要用到的類和方法NotificationManager類
NotificationManager類是用來管理系統的所有通知的類,該類的物件必須通過Context類的getSystemService()方法獲取。完整程式碼:
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notify()作用是告知系統顯示該通知,有notify (int id, Notification notification)和notify (String tag,int id, Notification
notification有一些常用的屬性: icon 設定通知圖示(在API23後使用setSmallIcon(Icon)替代) number 通知所顯示的事件數量,例如,收到郵件通知,則指的是郵件未讀數量(這是用API11建立的通知所表現的作用)。如果通知是用Notification.builder建立,則number表示擴充套件通知檢視,為0或者負數的時候,通知不顯示。
FLAG_NO_CLEAR 該通知不能被狀態列的清除按鈕給清除掉
FLAG_ONGOING_EVENT 通知放置在正在執行
FLAG_INSISTENT 是否一直進行,比如音樂一直播放,知道使用者響應
defaults 設定預設值
DEFAULT_ALL 使用所有預設值,比如聲音,震動,閃屏等等
DEFAULT_LIGHTS 使用預設閃光提示
DEFAULT_SOUND 使用預設提示聲音
DEFAULT_VIBRATE 使用預設手機震動
該物件的獲取方式為, PendingIntent.getActivity(Context context,int requestCode,Intent intent,int flags);requsetCode和flags一般預設設定為0; 下面用上面提到的知識,寫一個簡單的通知(基於API11之前):
public void showBaseNotification() {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify = new Notification();
notify.icon = R.drawable.ic_launcher;
notify.tickerText = "您有新短訊息,請注意查收!";
notify.when = System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
notify.setLatestEventInfo(this, "Notification Title",
"This is the notification message", pendingIntent);
notify.number = 1;
notify.flags |= Notification.FLAG_AUTO_CANCEL;
// 通過通知管理器來發起通知。如果id不同,則每click,在statu那裡增加一個提示
manager.notify(1, notify);
}
基於API11之後:
public void showNotification() {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder nb = new NotificationCompat.Builder(
getApplicationContext())
.setContentIntent(
PendingIntent.getActivity(MainActivity.this, 0,
new Intent(this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT))
.setAutoCancel(true)
.setContentTitle("test title")
.setContentText("message")
.setSmallIcon(R.drawable.ic_launcher)
.setLights(Color.RED, 600, 1000)
.setVibrate(new long[] { 0, 200, 300, 500 })
.setSound(
RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
manager.notify(1, nb.build());
}