Android8.0+ startService报错问题解决
Android 8.0为提高电池续航时间而引入的变更之一是,当您的应用进入已缓存状态时,如果没有活动的组件,系统将解除应用具有的所有唤醒锁。
此外,为提高设备性能,系统会限制未在前台运行的应用的某些行为。
* 现在,在后台运行的应用对后台服务的访问受到限制。
* 应用无法使用其清单注册大部分隐式广播(即,并非专门针对此应用的广播)。 默认情况下,这些限制仅适用于针对 O 的应用。不过,用户可以从 Settings 屏幕为任意应用启用这些限制,即使应用并不是以 O 为目标平台。
Android 8.0 还对特定函数做出了以下变更:
- 如果针对 Android 8.0 的应用尝试在不允许其创建后台服务的情况下使用
startService()
函数,则该函数将引发一个IllegalStateException
。 - 新的
Context.startForegroundService()
函数将启动一个前台服务。现在,即使应用在后台运行,系统也允许其调用Context.startForegroundService()
。不过,应用必须在创建服务后的五秒内调用该服务的startForeground()
函数。
在Android8.0之前直接用startService 可以直接启动服务的。
在8.0之后的版本里,启动的方法变成了startForegroundService();
我遇到的问题如下:异常信息:Context.startForegroundService() did not then call Service.startForeground()
原因:在系统创建服务后,应用有五秒的时间来调用该服务的 startForeground() 方法以显示新服务的用户可见通知。如果应用在此时间限制内未调用 startForeground(),则系统将停止服务并声明此应用为 ANR。
解决方法:在Service.OnCreate的时候添加通知
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String channelId = "****Service"; String channelName = "**服务"; int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel channel = new NotificationChannel(channelId, channelName, importance); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.createNotificationChannel(channel); // Notification notification = new Notification.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("*****服务") .setContentText("随时准备接收消息...") .setAutoCancel(true) .setShowWhen(true) .build(); int id = 10011; startForeground(id, notification); }
然后在调用的地方用改用startForegroundService(service);
这里我再做一下兼容处理,低于8.0的系统还是用startService( )
启动服务添加兼容处理: //开启服务兼容 Intent intentService = new Intent(SwapSpaceApplication.this, ZhkjLocalService.class); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { startForegroundService(intentService); } else { startService(intentService); }
然后还遇到个问题
android Q:No Network Security Config specified, using platform default
我的解决方法如下
添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
然后在application继续添加
android:usesCleartextTraffic="true"
另外在9.0的系统上需要添加权限:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />