Android监听UVC插拔
背景
- Platform: RK3399
- OS: Android7.1.2
- Kernel: v4.4.103
之前调试UVC,需监听UVC的插拔状态
处理
以下方式已在Android7.1.2上验证
/*获取USB设备*/
private UsbDevice getUsbCameraDevice(Context context) {
UsbManager usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
for(UsbDevice usbDevice : usbManager.getDeviceList().values()) {
Log.i("camera","\n"+usbDevice.toString());
if (isUsbCamera(usbDevice)) {
return usbDevice;
}
}
return null;
}
/*判断是否为UVC*/
private boolean isUsbCamera(UsbDevice usbDevice) {
return usbDevice != null && 239 == usbDevice.getDeviceClass() && 2 == usbDevice.getDeviceSubclass();
}
/*广播接收类*/
private class USBReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 这里可以拿到插入的USB设备对象
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
switch (intent.getAction()) {
case UsbManager.ACTION_USB_DEVICE_ATTACHED: // 插入USB设备
Log.i("camera","USB: 插入");
//if(getUsbCameraDevice(context) != null){
if (isUsbCamera(usbDevice)) {
new Handler().postDelayed(new Runnable(){
public void run() {
if(getCameraNumAndView() > 1) {
try {
changeCamera(TWO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, 2000);
}
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED: // 拔出USB设备
Log.i("camera","USB: 拔出");
new Handler().postDelayed(new Runnable(){
public void run() {
if(getCameraNumAndView() > 0){
try {
changeCamera(ONE);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}, 500);
break;
default:
break;
}
}
}
/*注册USB监听广播*/
private void registerReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
mUsbReceiver = new USBReceiver();
registerReceiver(mUsbReceiver, filter);
}
/*注销广播*/
private void unregisterUsbReceiver(){
unregisterReceiver(mUsbReceiver);
}
参考
评论