我有一个活动片段,里面有一个YouTubeThumbnailView
。视图是从异步任务设置的:
public class MyFragment extends Fragment {
private YouTubeThumbnailView mThumbnailView;
public class FetchThumbnailTask extends AsyncTask<> implements YouTubeThumbnailView.OnInitializedListener {
protected void onPostExecute(String videoId) {
mThumbnailView.setTag(videoId);
mThumbnailView.initialize(YOUTUBE_DATA_API_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
loader.setVideo((String) view.getTag());
}
}
}
当我启动(有时仅在从后退按钮时)缩略图中的视频YouTubeStandalonePlayer
时(单击缩略图时),这会导致以下错误:
E/ActivityThread: Activity com.example.app.MyActivity has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@1cc07092 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.app.MyActivity has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@1cc07092 that was originally bound here
我认为这与文档中发现的关于在使用完YouTubeThumbnailLoader
时释放的警告有关。正如其他 StackOverflow 问题中所建议的那样,我尝试将加载器保存为mThumbnailLoader
MyFragment
从onInitializationSuccess
并在单击操作中释放它:
@Override
public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
loader.setVideo((String) view.getTag());
mThumbnailLoader = loader;
}
@Override
public void onClick(View v) {
if (mThumbnailLoader != null) {
mThumbnailLoader.release();
}
Intent intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), YOUTUBE_DATA_API_KEY, (String) v.getTag());
startActivity(intent);
}
如何正确释放加载程序以避免此问题?
此问题似乎是由活动(因此片段)被单击事件以外的内容破坏引起的。只需重复mThumbnailLoader.release();
块onDestory()
即可解决问题。
此外,实际崩溃是由另一个问题引起的。就其本身而言,泄漏的ServiceConnection
错误仅在日志中可见,而不会对应用程序产生任何面向用户的影响。