Android8.0以后系统不允许直接采用startservice的方式启动后台服务,官网描述大概意思是这样儿式的:
- 如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用
startService()函数,则该函数将引发一个IllegalStateException。 - 新的
Context.startForegroundService()函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用Context.startForegroundService()。不过,应用必须在创建服务后的五秒内调用该服务的startForeground()函数。
既然不允许直接调用startservice了,那么怎么做呢?看上边的描述可以知道,可以用startForegroundService()来替代startservice,只不过需要在调用startForegroundService()之后需要在调用一个startForeground()函数,不然会报ANR。
具体写法入下:
首先修改启动方式if (Build.VERSION.SDK_INT >= 26) { context.startForegroundService(intent); } else { context.startService(intent); }- 其次在service里调用context.startForeground(SERVICE_ID, builder.getNotification());
context.startForeground(SERVICE_ID, builder.getNotification());
本文介绍Android8.0及更高版本中启动后台服务的方法。为避免IllegalStateException异常,需使用Context.startForegroundService()替代startService(),并在5秒内调用startForeground()函数以避免ANR。文中提供具体的代码实现。
4227

被折叠的 条评论
为什么被折叠?



