Search code examples
androidandroid-debug

how to achive Video View's pause and resume functionality in android?


I want to create a video view with pause and resume functionality. So to save current time I have used shared preferences as a temporary storage.But at a time of debugging it work perfect in onPause(),onStop(),onResume(),onStart().But when installed in the device then the video starts with a beginning every time.How to solve this issue?

@Override
protected void onResume() {
    super.onResume();
    resumeVideo();
}
@Override
protected void onPause() {
    super.onPause();
    saveCurrentTime();
}
@Override
protected void onStop() {
    super.onStop();
    saveCurrentTime();
}
@Override
protected void onRestart() {
    super.onRestart();
    resumeVideo();
}


//......to save current duration in shared preference
public void saveCurrentTime(){
    String current_time = String.valueOf(vdoView.getCurrentPosition());
    sharedPreference.putValue(this,Constants.SP_NAME,Constants.CURRENT_TIME,current_time);
}

//to resume video from given time
public void resumeVideo(){
    String time = sharedPreference.getValue(this, Constants.SP_NAME, Constants.CURRENT_TIME);
   if(!sharedPreference.getValue(this,Constants.SP_NAME,Constants.CURRENT_TIME).equals("")) {
        int t = Integer.parseInt(time);
        vdoView.seekTo(t);
    }

    vdoView.start();
}

Solution

  • It is apparent that your extra handlers are overwriting the preference with 0 at unexpected times, because the vdoView has changed state.

    Remove your onStop() and onRestart() (and onDestroy()) handlers. All you need is onPause() and onResume(). See the documentation for details.