android 8.0 通知适配

本文介绍了如何在Android 8.0 (Oreo)中正确使用通知分组功能,以确保应用的通知能够正常发送并显示。文章详细展示了创建通知渠道、设置通知属性的方法,并提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android 8.0 原有的通知直接失效,因为android 8.0 以后通知增加分组,如果不进行分组通知将不能正常发送。

class MainOreoActivity : AppCompatActivity() {
    var TAG = "tag"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TAG += localClassName
        setContentView(R.layout.activity_oreo_main)
        oreoText.text = getString(R.string.android_oreo)
        testNotify.text = getString(R.string.oreo_notify_test)
        testNotify.setOnClickListener({ testNotify() })
    }

    fun testNotify() {
        Log.d(TAG, getString(R.string.oreo_notify_test))
        val id = 1000
        val channelId = "channel_first"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            createChannelId(channelId)
        val build: NotificationCompat.Builder = NotificationCompat.Builder(this, channelId)     
        build.setContentTitle("test")//设置标题
                .setContentText(getString(R.string.oreo_notify_test))//设置内容
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round))//设置通知栏图标
                .setSmallIcon(R.mipmap.ic_launcher)//设置状态栏图标
                .setAutoCancel(true)//点击自动关闭
                /** setPriority() 方法共有5个等级:
                1. PRIORITY_MIN - 最低级别(-2);
                2. PRIORITY_LOW - 较低级别(-1);
                3. PRIORITY_DEFAULT - 默认级别(0);
                4. PRIORITY_HIGH - 较高级别(1);
                5. PRIORITY_MAX - 最高级别(2);
                 */
            .priority = NotificationCompat.PRIORITY_HIGH
        val n: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        n.notify(id, build.build())
    }

    /**
     * 创建分类
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private fun createChannelId(channel: String) {
        val ncGroup = NotificationChannelGroup("group_second", "通知渠道")
        val n: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        n.createNotificationChannelGroup(ncGroup)
        val chan = NotificationChannel(channel, "通知渠道", NotificationManager.IMPORTANCE_DEFAULT)
        //锁屏的时候是否展示通知
        // VISIBILITY_PRIVATE : 显示基本信息,如通知的图标,但隐藏通知的全部内容;
        // VISIBILITY_PUBLIC : 显示通知的全部内容;
        // VISIBILITY_SECRET : 不显示任何内容,包括图标。
        chan.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        n.createNotificationChannel(chan)
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值