[英]Detect when user connects his android device to a TV
How can I detect an micro HDMI cable connection in code? 如何检测代码中的微型HDMI电缆连接?
In example, when the user connects his android device to a TV. 例如,当用户将其android设备连接到电视时。
Use any of these two or both depending upon requirement : 根据需要使用这两个或两者之一:
/**
* 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;
}
}
and 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();
}
}
}
}
Declare this receiver in manifest. 在清单中声明此接收器。
<receiver android:name="__com.example.android__.HdmiListener" >
<intent-filter>
<action android:name="android.intent.action.HDMI_PLUGGED" />
</intent-filter>
</receiver>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.