1. 程式人生 > >Android BLE學習(一): Android搜尋BLE裝置

Android BLE學習(一): Android搜尋BLE裝置

背景

總結一下最近ble的學習情況。自從入手ble 51822開發板後就開始不停加班,中途出於好奇,業餘時間寫了一些微控制器上json解析相關的東西,妄圖使用藍芽傳輸json資料,不知道是否實用,既然開始寫了,得寫出點樣子,晃晃蕩蕩,2016年的1月份就過去了。

這裡本章我們主要總結一下ble搜尋相關的內容,先建立直觀印象,然後剖析ble模組與Android相關程式碼,看看原始碼與現象是如何對應的。最後,當我們瞭解流程後,就可以比較容易地理解藍芽協議中的一些內容,最終實現照我們自己的需求建立協議,開發屬於我們自己的模組的目的。

51822中自帶了藍芽協議棧,協議棧也規定了程式的框架,感覺這樣的好處就是簡化了開發流程,我們可以按照能跑通的demo進行修改即可,方便學習。

Android BLE 搜尋

BluetoothAdapter

以下是android官方對這個類的介紹

Represents the local device Bluetooth adapter. The BluetoothAdapter lets you perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address, and create a BluetoothServerSocket to listen for connection requests from other devices, and start a scan for Bluetooth LE devices.

To get a BluetoothAdapter representing the local Bluetooth adapter, when running on JELLY_BEAN_MR1 and below, call the static getDefaultAdapter() method; when running on JELLY_BEAN_MR2 and higher, retrieve it through getSystemService(String) with BLUETOOTH_SERVICE. Fundamentally, this is your starting point for all Bluetooth actions. Once you have the local adapter, you can get a set of BluetoothDevice objects representing all paired devices with getBondedDevices(); start device discovery with startDiscovery(); or create a BluetoothServerSocket to listen for incoming connection requests with listenUsingRfcommWithServiceRecord(String, UUID); or start a scan for Bluetooth LE devices with startLeScan(LeScanCallback).

大意在講這個類代表了本地藍芽介面卡,可以對藍芽進行一些基本操作,比如:
1.發現裝置
2.獲取配對裝置列表
3.獲取裝置mac地址
4.建立監聽
5.搜尋BLE裝置

我們所需要的就是其搜尋BLE裝置的功能。這也就是為什麼我們的Android程式在執行時只能看到ble裝置而看不到其他一些藍芽裝置的原因。

下面看一下我們需要用到搜尋ble裝置的API

boolean startLeScan(BluetoothAdapter.LeScanCallback callback)

啟動搜尋BLE裝置

boolean startLeScan(UUID[] serviceUuids, BluetoothAdapter.LeScanCallback callback)

搜尋指定serviceUUID的BLE裝置

void stopLeScan(BluetoothAdapter.LeScanCallback callback)

停止收索BLE裝置

其中的回撥函式就是收索到裝置後進行的回撥。

BlueToothAdapter通過BluetoothManager的getAdapter()方法獲取例項,具體程式碼如下:

final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

mBluetoothAdapter = bluetoothManager.getAdapter();

搜尋流程

Created with Raphaël 2.1.0開始開啟藍芽裝置檢查BLE裝置是否可用BLE裝置可用?開始搜尋BLE裝置並獲取相關資訊結束yesno

開啟藍芽裝置

這裡我們使用一個Intent來開啟系統牙,此處我們還需要為應用新增藍芽相關許可權

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

開啟藍芽,返回時接收Result,用於顯示藍芽是否開啟成功。

Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 1);

檢查BLE是否可用

private void checkBLEDevice(){
 // Use this check to determine whether BLE is supported on the device.  Then you can
 // selectively disable BLE-related features.
      if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, " ble not supported ", Toast.LENGTH_SHORT).show();
            finish();
}

// Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
// BluetoothAdapter throughBluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
        Toast.makeText(this, " ble not supported ", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
}

搜尋

mBluetoothAdapter.stopLeScan(mBLEScanCallback);//啟動搜尋BLE裝置

mBluetoothAdapter.startLeScan(mBLEScanCallback);//停止搜尋BLE裝置

當收索到內容時,將呼叫我們設定的回撥函式。可以得到訊號強度和BLE裝置資訊以及廣播內容。

new BluetoothAdapter.LeScanCallback(){
            @Override
            public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {

                Log.i("MainActivity", device.getAddress());
                addBLEDeviceData(device, rssi);

            }
        };

VONCHENCHEN_BLE就是我們的51822 BLE裝置。

VONCHENCHEN_BLE就是我們的51822 BLE裝置

小結

至此,我們就完成了BLE裝置的搜尋,總結一下就是使用BluetoothAdapter類提供的方法完成對BLE裝置的掃描,獲取到BLE裝置的相關資訊,如裝置名字和Mac地址等,我們可以使用這些資訊進行藍芽連線。