我有USB主机Android设备,我需要连接USB设备。检测usb设备到主机我写了下面的代码。
public class ReadData extends Activity {
UsbManager usbManager;
PendingIntent mPermissionIntent;
UsbDevice usbDevice;
Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_data);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
final String ACTION_USB_PERMISSION =
"com.example.udevice.USB_PERMISSION";
IntentFilter filter = new IntentFilter("android.hardware.usb.action.USB_ACCESSORY_ATTACHED");
registerReceiver(mUsbReceiver, filter);
}
private static final String ACTION_USB_PERMISSION =
"com.example.udevice.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
usbManager.requestPermission(usbDevice, mPermissionIntent);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(usbDevice != null){
//call method to set up device communication
int deviceId = usbDevice.getDeviceId();
int productId = usbDevice.getProductId();
Log.i("device id", "****"+deviceId);
Log.i("product id", "****"+productId);
}else{
Log.i("device id", "No USB device");
}
}
else {
Log.d("shiv", "permission denied for device ");
}
}
}
}
};
和清单如下:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.udevice"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.usb.host" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ReadData"
android:label="@string/title_activity_heat_con" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<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>
</manifest>
device_filter.xml
<resources>
<usb-device vendor-id="67b"
product-id="2303"/>
</resources>
在上面的xml文件中我添加了设备属性。每当USB设备连接到主机设备时,我都期待广播意图。但它没有发生。上面的代码有什么问题。
由于 希夫
答案 0 :(得分:5)
我认为您需要添加:
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
答案 1 :(得分:4)
你做错了。
供应商ID和设备ID应为十进制,而不是十六进制。例如,您需要定义如下
<resources>
<usb-device vendor-id="1659"
product-id="8963"/>
</resources>
我将您的设备ID和vendor-id从十六进制转换为十进制 如果有帮助,请告诉我