Android : youtube 播放器已发布
我收到此错误 致命异常:java.lang.IllegalStateException此 YouTubePlayer 已发布
,但未明确调用 release()
.这是发生崩溃的代码:
I'm getting this error Fatal Exception: java.lang.IllegalStateException
This YouTubePlayer has been released
, but release()
wasn't called explicitly.Here is the piece of code where crash occurs :
if(youtubePlayer != null){
time = youtubePlayer.getCurrentTimeMillis();//exception may occur
}
是否可以检查 youtubePlayer
是否已发布
?有回调吗?谢谢.
is it possible to check that youtubePlayer
was released
? Any callback ? Thanks.
推荐答案
Youtube SDK 中的大部分代码都被混淆了,这使得调试非常困难.没有任何直接的方法可以检查 YoutubePlayer 是否已发布这一事实也无济于事.
Most of the code in the Youtube SDK is obfuscated which makes it really hard to debug. And the fact that there isn't any direct method to check if the YoutubePlayer has been released or not doesn't help either.
话虽如此,我认为 让 YoutubePlayer 为空(在 onStop() 中)对我来说似乎更像是一种 hack 而不是适当的解决方案.您应该在 onDestroy() 中释放 YoutubePlayer,并且不要在任何地方手动将其分配为 null.检查 YoutubePlayer 是否已发布的一种简单方法是将您的调用(如 youtubePlayer.loadVideo()、cueVideo()、getCurrentTimeMillis() 等)放入 try catch 块并捕获 IllegalStateException 异常.强>
Having said that I think making YoutubePlayer null (in onStop()) seems more of a hack than a proper solution to me. You should release the YoutubePlayer in onDestroy() and don't manually assign it as null anywhere. One simple approach to check if the YoutubePlayer has been released or not is put your calls (like youtubePlayer.loadVideo(), cueVideo(), getCurrentTimeMillis() etc.) in a try catch block and catch the IllegalStateException exception.
根据 Youtube SDK 文档 关于错误:
public static final YouTubePlayer.ErrorReasonUNEXPECTED_SERVICE_DISCONNECTION
public static final YouTubePlayer.ErrorReason UNEXPECTED_SERVICE_DISCONNECTION
播放已被取消,播放器已被释放,因为与 YouTube API 服务的意外断开连接.任何进一步调用此播放器实例将导致错误,新播放器必须创建实例才能重新启用播放.
Playback has been canceled and the player has been released due to an unexpected disconnection from the YouTube API service. Any further calls to this player instance will result in errors, a new player instance must be created to re-enable playback.
所以要创建一个新的 YoutubePlayer 实例,只需调用 catch 块中的 initialize() 方法即可.
例子:
public void setVideoId(final String videoId) {
if (videoId != null && !videoId.equals(this.videoId)) {
this.videoId = videoId;
if (youtubePlayer != null) {
try {
youtubePlayer.loadVideo(videoId);
} catch (IllegalStateException e) {
initialize(API_KEY, this);
}
}
}
}
@Override
public void onDestroy() {
if (youtubePlayer != null) {
youtubePlayer.release();
}
super.onDestroy();
}
相关文章