在应用程序启动时,应用程序启动应该执行某些网络任务的服务。 以 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-推荐答案 strong>
我得到了解决方案。对于 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/
|