将应用程序置于后台时如何自动暂停视频

时间:2018-10-16 16:10:25

标签: java android

当我打开另一个应用程序并尝试返回它时,我试图自动暂停我的视频。

如果我需要的是在将应用程序置于后台后,当我回到该应用程序时,视频将返回到原位置。

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

1 个答案:

答案 0 :(得分:0)

您可以初始化一个变量,在其中放置视频视图的当前位置。

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