What You'll Learn

  1. Download Android Studio
  2. Install Flutter SDK

If on Mac:

  1. Install xCode

Platforms supported:

Install another_tv_remote

flutter pub add another_tv_remote

In order to forward the remote control inputs to your Flutter app the following changes must be added to the main activity of your app.

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        TvRemoteEventProcessor.notifyEvent(event = event)
        return super.onKeyDown(keyCode, event)
    }
    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        TvRemoteEventProcessor.notifyEvent(event = event)
        return super.onKeyUp(keyCode, event)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {

        when(event.keyCode) {
            KeyEvent.KEYCODE_BUTTON_B,
            KeyEvent.KEYCODE_BACK,

            KeyEvent.KEYCODE_BUTTON_SELECT,
            KeyEvent.KEYCODE_BUTTON_A,
            KeyEvent.KEYCODE_ENTER,
            KeyEvent.KEYCODE_DPAD_CENTER,
            KeyEvent.KEYCODE_NUMPAD_ENTER -> {
                // Skip the center pad because you get it on the on onKeyDown
                return super.dispatchKeyEvent(event)
            }
        }
        if(event.action == KeyEvent.ACTION_DOWN) {
            TvRemoteEventProcessor.notifyEvent(event = event)
        }
        return super.dispatchKeyEvent(event)
    }

In order for the Flutter app to show up on your TV the following changes must also be made to the AndroidManifest.xml file:

Add the category to the intent filter of the main activity

<category android:name="android.intent.category.LEANBACK_LAUNCHER" />

And add the leanback feature to the manifest. Since we might run our Flutter app on both mobile and TVs we'll mark it as optional.

<uses-feature android:name="android.software.leanback"
        android:required="false" />

The key presses will arrived on the Flutter app via a stream. In this example we will listen for the dPad up/down press events and the OK button from the remote.

    AnotherTvRemote.getTvRemoteEvents().listen((event) {
      print ("Received event: $event");
      if (event.action == KeyAction.down) {
        if (event.type == KeyType.dPadDown) {
          // TODO Perform action.
        }
        else if (event.type == KeyType.dPadUp) {
          // TODO Perform action.
        }
        else if (event.type == KeyType.ok) {
          // TODO Perform action.
        }
      }
    });