Android高版本通知栏问题

应用新版本上线,出现了个小插曲,高版本通知栏不显示下载进度。通过查阅资 https://developer.android.google.cn/training/notify-user/build-notification?hl=en 发现高版本SDK有些方法已经优化替换,并且notification 加入了NotificationChannel,所以修改了下,代码如下。

fun showNotification(context: Context?, notifyId: Int, largeIcon: Int, smallIcon: Int, totalLenth: Long, currentLength: Long) {
        context ?: return

        val d = currentLength / totalLenth
        var rate = 0f
        if (d != 1L) {
            rate = currentLength * 0.1f / (totalLenth * 0.1f)
        } else {
            rate = 1f
        }
        val percent = (rate * 100).toInt()

        if (mNotificationManager == null)
            mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?

        val customRemoteView = getRemoteView(context, percent, largeIcon)
        val customRemoteViewBig = getRemoteView(context, percent, largeIcon)

        //8.0+
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW))
        }

        val notification = NotificationCompat.Builder(context, CHANNEL_ID).run {
            setSmallIcon(smallIcon)
//            setContentIntent(pendingIntent)//设置跳转页面
            setCustomContentView(customRemoteView)
            priority = NotificationCompat.PRIORITY_LOW //低于api26 ,设置优先级优先级越大越靠前
            setStyle(android.support.v4.media.app.NotificationCompat.MediaStyle()) // 扩展通知在 Android 4.1 之前的平台上不可用
            setOngoing(true)//禁止侧滑删除
            setAutoCancel(false)//设置点击取消?可点击取消:不可点击取消
            setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
        }.build()

        if (100 == percent) {
            mNotificationManager?.cancel(notifyId)
        } else {
            mNotificationManager?.notify(NOTIFYCATION_ID, notification)
        }

    }

  
    private fun getRemoteView(context: Context, percent: Int, largeIcon: Int): RemoteViews {

        val remoteViews = RemoteViews(context.packageName, R.layout.notification_item).also {
            /*** 自定义  Notification 的显示 */
            it.setImageViewResource(R.id.icon, largeIcon)
            it.setProgressBar(R.id.progress1, 100, percent, false)
            it.setTextViewText(R.id.tv_progress, "$percent%")
        }
        return remoteViews
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值