I have a very basic question. In the code below, the purpose is to pass a VideoView with an already initialized URL asset into the AsyncTask below. The Task will start the video and track the progress as it plays. So far, it appears to print the progressPercentage correctly and breaks out of the loop when it reaches 100%. However, if I hit "back" or exit the Activity that hosts the VideoView during playback, this AsyncTask will run infinitely. How can I avoid this from happening? I thought of comparing the "current" value with a "prev_current" value... but if the user decides to FF or RW to a specific spot in the video, I would not want this Task to exit.
public class VideoPlayerProgressAsyncTask extends AsyncTask<Void, Integer, Void>{
private VideoView video;
private int duration = 0; // in milliseconds
private int current = 0; // in milliseconds
private int progressPercentage = 0; // range [0..100]
public VideoPlayerProgressAsyncTask(VideoView vid) {
video = vid;
}
@Override
protected Void doInBackground(Void... params) {
video.start();
video.requestFocus();
video.setOnPreparedListener(new OnPreparedListener(){
@Override
public void onPrepared(MediaPlayer mp) {
duration = video.getDuration();
}
});
while(progressPercentage <= 100) {
current = video.getCurrentPosition(); // in milliseconds
try{
int temp = (int) (current * 100 / duration);
publishProgress(temp);
if(progressPercentage >= 100)
break;
}
catch(Exception e){ }
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressPercentage = values[0];
}
}
try to cancel the asynctask on onPause() of your activity
@Override
protected void onPause() {
videoPlayerProgressAsyncTask_Object.cancel(true);
}