• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Android 8.0 : java. lang.IllegalStateException: 不允许启动服务 Intent

[复制链接]
菜鸟教程小白 发表于 2022-8-1 01:19:10 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

在应用程序启动时,应用程序启动应该执行某些网络任务的服务。
以 API 级别 26 为目标后,我的应用程序无法在后台在 Android 8.0 上启动服务。

Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=my.app.tt/com.my.service }: app is in background uid UidRecord{90372b1 u0a136 CEM idle procs:1 seq(0,0,0)}



据我了解,它与:
Background execution limits

The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.



在不允许的情况下 ” - 它的实际含义是什么?以及如何解决它。我不想将我的服务设置为“前台”



Best Answer-推荐答案


我得到了解决方案。对于 8.0 之前的设备,您只需使用 startService() ,但对于 7.0 后的设备,您必须使用 startForgroundService() .这是启动服务的代码示例。

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(new Intent(context, ServedService.class));
    } else {
        context.startService(new Intent(context, ServedService.class));
    }
在服务类中,请添加以下代码以进行通知:
@Override
public void onCreate() {
    super.onCreate();
    startForeground(1,new Notification());
}
其中 O 是 Android 版本 26。
如果您不希望您的服务在前台运行并希望它在后台运行,请发布 Android O,您必须将服务绑定(bind)到如下连接:
Intent serviceIntent = new Intent(context, ServedService.class);
context.startService(serviceIntent);
context.bindService(serviceIntent, new ServiceConnection() {
     @Override
     public void onServiceConnected(ComponentName name, IBinder service) {
         //retrieve an instance of the service here from the IBinder returned 
         //from the onBind method to communicate with 
     }

     @Override
     public void onServiceDisconnected(ComponentName name) {
     }
}, Context.BIND_AUTO_CREATE);

关于Android 8.0 : java. lang.IllegalStateException: 不允许启动服务 Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445265/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap