How to check the HDMI device connection status in Android?

前端 未结 5 600
不知归路
不知归路 2020-12-03 05:55

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 BroadcastRe

5条回答
  •  天涯浪人
    2020-12-03 06:17

    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.

提交回复
热议问题