Android端APP開啟藍(lán)牙廣播[2022-11-04]

public static final UUID BLE_ADV_SERVICE = UUID.fromString("D5C52A02-E89C-49B3-A2A3-B4FD24F1C4CA");//廣播UUID
1.廣播設(shè)置(AdvertiseSettings

AdvertiseSettings mAdvertiseSettings = new AdvertiseSettings.Builder()
        //設(shè)置廣播模式,以控制廣播的功率和延遲。
        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
        //發(fā)射功率級別
        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
        //不得超過180000毫秒。值為0將無時間限制廣播。
        .setTimeout(0)
        //設(shè)置是否可以連接
        .setConnectable(connectable)
        .build();

2.廣播包設(shè)置(AdvertiseData)

AdvertiseData mAdvertiseData = new AdvertiseData.Builder()
        .setIncludeDeviceName(true)
        .build();

3.掃描包設(shè)置(AdvertiseData)

//初始化掃描響應(yīng)包
AdvertiseData mScanResponseData = new AdvertiseData.Builder()
        //隱藏廣播設(shè)備名稱
        .setIncludeDeviceName(false)
        //設(shè)置廣播的服務(wù)UUID
        .addServiceUuid(new ParcelUuid(BLE_ADV_SERVICE))
        //設(shè)置廠商數(shù)據(jù)
        .addManufacturerData(0x11,hexStrToByte(mData))
        .build();

4.廣播回調(diào)設(shè)置(AdvertiseCallback)

private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
        public void onStartSuccess(android.bluetooth.le.AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            if (settingsInEffect != null) {
                Log.d(TAG, "開啟廣播成功onStartSuccess TxPowerLv=" + settingsInEffect.getTxPowerLevel() + "           mode=" + settingsInEffect.getMode() + " timeout=" + settingsInEffect.getTimeout());
            } else {
                Log.d(TAG, "開啟廣播成功onStartSuccess, settingInEffect is null");
            }
        }

        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.d(TAG, "開啟廣播失敗onStartFailure errorCode=" + errorCode);

              }
};

5.開啟廣播

//獲取藍(lán)牙設(shè)配器
BluetoothManager bluetoothManager = (BluetoothManager)
        getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//設(shè)置設(shè)備藍(lán)牙名稱
mBluetoothAdapter.setName("XXXXXX");
BluetoothLeAdvertiser mBluetoothAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
mBluetoothAdvertiser.startAdvertising(mAdvertiseSettings, mAdvertiseData,mScanResponseData , mAdvCallback )

參考文章

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容