2015-04-07 44 views

回答

2

使用任意兩個或兩個取決於需求:

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

清單中聲明該接收機。

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