I'm searching for a solution to preload some videos from different urls into VideoViews, so that they could be played without any delay. I'm trying to do this in an async task:
class VideoPreloadTask extends AsyncTask<String, Void, Void> {
private Context mContext;
private CustomVideoView mVideoView;
public VideoPreloadTask(Context context) {
mContext = context;
}
@Override
public void onPreExecute() {
mVideoView = new CustomVideoView(mContext);
}
@Override
protected Void doInBackground(String... params) {
final String url = params[0];
mVideoView.setVideoPath(url);
mVideoView.setOnPreparedListener(new OnPreparedListener() {
//Wird aufgerufen, wenn das Video fertig geladen ist
@Override
public void onPrepared(MediaPlayer mp) {
mCounter++;
mVideoView.pause();
mVideoView.setPreloaded(true);
//Fuege das fertig geladene Video der Liste hinzu
mVideos.put(url, mVideoView);
}
});
mVideoView.start();
return null;
}
}
Now within the doInBackground-Method I set the path Url and start the loading of the video with start(). But the onPrepare-Listener does not work. The function never gets called and I don't understand why. I've tried loading some videos outside of an async task and it works well.
The async tasks are started like this:
for(String url : videoUrls) {
VideoPreloadTask task = new VideoPreloadTask(context);
task.execute(url);
}
and my CustomVideoView-Class looks like the following:
public class CustomVideoView extends VideoView {
private boolean mPreloaded = false;
private String mPath = "";
public CustomVideoView(final Context context) {
super(context);
}
public CustomVideoView(final Context context, final AttributeSet set) {
super(context, set);
}
@Override
public void setVideoPath(String url) {
super.setVideoPath(url);
mPath = url;
}
public boolean isPreloaded() {
return mPreloaded;
}
public void setPreloaded(boolean isPreloaded) {
mPreloaded = isPreloaded;
}
public String getVideoPath() {
return mPath;
}
}
Does anybody know, what causes this behaviour or where I've made a mistake?
Finally solved my problem. For everyone whos interested, heres the answer:
It seems as if Android only preloads the VideoViews video, when the view is part of an XML-Layout, which is also currently active. So if you want to preload a video, make the videoview part of your xml and do not create a videoview-object with the constructor, as I've done it. Then it should work! :D