歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 平台上藍牙開發的關於 UUID 設置的注意事項

Android 平台上藍牙開發的關於 UUID 設置的注意事項

日期:2017/3/1 10:11:04   编辑:Linux編程

由於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 10Create 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.

Copyright © Linux教程網 All Rights Reserved