美文网首页安卓
Android 弹自定义Notification

Android 弹自定义Notification

作者: 卖炭少年炭治郎 | 来源:发表于2020-09-10 14:51 被阅读0次

基本使用

  1. 弹通知 测试UI
            val notificationId = 111
            val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val rootView = RemoteViews(context.packageName,R.layout.layout_notification)
            val builder = NotificationCompat.Builder(context, "zyl")
            val notification =
                builder
                    .setContent(rootView)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build()
            manager.notify(notificationId,notification)

2.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@color/colorAccent"
    android:layout_height="wrap_content">

    <ImageView
        android:background="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

系统原始的Notification

fun showNotificationWithIcon(
        context: Context,
        title: String,
        content: String,
        notificationId: Int,
        smallIconResId: Int,
        largeIconResId: Int
    ) {
        val notification: Notification = NotificationCompat.Builder(context)
            .setSmallIcon(smallIconResId)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, largeIconResId))
            .setContentTitle(title)
            .setContentText(content)
            .setTicker(content)
            .setAutoCancel(true)
            .build()
        val manager = context
            .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(notificationId, notification)
    }

总结

1. 报错 Bad notification posted from package com.zyl.testdemo: Couldn't expand RemoteViews

布局文件中使用ConstraintLayout,导致RemoteViews不支持该布局控件,崩溃

相关文章

网友评论

    本文标题:Android 弹自定义Notification

    本文链接:https://www.haomeiwen.com/subject/qzdpektx.html