How do I resume MediaPlayer in Android?

I am making one media player for video streaming. This works well, but when I press the home button and the activity goes in the background again, I open the media player so it starts over from the beginning rather than resuming. than how to resume video in media player. here is my code

public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
    OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "log_tag";
private boolean b =false;
private int seekint,seeksec;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.customvideoview);
    extras = getIntent().getExtras();

    linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
    linearLayoutMediaController.setVisibility(View.GONE);

    hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
    hideMediaController.setAnimationListener(this);

    imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
    imageViewPauseIndicator.setVisibility(View.GONE);
    if (player != null) {
        if (!player.isPlaying()) {
            imageViewPauseIndicator.setVisibility(View.VISIBLE);
        }
    }

    textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
    textViewLength = (TextView) findViewById(R.id.textViewLength);

    surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
    surfaceViewFrame.setOnClickListener(this);
    surfaceViewFrame.setClickable(false);

    seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
    seekBarProgress.setOnSeekBarChangeListener(this);
    seekBarProgress.setProgress(0);

    progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);

    holder = surfaceViewFrame.getHolder();
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    player = new MediaPlayer();
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnBufferingUpdateListener(this);
    player.setOnSeekCompleteListener(this);
    player.setScreenOnWhilePlaying(true);
    player.setDisplay(holder);
}
@Override
protected void onDestroy() {
super.onDestroy();
        player.stop();
        player.release();
        player = null;
        Toast.makeText(VideoSample.this, "back",Toast.LENGTH_SHORT).show();
        finish();
}
private void playVideo() {
    if (extras.getString("video_path").equals("VIDEO_URI")) {
        showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
    } else {
        new Thread(new Runnable() {
            public void run() {
                try {
                    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    player.setDataSource(VideoSample.this, Uri.parse(extras.getString("video_path")));
                    //player.setVolume(0, 0);
                    player.setVolume(AudioManager.ADJUST_LOWER, AudioManager.ADJUST_RAISE);
                    //player.setAudioStreamType(AudioEncoder.DEFAULT);
                    player.prepareAsync();
                } catch (IllegalArgumentException e) {
                    showToast("Error while playing video");
                    e.printStackTrace();
                    Log.i(TAG,"tag"+ e.getMessage());
                } catch (IllegalStateException e) {
                    showToast("Error while playing video");
                    e.printStackTrace();
                    Log.i(TAG, "tag"+e.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                    showToast("Error while playing video. Please, check your network connection.");
                    Log.i(TAG, "tag"+e.getLocalizedMessage());
                }
            }
        }).start();
    }
}

private void showToast(final String string) {
    runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
            finish();
        }
    });
}

private void hideMediaController() {
    new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(5000);
                runOnUiThread(new Runnable() {
                    public void run() {
                        linearLayoutMediaController.startAnimation(hideMediaController);
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();
}


public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
    if (!fromUser) {
        textViewPlayed.setText(Utils.durationInSecondsToString(progress));
    }
}

public void onStartTrackingTouch(SeekBar seekBar) {
}

public void onStopTrackingTouch(SeekBar seekBar) {
    if (player.isPlaying()) {
        progressBarWait.setVisibility(View.VISIBLE);
        player.seekTo(seekBar.getProgress() * 1000);
        Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
    }
}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

public void surfaceCreated(SurfaceHolder holder) {
    playVideo();
}

public void surfaceDestroyed(SurfaceHolder holder) {

}

public void onPrepared(MediaPlayer mp) {
    if (!player.isPlaying()) {
        b = true;
        player.start();

        updateMediaProgress();
        linearLayoutMediaController.setVisibility(View.VISIBLE);
        hideMediaController();
    }
    Log.i(TAG, "========== onPrepared ===========");
    int duration = mp.getDuration() / 1000; // duration in seconds
    seekBarProgress.setMax(duration);
    textViewLength.setText(Utils.durationInSecondsToString(duration));
    progressBarWait.setVisibility(View.GONE);

    // Get the dimensions of the video
    int videoWidth = player.getVideoWidth();
    int videoHeight = player.getVideoHeight();
    float videoProportion = (float) videoWidth / (float) videoHeight;
    Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);

    // Get the width of the screen
    int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
    int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
    float screenProportion = (float) screenWidth / (float) screenHeight;
    Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);


    android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();

    if (videoProportion > screenProportion) {
        lp.width = screenWidth;
        lp.height = (int) ((float) screenWidth / videoProportion);
    } else {
        lp.width = (int) (videoProportion * (float) screenHeight);
        lp.height = screenHeight;
    }


    surfaceViewFrame.setLayoutParams(lp);


    surfaceViewFrame.setClickable(true);
}

public void onCompletion(MediaPlayer mp) {
    mp.stop();
    if (updateTimer != null) {
        updateTimer.cancel();
    }
    finish();
}


private void updateMediaProgress() {
    updateTimer = new Timer("progress Updater");
    updateTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    if(player != null){
                    int position = player.getCurrentPosition();
                    seekBarProgress.setProgress(position / 1000);
                    }
                }
            });
        }
    }, 0, 1000);
}

public void onBufferingUpdate(MediaPlayer mp, int percent) {
    Log.v("log_tag","buffer"+mp.getDuration()*percent/100);
    if(b){
    int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
    seekBarProgress.setSecondaryProgress(progress / 1000);
    }
}

public void onClick(View v) {
    if (v.getId() == R.id.surfaceViewFrame) {
        if (linearLayoutMediaController.getVisibility() == View.GONE) {
            linearLayoutMediaController.setVisibility(View.VISIBLE);
            hideMediaController();
        } else if (player != null) {
            if (player.isPlaying()) {
                b = false;
                player.pause();
                imageViewPauseIndicator.setVisibility(View.VISIBLE);
            } else {
                b = true;
                player.start();
                imageViewPauseIndicator.setVisibility(View.GONE);
            }
        }
    }
}

public void onSeekComplete(MediaPlayer mp) {
    progressBarWait.setVisibility(View.GONE);
}

public void onAnimationEnd(Animation animation) {

}

public void onAnimationRepeat(Animation animation) {

}

public void onAnimationStart(Animation animation) {
    linearLayoutMediaController.setVisibility(View.GONE);
}

      

}

+4


source to share


1 answer


To pause the media player, I used:

Mediaplayer.pause();
media_length=Mediaplayer.getCurrentPosition();

      

And to resume the player from the position he left off:



Mediaplayer.seekTo(length);
Mediaplayer.start();

      

Mediaplayer.start();

Missing in your code after setting the position of the search bar.

+6


source







All Articles