java - 检测用户何时将其 Android 设备连接到电视

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

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

最佳答案

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

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

和广播接收器

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();
        }
    }
}
}

在 list 中声明此接收者。

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

关于java - 检测用户何时将其 Android 设备连接到电视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29487226/

相关文章:

java - Android使用camera2复制内置视频录制质量和帧率

导航栏上方的android Q内容

android - 带安卓 Lollipop 的索尼 Xperia Z 未注册 ACTION_USB_DEVICE_ATTACHED

java - Android READ_EXTERNAL_STORAGE 权限不起作用

android - Lollipop : making my activity stay in the task that launched the share intent

java - 从父类(super class)数组访问子类字段?

java - 为什么atomic提供compare_exchange_strong?

java - 如何获取包含在指定字符串中的特定字符串?

Android,OptionMenu ResourceNotFoundException;当切换到陆地空间

java - Android:绝对清除 Activity