Android back button and MediaController

Based on the source code, this should work:

  1. Extend MediaController (for the purposes of this answer, call it RonnieMediaController)
  2. Override dispatchKeyEvent() in RonnieMediaController
  3. Before chaining to the superclass, check for KeyEvent.KEYCODE_BACK, and if that is encountered, tell your activity to finish()
  4. Use RonnieMediaController instead of MediaController with your VideoView

Personally, I'd just leave it alone, as with this change your user cannot make a RonnieMediaController disappear on demand.


You can simply write:

mVideoView.setMediaController(new MediaController(this){
        public boolean dispatchKeyEvent(KeyEvent event)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
                ((Activity) getContext()).finish();

            return super.dispatchKeyEvent(event);
        }
    });

No need to create new class.


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