Pause and resume media playback with external keyboard Spacebar

Whenever your app plays a media file, users should be able to pause and resume playback by pressing the Spacebar on a physical keyboard.

Respond to keypress events

Apps based on Jetpack Compose or views respond to keyboard key presses in similar ways: the app listens for keypress events, filters the events, and responds to keypresses such as a Spacebar keypress.

1. Listen for keyboard events

Compose

With Jetpack Compose, use either the onPreviewKeyEvent or the onKeyEvent modifier within the layout that manages the keystroke:

Column(modifier = Modifier.onPreviewKeyEvent { event ->
    if (event.type == KeyEventType.KeyUp) {
        ...
    }
    ...
})

or

Column(modifier = Modifier.onKeyEvent { event ->
    if (event.type == KeyEventType.KeyUp) {
        ...
    }
    ...
})

Views

In an activity in your app, override the onKeyUp() method:

Kotlin

override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
    ...
}

Java

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    ...
}

The method is invoked every time a pressed key is released, so it fires exactly once for every keystroke.

2. Filter Spacebar presses

Inside the Compose onPreviewKeyEvent and onKeyEvent modifier methods or views onKeyUp() method, filter for KeyEvent.KEYCODE_SPACE to send the correct event to your media component:

Compose

Column(modifier = Modifier.onPreviewKeyEvent { event ->
    if (event.type == KeyEventType.KeyUp && event.key == Key.Spacebar) {
        ...
    }
    ...
})

or

Column(modifier = Modifier.onKeyEvent { event ->
    if (event.type == KeyEventType.KeyUp && event.key == Key.Spacebar) {
        ...
    }
    ...
})

Views

Kotlin

if (keyCode == KeyEvent.KEYCODE_SPACE) {
    togglePlayback()
    return true
}
return false

Java

if (keyCode == KeyEvent.KEYCODE_SPACE) {
    togglePlayback();
    return true;
}
return false;

Key points

Compose

  • onPreviewKeyEvent: Modifier that enables a component to intercept hardware key events when it (or one of its children) is focused.
  • onKeyEvent: Similar to onPreviewKeyEvent, modifier that enables a component to intercept hardware key events when the component (or one of its children) is focused.

Views

  • onKeyUp(): Event handler called when a key is released and not handled by a view (such as TextView) within an activity.

Results

Your app can now respond to Spacebar key presses to pause and resume a video or other media.

Collections that contain this guide

This guide is part of these curated Quick Guide collections that cover broader Android development goals:

Enable your app to support an optimized user experience on tablets, foldables, and ChromeOS devices.

Have questions or feedback

Go to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts.