OliverDamon
OliverDamon

Reputation: 147

How to pause video automatically when placing the app in background

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);
    }
}

Upvotes: 1

Views: 462

Answers (1)

Gioele.sandrin
Gioele.sandrin

Reputation: 64

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();
    }
}

Upvotes: 1

Related Questions