下面介绍一个普通的通知的构建。 示例代码:
普通通知 //触发事件 val mIntent:Intent = Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com")) //通知管理器 val manager:NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager //通知触发事件Intent val pendingIntent:PendingIntent = PendingIntent.getActivity(this, 0 ,mIntent, 0) //信道创建和设置,注意channelId val notificationChannel:NotificationChannel = NotificationChannel("test", "测试普通", NotificationManager.IMPORTANCE_DEFAULT) manager.createNotificationChannel(notificationChannel) //构建者模式创建通知 val builder:Notification = NotificationCompat.Builder(this@MainActivity, "test") .setAutoCancel(true) .setContentTitle("普通通知") .setContentIntent(pendingIntent) .setContentText("测试") .setSmallIcon(R.drawable.ic_launcher_background) .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_background)) .build() //发送通知 manager.notify(1, builder) 悬挂通知 使用setFullScreenIntent来将notification变为悬挂式。 PendingIntent hangPendingIntent = PendingIntent.getActivity(this, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT); 折叠通知 使用RemoteViews来创建折叠的视图对象,设置notification.contentView为remoteViews,或者notification.bigContentView为remoteViews。