gpt4 book ai didi

android - 如何在 Android 中检测 USB 设备

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:42 25 4
gpt4 key购买 nike

我有 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 ");
}
}
}
}
};

list 如下:

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

设备过滤器.xml

 <resources>
<usb-device vendor-id="67b"
product-id="2303"/>
</resources>

在上面的 xml 文件中,我添加了设备属性。每当 USB 设备连接到主机设备时,我都期待广播 Intent 。但它没有发生。上面的代码有什么问题。

谢谢刀锋

最佳答案

我认为你需要添加:

<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>

It is described here

关于android - 如何在 Android 中检测 USB 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com