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);

    }

發(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)一管理通知的如下行為:

  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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容