我正在开发一个媒体应用程序。我想知道如何保持我的应用在 Oreo 之前的一些旧行为,例如,即使服务不再设置为前台,通知和服务(用于播放)也会挂在那里。
我们在播放开始时调用 startService(MediaPlaybackService.class) 来启动服务,然后创建一个通知并在服务上调用 startForeground()。到目前为止一切顺利 - 如果用户退出应用程序,用户仍将在后台播放媒体,并且可以通过通知控制播放。
当用户暂停播放时,我们调用 stopForeground(false) 使通知消失。问题来了,从Android Oreo开始,系统会阻止启动非前台服务并停止正在运行的服务。在我的情况下,在暂停播放时,服务变为非前台并且会被系统停止。并且由于它就像一个正确的 stopSelf() 调用,将 onStartCommand() 设置为返回“START_STICKY”似乎无助于向服务提供另一个启动调用,即使这样做也很可能无法工作,因为应用程序仍在在背景中。
看起来它适用于 Spotify - 当播放暂停时,他们的通知会无限期地保留;并且通知是可忽略的,所以我认为它没有设置为前台。想知道它对 Spotify 是如何工作的吗?
这是一些示例代码:
class MyService extends MediaBrowserServiceCompat implements PlayerStateListener {
public int onStartCommand(...) {
//....
return START_STICKY;
}
void onPlaybackStarts() {
makeServiceStart(); // handles before and after 26
Notification notif = buildNotif();
startForeground(NOTIF_ID, notif); // non-zero value
}
void onPlaybackStops() {
// if app is in background at this point, system will stop the service short after the line below.
stopForeground(false);
if (state == Player.IDLE) {
stopSelf();
}
}
}