我正在摆弄USB主机,按照on the Android Developers站点的指导原则,我创建了一个Hello World,一旦插入特定的USB设备,它就会启动。但是,当我尝试“从意图中删除表示连接的设备的UsbDevice”时,它返回null:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
// device is always null
if (device == null){Log.i(TAG,"Null device");}这是我的清单:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />
</activity>
</application>和我的xml/device_filter.xml (我知道它们是正确的VID和PID,因为我有一个使用on the Android Developers站点描述的枚举方法的类似应用程序):
<resources>
<usb-device vendor-id="1234" product-id="1234"/>
</resources>发布于 2013-10-15 17:37:38
当您的应用程序由于USB设备连接事件而被(重新)启动时,当onResume被调用时,设备将被传递给intent。您可以使用getParcelableExtra方法访问它。例如:
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
Log.d("onResume", "intent: " + intent.toString());
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (usbDevice != null) {
Log.d("onResume", "USB device attached: name: " + usbDevice.getDeviceName());发布于 2013-07-24 17:09:20
我找到了一个变通方法(或者是预期的用法?)感谢Taylor Alexander。基本上,我理解的方式是,触发打开应用程序的意图只会打开应用程序。在此之后,您必须按照onResume方法中的Android开发人员页面的Enumerating Devices部分来搜索和访问usb设备。
@Override
public void onResume() {
super.onResume();
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
// Your code here!
}我不相信这是正确的方法,但它似乎是有效的。如果任何人有任何进一步的建议,我很乐意倾听。
https://stackoverflow.com/questions/17828869
复制相似问题