天天看點

android usb attached,android – 無法接收UsbManager.ACTION_USB_DEVICE_ATTACHED / UsbManager.ACTION_USB_DEV...

我最近正在編寫一個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

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

}

}

}

};

的Manifest.xml

android:label="USBActivity"

android:screenOrientation="portrait">

android:resource="@xml/device_filter" />

android:resource="@xml/device_filter" />

res / xml中的device_filter,嘗試了所有3個設定并且不使用:

如果有人知道發生了什麼?或者告訴我如何檢測廣播意圖是否有效,非常感謝.