2021-09-15

Android usb数据通讯

  1. 获取UsbManager
  2. getDeviceList()获取设备,根据mVendorId或者mProductId过滤设备
  3. 判断权限,没有权限请求权限requestPermission
  4. 获取usb接口,找到对应的usb端口(读或写的UsbEndpoint)
  5. 打开设备,获取连接UsbDeviceConnection
  6. claimInterface找到设备
  7. bulkTransfer数据读写

经典蓝牙通讯

private static final String TAG = "BluetoothPort";
    private BluetoothDevice mDevice;
    private BluetoothSocket mSocket;
    private BluetoothAdapter mAdapter;
    private ConnectThread mConnectThread;
    private InputStream inputStream;
    private OutputStream outputStream;
    private Context mContext;
    private Handler mHandler;
    private int mState;
    private int readLen;
    private final UUID PRINTER_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
    private BroadcastReceiver boundDeviceReceiver;

    public BluetoothDevice getDevice() {
        return mDevice;
    }

    public HprtBluePort(Context context, BluetoothDevice device, Handler handler){
        this.boundDeviceReceiver = new BoundBroadcastReceiver();
        this.mHandler = handler;
        this.mDevice = device;
        this.mAdapter = BluetoothAdapter.getDefaultAdapter();
        this.mState = PrinterConstants.Connect.CLOSED;
        this.mContext = context;
    }


    private synchronized void setState(int state) {
        Utils.Log("HprtBluePort", "setState() " + this.mState + " -> " + state);
        if (this.mState != state) {
            this.mState = state;
            if (this.mHandler != null) {
                this.mHandler.obtainMessage(this.mState).sendToTarget();
            }
        }

    }

    public int getState() {
        return this.mState;
    }

    public void close() {
        Utils.Log("BluetoothPort", "close()");

        try {
            if (this.mSocket != null) {
                this.mSocket.close();
            }
        } catch (IOException var2) {
            Utils.Log("BluetoothPort", "close socket failed");
            var2.printStackTrace();
        }

        this.mConnectThread = null;
        this.mDevice = null;
        this.mSocket = null;
        if (this.mState != PrinterConstants.Connect.FAILED) {
            this.setState(PrinterConstants.Connect.CLOSED);
        }

    }

    public int write(byte[] data) {
        try {
            if (this.outputStream != null) {
                this.outputStream.write(data);
                this.outputStream.flush();
                return 0;
            } else {
                return -1;
            }
        } catch (IOException var3) {
            Utils.Log("BluetoothPort", "write error.");
            var3.printStackTrace();
            return -1;
        }
    }

    public byte[] read() {
        byte[] readBuff = null;

        try {
            if (this.inputStream != null && (this.readLen = this.inputStream.available()) > 0) {
                readBuff = new byte[this.readLen];
                this.inputStream.read(readBuff);
            }
        } catch (IOException var3) {
            Utils.Log("BluetoothPort", "read error");
            var3.printStackTrace();
        }

        Log.w("BluetoothPort", "read length:" + this.readLen);
        return readBuff;
    }

    private boolean ReTryConnect() {
        Utils.Log("BluetoothPort", "android SDK version is:" + Build.VERSION.SDK_INT);

        try {
            if (Build.VERSION.SDK_INT >= 10) {
                this.mSocket = this.mDevice.createInsecureRfcommSocketToServiceRecord(this.PRINTER_UUID);
            } else {
                Method e = this.mDevice.getClass().getMethod("createRfcommSocket", Integer.TYPE);
                this.mSocket = (BluetoothSocket)e.invoke(this.mDevice, 1);
            }

            this.mSocket.connect();
            return false;
        } catch (Exception var2) {
            Utils.Log("BluetoothPort", "connect failed:");
            var2.printStackTrace();
            return true;
        }
    }

    private void pairOrConnect(boolean pair){
        if (pair) {
            IntentFilter boundFilter = new IntentFilter("android.bluetooth.device.action.BOND_STATE_CHANGED");
            this.mContext.registerReceiver(this.boundDeviceReceiver, boundFilter);
            boolean success = false;

            try {
                Method e = BluetoothDevice.class.getMethod("createBond");
                success = (Boolean)e.invoke(this.mDevice);
            } catch (Exception var8) {
                var8.printStackTrace();
            }
            Log.i("BluetoothPort", "createBond is success? : " + success);
        } else {
            this.mConnectThread = new ConnectThread();
            this.mConnectThread.start();
        }
    }

    public void open() {
        Utils.Log("BluetoothPort", "connect to: " + this.mDevice.getName());
        if (this.mState != PrinterConstants.Connect.CLOSED) {
            this.close();
        }

        if (this.mDevice.getBondState() == 10) {
            Log.i("BluetoothPort", "device.getBondState() is BluetoothDevice.BOND_NONE");
            this.pairOrConnect(true);
        } else if (this.mDevice.getBondState() == 12) {
            this.pairOrConnect(false);
        }

    }

    private class BoundBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.bluetooth.device.action.BOND_STATE_CHANGED".equals(action)) {
                BluetoothDevice device = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
                if (!HprtBluePort.this.mDevice.equals(device)) {
                    return;
                }

                switch(device.getBondState()) {
                    case 10:
                        HprtBluePort.this.mContext.unregisterReceiver(HprtBluePort.this.boundDeviceReceiver);
                        HprtBluePort.this.setState(PrinterConstants.Connect.FAILED);
                        Utils.Log("BluetoothPort", "bound cancel");
                        break;
                    case 11:
                        Utils.Log("BluetoothPort", "bounding......");
                        break;
                    case 12:
                        Utils.Log("BluetoothPort", "bound success");
                        HprtBluePort.this.mContext.unregisterReceiver(HprtBluePort.this.boundDeviceReceiver);
                        HprtBluePort.this.pairOrConnect(false);
                }
            }
        }
    }


    private class ConnectThread extends Thread{
        @Override
        public void run() {
            boolean hasError = false;
            HprtBluePort.this.mAdapter.cancelDiscovery();
            try {
                HprtBluePort.this.mSocket = HprtBluePort.this.mDevice.createRfcommSocketToServiceRecord(HprtBluePort.this.PRINTER_UUID);
                HprtBluePort.this.mSocket.connect();
            } catch (IOException e) {
                e.printStackTrace();
                hasError = HprtBluePort.this.ReTryConnect();
            }
            synchronized (this){
                HprtBluePort.this.mConnectThread = null;
            }
            if(!hasError){
                try {
                    HprtBluePort.this.inputStream = HprtBluePort.this.mSocket.getInputStream();
                    HprtBluePort.this.outputStream = HprtBluePort.this.mSocket.getOutputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(hasError){
                HprtBluePort.this.setState(PrinterConstants.Connect.FAILED);
                HprtBluePort.this.close();
            } else {
                HprtBluePort.this.setState(PrinterConstants.Connect.SUCCESS);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值