Android 注册service报错,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

我的解决方法如下

添加网络权限:

然后在application继续添加

android:usesCleartextTraffic="true"另外在9.0的系统上需要添加权限:

958ecd8af623e43a6c7415a3d7bee696.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值