检测用户将其Android设备连接到电视的时间

时间:2015-04-07 08:34:47

标签: java android android-5.0-lollipop android-4.4-kitkat

如何在代码中检测micro HDMI线缆连接? 例如,当用户将他的Android设备连接到电视时。

1 个答案:

答案 0 :(得分:3)

根据要求使用这两者中的任何一个或两者:

/**
 * 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;
    }
}

和Broadcastreceiver

public class HdmiListener extends BroadcastReceiver {

private static String HDMIINTENT = "android.intent.action.HDMI_PLUGGED";

@Override
public void onReceive(Context ctxt, Intent receivedIt) {
    String action = receivedIt.getAction();

    if (action.equals(HDMIINTENT)) {
        boolean state = receivedIt.getBooleanExtra("state", false);

        if (state == true) {
            Log.d("HDMIListner", "BroadcastReceiver.onReceive() : Connected HDMI-TV");
            Toast.makeText(ctxt, "HDMI >>", Toast.LENGTH_LONG).show();    
        } else {
            Log.d("HDMIListner", "HDMI >>: Disconnected HDMI-TV");
            Toast.makeText(ctxt, "HDMI DisConnected>>", Toast.LENGTH_LONG).show();
        }
    }
}
}

在清单中声明此接收器。

<receiver android:name="__com.example.android__.HdmiListener" >
    <intent-filter>
        <action android:name="android.intent.action.HDMI_PLUGGED" />
    </intent-filter>
</receiver>