初始化Notification
private NotificationManager mN = null;
private static final int NOTIFY_ID = 0X123;
private static final String CHANNEL_ID = "my_channel_id";
private void initNotify() {
mN = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String name = "test Channel";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("test channel description");
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{0, 50, 100, 150});
// channel.setSound(Uri.parse("android.resource://org.crazyit.ui/" + R.raw.msg), null);
mN.createNotificationChannel(channel);
}
發(fā)送Notification
@RequiresApi(api = Build.VERSION_CODES.P)
private void makeNotification() {
Intent intent = new Intent(NotificationAct.this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(NotificationAct.this, 0, intent, 0);
Person p = new Person.Builder()
.setName("sun")
.setIcon(Icon.createWithResource(this, R.drawable.sun_head))
.build();
Notification.MessagingStyle messagingStyle = new Notification.MessagingStyle(p);
messagingStyle.setConversationTitle("a new notification");
Notification.MessagingStyle.Message message =
new Notification.MessagingStyle.Message("congratulation, you got a salary rise", System.currentTimeMillis(), p);
message.setData("image/jpeg", Uri.parse("file:///mnt/sdcard/list.png"));
messagingStyle.addMessage(message);
Notification notify = new Notification.Builder(this, CHANNEL_ID)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setStyle(messagingStyle)
.setContentIntent(pi)
.build();
mN.notify(NOTIFY_ID, notify);
}
android8開(kāi)始使用了Notification的channel來(lái)統(tǒng)一管理通知,開(kāi)發(fā)者可以為不同類型的通知?jiǎng)?chuàng)建同一個(gè)通知channel,而用戶可以通過(guò)channel來(lái)統(tǒng)一管理這些通知的行為----所有使用統(tǒng)一個(gè)channel的通知都具有相同的行為。
通知channel可以統(tǒng)一管理通知的如下行為:
- 重要性
- 聲音
- 閃光燈
- .....
Android 9 new feature for notification - MessagingStyle can use Person as the params
- Message can use setData to have more data(such as image)