美文网首页
解决Android8.0之后开启service时报错Illega

解决Android8.0之后开启service时报错Illega

作者: 安卓_背包客 | 来源:发表于2020-07-27 10:35 被阅读0次

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,可以正常跑起来了。

相关文章

网友评论

      本文标题:解决Android8.0之后开启service时报错Illega

      本文链接:https://www.haomeiwen.com/subject/rzaalktx.html