解决Android8.0之后开启service时报错IllegalStateException: Not allowed to start service Intent ...

mContext.startService(Intent(mContext, UpdataLocationsService::class.java))

IllegalStateException startService
查找资料说是Android 8.0 不再允许后台service直接通过startService方式去启动,否则就会引起IllegalStateException。而网上给出的解决方式大多是这样的
解决办法

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mContext.startForegroundService(Intent(mContext, UpdataLocationsService::class.java))
        } else {
            mContext.startService(Intent(mContext, UpdataLocationsService::class.java))
        }

然后必须在Myservice中调用startForeground():

@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}

不过可能是我代码本身的问题,使用上面代码之后应用报出RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid ch...

然后做了一些修改,其他的不变,只是在要开启的service中给notification添加 channelId:

 val CHANNEL_ID_STRING = "service_01"
    override fun onCreate() {
        super.onCreate()
        val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        var mChannel: NotificationChannel? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = NotificationChannel(
                CHANNEL_ID_STRING, getString(R.string.app_name),
                NotificationManager.IMPORTANCE_LOW
            )
            notificationManager.createNotificationChannel(mChannel);
            val notification =
                Notification.Builder(applicationContext, CHANNEL_ID_STRING)
                    .setContentText("正在后天定位")
                    .build()
            startForeground(1, notification)
        }
    }

ok,可以正常跑起来了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容