[置顶] Android 平台上蓝牙开发的关于 UUID 设置的注意事项

由于 Android 蓝牙的通信都需要用到 UUID,如果由手机发起搜索,当搜索到电脑的蓝牙时,能够得到蓝牙的地址(address),但通信时需要得到 BluetoothSocket,而 BluetoothSocket 则需要电脑蓝牙的 UUID,请问这个是怎么样得到的呢?

在蓝牙中,每个服务和服务属性都唯一地由"全球唯一标识符" (UUID)来校验。正如它的名字所暗示的,每一个这样的标识符都要在时空上保证唯一。UUID 类可表现为短整形(16 或 32 位)和长整形(128 位)UUID。它提供了分别利用 String 和 16 位或 32 位数值来创建类的构造函数,提供了一个可以比较两个 UUID(如果两个都是 128 位)的方法,还有一个可以转换一个 UUID 为一个字符串的方法。UUID 实例是不可改变的(immutable),只有被 UUID 标示的服务可以被发现。
 

在 Linux 下你用一个命令 uuidgen -t 可以生成一个 UUID 值;在 Windows 下则执行命令 uuidgen 。UUID 看起来就像如下的这个形式:2d266186-01fb-47c2-8d9f-10b8ec891363。当使用生成的 UUID 去创建一个 UUID 对象,你可以去掉连字符。

 

我搞定了电脑和 Android 手机的蓝牙通信问题。
首先解答几个问题
1. 两边的 UUID 必须是一样的,这是一个服务的唯一标识,而且
这个 UUID 的值必须是
00001101-0000-1000-8000-00805F9B34FB
为什么呢?因为这个是 Android 的 API 上面说明的,用于普通蓝牙适配器和 Android 手机蓝牙模块连接的,请大家自己看一下 Android 有关 bluetooth的 API。


2. 在连接的时候,如果电脑作为 server(一直监听是否有服务连接),Android 手机作为 client(主动和电脑建立连接),则需要在手机端调用这样一行代码:mmSocket.connect();
其中 mmSocket 是一个 BluetoothSocket 类,在这句话之前请确定你已经把手机和电脑进行了配对,而且那些乱七八糟的设置都搞定了。

http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html

public BluetoothSocket createInsecureRfcommSocketToServiceRecord (UUID uuid)

Since: API Level 10

Create an RFCOMM BluetoothSocket socket ready to start an insecure outgoing connection to this remote device using SDP lookup of uuid.

The communication channel will not have an authenticated link key i.e it will be subject to man-in-the-middle attacks. For Bluetooth 2.1 devices, the link key will be encrypted, as encryption is mandatory. For legacy devices (pre Bluetooth 2.1 devices) the link key will be not be encrypted. UsecreateRfcommSocketToServiceRecord(UUID) if an encrypted and authenticated communication channel is desired.

This is designed to be used with listenUsingInsecureRfcommWithServiceRecord(String, UUID) for peer-peer Bluetooth applications.

Use connect() to initiate the outgoing connection. This will also perform an SDP lookup of the given uuid to determine which channel to connect to.

The remote device will be authenticated and communication on this socket will be encrypted.

Hint: If you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if you are connecting to an Android peer then please generate your own unique UUID.

原文地址:https://www.cnblogs.com/leonxyzh/p/7289189.html