自定义Notification 实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| private var rv: RemoteViews? = null private var rvExpanded: RemoteViews? = null private fun customNotification(process: Int) { if (rv == null) rv = RemoteViews(packageName, R.layout.notification_small) rv?.setTextViewText(R.id.notification_title, "这是一个小标题") if (rvExpanded == null) rvExpanded = RemoteViews(packageName, R.layout.notification_large) rvExpanded?.setTextViewText(R.id.large_notification_title, "这是一个大标题,支持很多的内容: $process%")
val intentNotification = Intent(this, PlayMusicActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP } val pendIntent = PendingIntent.getActivity( this, 0, intentNotification, PendingIntent.FLAG_UPDATE_CURRENT )
val customNotification = NotificationCompat.Builder(applicationContext, CHANNEL_ID) .setSmallIcon(R.drawable.bravo) .setStyle(NotificationCompat.DecoratedCustomViewStyle()) .setCustomContentView(rv!!) .setContent(rvExpanded!!) .setCustomBigContentView(rvExpanded!!) .setCustomHeadsUpContentView(rvExpanded!!) .setOngoing(true) .setAutoCancel(false) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setPriority(NotificationCompat.PRIORITY_HIGH) .setOnlyAlertOnce(true) .setContentIntent(pendIntent) .build() startForeground(NOTIFICATION_ID, customNotification) }
|
1.使用 NotificationCompat
兼容各个版本差异性
2.RemoteViews
布局文件不支持 constraintlayout
,切记
3.在SDK 26之后必须要绑定Channel,所以通知要先创建Channel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| fun checkAndCreateChannel( context: Context, channelId: String, channelName: String, desc: String = channelName ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationManager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager try { val nc = notificationManager.getNotificationChannel(channelId) Log.d("ChannelHelper", "${nc.id} Notification Channel exist.") } catch (e: Exception) { Log.d("ChannelHelper", "empty channel need create.") val mChannel = NotificationChannel( channelId, channelName, NotificationManager.IMPORTANCE_HIGH ).apply { description = desc enableLights(true) enableVibration(true) } notificationManager.createNotificationChannel(mChannel) } } }
|