要在Android應用中使用USB攝像頭,首先需要確保設備支持USB攝像頭,并且已經連接到設備上。接下來,可以按照以下步驟在應用中使用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" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// 打開USB攝像頭
// 獲取USB設備的ID和攝像頭信息
}
} else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
private void requestUSBPermission() {
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
UsbDevice device = ... // 獲取USB設備
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, filter);
usbManager.requestPermission(device, permissionIntent);
}
private Camera camera;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
if (surfaceHolder != null) {
surfaceCreated(surfaceHolder);
}
}
@Override
protected void onPause() {
super.onPause();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
通過以上步驟,就可以在Android應用中成功使用USB攝像頭。需要注意的是,使用USB攝像頭可能會因為不同設備和Android版本的差異而有所不同,需要根據具體情況進行調整。