Android 8.0 还对特定函数做出了以下变更:
(1)如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用 startService() 函数,
则该函数将引发一个 IllegalStateException。新的 Context.startForegroundService() 函数将启动一个前台服务。
(2)即使应用在后台运行,系统也允许其调用 Context.startForegroundService()。不过,
应用必须在创建服务后的五秒内调用该服务的 startForeground() 函数。
解决方案
// 启动服务的地方
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, ServedService.class));
} else {
context.startService(new Intent(context, ServedService.class));
}
// service 类内部 oncreate
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForeground(1,new Notification()); //这个id不要和应用内的其他同志id一样,不行就写 int.maxValue() //context.startForeground(SERVICE_ID, builder.getNotification());
}
}
Android8.0对启动后台服务进行了限制,应用在尝试使用startService()时可能会引发IllegalStateException,需改用Context.startForegroundService()启动前台服务。系统要求服务在创建后五秒内调用startForeground()。开发者需要根据Android版本判断并适配服务启动方式。
3144

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



