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


相关推荐

  • resnet101网络结构图_resnet有全连接层吗

    resnet101网络结构图_resnet有全连接层吗resnet网络代码importtorchimporttorch.nnasnnimporttorchvisionimportnumpyasnpfromtorchsummaryimportsummaryprint(“PyTorchVersion:”,torch.__version__)print(“TorchvisionVersion:”,torchvi…

    2022年10月7日
    4
  • MPLS 虚拟专用网络 Hub and Spoke实验

    MPLS 虚拟专用网络 Hub and Spoke实验

    2021年4月12日
    971
  • 什么是ADO.NET

    什么是ADO.NET

    2021年7月31日
    59
  • PDF补丁丁( PDFPatcher.)

    PDF补丁丁( PDFPatcher.)PDF 补丁丁是一个用于修改 PDF 文件信息的工具 它具有以下功能 修改 PDF 信息 修改文档属性 页码编号 页面链接 页面尺寸 删除自动打开网页等动作 去除复制及打印限制 设置阅读器初始模式 贴心 PDF 书签编辑器 可批量修改 PDF 书签属性 颜色 样式 目标页码 缩放比例等 在书签中执行查找替换 支持正则表达式及 XPath 匹配 生成 PDF 书签 无需手工输入 自动识别正文标题或目录 为 PDF 文档生成书签 制作 PDF 文件 合并已有 PDF 文件或图片 生成新的 PDF 文件 可挂上书签 拆分或合并 PDF 文件

    2026年3月18日
    3
  • 安卓ROM简单定制、打包、签名、换字体「建议收藏」

    安卓ROM简单定制、打包、签名、换字体「建议收藏」2019独角兽企业重金招聘Python工程师标准>>>…

    2022年10月15日
    4
  • Pulsar整理

    Pulsar整理Pulsar 整理一 Pulsar 简述 1 1 定义 ApachePulsar 是一个分布式 高性能的服务器到服务器的消息解决方案 ApachePulsar 是最初在 Yahoo 创建的开源分布式 pub sub 消息传递系统 现已成为 ApacheSoftwa 的一部分 1 2Pulsar 基础架构概述 Plusar 包含以下几种组件 如下图 架构之间的协作 如下图 1

    2026年3月19日
    2

发表回复

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

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