Android back button and MediaController
Based on the source code, this should work:
- Extend
MediaController
(for the purposes of this answer, call itRonnieMediaController
) - Override
dispatchKeyEvent()
inRonnieMediaController
- Before chaining to the superclass, check for
KeyEvent.KEYCODE_BACK
, and if that is encountered, tell your activity tofinish()
- Use
RonnieMediaController
instead ofMediaController
with yourVideoView
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; }); }