Unity android 接USBCamera

目录


一、前提

  1. unity打包android后,链接USB摄像头,需要USB权限。

二、流程

1.Unity导出android工程,Player配置如图:

2.导出android工程

3.在android工程中找到AndroidManifest.xml加入usb权限相关

复制代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
  <application android:extractNativeLibs="true">
    <activity android:name="com.unity3d.player.UnityPlayerActivity" android:theme="@style/UnityThemeSelector" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:resizeableActivity="false" android:hardwareAccelerated="false">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        //此处
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
      </intent-filter>

      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="android.notch_support" android:value="true" />
    </activity>
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />
    <meta-data android:name="unity.launch-fullscreen" android:value="True" />
    <meta-data android:name="unity.allow-resizable-window" android:value="False" />
    <meta-data android:name="notch.config" android:value="portrait|landscape" />
  </application>
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.CAMERA" />
  //此处
  <uses-feature android:name="android.hardware.usb.host" />
 //此处
  <uses-permission android:name="android.permission.USB_PERMISSION" />
  <uses-feature android:name="android.hardware.camera" android:required="false" />
  <uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
  <uses-feature android:name="android.hardware.camera.front" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>

备注主要三行如下:

复制代码
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

4.找到UnityPlayerActivity.java,在unity启动onResume方法里面新增打开USB权限设置:

java 复制代码
    private static final String TAG = "unity";

    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private UsbManager usbManager;
    private UsbDeviceConnection connection;

    private PendingIntent permissionIntent;
    private boolean permissionGranted = false;

    private BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "USB设备连接有变化,链接到:"+action);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    unregisterReceiver(usbReceiver);
                    UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (usbDevice != null) {
                            // 用户已授权访问USB设备
                            connectUsbDevice(usbDevice);
                        }
                    } else {
                        Log.d(TAG, "用户未授权访问USB设备");
//                        requestPermission(usbDevice);
                    }
                }
            }
        }
    };

    // Resume Unity
    @Override protected void onResume()
    {
        super.onResume();

        if (MultiWindowSupport.getAllowResizableWindow(this))
            return;

        mUnityPlayer.resume();

        openUsbDevice();
    }

    private  void openUsbDevice(){
        //        //获取注册usb
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

        // 获取已连接的USB设备列表
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        if (deviceIterator.hasNext()) {
            UsbDevice  device = deviceIterator.next();
            permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            Log.e(TAG, "getDeviceList: " + device.getVendorId()+"=="+device.getProductId());
            ///注册广播
            registerReceiver(usbReceiver, filter);
            usbManager.requestPermission(device, permissionIntent);
        } else {
            Log.d(TAG, "没有找到已连接的USB设备");
            Toast.makeText(this, "没有找到已连接的USB设备", Toast.LENGTH_SHORT).show();
        }
    }

    private void connectUsbDevice(UsbDevice usbDevice) {
        if (usbDevice == null) {
            return;
        }

        connection = usbManager.openDevice(usbDevice);
        if (connection != null) {
            // 在此处执行USB通信操作
            Log.d(TAG, "USB设备已连接");
            Toast.makeText(this, "USB设备已连接", Toast.LENGTH_SHORT).show();
        } else {
            Log.d(TAG, "无法打开USB设备连接");
            Toast.makeText(this, "无法打开USB设备连接", Toast.LENGTH_SHORT).show();
        }
    }
相关推荐
2501_915106321 小时前
iOS 抓包工具选择与配置指南 从零基础到高效调试的完整流程
android·ios·小程序·https·uni-app·iphone·webview
_一条咸鱼_2 小时前
Android Runtime内存安全保护机制深度解析(80)
android·面试·android jetpack
音视频牛哥2 小时前
Android与Unity跨平台共享纹理的低延迟RTSP/RTMP播放器实现
unity3d·音视频开发·视频编码
2c237c62 小时前
Uniapp中双弹窗为什么无法显示?
android·javascript·uni-app
叶羽西3 小时前
将Android Studio创建的一个apk工程放到Android15源码中构建
android
CYRUS_STUDIO13 小时前
深入 Android syscall 实现:内联汇编系统调用 + NDK 汇编构建
android·操作系统·汇编语言
死也不注释14 小时前
【第一章编辑器开发基础第一节绘制编辑器元素_6滑动条控件(6/7)】
android·编辑器
程序员JerrySUN15 小时前
Linux 文件系统实现层详解:原理、结构与驱动衔接
android·linux·运维·数据库·redis·嵌入式硬件
2501_9160137416 小时前
iOS 加固工具使用经验与 App 安全交付流程的实战分享
android·ios·小程序·https·uni-app·iphone·webview
南棱笑笑生16 小时前
20250715给荣品RD-RK3588开发板刷Android14时打开USB鼠标
android·计算机外设