Notification使用

初始化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可以统一管理通知的如下行为:

  1. 重要性
  2. 声音
  3. 闪光灯
  4. .....
    Android 9 new feature for notification
  5. MessagingStyle can use Person as the params
  6. Message can use setData to have more data(such as image)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容