【问题标题】:startForeground() always shows a popup on Samsung 8.0 devicestartForeground() 总是在三星 8.0 设备上显示一个弹出窗口
【发布时间】:2018-07-26 06:43:14
【问题描述】:

每次我在前台服务中使用startForeground() 在通知中更新状态时,我都遇到了三星 Galaxy S7 Edge 显示弹出通知的问题。

首先,所有 Android 8.0 设备都存在此问题,但通过将通知通道优先级设置为 IMPORTANCE_LOW 很容易解决。但是三星设备的问题仍然存在。

那么,问题是,如何在三星 8.0+ 设备上静默更新前台服务通知?

我的代码如下。

应用类:

override fun onCreate() {
        super.onCreate()
        //other code
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannels(listOf(
                    //
                    NotificationChannel(MY_NOTIFICATION_CHANNEL, "My channel", NotificationManager.IMPORTANCE_LOW).apply {
                        setSound(null, null)
                    }
                    //
            ))
        }
    }

服务启动前台:

val notification = NotificationCompat.Builder(this, MY_NOTIFICATION_CHANNEL)
                .setSmallIcon(android.R.drawable.stat_sys_warning)
                .setColor(App.context().resources.getColor(R.color.primary_dark))
                .setContentText(if (/*logic*/) "This" else "That")
                .addAction(0, if (enable) "Disable" else "Enable", firstIntent)
                .addAction(0, "Another action", secondIntent)
                .build()

        startForeground(MY_NOTIFICATION_ID, notification)

【问题讨论】:

  • 为什么要多次使用startForeground? android 多次显示您的通知是有意义的。您可以在尚未启动时显示 (start)。 startForeground 将始终显示通知。
  • @AdibFaramarzi 我已经更改了代码以检查是否已经有正在进行的通知并使用NotificationManager 来更新通知而不是另一个startForeground()。不过没有区别。

标签: android android-notifications android-8.0-oreo


【解决方案1】:

我一直在调查同样的事情。您能做的最好的事情是在没有频道的情况下创建通知。服务从托盘中的任何内容开始。似乎对我有用。

NotificationCompat.Builder(this)

但是,此构造函数在 26.1.0 中已弃用

【讨论】:

  • 我认为你不能在没有任何通知的情况下运行前台服务。
  • 正确,需要通知。但是,在 Android 8 中,如果您创建没有 Channel 的通知,它将不会出现在托盘中。根据我的经验,前台服务仍在运行,但通知不可见。但请注意,这种在没有通道的情况下创建通知的方式已被弃用。
【解决方案2】:

NotificationCompat.BuildersetOnlyAlertOnce 方法,当设置为true 时,它只会显示一次弹出窗口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多