Android 9.0 (APi 28): java.lang.IllegalStateException: 不允许启动服务 Intent

Android 9.0 (APi 28): java.lang.IllegalStateException: Not allowed to start service Intent

我正在构建一个音乐应用程序,一切正常,但最近,应用程序会崩溃。当在 fabric 上看到我的崩溃列表时,请注意只发生在 os 9.

Fatal Exception: java.lang.RuntimeException Unable to start activity ComponentInfo{android.store/android.store.MusicPlayerActivity}: java.lang.IllegalStateException: Not allowed to start service Intent { act=android.store.mediaservice.PLAY_PLAYLIST cmp=android.store/.mediaservice.MediaService (has extras) }: app is in background uid UidRecord{1aba0fa u0a192 SVC bg:+5m42s914ms idle change:uncached procs:1 seq(0,0,0)}

我无法重现该问题,因为它很少发生。 以下代码导致崩溃:

if (intent.hasExtra(MediaService.EXTRAS_INDEX)) {
    Intent i = new Intent(getApplicationContext(), MediaService.class);
    i.setAction(MediaService.ACTION_PLAY_PLAYLIST);             i.putExtra(MediaService.EXTRAS_INDEX, intent.getIntExtra(MediaService.EXTRAS_INDEX, 0));
    i.putExtra(MediaService.EXTRAS_TRACK_IDLIST, intent.getStringArrayExtra(MediaService.EXTRAS_TRACK_IDLIST));     startService(i);
} else if (intent.hasExtra(EXTRAS_SHUFFLE)) {
    Intent i = new Intent(getApplicationContext(), MediaService.class);
    i.setAction(MediaService.ACTION_PLAY_SHUFFLE);
    i.putExtra(MediaService.EXTRAS_TRACK_IDLIST, intent.getStringArrayExtra(MediaService.EXTRAS_TRACK_IDLIST));
    startService(i);
}

那么导致崩溃的主要原因是什么以及解决方法?

对于 Oreo 之前的设备,您必须使用 startService(),但是从 Oreo 开始的设备,您必须使用 startForgroundService()。检查下面的示例代码。

   ContextCompat.startForegroundService(new Intent(context, MyService.class));

Background Execution Limits in Android Oreo。 ContextCompat 使 Build.Version 检查内部并调用正确的方法

要向用户显示通知,请在您的服务中使用以下代码。

@Override
public void onCreate() {
    super.onCreate();
    startForeground(NOTIFICATION_ID,new Notification());
}