泄漏并发布YouTubeThumbnailLoaders

时间:2016-06-12 23:27:05

标签: java android youtube-api

我有一个活动片段,里面有一个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);
}

如何正确释放加载程序以避免此问题?

1 个答案:

答案 0 :(得分:0)

这个问题似乎是由于活动(因此片段)被click事件以外的东西破坏而引起的。只需重复mThumbnailLoader.release();中的onDestory()块即可解决此问题。

此外,实际崩溃是由另一个问题引起的。泄漏的ServiceConnection错误只能在日志中看到,而不会对应用程序产生任何面向用户的影响。