android 8.0 通知适配

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ff_hh/article/details/80266688

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)
    }
}


展开阅读全文

没有更多推荐了,返回首页