Android - VideoView需要按两次BACK才能退出解决方法

发布于:2024-04-14 ⋅ 阅读:(131) ⋅ 点赞:(0)

 从Android back button and MediaController - Stack Overflow得到启发,开始是个秀才认字认半边,没有把文章和回复看全,然后高版本的Android还是没有解决。后来看到以下回复:

The previous solutions no longer work with Android Pie +, you must instead :

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        mediaController.addOnUnhandledKeyEventListener((v, event) -> {
            //Handle BACK button
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
            {
                mediaController.hide(); //Hide mediaController,according to your needs, you can also called here onBackPressed() or finish() 
            }
            return true;
        });
    }

豁然开朗,终于找到了最终原因,把此代码加入mediaController后成功修复。

原理:VideoView设置的MediaController会阻挡返回键,低版本的Android在dispatchKeyEvent中处理,高版本的Android直接未处理丢弃了,需要在addOnUnhandledKeyEventListener处理,所以把所有代码添加后,解决后的代码如下:


        MediaController mediaController = new MediaController(this){
            public boolean dispatchKeyEvent(KeyEvent event)
            {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                    if (mVideoView.isPlaying()) {
                        mVideoView.stopPlayback();
                    }
                    DyTaskCaseActivity.this.finish();// ((Activity) getContext()).finish();
                }
                return super.dispatchKeyEvent(event);
            }
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            mediaController.addOnUnhandledKeyEventListener((v, event) -> {
                //Handle BACK button
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                {
                    mediaController.hide(); //Hide mediaController,according to your needs, you can also called here onBackPressed() or finish()
//                    onBackPressed();
                    if (mVideoView.isPlaying()) {
                        mVideoView.stopPlayback();
                    }
                    DyTaskCaseActivity.this.finish();
                }
                return true;
            });
        }
        mVideoView.setMediaController(mediaController);


网站公告

今日签到

点亮在社区的每一天
去签到