初始化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);
}
发送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开始使用了Notification的channel来统一管理通知,开发者可以为不同类型的通知创建同一个通知channel,而用户可以通过channel来统一管理这些通知的行为----所有使用统一个channel的通知都具有相同的行为。
通知channel可以统一管理通知的如下行为:
- 重要性
- 声音
- 闪光灯
- .....
Android 9 new feature for notification - MessagingStyle can use Person as the params
- Message can use setData to have more data(such as image)