Android 8.0: java.lang.IllegalStateException: Not allowed to start service Intent

前端 未结 17 1054
借酒劲吻你
借酒劲吻你 2020-11-22 09:15

On application launch, app starts the service that should to do some network task. After targeting API level 26, my application fails to start service on Android 8.0 on back

17条回答
  •  失恋的感觉
    2020-11-22 09:42

    As @kosev said in his answer you can use JobIntentService. But I use an alternative solution - I catch IllegalStateException and start the service as foreground. For example, this function starts my service:

    @JvmStatic
    protected fun startService(intentAction: String, serviceType: Class<*>, intentExtraSetup: (Intent) -> Unit) {
        val context = App.context
        val intent = Intent(context, serviceType)
        intent.action = intentAction
        intentExtraSetup(intent)
        intent.putExtra(NEED_FOREGROUND_KEY, false)
    
        try {
            context.startService(intent)
        }
        catch (ex: IllegalStateException) {
            intent.putExtra(NEED_FOREGROUND_KEY, true)
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            }
            else {
                context.startService(intent)
            }
        }
    }
    

    and when I process Intent I do such thing:

    override fun onHandleIntent(intent: Intent?) {
        val needToMoveToForeground = intent?.getBooleanExtra(NEED_FOREGROUND_KEY, false) ?: false
        if(needToMoveToForeground) {
            val notification = notificationService.createSyncServiceNotification()
            startForeground(notification.second, notification.first)
    
            isInForeground = true
        }
    
        intent?.let {
            getTask(it)?.process()
        }
    }
    

提交回复
热议问题