当前位置:   article > 正文

解决Developer warning for package xxx,Failed to post notification on channel “null“

developer warning for package

Android O开始,系统不允许后台应用创建后台服务,要改为使用前台服务,并且应用5S内要调用该服务的startForeground()方法,否则系统将停止服务并报ANR异常:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(serviceStartIntent)
} else {
    startService(serviceStartIntent)
}
  • 1
  • 2
  • 3
  • 4
  • 5

调用startForeground(),需要传一个notification对象,在API 26以上中要使用Notification.Builder(Context, String) ,并且要指明 NotificationChannel 的Id. 如果不加则会提示:Developer warning for package xxx,Failed to post notification on channel “null”

/**
 * @see Service.onStartCommand
 */
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = "001"
        val channelName = "myChannel"
        val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_NONE)
        channel.lightColor = Color.BLUE
        channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(channel)
        val notification: Notification

        notification = Notification.Builder(applicationContext, channelId)
                .setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build()

        startForeground(101, notification)

    } else {
        startForeground(101, Notification())
    }

    return START_STICKY
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
/**
 * @see Service.onDestroy
 */
override fun onDestroy() {
    stopForeground(true)
    super.onDestroy()
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/122850
推荐阅读
相关标签
  

闽ICP备14008679号