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地址等,我們可以使用這些信息進行藍牙連接。

發佈了83 篇原創文章 · 獲贊 25 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章