要實現Android設備連接USB攝像頭并進行實時預覽,可以通過以下步驟實現:
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
for (UsbDevice device : deviceList.values()) {
if (device.getDeviceClass() == UsbConstants.USB_CLASS_VIDEO) {
// 打開USB連接
}
}
SurfaceView surfaceView = findViewById(R.id.surfaceView);
SurfaceHolder holder = surfaceView.getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 初始化攝像頭
Camera camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
});
需要注意的是,對于不同的Android設備和USB攝像頭,可能需要根據具體情況對代碼進行調整和優化,以確保能夠正確連接USB攝像頭并實現實時預覽。