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

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

1
2
3
4
5
6
7
8
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()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
     * 取得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进行蓝牙连接最好先进行配对操作。

android开发之蓝牙配对连接的方法的更多相关文章

  1. 【视频】零基础学Android开发:蓝牙聊天室APP(四)

    零基础学Android开发:蓝牙聊天室APP第四讲 4.1 ListView控件的使用 4.2 BaseAdapter具体解释 4.3 ListView分布与滚动事件 4.4 ListView事件监听 ...

  2. 【视频】零基础学Android开发:蓝牙聊天室APP(二)

    零基础学Android开发:蓝牙聊天室APP第二讲 2.1 课程内容应用场景 2.2 Android UI设计 2.3 组件布局:LinearLayout和RelativeLayout 2.4 Tex ...

  3. Android开发——RecyclerView特性以及基本使用方法(二)

    0.  前言 随着Android的发展,虽然ListView依旧重要,但RecyclerView确实越来越多的被大家使用.但显然并不能说RecyclerView就一定优于ListView,而是应该根据 ...

  4. Android开发——RecyclerView特性以及基本使用方法(一)

    )关于点击事件,没有像ListView那样现成的API,但是自己封装起来也不难,而且我们使用ListView时,如果item中有可点击组件,那么点击事件的冲突也是一个问题,而在RecyclerView ...

  5. 【视频】零基础学Android开发:蓝牙聊天室APP(三)

    零基础学Android开发:蓝牙聊天室APP第三讲 3.1 ImageView.ImageButton控件具体解释 3.2 GridView控件具体解释 3.3 SimpleAdapter适配器具体解 ...

  6. 【视频】零基础学Android开发:蓝牙聊天室APP(一)

    零基础学Android开发:蓝牙聊天室APP第一讲 1. Android介绍与环境搭建:史上最高效Android入门学习 1.1 Google的大小战略 1.2 物联网与云计算 1.3 智能XX设备 ...

  7. Android开发之清除缓存功能实现方法,可以集成在自己的app中,增加一个新功能。

    作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985 Android开发之清除缓存功能实现方法,可以集成在自己的app中,增加一个新功能. 下面是一个效果图 ...

  8. Android开发 静态static类与static方法持有Context是否导致内存泄露的疑问

    简述 在Android开发的过程中,难免会使用单例模式或者静态方法工具类.我们会让它们持有一些外部的Context或者View一般有以下几种情况: 单例模式,类的全局变量持有Context 或 Vie ...

  9. Android开发中Parcelable接口的使用方法

    在网上看到很多Android初入门的童鞋都在问Parcelable接口的使用方法,小编参考了相关Android教程,看到里面介绍的序列化方法主要有两种分别是实现Serializable接口和实现Par ...

随机推荐

  1. iOS推送介绍

    iOS消息推送的工作机制可以简单的用下图来概括: Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务 ...

  2. BZOJ 2100: [Usaco2010 Dec]Apple Delivery( 最短路 )

    跑两遍最短路就好了.. 话说这翻译2333 ---------------------------------------------------------------------- #includ ...

  3. [K/3Cloud] 如何从被调用的动态表单界面返回数据

    在需要返回数据的地方调用表单返回方法完成数据返回 this.View.ReturnToParentWindow(retData); 在调用界面的回调函数中取出返回结果的ReturnData即可使用. ...

  4. 「操作系统」:The most useful condition codes

    CF: Carry Flag.The most recent operation generated a carry out of the most significant bit. Used to ...

  5. poj 2021 Relative Relatives(暴力)

    题目链接:http://poj.org/problem?id=2021 思路分析:由于数据较小,采用O(N^2)的暴力算法,算出所有后代的年龄,再排序输出. 代码分析: #include <io ...

  6. 3644 - X-Plosives(水题,并差集)

    3644 - X-Plosives A secret service developed a new kind of explosive that attain its volatile proper ...

  7. hadoop的WordCount样例

    package cn.lmj.mapreduce; import java.io.IOException; import java.util.Iterator; import org.apache.h ...

  8. Codeforces Round #246 (Div. 2)

    题目链接:Codeforces Round #246 (Div. 2) A:直接找满足的人数,然后整除3就是答案 B:开一个vis数组记录每一个衣服的主场和客场出现次数.然后输出的时候主场数量加上反复 ...

  9. 【转】linux挂载新硬盘,开机自动挂载

    [转]linux挂载新硬盘,开机自动挂载 ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※ Linux的硬盘识别: 2.6 kernel以后,linux会将 ...

  10. Codeforces Round #316 (Div. 2A) 570A Elections

    题目:Click here #include <bits/stdc++.h> using namespace std; typedef long long ll; const int IN ...