Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the HDMI device connection status in Android?

I need to detect whether an HDMI device is connected or not to my Android device. For this I'm using a BroadcastReceiver and it is able to detect also. But with BroadcastReceiver I'm unable to handle the scenario when the HDMI device is connected even before my application was launced. In this case the BroadcastReceiver is unable to find if any HDMI device is connected or not. Is there any way I can get to know if any HDMI device is connected or not at any point?

like image 611
rohitb Avatar asked Dec 27 '11 12:12

rohitb


People also ask

How do I fix my HDMI connection?

If you want to connect your Android phone or tablet to the TV, make sure the HDMI connection setting is enabled on your device. To do it, go to Settings > Display Entries > HDMI connection. If the HDMI connection setting is disabled, enable it.


1 Answers

I came up with this using the other answers and some from elsewhere:

/**
 * Checks device switch files to see if an HDMI device/MHL device is plugged in, returning true if so.
 */
private boolean isHdmiSwitchSet() {

    // The file '/sys/devices/virtual/switch/hdmi/state' holds an int -- if it's 1 then an HDMI device is connected.
    // An alternative file to check is '/sys/class/switch/hdmi/state' which exists instead on certain devices.
    File switchFile = new File("/sys/devices/virtual/switch/hdmi/state");
    if (!switchFile.exists()) {
        switchFile = new File("/sys/class/switch/hdmi/state");
    }
    try {
        Scanner switchFileScanner = new Scanner(switchFile);
        int switchValue = switchFileScanner.nextInt();
        switchFileScanner.close();
        return switchValue > 0;
    } catch (Exception e) {
        return false;
    }
}

If you're checking often, you'd want to store the result and update it with @hamen's listener.

like image 107
Tom Avatar answered Sep 19 '22 17:09

Tom