我最近正在编写 USB 主机应用程序,但由于无法检测到设备附加/分离事件而被卡住,我遵循了 http://developer.android.com/guide/topics/connectivity/usb/host的编码说明.html并参考网络中其他人的编码,查了好几遍,还是没找到问题。经过我的调试,似乎 UsbManager.ACTION_USB_DEVICE_ATTACHED/UsbManager.ACTION_USB_DEVICE_DETACHED 意图没有发生,因为我尝试使用 Context.sendBroadcast() 发送自定义的 Intent,而我的 BroadcastReceiver 可以接收到该意图。但是当我连接/分离 USB 设备时,BroadcastReceiver 不会运行。我使用的手机是HTC One-X,我确信OTG功能是正确的,因为鼠标功能很好。这是我的代码片段。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.launcher);
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
if(mUsbManager == null) {
Log.d(TAG, "mUsbManager is null");
}
// listen for new devices
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
// filter.addAction("MyTest");
registerReceiver(mUsbReceiver, filter);
}
广播接收器
BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "mUsbReceiver.onReceive start");
String action = intent.getAction();
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
setDevice(device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mDevice != null && mDevice.equals(device)) {
setDevice(null);
}
}
}
};
清单.xml
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
<uses-sdk android:minSdkVersion="12" />
<application>
<activity android:name=".USBActivity"
android:label="USBActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- <receiver android:name=".mUsbReceiver"> -->
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"
android:resource="@xml/device_filter" />
<!-- </receiver> -->
</activity>
</application>
在 res/xml 中的 device_filter,所有 3 个设置都已尝试但未使用:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- iCooby mouse -->
<!-- <usb-device vendor-id="15d9" , /> -->
<!-- <usb-device vendor-id="5593" product-id="2637"/> -->
<usb-device />
</resources>
如果有人知道发生了什么?或者告诉我如何检测广播意图是否处于活动状态,非常感谢。