我正在开发一个媒体应用程序 . 我想知道如何保留我的应用程序在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();
    }
  }
}