在应用程序启动时,应用程序启动应该执行某些网络任务的服务。
以 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)}
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.
我得到了解决方案。对于 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。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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |