使用效果:
授权实现过程:
1.在AndroidManifest.xml中增加android.hardware.usb.action.USB_DEVICE_ATTACHED的action及meta-data
action:
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
meta-data:
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter"/>
2.增加USB设备过滤
3.获取USB管理服务:
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
4.获取USB设备列表:
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
5.遍历USB设备列表:
for (UsbDevice dev: deviceList.values()){String usbInfo = "DeviceID: "+dev.getDeviceId()+"\n"+"VendorId: "+dev.getVendorId()+"\n"+"ProductId: "+dev.getProductId()+"\n"+"Manufacturer: "+dev.getManufacturerName()+"\n"+"Product: "+dev.getProductName()+"\n"+"Version: "+dev.getVersion()+"\n";tv.setText(usbInfo);System.out.println("==========================");System.out.println(usbInfo);System.out.println("==========================");
}
6.注册USB授权广播:
//设备授权配置//Android14 API34 及或更高使用 FLAG_IMMUTABLE//Android14 API33 及或更低使用 FLAG_MUTABLEPendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0,new Intent(ACTION_USB_PERMISSION),Build.VERSION.SDK_INT>=34? PendingIntent.FLAG_IMMUTABLE:PendingIntent.FLAG_MUTABLE);IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);if (Build.VERSION.SDK_INT>=33){registerReceiver(mUsbReceiver, filter,Context.RECEIVER_EXPORTED);}else{registerReceiver(mUsbReceiver, filter);}
7.实现广播接收器
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";private final String TAG = "usb_auth_demo";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 device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){if(device != null){Log.i(TAG,"设备授权成功");Toast.makeText(context,"设备授权成功",Toast.LENGTH_LONG).show();}}else{Log.d(TAG, "设备拒绝授权: " + device);}}}}};
2.请求USB设备权限:
mUsbManager.requestPermission(dev, mPermissionIntent);
完整示例源码:
https://github.com/tonyimax/usb_auth_demo.git