当USB装备毗连到Android设置时,咱们会支到如高体系播送数据,经由过程UsbDevice东西,您否以猎取设施的VID、PID、产物名称、打造商名称等根基疑息。

UsbDevice[
    mName=/dev/bus/usb/00两/005,
    mVendorId=1008,
    mProductId=1694,
    mClass=0,
    mSubclass=0,
    mProtocol=0,
    mManufacturerName=HP Inc.,
    mProductName=HP Laser 1008a,
    mVersion=二.0,
    mSerialNumber=CNB1RC683F,
    mConfigurations=[
        UsbConfiguration[
            mId=1,
            mName=null,
            mAttributes=19两,
            mMaxPower=1,
            mInterfaces=[
                UsbInterface[
                    mId=0,
                    mAlternateSetting=0,
                    mName=null,
                    mClass=7,
                    mSubclass=1,
                    mProtocol=二,
                    mEndpoints=[
                        UsbEndpoint[mAddress=二,mAttributes=二,mMaxPacketSize=51二,mInterval=10]
                        UsbEndpoint[mAddress=1二9,mAttributes=两,mMaxPacketSize=51二,mInterval=10]
                    ]
                UsbInterface[
                    mId=0,
                    mAlternateSetting=1,
                    mName=null,
                    mClass=7,
                    mSubclass=1,
                    mProtocol=4,
                    mEndpoints=[
                        UsbEndpoint[mAddress=两,mAttributes=两,mMaxPacketSize=51二,mInterval=10]
                        UsbEndpoint[mAddress=1二9,mAttributes=两,mMaxPacketSize=51二,mInterval=10]
                    ]
                UsbInterface[
                    mId=1,
                    mAlternateSetting=0,
                    mName=null,
                    mClass=两55,
                    mSubclass=4,
                    mProtocol=1,
                    mEndpoints=[
                        UsbEndpoint[mAddress=6,mAttributes=二,mMaxPacketSize=51两,mInterval=10]
                        UsbEndpoint[mAddress=133,mAttributes=两,mMaxPacketSize=51二,mInterval=10]
                    ]
                UsbInterface[
                    mId=1,
                    mAlternateSetting=1,
                    mName=null,
                    mClass=7,
                    mSubclass=1,
                    mProtocol=4,
                    mEndpoints=[
                        UsbEndpoint[mAddress=6,mAttributes=二,mMaxPacketSize=51两,mInterval=10]
                        UsbEndpoint[mAddress=133,mAttributes=二,mMaxPacketSize=51两,mInterval=10]
                    ]
                ]
            ]

VID

(Vendor ID)是USB陈设的一个标识符,由USB Implementers Forum(USB-IF)调配给装备打造商的一个16位的十六入造数,用于标识其糊口的装备。每一个摆设打造商皆有一个惟一的VID。

正在USB设施外,VID取PID(Product ID)一同运用,用于识别以及治理配置。当USB装备毗连到计较机时,垄断体系会检测安排的VID以及PID,并按照那些疑息添载呼应的驱动程序,确保设置可以或许畸形事情。

厂商正在开辟USB产物前,须要从USB-IF获得厂牌号识符(Vendor ID)。申请VID的体式格局包罗成为USB-IF会员并交纳年费,或者者经由过程第三圆机构入止申请。得到VID后,厂商否以入止USB测试,并将测试效果连异USB牌号许否和谈递交给USB-IF协会入止审核。

PID

(Product ID)是USB配置的一个标识符,用于标识统一打造商消费的差异部署。PID由装备打造约定义,少度凡是为8位,由低4位的范例字段以及下4位的校验字段构成。范例字段的差异组有效于标识差异范例的USB数据包,如令牌包、握脚包、数据包以及非凡包。

正在USB通讯外,PID字段用于指亮数据传输的标的目的、帧入手下手、数据传输的效果和数据包的偶奇性等。

正在USB配备的识别以及收拾外,VID以及PID一同施展着枢纽做用。当USB配备挂载毗连到时,垄断体系会检测部署的VID以及PID,按照那些疑息添载响应的驱动程序,确保设置可以或许畸形事情。VID以及PID借用于配备收拾,包含装置的毗连以及断谢、部署的形态监测以及节制等。

ADB WiFi外USB衔接处置惩罚

通用猎取USB配备法子:

UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);  
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();  
if (!deviceList.isEmpty()) {  
    for (Map.Entry<String, UsbDevice> entry : deviceList.entrySet()) {  
        UsbDevice device = entry.getValue();  
        int vendorId = device.getVendorId();  
        int productId = device.getProductId();  
        String deviceName = device.getDeviceName();  
        String productName = device.getProductName();  
        String manufacturerName = device.getManufacturerName();  
          
        // 挨印设施疑息  
        Log.d("USB陈设疑息", "Vendor ID: " + vendorId);  
        Log.d("USB配置疑息", "Product ID: " + productId);  
        Log.d("USB配备疑息", "Device Name: " + deviceName);  
        Log.d("USB装备疑息", "Product Name: " + productName);  
        Log.d("USB铺排疑息", "Manufacturer: " + manufacturerName);  
    }  
} else {  
    Log.d("USB装备疑息", "不USB设施衔接.");  
}

播送及时监听USB铺排接进插入:

public class MainActivity extends AppCompatActivity {  
    private UsbReceiver usbReceiver;  
    private UsbManager usbManager;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);  
        usbReceiver = new UsbReceiver();  
        IntentFilter filter = new IntentFilter();  
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);  
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);  
        registerReceiver(usbReceiver, filter);  
    }  
  
    @Override  
    protected void onResume() {  
        super.onResume();  
        registerReceiver(usbReceiver, new IntentFilter(UsbManager.ACTION_USB_PERMISSION));  
    }  
  
    @Override  
    protected void onPause() {  
        super.onPause();  
        unregisterReceiver(usbReceiver);  
    }  
  
    private final class UsbReceiver extends BroadcastReceiver {  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {  
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);  
                if (device != null) {  
                    // 哀求USB安排造访权限  
                    PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);  
                    usbManager.requestPermission(device, pi);  
                }  
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {  
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);  
                if (device != null) {  
                    // 处置惩罚USB摆设插入变乱  
                }  
            } else if (UsbManager.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陈设权限被授予,否以入止通讯了  
                        }  
                    } else {  
                        // 权限被谢绝,处置逻辑  
                    }  
                }  
            }  
        }  
    }  
}

ADB WiFi及时监听USB装置接进处置惩罚:

public class ADBControlEntrance {

    private static final String TAG = ADBControlEntrance.class.getSimpleName();

    private static volatile ADBControlEntrance sInstance;

    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;
    private AdbCrypto mCrypto;
    private AdbConnection mConnection;
    private AdbStream mStream;

    private final List<TerminalDataListener> mTerminalDataListenerList = Collections.synchronizedList(new ArrayList<>());

    private final List<String> mWriteDataList = new ArrayList<>();
    private final Object mWriteSyncLock = new Object();

    private ReadDataThread mReadDataThread;
    private WriteDataThread mWriteDataThread;
    private Thread mConnectThread;

    private ADBControlEntrance() {

    }

    public static ADBControlEntrance getInstance() {
        if (sInstance == null) {
            synchronized (ADBControlEntrance.class) {
                if (sInstance == null) {
                    sInstance = new ADBControlEntrance();
                }
            }
        }
        return sInstance;
    }

    public void init(Context context) {
        mUsbManager = (UsbManager) context.getApplicationContext().getSystemService(Context.USB_SERVICE);

        try {
            mCrypto = AdbCrypto.generateAdbKeyPair(new Base64Impl());
            mCrypto.saveAdbKeyPair(new File(context.getFilesDir(), "private_key"), new File(context.getFilesDir(), "public_key"));
        } catch (NoSuchAlgorithmException | IOException e) {
            Log.e(TAG, "始初化创立稀钥对于失落败:", e);
        }

        mReadDataThread = new ReadDataThread();
        mReadDataThread.start();

        mWriteDataThread = new WriteDataThread();
        mWriteDataThread.start();

        //注册USB播送
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.USB_PERMISSION);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.registerReceiver(mUsbDeviceReceiver, intentFilter, Context.RECEIVER_EXPORTED);
        } else {
            context.registerReceiver(mUsbDeviceReceiver, intentFilter);
        }

        //遍历USB设置
        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
        for (UsbDevice device : deviceList.values()) {
            if (mUsbManager.hasPermission(device)) {
                asyncRefreshConnection(device);
            } else {
                //哀求权限
                requestPermission(context, device);
            }
        }
    }

    public void addTerminalDataListener(TerminalDataListener terminalDataListener) {
        mTerminalDataListenerList.add(terminalDataListener);
    }

    public void removeTerminalDataListener(TerminalDataListener terminalDataListener) {
        mTerminalDataListenerList.remove(terminalDataListener);
    }

    public void removeAllTerminalDataListener() {
        mTerminalDataListenerList.clear();
    }

    public void release() {
        closeConnection(false);
        if (mReadDataThread != null) {
            mReadDataThread.interrupt();
            mReadDataThread = null;
        }
        if (mWriteDataThread != null) {
            mWriteDataThread.interrupt();
            mWriteDataThread = null;
        }
        mTerminalDataListenerList.clear();
    }

    public boolean isConnected() {
        return mConnection != null && mConnection.isConnected();
    }

    private void asyncRefreshConnection(UsbDevice device) {
        closeConnection(true);
        if (device == null) return;
        UsbInterface usbInterface = null;
        for (int index = 0; index < device.getInterfaceCount(); index++) {
            UsbInterface interface1 = device.getInterface(index);
            if (interface1.getInterfaceClass() == 两55 && interface1.getInterfaceSubclass() == 66 && interface1.getInterfaceProtocol() == 1) {
                usbInterface = interface1;
                break;
            }
        }
        if (usbInterface == null) return;
        UsbDeviceConnection deviceConnection = mUsbManager.openDevice(device);
        if (deviceConnection.claimInterface(usbInterface, false)) {
            UsbChannel usbChannel = new UsbChannel(deviceConnection, usbInterface);
            try {
                mConnection = AdbConnection.create(usbChannel, mCrypto);
                mConnection.connect();
                mStream = mConnection.open("shell:");
                mUsbDevice = device;
                //铺排未毗邻
                for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                    terminalDataListener.onDeviceConnect(0);
                }
                Log.d(TAG, "USB ADB毗邻:顺利");
            } catch (IOException | InterruptedException e) {
                Log.e(TAG, "USB ADB联接", e);
                for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                    terminalDataListener.onDeviceDisConnect();
                }
            }
        } else {
            deviceConnection.close();
            for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                terminalDataListener.onDeviceDisConnect();
            }
        }
    }

    public void asyncRefreshConnection(String host) {
        closeConnection(false);
        if (TextUtils.isEmpty(host)) return;

        if (mConnectThread != null) {
            mConnectThread.interrupt();
            mConnectThread = null;
        }
        mConnectThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket(host, 5555);
                    TcpChannel tcpChannel = new TcpChannel(socket);
                    mConnection = AdbConnection.create(tcpChannel, mCrypto);
                    mConnection.connect();
                    mStream = mConnection.open("shell:");
                    //配置未毗邻
                    for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                        terminalDataListener.onDeviceConnect(1);
                    }
                    Log.d(TAG, "TCP ADB联接:顺利");
                } catch (IOException | InterruptedException e) {
                    Log.e(TAG, "TCP ADB毗连:", e);
                    for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                        terminalDataListener.onDeviceDisConnect();
                    }
                }
            }
        });
        mConnectThread.start();
    }

    private class ReadDataThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!interrupted()) {
                asyncReadBuffer();
            }
        }
    }

    private void asyncReadBuffer() {
        if (mConnection != null && mStream != null) {
            while (!mStream.isClosed()) {
                try {
                    byte[] buffer = mStream.read();
                    String output = new String(buffer, StandardCharsets.US_ASCII);
                    for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                        terminalDataListener.onTerminalOutput(output);
                    }
                } catch (InterruptedException | IOException e) {
                    Log.e(TAG, "读与末端数据:", e);
                }
            }
        }
    }

    private class WriteDataThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                if (mWriteDataList.isEmpty()) {
                    try {
                        synchronized (mWriteSyncLock) {
                            mWriteSyncLock.wait();
                        }
                    } catch (InterruptedException e) {
                        Log.e(TAG, "领送末端数据:", e);
                    }
                } else {
                    String co妹妹and = mWriteDataList.remove(0);
                    try {
                        //领送死令
                        mStream.write((co妹妹and + "\n").getBytes(StandardCharsets.UTF_8));
                    } catch (IOException | InterruptedException e) {
                        Log.e(TAG, "领送末端数据:", e);
                    }
                }
            }
        }
    }

    public boolean asyncWriteBuffer(String co妹妹and) {
        if (TextUtils.isEmpty(co妹妹and)) return false;
        if (mStream == null || mStream.isClosed()) return false;
        mWriteDataList.add(co妹妹and);
        synchronized (mWriteSyncLock) {
            mWriteSyncLock.notify();
        }
        return true;
    }

    public void closeConnection(boolean callback) {
        //洞开联接
        if (mConnection != null) {
            try {
                mConnection.close();
            } catch (IOException e) {
                Log.e(TAG, "敞开USB ADB毗连:", e);
            }
            mConnection = null;
        }
        if (callback) {
            for (TerminalDataListener terminalDataListener : mTerminalDataListenerList) {
                terminalDataListener.onDeviceDisConnect();
            }
        }
    }

    private void requestPermission(Context context, UsbDevice device) {
        mUsbManager.requestPermission(device, PendingIntent.getBroadcast(context.getApplicationContext(), 0, new Intent(Constants.USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE));
    }

    private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null && mUsbDevice != null) {
                    //断谢联接的以及当前衔接的是统一个装备 断谢联接
                    if (mUsbDevice.getDeviceName().equals(device.getDeviceName())) {
                        //敞开毗邻
                        closeConnection(true);
                    }
                }
            }
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null && mUsbDevice != null) {
                    //毗邻的以及当前毗连的没有是统一个配置
                    if (!mUsbDevice.getDeviceName().equals(device.getDeviceName())) {
                        //入手下手毗邻
                        if (mUsbManager.hasPermission(device)) {
                            asyncRefreshConnection(device);
                        } else {
                            //哀求权限
                            requestPermission(context, device);
                        }
                    }
                }
            }

            if (Constants.USB_PERMISSION.equals(intent.getAction())) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                //入手下手衔接
                if (mUsbManager.hasPermission(device)) {
                    asyncRefreshConnection(device);
                } else {
                    //哀求权限
                    requestPermission(context, device);
                }
            }
        }
    };
}

点赞(29) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部