Android 9.0(API 28):java.lang.IllegalStateException:不允许启动服务意图

1cosmwyk  于 12个月前  发布在  Android
关注(0)|答案(1)|浏览(83)

我正在构建一个音乐应用程序,一切都很好,但最近,应用程序将崩溃.当看到我的崩溃列表上的面料,所以注意,只发生在os 9。
致命异常:java.lang.RuntimeException无法启动活动entInfo {android.store/android.store.MusicPlayerActivity}:java.lang.IllegalStateException:不允许启动服务Intent { act=android.store.mediaservice. MediaList_PLAYLIST cmp=android.store/.mediaservice.MediaService(具有额外功能)}:应用程序在后台uid UidRecord{1aba 0 fa u 0a 192 SVC bg:+5m42s914ms空闲更改:未缓存进程: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);
}

那么造成死机的主要原因和解决方法是什么呢?

k5hmc34c

k5hmc34c1#

对于pre 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());
}

相关问题