我在Android操作系统上使用Service
类。
我计划在后台使用Service
。
Android文档指出:
如果应用程序的目标是API级别26或更高,则系统对使用或创建后台服务施加限制,除非应用程序本身位于前台。如果应用程序需要创建前台服务,应用程序应该调用
startForegroundService()
。
如果使用startForegroundService()
,则Service
将引发以下错误。
Context.startForegroundService() did not then call
Service.startForeground()
这是怎么回事?
发布于 2017-07-12 02:51:28
来自谷歌在Android8.0行为变化上的文档
该系统允许应用程序在后台调用Context.startForegroundService()。但是,应用程序必须在创建服务后5秒钟内调用该服务的startForeground()方法。
解决方案:在startForeground()
中调用onCreate()
中的Service
,使用Context.startForegroundService()
另见:背景执行限制 for Android8.0(奥利奥)
发布于 2017-09-27 14:04:19
然后我打电话给ContextCompat.startForegroundService(this, intent)
来启动服务
在役onCreate
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
发布于 2018-06-05 03:17:10
之所以会出现此问题,是因为Android框架不能保证您的服务在5秒内启动,但另一方面,框架对前台通知有严格的限制,必须在5秒内触发,而无需检查框架是否尝试启动服务。
这绝对是一个框架问题,但并非所有面临此问题的开发人员都在尽力而为:
startForeground
通知必须同时位于onCreate
和onStartCommand
中,因为如果您的服务已经创建,并且您的活动正试图再次启动它,则不会调用onCreate
。stopSelf
之前调用startForeground
。对于以上所有的3,这个问题可以减少一点,但仍然不是一个修复,真正的修复或者说解决办法是将目标sdk版本降到25。
请注意,最有可能的Android P仍然存在这一问题,因为Google甚至不了解正在发生的事情,并且不认为这是他们的错,请阅读#36和#56以获得更多信息。
https://stackoverflow.com/questions/44425584
复制相似问题