一、需求
在Android应该开发过程中,用到了USB通讯,需要应用监控USB设备的插入和拔出,从而刷新USB设备列表。
二、实现
在使用时,需要register和unregister。
通过UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);可以获取到USB设备信息。
public class USBBroadcastReceiver extends BroadcastReceiver { private OnUsbListener usbListener; @Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action) ||
UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
usbListener.onStateChanged();
}
} public void registerUsbReceiver(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
context.registerReceiver(this, filter);
} public void unregisterUsbReceiver(Context context) {
context.unregisterReceiver(this);
} public void setUsbListener(OnUsbListener usbListener) {
this.usbListener = usbListener;
} @FunctionalInterface
public interface OnUsbListener {
void onStateChanged();
}
}