Android Cancel Async task when back pressed - android

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

remove super.onBackPressed(); for onBackPressed() to work.And to cancel the async you can call sync.cancel()

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

Related

Android Mediaplayer multiple instances when activity resumes

I am developing an app that plays a stream by using the built-in Android Mediaplayer. Everything works fine apart the fact that when I press the "home" button and then open the activity again, the app just starts a new instance of the mediaplayer and I can hear the stream twice without the possibility to stop the first one.
Scenario.
My app is only made of one activity.
I open my app first time and the stream starts.
Push the home button and the activity is "minimized" but the music still plays
I open my app again and it just starts a new instance of the mediaplayer playing the same music twice.
I check onResume if the mediaplayer is null or playing but somehow it appears to be always null thus a new instance is created.
My pseudo code...
public class MainActivity {
private MediaPlayer _mp;
private PlayTask _playTask;
private PauseTask _pauseTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume(){
super.onResume();
if(_mp != null && _mp.isPlaying()){
// I should find a playing mediaplayer here but it's always null!!!
Toast.makeText(MainActivity.this, "Playing mediaplayer found!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "No mediaplayer found :(", Toast.LENGTH_SHORT).show();
}
}
/* ...:::============= *** ASYNCTASK Definition START *** =============:::... */
private class PlayTask extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
if(_mp == null)
_mp = new MediaPlayer();
else if(_mp.isPlaying()){
_mp.stop();
_mp.release();
_mp = null;
_mp = new MediaPlayer();
}
}
#Override
protected Integer doInBackground(Void...voids) {
try{
_mp.setDataSource(URL_DATASOURCE);
_mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
_mp.prepare();
_mp.start();
}
catch(Exception ex){
}
return 0;
}
#Override
protected void onPostExecute(Integer i) {
}
}
private class PauseTask extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
// Do Nothing here...for now
}
#Override
protected Integer doInBackground(Void...voids) {
_mp.stop();
_mp.release();
_mp = null;
return 0;
}
#Override
protected void onPostExecute(Integer i) {
}
}
public void playPause(View view){
if(_play){
_playTask = new PlayTask();
_playTask.execute();
}
else{
_pauseTask = new PauseTask();
_pauseTask.execute();
}
}
}
Any idea? Thanks

How to pause Android VideoView after 4 seconds of playing

I Want to pause my video play after 4 seconds of playing, then I want to pop up a message to the user. Can someone point me in the right direct how to pause the video after 4 seconds please. Thanks
V2 Implemented #gogothebee feedback {Now the video pause at position 0 (before it actually start).
public class PlayVideoActivity extends ActionBarActivity {
public static final String TAG = PlayVideoActivity.class.getSimpleName();
Bundle bunde;
Intent intent;
String content_actual_content;
VarController vc = new VarController(PlayVideoActivity.this);
public ImageLoader imageLoader;
private VideoView mVideoView;
private MediaController mMediaController;
ProgressBar pbplay1;
private boolean isActive;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video); //playvideo (FullScreen)
handler = new Handler();
//Hide Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Set ProgressBar
pbplay1 = (ProgressBar) findViewById(R.id.pbplay1);
//Get Link from ImageAdapter
intent = this.getIntent();
bunde = intent.getExtras();
content_actual_content = bunde.getString("content_actual_content");
Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse(content_actual_content));
mVideoView.setMediaController(new MediaController(PlayVideoActivity.this));
mVideoView.requestFocus();
mVideoView.setMediaController(mMediaController);
//new myAsync().execute();
}//--- end onCreate
#Override
protected void onPause() {
super.onPause();
isActive = false;
}
#Override
protected void onResume() {
super.onResume();
isActive = true;
mVideoView.requestFocus();
mVideoView.start();
scheduleVideoPause(4000);
}
private void scheduleVideoPause(int msec) {
handler.removeCallbacksAndMessages(null);
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(!isActive) {
return;
}
mVideoView.pause();
Toast.makeText(PlayVideoActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}, msec);
}
V1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video); //playvideo (FullScreen)
//Hide Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Set ProgressBar
pbplay1 = (ProgressBar) findViewById(R.id.pbplay1);
//Get Link from ImageAdapter
intent = this.getIntent();
bunde = intent.getExtras();
content_actual_content = bunde.getString("content_actual_content");
Toast.makeText(PlayVideoActivity.this, "You're on Video Player with link: " + content_actual_content, Toast.LENGTH_SHORT).show();
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse(content_actual_content));
mMediaController = new MediaController(PlayVideoActivity.this);
mVideoView.setMediaController(mMediaController);
mVideoView.requestFocus();
mVideoView.start();
//new myAsync().execute();
Log.i("**********************", "getCurrentPosition: " + mVideoView.getCurrentPosition());
if (mVideoView.getCurrentPosition() == 4000) {
mVideoView.pause();
Toast.makeText(PlayVideoActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}//--- end onCreate
It seems that there's no way to do it easily. However, my solution is to spawn a background timer that runs every 100ms (adjustable) and check the current position. Once it is past the desired threshold (4000ms in this case), the video is stopped. I know it's not elegant and won't work exactly at 4000ms, but if anyone has a better idea, please share it. When adjusting the pooling interval in case you want to get as close as possible to 4000ms, don't go too low for performance reasons.
This solution can also be refactored as it's quite messy, but I wanted to show the concept in as little code as possible.
private Timer timer;
private boolean isActive;
private VideoView mVideoView;
private final static int POOLING_INTERVAL_MS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initiate Player
mVideoView = (VideoView) findViewById(R.id.videoview);
mVideoView.setVideoURI(Uri.parse("Your-Video-URI"));
mVideoView.setMediaController(new MediaController(this));
}
#Override
protected void onPause() {
super.onPause();
isActive = false;
cancelProgressPooling();
}
#Override
protected void onResume() {
super.onResume();
isActive = true;
mVideoView.requestFocus();
mVideoView.start();
initVideoProgressPooling(4000);
}
private void initVideoProgressPooling(final int stopAtMsec) {
cancelProgressPooling();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mVideoView.post(new Runnable() {
#Override
public void run() {
if (!isActive) {
cancelProgressPooling();
return;
}
if(mVideoView.getCurrentPosition() >= stopAtMsec) {
mVideoView.pause();
cancelProgressPooling();
Toast.makeText(MainActivity.this, "Video has PAUSED at: " + mVideoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();
}
}
});
}
}, 0, POOLING_INTERVAL_MS);
}
private void cancelProgressPooling() {
if(timer != null) {
timer.cancel();
}
timer = null;
}

How to change the value of the String variable of Videoview URL after click Button?

i want play many videos in same videoview
when click on button , The online video play in videoview in other layout
example :
there are three button in "layout 1"
after click on any button go to "layout 2"
there is one VideoView in "Layout 2 "
everyone action Click on Button is Change String Value "VideoURl" in VideoView
The question is : How can I change the value of the String variable in the Layout 2 When you click on any button in the Layout 1?!!]1
http://i.stack.imgur.com/ytQiE.jpg
public class MainActivity extends Activity{
Button button1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(context, Main2Activity.class);
i.putExtra("VidURL1", "http://img580.imageshack.us/img580/416/4dojlrwiknaexgxaiyqfbz.mp4");
startActivity(i);
}
});
}
}
The Code activity 2 :
public class Main2Activity extends Activity {
private ProgressDialog pDialog;
VideoView videoview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoview = (VideoView) findViewById(R.id.VideoView);
new StreamVideo().execute();
}
private class StreamVideo extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Main2Activity.this);
pDialog.setTitle("Android Video Streaming Tutorial");
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(Void args) {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(
Main2Activity.this);
mediacontroller.setAnchorView(videoview);
// Get the URL from String VideoURL
Uri video = Uri.parse(VideoURL);
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoview.start();
}
});
} catch (Exception e) {
pDialog.dismiss();
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
you can pass data between two activity using intent
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent)
and to get data from the activity1
String Url = getIntent().getExtras().getString("yourKey");

Remove Backward & Forward Button From Media Controller

I Use MediaController to play my audio. But, I want to remove Backward & Forward Button from my MediaController. Please, help me. (PS. A Code is be useful) How can I edit it.
public class Main extends Activity implements MediaPlayerControl {
private static final String PLAY_AUDIO = "PLAY_AUDIO";
private MediaController mMediaController
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
public void onClick(View v) {
//next button clicked
}
}, new View.OnClickListener() {
public void onClick(View v) {
//previous button clicked
}
});
try {
mMediaPlayer.setDataSource(
this,
Uri.parse("android.resource://com.app.audioplayer/raw/allforyou")
);
mMediaPlayer.prepare();
} catch (IOException e) {
Log.e(PLAY_AUDIO, "Could not open file " + " " + " for playback.", e);
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
mMediaPlayer.start();
}
});
}
});
}
}
Simplest solution ...
MediaController mediaController = new MediaController(this, false);
Courtesy : #Meow meo (in comments of original question)

flicker is coming before and after playing a video clip

I am playing a video when I click on a button. But at that time a flicker (black flash) is coming before and after that video clip. Any suggestions. Thanks in advance
Below is my code
babyFace=(ImageView)findViewById(R.id.babyFace);
lEye =(ImageView)findViewById(R.id.lEye);
lEye.setOnClickListener(DisplayListener);
private OnClickListener DisplayListener=new OnClickListener (){
#Override
public void onClick(View image) {
videoView.setVideoURI(Uri.parse("android.resource://com.babypalyface/raw/mdpi_l_dimple");
playVideo();
}
private void playVideo()
{
videoView.setVisibility(View.VISIBLE);
videoView.requestFocus();
videoView.start();
videoView.setOnCompletionListener(VideoViewListener);
}
OnCompletionListener VideoViewListener=new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
videoView.destroyDrawingCache();
videoView.clearFocus();
videoView.setVisibility(View.GONE);
}
};
Modify below code to play your video. Suggest you .. before showing the content to user give some time to download few bytes of content. Hope this helps
public class PlayVideo extends Activity{
ProgressDialog dialog;
int increment;
VideoView video;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
video = (VideoView)findViewById(R.id.VideoView01);
MediaController mc = new MediaController(this);
video.setMediaController(mc);
video.setVideoPath("rtsp://v5.cache8.c.youtube.com/CjYLENy73wIaLQnAHrGa4Moc0RMYESARFEIJbXYtZ29vZ2xlSARSBWluZGV4YO7F8s7Fh92ZTAw=/0/0/0/video.3gp");
increment = 1;
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// reset the bar to the default value of 0
dialog.setProgress(0);
int maximum = 100;
// set the maximum value
dialog.setMax(maximum);
// display the progressbar
dialog.show();
// create a thread for updating the progress bar
Thread background = new Thread(new Runnable() {
public void run() {
try {
Looper.prepare();
Thread.sleep(20000);
progressHandler
.sendMessage(progressHandler.obtainMessage());
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
}
Looper.loop();
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
dialog.dismiss();
video.start();
}
};
}

Categories

Resources