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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ITDSD- 3.分布式工程学综述

    ITDSD- 3.分布式工程学综述英文版地址:ITDSD-3.OverviewofDistributedEngineeringSunshuo(sun.shuo@aliyun.com)导论这是关于分布式架构新手入门的第三篇文章。这一篇文章主要简要的介绍分布式工程学在理论上的基本概念,历史和现状,以及未来发展方向。让大家能够了解为什么学习分布式工程学。分布式工程学在计算机科学中的地位,以及分布式工程学要解决的问…

    2022年5月31日
    27
  • Net开源的地址[通俗易懂]

    Net开源的地址[通俗易懂]https://github.com/dotnet其中有corefx,coreclr,roslyn开源等等

    2022年7月15日
    13
  • 《数据仓库与数据挖掘教程》ch01绪论 章节整理

    《数据仓库与数据挖掘教程》ch01绪论 章节整理数据仓库概述从传统数据库到数据仓库计算机数据处理有两种主要方式事务型处理分析型处理传统数据库与事务处理传统数据库是长期存储在计算机内的、有组织的、可共享的数据集合有严格的数学理论支持,并在商业领域得到普及应用。联机事务处理(On-LineTransactionProcessing)系统,简称OLTP系统。数据存储在传统数据库中,成为OLTP数据库处理特点:实时响应,数…

    2022年6月17日
    20
  • mysql字符串截取函数_excel 截取部分字符

    mysql字符串截取函数_excel 截取部分字符MySQL 字符串截取函数:left(), right(), substring(), substring_index()。还有 mid(), substr()。其中,mid(), substr() 等价于 substring() 函数,substring() 的功能非常强大和灵活。  1. 字符串截取:left(str, length)  mysql> select left(‘sqls

    2022年10月2日
    3
  • 一小时搞定 简单VBA编程 Excel宏编程快速扫盲

    一小时搞定 简单VBA编程 Excel宏编程快速扫盲Excel宏编程可以快速完成批量表格操作:复制粘贴、数据过滤等,宏代码基于VB语言实现,有基础的编程经验就能快速阅读。下面是我的学习笔记。1.ExcelVBA编辑界面(进入路径:sheet名称–>鼠标右键菜单–>查看代码)2.输入代码方法:在VBE编辑器的代码模块中输入VBA代码,通常有以下几种方法:■手工键盘输入;■使用…

    2022年4月27日
    53
  • python怎么把字体调大_python修改字体

    python怎么把字体调大_python修改字体Pycharm4.5是一款非常强大的Python代码编辑器,其具备了易于上手、功能强大等特点,深受广大开发人员的青睐,而在使用的过程中,我们常常需要设置字体的大小以及背景颜色等参数,从而能够为用户带来更好的代码编辑效果,而部分刚入手的用户可能还不知到如何进行设置,小编这里为用户带来了Pycharm4.5设置字体大小与背景颜色的操作操作教程,有需要的用户赶紧来了解一下吧,想必能够为用户带来帮助!方法…

    2022年8月26日
    8

发表回复

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

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