Le *_*inh 3 android android-service android-9.0-pie
我正在构建一个音乐应用程序,一切正常,但最近,应用程序将崩溃。当在结构上看到我的崩溃列表时,请注意仅在 os 9 上发生。
致命异常:java.lang.RuntimeException 无法启动活动 ComponentInfo{android.store/android.store.MusicPlayerActivity}:java.lang.IllegalStateException:不允许启动服务 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);
}
Run Code Online (Sandbox Code Playgroud)
那么导致崩溃的主要原因是什么?对此的解决方案是什么?
对于 Oreo 之前的设备,您必须使用startService(),但从 Oreo 开始的设备,您必须使用startForgroundService(). 检查下面的示例代码。
ContextCompat.startForegroundService(new Intent(context, MyService.class));
Run Code Online (Sandbox Code Playgroud)
Android Oreo 中的后台执行限制。ContextCompat 使 Build.Version 检查内部并调用正确的方法
要向用户显示通知,请在您的服务中使用以下代码。
@Override
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION_ID,new Notification());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6905 次 |
| 最近记录: |