android开发之蓝牙配对连接的方法「建议收藏」

新年第一篇。最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结。在做android蓝牙串口连接的时候一般会使用BluetoothSocket tmp = null;// Get a BluetoothSocket for a connection with the// given BluetoothDevi

大家好,又见面了,我是全栈君。

新年第一篇。

最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结。

在做android蓝牙串口连接的时候一般会使用

BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
         tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
	Log.e(TAG, "create() failed", e);
}

然后是tmp赋给BluetoothSocket,接着调用connect方法进行蓝牙设备的连接。

可是 BluetoothSocket 的connect方法本身就会报很多异常错误。

以下根据对蓝牙开发的一点研究可通过以下方法解决:

方法1.先进行蓝牙自动配对,配对成功,通过UUID获得BluetoothSocket,然后执行connect()方法。

方法2.通过UUID获得BluetoothSocket,然后先根据mDevice.getBondState()进行判断是否需要配对,最后执行connnect()方法。

 

    private class ConnectThread extends Thread {
        String macAddress = "";

        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            mBluetoothAdapter.cancelDiscovery();
            try {
                socket = mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
                
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Log.e(TAG, "Socket", e);
            }             
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {                
                connectDevice();
            }
            // 重置ConnectThread 
            //synchronized (BluetoothService.this) {
               //ConnectThread = null;
            //}
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }
    }

接下来是调用的连接设备方法connectDevice():

protected void connectDevice() {  
        try {  
            // 连接建立之前的先配对  
            if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {  
                Method creMethod = BluetoothDevice.class  
                        .getMethod("createBond");  
                Log.e("TAG", "开始配对");  
                creMethod.invoke(mBluetoothDevice);  
            } else {  
            }  
        } catch (Exception e) {  
            // TODO: handle exception  
            //DisplayMessage("无法配对!");  
            e.printStackTrace();  
        }  
        mBluetoothAdapter.cancelDiscovery();  
        try {  
            socket.connect();  
            //DisplayMessage("连接成功!"); 
            //connetTime++;
            connected = true;
        } catch (IOException e) {  
            // TODO: handle exception  
            //DisplayMessage("连接失败!");
            connetTime++;
            connected = false;
            try {  
                socket.close();
                socket = null;
            } catch (IOException e2) {  
                // TODO: handle exception  
                Log.e(TAG, "Cannot close connection when connection failed");  
            }  
        } finally {
            connecting = false;
        }  
    }

 

方法3.利用反射通过端口获得BluetoothSocket,然后执行connect()方法。

    private class ConnectThread extends Thread {
        String macAddress = "";

        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            mBluetoothAdapter.cancelDiscovery();
            initSocket();                         
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {
                try {
                    socket.connect();
                    connected = true;
                } catch (IOException e1) {
                    connetTime++;
                    connected = false;
                    // 关闭 socket
                    try {
                        socket.close();
                        socket = null;
                    } catch (IOException e2) {
                        //TODO: handle exception  
                        Log.e(TAG, "Socket", e2);
                    }
                } finally {
                    connecting = false;
                }
                //connectDevice();
            }
            // 重置ConnectThread 
            //synchronized (BluetoothService.this) {
               //ConnectThread = null;
            //}
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }
    }

接下来是初始化并得到BluetoothSocket的方法

/**
     * 取得BluetoothSocket
     */
    private void initSocket() {
        BluetoothSocket temp = null;
        try {            
            Method m = mBluetoothDevice.getClass().getMethod(
                    "createRfcommSocket", new Class[] { int.class });
            temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1            
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        socket = temp;
    }

 

要点:1.蓝牙配对和连接是两回事,不可混为一谈。

   2.蓝牙串口连接可通过端口 (1-30)和UUID两种方法进行操作。

   3.通过UUID进行蓝牙连接最好先进行配对操作。

 

作者:jason0539

博客:http://blog.csdn.net/jason0539(转载请说明出处)

扫码关注我微信公众号

android开发之蓝牙配对连接的方法「建议收藏」

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/121375.html原文链接:https://javaforall.net

(0)
上一篇 2022年3月10日 下午11:00
下一篇 2022年3月11日 上午6:00


相关推荐

  • 分子模拟软件amber_Gromacs联用GAFF力场处理水溶剂下小分子动力学

    分子模拟软件amber_Gromacs联用GAFF力场处理水溶剂下小分子动力学与GROMACS偏重生物大分子模拟的力场不同,AMBER支持很多方便处理有机小分子的力场(详见http://sobereva.com/115),如GAFF力场,简单而又有不错的精度,适合处理有机小分子;这里将介绍用Gaussian计算RESP电荷,交由Amber生成GAFF力场下的拓扑文件,最后用GROMACS模拟的过程。软件版本:AmberTools18,Gromacs2019-beta-1…

    2022年5月25日
    103
  • 小爱音箱Pro接入豆包AI[项目代码]

    小爱音箱Pro接入豆包AI[项目代码]

    2026年3月17日
    2
  • Android 9.0 WebView无法加载页面报错 net:ERR_CLEARTEXT_NOT_PERMITTED

    Android 9.0 WebView无法加载页面报错 net:ERR_CLEARTEXT_NOT_PERMITTED

    2021年10月2日
    124
  • eclipse导入jar包的三种方法

    eclipse导入jar包的三种方法使用 Eclipse 开发应用程序 少不了使用第三方 jar 包 而每次引入 jar 包都是一个不小的问题 不仅那些 jar 包的位置经常弄不清楚 而且很浪费时间 鉴于此 我列举了三种常用的 jar 包引入方式 其中第一种是我们最常用的普通操作方式 而第二种和第三种则是快速版的操作方式 nbsp nbsp 下面看第一种方式 基本步骤式 nbsp nbsp 右键项目属性 选择 Property 在弹出的对话框左侧列表中选择 JavaBuildP

    2026年3月19日
    2
  • 神经网络基础-多层感知器(MLP)

    神经网络基础-多层感知器(MLP)在深度学习的路上 从头开始了解一下各项技术 本人是 DL 小白 连续记录我自己看的一些东西 大家可以互相交流 本文参考 本文参考吴恩达老师的 Coursera 深度学习课程 很棒的课 推荐 nbsp 本文默认你已经大致了解深度学习的简单概念 如果需要更简单的例子 可以参考吴恩达老师的入门课程 http study 163 com courses search keyword E5 90 B4 E6

    2026年3月26日
    2
  • Dataset之CIFAR-10:CIFAR-10数据集的简介、下载、使用方法之详细攻略

    Dataset之CIFAR-10:CIFAR-10数据集的简介、下载、使用方法之详细攻略Dataset之CIFAR-10:CIFAR-10数据集的简介、下载、使用方法之详细攻略目录CIFAR-10的简介1、与MNIST数据集中目比,CIFAR-10真高以下不同点2、TensorFlow官方示例的CIFAR-10代码文件3、CIFAR-10数据集的数据文件名及用途4、基于CIFAR-10数据集最新算法预测准确率对比CIFAR-10的下载1、下载CIFAR-10数据集的全部数据CIFAR-10使用方法1、使用TF读取CIFAR-10数据官网链接:TheCIFAR-10datas

    2022年10月17日
    7

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号