通过注册广播的方式监听USB设备 。
广播Action
定义广播
private final BroadcastReceiver mUsbMonitorReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
int vendorId = device.getVendorId();
int productId = device.getProductId();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
int vendorId = device.getVendorId();
int productId = device.getProductId();
}
}
};
根据Usb设备VenorId和ProductId检索被监听的Usb设备节点。
注册广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
try {
context.registerReceiver(mUsbMonitorReceiver, intentFilter);
} catch (Exception e) {
e.printStackTrace();
}
注销广播
try {
context.unregisterReceiver(mUsbMonitorReceiver);
} catch (Exception e) {
e.printStackTrace();
}
有些系统或者设备监听不到Usb设备的插入或者挂载的事件,可通过轮询的方式根据Usb设备的节点信息(一般是VendorId和ProductId)进行检测。
根据 VendorId 和 ProductId查找Usb设备
public static UsbDevice findUsbDevice(Context context, int vendorId, int productId) {
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
final HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList != null) {
final Iterator<UsbDevice> iterator = deviceList.values().iterator();
while (iterator.hasNext()) {
UsbDevice device = iterator.next();
if (device.getVendorId() == vendorId && device.getProductId() == productId) {
return device;
}
}
}
return null;
}
开始轮询
private void startUsbMonitor() {
mHandlerThread = new HandlerThread("UsbMonitor");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_CHECK_USB_DEVICE: {
boolean found = findUsbDevice(context, vendorId, productId) != null;
if (!found){
mHandler.sendEmptyMessageDelayed(EVENT_CHECK_USB_DEVICE, 5000);
} else {
// TODO:
}
break;
}
default:
break;
}
}
};
mHandler.sendEmptyMessage(EVENT_CHECK_USB_DEVICE);
}
结束轮询
private void stopUsbMonitor() {
if (mHandler != null) {
mHandler.getLooper().quit();
mHandler = null;
}
if (mHandlerThread != null) {
mHandlerThread.quitSafely();
mHandlerThread = null;
}
}
备注:本文原创,如有侵权,请联系删除!!!
|