1

I'm trying to pause my video automatically when I open another app and then go back to it.

In case what I need is that after I put the app in the background, when I get back to it, the video returns where I was.

public class PlayerActivity extends AppCompatActivity {

    private VideoView videoView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        videoView = findViewById(R.id.videoView);

        hideStatusBar();

        getSupportActionBar().hide();

        videoView.setMediaController(new MediaController(this));
        String episodio = getIntent().getStringExtra("episodio");

        Uri vidUri = Uri.parse("http:" + episodio);
        videoView.setVideoURI(vidUri);

        videoView.start();

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (videoView != null) {
            videoView.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (videoView.isPlaying()) {
            videoView.pause();
        }
    }

    public void hideStatusBar() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        View decorView = getWindow().getDecorView();
        int uiOpcoes = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOpcoes);
    }
}
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
OliverDamon
  • 147
  • 9
  • with the current implementation, what is the behaviour? – user1506104 Oct 16 '18 at 16:16
  • It simply plays normal, but when I put it in the background it does not come back to where I stopped. – OliverDamon Oct 16 '18 at 16:18
  • can you confirm that videoView.pause() is executed AND is working? – user1506104 Oct 16 '18 at 16:22
  • First of all it is the best to handle all video/audio functionality on a service. Secondly, when you return from background, onCreate is being called so you have to save all relevant data in a bundle/saveinstancestate or on a sharedpreference and then when return from background, fetch the relevant data to initialize the video. – lior_13 Oct 16 '18 at 16:26
  • Could you give me an example? – OliverDamon Oct 16 '18 at 16:26
  • https://stackoverflow.com/questions/21392676/how-can-i-save-media-player-state – lior_13 Oct 16 '18 at 16:29

1 Answers1

1

You can initialize an variable where you put the current position of the videoview.

Int CurrentPosition = 0;

@Override
protected void onResume() {
    super.onResume();
    if (videoView != null) {
        videoView.seekTo(CurrentPosition);
        videoView.start();
    }
}


@Override
protected void onPause() {
    super.onPause();
    if (videoView.isPlaying()) {
        videoView.pause();
        CurrentPosition = videoView.getCurrentPosition();
    }
}