Reputation: 627
I am loading video from async task. When video took too long to load then back press to cancel.
My code here
public class LiveStreaming extends AppCompatActivity {
VideoView videoView;
private myAsync sync;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_live_streaming);
String videourl = getIntent().getStringExtra("Link");
videoView = (VideoView) findViewById(R.id.videoStreaming);
progressDialog = ProgressDialog.show(this, "",
"Loading TV...", true);
progressDialog.setCancelable(false);
// progressDialog.dismiss();
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
Uri video = Uri.parse(videourl);// insert video url
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.requestFocus();
sync = new myAsync();
sync.execute();
// PlayVideo();
}
private class myAsync extends AsyncTask<Void, Integer, Void> {
int duration = 0;
int current = 0;
private volatile boolean running = true;
@Override
protected void onCancelled() {
running = true;
}
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
videoView.start();
duration = videoView.getDuration();
}
});
do {
current = videoView.getCurrentPosition();
System.out.println("duration - " + duration + " current- "
+ current);
if (sync.isCancelled())
break;
}
while (current != duration || current == 0);
return null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (sync!=null){
this.finish();
}
}
}
I debugged my app.
When back pressed then method wasn't called. I don't know what is the problem
Thank you
Upvotes: 0
Views: 822
Reputation: 2727
Declare your async task in your activity.
private YourAsyncTask mTask;
Instantiate your async task where you want to use
mTask = new YourAsyncTask().execute();
And then cancel where you want to stop the task
mTask.cancel(true);
Hope this helps
Upvotes: 1
Reputation: 534
remove super.onBackPressed();
for onBackPressed()
to work.And to cancel the async you can call sync.cancel()
Upvotes: 1