Android 主动连接指定的蓝牙设备

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rocklee/article/details/87893792

      网上查到的资料都是基本默认连接好的蓝牙设备通讯, 但如果app在设置时已经配置好将要连接的蓝牙设备参数, 使用时要自动连接这个蓝牙设备又如何实现 ?

      下面给出代码,让有需要的同学作参考:

/***
     * 向指定的蓝牙设备发送数据
     * @param pvsMac
     * @param pvsContent
     * @throws IOException
     */
    public void send(String pvsMac,byte[] pvsContent) throws IOException {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice lvDevice= adapter.getRemoteDevice(pvsMac);
        //BluetoothSocket lvSocket=lvDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
        BluetoothSocket lvSocket=null;
        try {
            lvSocket=(BluetoothSocket) lvDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(lvDevice,1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        OutputStream lvOs=null;
        try {
            try {
                lvSocket.connect();
            }
            catch (Exception e){
                lvSocket.close();
                throw e;
            }
            lvOs = lvSocket.getOutputStream();
            lvOs.write(pvsContent);
        }finally {
            if (lvOs!=null) lvOs.close();
            //lvSocket.close(); outputstream close时已经关闭socket了,所以无需再close
        }
    }

猜你喜欢

转载自blog.csdn.net/rocklee/article/details/87893792