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
    }

 

你可能感兴趣的:(开发问题)