Android 9 (Pie), Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord

前端 未结 6 2326
感情败类
感情败类 2020-12-13 20:17

First of all, I looked at these;

  • Context.startForegroundService() did not then call Service.startForeground()
  • Context.startForegroundService() did not
6条回答
  •  时光取名叫无心
    2020-12-13 21:18

    The Android Service component is a bit tricky to get working properly, especially on later Android versions where the OS adds additional restrictions. As mentioned in other answers, when starting your Service, use ContextCompat.startForegroundService(). Next, in Service.onStartCommand(), call startForeground() immediately. Store the Notification you want to show as a member field and use that unless it is null. Example:

    private var notification:Notification? = null
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (notification == null) {
            notification = createDefaultNotification()
        }
        startForeground(NOTIFICATION_ID, notification)
    
        // Do any additional setup and work herre
    
        return START_STICKY
    }
    

    Always return START_STICKY in your Service. Anything else is probably the wrong thing, especially if you're doing a audio player of any kind. In fact, if you're doing an audio player, you shouldn't implement your own Service but use MediaBrowserServiceCompat (from AndroidX) instead.

    I also recommend the blog posts I wrote on this: https://hellsoft.se/how-to-service-on-android-part-3-1e24113152cd

提交回复
热议问题