天天看点

Android 发送通知 notification

Android studio 4.0.1    SDK 30 Android10.0+

Android 8.0之后需要配置通知渠道 来看一下官方文档的实例代码

https://developer.android.com/training/notify-user/build-notification#java

private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
           

首先需要配置通知渠道,new NotificationChannel(CHANNEL_ID, name, importance); 实例化渠道对象时配置渠道ID,名字和描述

Android 发送通知 notification

ID不在app中显性显示,Message ,app message 分别为配置的渠道名和渠道描述,可以在application中直接对需要申请的渠道进行申请, 官方文档中亦有描述解释渠道申请代码可以反复被执行,创建现有通知渠道不会执行任何操作

渠道创建好之后下面构建一个通知进行提示

// Create an explicit intent for an Activity in your app
    Intent intent = new Intent(this, AlertDetails.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true);
    
           

其中 AlertDetails.class 为点击通知进行执行的意图指向方,setFlags部分参考官方文档说明,按需配置

在合适的地方触发发送通知

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    // notificationId is a unique int for each notification that you must define
    notificationManager.notify(notificationId, builder.build());
    
           

注意此处需配置每个种类唯一ID 例如

notificationManager.notify(0, builder.build());
           

如果需要显示悬浮通知,在申请渠道时务必将优先级设置为

int importance = NotificationManager.IMPORTANCE_HIGH;
           
Android 发送通知 notification