Android通知——Notification

Posted Android-kongqw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android通知——Notification相关的知识,希望对你有一定的参考价值。

android通知——Notification

创建通道

在显示通知之前必须先设置通道,这是必须前提。
可以在此对此通道的通知进行基本的设置,例如是否显示呼吸灯、是否震动、优先级等。

代码大概长这样:

/**
 * 创建通知渠道(8.0后新增,必须)
 * 应该再应用启动时就自己支持创建渠道,否则收不到通知,可以重复创建
 */
private fun createNotificationChannel() 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
        val name = "测试通知"
        val descriptionText = "测试通知的渠道"
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel =
            NotificationChannel(CHANNEL_ID_NOTIFICATION_BASIC, name, importance).apply 
                description = descriptionText
                enableLights(false)
                enableVibration(false)
                vibrationPattern = LongArray(0)
                setSound(null, null)
            
        notificationManager.createNotificationChannel(channel)
    

此操作需要在显示通知前完成,可以重复调用。
创建完通道后可以再设置中看到。

CHANNEL_ID_NOTIFICATION_BASIC 是我们自定义的 CHANNEL_ID 后面显示通知的时候会用到

private const val CHANNEL_ID_NOTIFICATION_BASIC = "CHANNEL_ID_NOTIFICATION_BASIC"

在显示通知之前,我们先创建一个NotificationManager

private lateinit var notificationManager: NotificationManager

notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

基本样式通知

/**
 * 显示基本通知
 */
private fun showBasicNotification2() 
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("基本通知")
        .setContentText("我是基本通知内容")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .build()
    notificationManager.notify(id++, build)

可以展开大图的通知

private fun showBigPictureNotification() 
    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("可展开大图")
        .setContentText("我是可展开大图的通知")
        .setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap))
        .build()
    notificationManager.notify(id++, build)

可以展开大段文字的通知

private fun showBigTextNotification() 
    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("可展开大段文字")
        .setContentText("我是可展开大段文字的通知")
        .setLargeIcon(bitmap)
        .setStyle(
            NotificationCompat.BigTextStyle()
                .setBigContentTitle("大段文字")
                .bigText("大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字大段文字")
        )
        .build()

    notificationManager.notify(id++, build)

列表样式的通知

private fun showMessageSnippetNotification() 
    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("列表样式的通知")
        .setContentText("我是列表样式的通知")
        .setLargeIcon(bitmap)
        .setStyle(
            NotificationCompat.InboxStyle()
                .addLine("1111111")
                .addLine("2222222")
                .addLine("3")
                .addLine("444")
                .addLine("555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555")
                .addLine("6666666666666666")
        )
        .build()

    notificationManager.notify(id++, build)

列表中最多显示6行(addLine 6次),多余6行的内容将无法显示。

对话样式的通知

private fun showMessagingNotification() 
    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))
    val createWithBitmap = IconCompat.createWithBitmap(bitmap)
    val message1 = NotificationCompat.MessagingStyle.Message("你好啊", System.currentTimeMillis(), Person.Builder().setName("张三").setIcon(createWithBitmap).build())
    val message2 = NotificationCompat.MessagingStyle.Message("谢谢", System.currentTimeMillis(), Person.Builder().setName("李四").setBot(true).build())
    val message3 = NotificationCompat.MessagingStyle.Message("Hello!", System.currentTimeMillis(), Person.Builder().setName("王五").setImportant(true).build())
    val message4 = NotificationCompat.MessagingStyle.Message("Android", System.currentTimeMillis(), Person.Builder().setName("赵六").setIcon(createWithBitmap).build())
    val message5 = NotificationCompat.MessagingStyle.Message("Notification", System.currentTimeMillis(), Person.Builder().setName("小七").build())
    val message6 = NotificationCompat.MessagingStyle.Message("biubiubiu~", System.currentTimeMillis(), Person.Builder().setName("老八").build())
    
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setLargeIcon(bitmap)
        .setStyle(
            NotificationCompat.MessagingStyle(Person.Builder().setName("kongqw").build())
                .addMessage(message1)
                .addMessage(message2)
                .addMessage(message3)
                .addMessage(message4)
                .addMessage(message5)
                .addMessage(message6)
        )
        .build()

    notificationManager.notify(id++, build)

列表中最多显示5条,后添加的消息会挤掉前面的消息。

媒体控件样式的通知

需要先添加一个依赖

implementation "androidx.media:media:1.1.0"
private fun showMediaNotification() 

    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))

    val pendingIntentPrevious: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("com.kongqw.notification.media.previous"), 0)
    val pendingIntentPause: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("com.kongqw.notification.media.pause"), 0)
    val pendingIntentNext: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("com.kongqw.notification.media.next"), 0)
    val pendingIntentPlay: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("com.kongqw.notification.media.play"), 0)

    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("媒体控件样式通知")
        .setContentText("我是媒体控件样式通知")
        .addAction(android.R.drawable.ic_media_previous, "Previous", pendingIntentPrevious)
        .addAction(android.R.drawable.ic_media_pause, "Pause", pendingIntentPause)
        .addAction(android.R.drawable.ic_media_next, "Next", pendingIntentNext)
        .addAction(android.R.drawable.ic_media_play, "Play", pendingIntentPlay)
        .setLargeIcon(bitmap)
        .setStyle(
            androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1, 2) // .setMediaSession()
        )
        .build()

    notificationManager.notify(id++, build)

上述代码中addAction添加了4个控制按钮,setShowActionsInCompactView设置了通知在收起状态下,显示第012个按钮。

点击通知跳转Activity

基本样式通知的基础上举例,只需要setContentIntent即可

private fun showBasicNotification3() 
    // 创建一个跳转的Intent
    val intent = Intent(this, MainActivity::class.java).apply  
        // ... 其他一些设置信息
    
    // 创建 PendingIntent
    val jumpIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
    
    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("基本通知")
        .setContentText("我是基本通知内容,点击可以跳转Activity.")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // 设置跳转,点击打开MainActivity
        .setContentIntent(jumpIntent)
        .build()

    notificationManager.notify(id++, build)

添加Action

同样在基本样式通知的基础上举例,Action可以添加点击跳转行为,也可以添加点击发送广播的行为。

private fun showBasicNotification4() 
    // 创建一个跳转的Intent
    val intent = Intent(this, MainActivity::class.java).apply 
        // ... 其他一些设置信息
    
    // 创建 PendingIntent
    val jumpIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

    // 创建发送广播的Intent
    val sendBroadcastIntent: PendingIntent = PendingIntent.getBroadcast(this, 0, Intent("com.kongqw.notificationsimple.action"), 0)

    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("基本通知")
        .setContentText("我是带有Action的基本通知内容")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // 设置点击跳转的Action
        .addAction(R.mipmap.ic_launcher, "点我打开MainActivity", jumpIntent)
        // 设置点击发送广播的Action
        .addAction(R.mipmap.ic_launcher, "点我发送一条广播", sendBroadcastIntent)
        .build()

    notificationManager.notify(id++, build)

  • jumpIntent 设置了点击跳转到MainActivity
  • sendBroadcastIntent 设置了发送广播的内容,动态注册一个广播后自行验证即可。

在通知中直接回复

private fun showReplayNotification() 
    // 设置回复后的广播
    val replyPendingIntent: PendingIntent = PendingIntent.getBroadcast(applicationContext, 0, Intent("com.kongqw.notificationsimple.reply"), PendingIntent.FLAG_UPDATE_CURRENT)
    // 设置回复输入框
    val remoteInput: RemoteInput = RemoteInput.Builder("KEY_TEXT_REPLY").setLabel("请输入").build()
    // 设置回复按钮
    val replyAction = NotificationCompat.Action.Builder(R.drawable.ic_launcher_background, "回复", replyPendingIntent).addRemoteInput(remoteInput).build()
    // 模拟收到的消息
    val bitmap = BitmapFactory.decodeStream(resources.assets.open("picture.jpg"))
    val message = NotificationCompat.MessagingStyle.Message("你好啊", System.currentTimeMillis(), Person.Builder().setName("张三").setIcon(IconCompat.createWithBitmap(bitmap)).build())

    val build = NotificationCompat.Builder(this, CHANNEL_ID_NOTIFICATION_BASIC)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setStyle(NotificationCompat.MessagingStyle(Person.Builder().setName("kongqw").build()).addMessage(message))
        // 回复
        .addAction(replyAction)
        .build()

    notificationManager.notify(id++, build)

  • KEY_TEXT_REPLY 用来标记回复的文字内容,在广播接收者中使用该字段来获取回复的文字

广播接收(代码仅供参考,注册广播请自行处理)

inner class MyBroadcastReceiver : BroadcastReceiver() 
    override fun onReceive(context: Context?, intent: Intent?) 
        when (intent?.action) 
            "com.kongqw.notificationsimple.action" -> Toast.makeText(applicationContext, "收到广播", Toast.LENGTH_SHORT).show()
            "com.kongqw.notificationsimple.reply" -> 
                val charSequence = RemoteInput.getResultsFromIntent(intent)?.getCharSequence("KEY_TEXT_REPLY"以上是关于Android通知——Notification的主要内容,如果未能解决你的问题,请参考以下文章

android笔记:Notification通知的使用

Android中使用Notification实现宽通知栏(Notification示例二)

Android通知——Notification

Android通知——Notification

Android通知大图尺寸

android:Notification实现状态栏的通知