2013-10-04 220 views
2

我正在使用Galaxy SII(Android版本4.1.2),并且我正在尝试构建一个可以告诉我是否连接了USB设备的应用程序。查找USB设备android

我也有一个OTG适配器(工作很好..)当我连接键盘/鼠标时,我的偶尔识别它们,我可以顺利使用它们。

在我的代码中,我尝试遍历连接的设备,但它就像没有连接。这是我的代码:

UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); 
    // Get the list of attached devices 
    HashMap<String, UsbDevice> devices = manager.getDeviceList(); 

    Toast.makeText(this, "Number of devices: " + devices.size(), Toast.LENGTH_LONG).show();  

    // Iterate over all devices 
    Iterator<String> it = devices.keySet().iterator(); 
    while (it.hasNext()) 
    { 
     String deviceName = it.next(); 
     UsbDevice device = devices.get(deviceName); 

     String VID = Integer.toHexString(device.getVendorId()).toUpperCase(); 
     String PID = Integer.toHexString(device.getProductId()).toUpperCase(); 
     Toast.makeText(this, deviceName + " " + VID + ":" + PID + " " + manager.hasPermission(device), Toast.LENGTH_LONG).show();   
    } 

这是清单:

<?xml version="1.0" encoding="utf-8"?> 
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.ipad" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-feature android:name="android.hardware.usb.host"/> 
    <uses-sdk android:minSdkVersion="12" /> 

    <application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme">   
    <activity 
     android:name="com.example.ipad.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" />    
     </intent-filter>    
     </activity> 
    </application> 
    </manifest> 

THX对您有所帮助:)

回答