Android为蓝牙设备之间的通信封装好了一些调用接口,使得实现Android的蓝牙通信功能并不困难。可通过UUID使两个设备直接建立连接。

具体步骤:

1. 获取BluetoothAdapter实例,注册一个BroadcastReceiver监听蓝牙扫描过程中的状态变化

1
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
1
2
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
1
 
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
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
 
 
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                // Get the BluetoothDevice object from the Intent
                // 通过EXTRA_DEVICE附加域来得到一个BluetoothDevice设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 
                // If it's already paired, skip it, because it's been listed already
                // 如果这个设备是不曾配对过的,添加到list列表
                if (device.getBondState() != BluetoothDevice.BOND_BONDED)
                {
                    list.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), false));
                    clientAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
            // When discovery is finished, change the Activity title
            }
            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                setProgressBarIndeterminateVisibility(false);
                if (mListView.getCount() == 0)
                {
                    list.add(new ChatMessage("没有发现蓝牙设备", false));
                    clientAdapter.notifyDataSetChanged();
                    mListView.setSelection(list.size() - 1);
                }
            }
        }
    };

2. 打开蓝牙(enable),并设置蓝牙的可见性(可以被其它设备扫描到,客户端是主动发请求的,可不设置,服务端必须设置可见)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
       if (mBluetoothAdapter != null) {
    if (!mBluetoothAdapter.isEnabled()) {
        // 发送打开蓝牙的意图,系统会弹出一个提示对话框
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, RESULT_FIRST_USER);
         
        // 设置蓝牙的可见性,最大值3600秒,默认120秒,0表示永远可见(作为客户端,可见性可以不设置,服务端必须要设置)
        Intent displayIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        displayIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
        startActivity(displayIntent);
         
        // 直接打开蓝牙
        mBluetoothAdapter.enable();
    }
}

3. 扫描,startDiscovery()方法是一个很耗性能的操作,在扫描之前可以先使用getBondedDevices()获取已经配对过的设备(可直接连接),避免不必要的消耗。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  private void scanDevice() {
    // TODO Auto-generated method stub
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    } else {
         
        // 每次扫描前都先判断一下是否存在已经配对过的设备
        Set<bluetoothdevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                list.add(new ChatMessage(device.getName() + "\n" + device.getAddress(), true));
            }
        } else {
                list.add(new ChatMessage("No devices have been paired", true));
                clientAdapter.notifyDataSetChanged();
                mListView.setSelection(list.size() - 1);
         }             
             /* 开始搜索 */
             mBluetoothAdapter.startDiscovery();
    }
}</bluetoothdevice>

4. 通过Mac地址发送连接请求,在这之前必须使用cancelDiscovery()方法停止扫描。

1
2
3
4
        mBluetoothAdapter.cancelDiscovery();
 
// 通过Mac地址去尝试连接一个设备
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothMsg.BlueToothAddress);

5. 通过UUID使两个设备之间建立连接。

客户端:主动发请求

1
2
3
4
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
                
// 通过socket连接服务器,这是一个阻塞过程,直到连接建立或者连接失效
socket.connect();

服务端:接受一个请求

1
2
3
4
5
6
7
BluetoothServerSocket mServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(PROTOCOL_SCHEME_RFCOMM,
                   UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));      
            
/* 接受客户端的连接请求 */
// 这是一个阻塞过程,直到建立一个连接或者连接失效
// 通过BluetoothServerSocket得到一个BluetoothSocket对象,管理这个连接
BluetoothSocket socket = mServerSocket.accept();

6. 通过InputStream/outputStream读写数据流,已达到通信目的。

1
2
OutputStream os = socket.getOutputStream();
os.write(msg.getBytes());
1
2
3
4
5
6
7
InputStream is = null;
try {
    is = socket.getInputStream();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

7. 关闭所有线程以及socket,并关闭蓝牙设备(disable)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
        if (mClientThread != null) {
    mClientThread.interrupt();
    mClientThread = null;
}
if (mReadThread != null) {
    mReadThread.interrupt();
    mReadThread = null;
}
try {
    if (socket != null) {
        socket.close();
        socket = null;
    }
} catch (IOException e) {
    // TODO: handle exception
}
1
2
3
4
5
6
        if (mBluetoothAdapter != null) {
    mBluetoothAdapter.cancelDiscovery();
    // 关闭蓝牙
    mBluetoothAdapter.disable();
}
unregisterReceiver(mReceiver);

主要步骤就是这些,为了能够更好的理解,我将服务器端和客户端的代码分开来写了两个程序,下载地址:http://download.csdn.net/detail/visionliao/8417235

结伴旅游,一个免费的交友网站:www.jieberu.com

推推族,免费得门票,游景区:www.tuituizu.com

Android蓝牙通信的更多相关文章

  1. Android蓝牙通信总结

    这篇文章要达到的目标: 1.介绍在Android系统上实现蓝牙通信的过程中涉及到的概念. 2.在android系统上实现蓝牙通信的步骤. 3.在代码实现上的考虑. 4.例子代码实现(手持设备和蓝牙串口 ...

  2. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  3. Android蓝牙通信具体解释

    蓝牙通信的大概过程例如以下: 1.首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket.获取输入输出流 4,读取和写入数据 5.断开连接关闭蓝牙 还要发送配对码发送进行推断! 以下是全部的源码:不 ...

  4. (转)android 蓝牙通信编程

    转自:http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样 ...

  5. Android蓝牙通信功能开发

    1. 概述 Bluetooth 是几乎现在每部手机标准配备的功能,多用于耳机 mic 等设备与手机的连接,除此之外,还可以多部手机之间建立 bluetooth 通信,本文就通过 SDK 中带的一个聊天 ...

  6. android 蓝牙通信编程讲解

    以下是开发中的几个关键步骤: 1,首先开启蓝牙 2,搜索可用设备 3,创建蓝牙socket,获取输入输出流 4,读取和写入数据 5,断开连接关闭蓝牙 下面是一个demo 效果图: SearchDevi ...

  7. android 蓝牙 通信 bluetooth

    此例子基于 android demo Android的蓝牙开发,虽然不多用,但有时还是会用到,  Android对于蓝牙开发从2.0版本的sdk才开始支持,而且模拟器不支持,测试需要两部手机:     ...

  8. Android 蓝牙通信——AndroidBluetoothManager

    转载请说明出处! 作者:kqw攻城狮 出处:个人站 | CSDN To get a Git project into your build: Step 1. Add the JitPack repos ...

  9. Android BLE设备蓝牙通信框架BluetoothKit

    BluetoothKit是一款功能强大的Android蓝牙通信框架,支持低功耗蓝牙设备的连接通信.蓝牙广播扫描及Beacon解析. 关于该项目的详细文档请关注:https://github.com/d ...

随机推荐

  1. Java 日志系统

    Java 日志系统 1. 创建日志记录器 private final Logger logger = LoggerFactory.getLogger(LoggerTest.class); 2. 打印日 ...

  2. ubuntu 网卡名称重命名

    ubuntu 网卡名称重命名 参考:https://blog.csdn.net/hzj_001/article/details/81587824 biosdevname 和 net.ifnames 两 ...

  3. HTTP缓存总结

    在具体了解 HTTP 缓存之前先来明确几个术语:1.缓存命中率:从缓存中得到数据的请求数与所有请求数的比率.理想状态是越高越好.2.过期内容:超过设置的有效时间,被标记为“陈旧”的内容.通常过期内容不 ...

  4. CSS—BFC原理解析与应用

    我们在很多地方都见过BFC这个词,或许能够知道大概意思,但是有时候它的具体原理以及作用会记得很模糊,下面就对BFC这个概念深入学习下. 块级格式化上下文(Block Formatting Contex ...

  5. WebApi 跨域解决方案 --CORS

    跨站HTTP请求(Cross-site HTTP request)是指发起请求的资源所在域不同于请求指向的资源所在域的HTTP请求. 比如说,我在Web网站A(www.a.com)中通过<img ...

  6. LINUX中lrzsz软件的使用

    安装lrzsz 可以在Linux 和 windows直接相互传文件 Linux无论ssh跳过去也可以sz rz打开图像进行传输文件 [root@master2 ~]# yum install lrzs ...

  7. 用 Portainer 远程管理 docker

    参考的官网地址为:https://portainer.readthedocs.io/en/stable/deployment.html 先更新Centos docker 镜像加速地址: curl -s ...

  8. yocto 项目编译

    1. 编译整个项目 构建编译环境: ~/fsl_6dl_release$ MACHINE=imx6dlsabresd source fsl-setup-release.sh -b build-wayl ...

  9. linux基础—课堂随笔05_文本三剑客之SED

    1.简介 sed是非交互式的编辑器,它不会修改文件,除非使用shell重定向来保存结果.默认情况下,所有的输出行都被打印到屏幕上. sed编辑器逐行处理文件(或输入),并将结果发送到屏幕.具体过程如下 ...

  10. 使用幕布时,在Session过期后,弹出框加载出登陆的HTML的问题

    思路:在登陆页面判断当前加载的Url是否时login/index ,如果不是跳转到登陆页 //设置或获取对象指定的文件名或路径. var Url = window.location.pathname; ...