RedBassett RedBassett - 5 months ago 84
Android Question

Leaks and releasing YouTubeThumbnailLoaders

I have an activity fragment with a single

YouTubeThumbnailView
in it. The view is set from an async task:

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());
}
}
}


This causes the following error when I launch (or sometimes only when hitting the back button from) a
YouTubeStandalonePlayer
for the video in the thumbnail (when the thumbnail is clicked):

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


I assumed this had to do with the warning found in the docs about releasing
YouTubeThumbnailLoader
s when done with them. As suggested in other StackOverflow questions, I tried saving the loader as
mThumbnailLoader
in
MyFragment
from
onInitializationSuccess
and releasing it in the click action:

@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);
}


How do I correctly release the loader to avoid this issue?

Answer

This issue seems to be caused by the activity (and therefore fragment) being destroyed by something other than the click event. Simply repeating the mThumbnailLoader.release(); block in onDestory() fixed the issue.

Additionally, the actual crash was being caused by another issue. On its own the leaked ServiceConnection error is only visible in the log without any user-facing impact on the app.