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 )