Android安卓状态栏消息推送通知(Notification)

版权声明:版权声明@忆痕惜dxh | https://blog.csdn.net/qq_38717971/article/details/83576883

我从不猜测,猜测是一个很坏的习惯——会影响正常的逻辑推理能力。              ——阿瑟·柯南·道尔 《福尔摩斯探案集》


近日,在做安卓项目开发的时候涉及到状态栏通知的需求,查了资料,总结一个简单有效的方法,下面放上代码(Kotlin版):

//该代码为Kotlin,读者可根据需求稍作调整
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    var notification: Notification
    val intent = PendingIntent.getActivity(this,
            100, Intent(this, MainActivity::class.java),
            PendingIntent.FLAG_CANCEL_CURRENT)
    val largeIcon = BitmapFactory.decodeResource(
            this.resources, android.R.drawable.ic_media_play)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        val mChannel = NotificationChannel("id", "name",NotificationManager.IMPORTANCE_LOW)
        notificationManager.createNotificationChannel(mChannel)
        notification = Notification.Builder(this)
                .setChannelId("id")
                .setContentTitle("标题")
                .setContentText("内容内容内容内容内容内容内容内容内容内容")
                .setContentIntent(intent)
                .setLargeIcon(largeIcon)
                .setSmallIcon(android.R.drawable.ic_media_play).build()
    }else{
        val builder = NotificationCompat.Builder(this)
                .setContentTitle("标题")
                .setContentText("内容内容内容内容内容内容内容内容内容内容")
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setAutoCancel(true)
                .setLargeIcon(largeIcon)
                .setSmallIcon(android.R.drawable.ic_media_play)
                .setContentIntent(intent)
        notification = builder.build()
    }
    notificationManager.notify(0,notification)

猜你喜欢

转载自blog.csdn.net/qq_38717971/article/details/83576883