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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With