ExoPlayer在后台停止播放

7
我有一个应用程序,保持一个全局的ExoPlayer实例来方便后台音频流。在打开了很多应用程序之后,音频停止播放。
发生的情况如下:
- 打开开始播放音频的Activity - 按返回按钮关闭Activity - 音频仍在播放,如果你不管设备它会一直播放(这是预期的)
然而,在最后一步之后打开十几个或更多的应用程序后,ExoPlayer在某些时候停止播放。我猜测是进行了内存清理,因此ExoPlayer被解除分配。我尝试从日志中获取更多信息,但到目前为止帮助很少。
在android.app.Service中保持对ExoPlayer的引用没有任何区别。
我正在测试的设备是Nexus 5,Android 5.1.x,但是这个问题也会发生在其他设备上。
我在ExoPlayer文档页面、StackOverflow或Google上找不到解决方法。有人知道防止ExoPlayer停止播放的正确方法吗?

2
你尝试过将它放在前台“Service”中吗? - Ricardo
是的,我尝试在android.app.Service中保存它的引用。 - ByteWelder
1
我不是指任何服务,而是指在前台启动的服务。 - Ricardo
谢谢,我会尝试的! - ByteWelder
@Ricardo,它起作用了。如果您添加您的答案,我会接受它。我还在ExoPlayer错误跟踪器中找到了该解决方案的确认:https://github.com/google/ExoPlayer/issues/421 - ByteWelder
显示剩余5条评论
1个回答

11
为了确保一个 Service 能够尽可能长时间地在系统不被杀死的情况下存活,你需要将其作为前台服务启动。
这意味着会有一个通知告知用户该服务正在运行,以便用户能够知晓。因此,你必须使用相应的通知来启动服务。以下是文档中的示例:
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
            System.currentTimeMillis()); 
Intent notificationIntent = new Intent(this, ExampleActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
notification.setLatestEventInfo(this, getText(R.string.notification_title),
            getText(R.string.notification_message), pendingIntent); 
startForeground(ONGOING_NOTIFICATION_ID, notification);

非常感谢您分享这个知识!+1 - Ankit Aggarwal
@AnkitAggarwal 这个代码块在你那边能正常工作吗? - Maveňツ
2
针对Android 8.0及以上版本,通知需要频道ID。更多信息请参考此处:https://developer.android.com/training/notify-user/channels - G Singh
能否更新这个答案以适应最近的Android更新?谢谢! - toto_tata

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接