public static final UUID BLE_ADV_SERVICE = UUID.fromString("D5C52A02-E89C-49B3-A2A3-B4FD24F1C4CA");//广播UUID
1.广播设置(AdvertiseSettings
)
AdvertiseSettings mAdvertiseSettings = new AdvertiseSettings.Builder()
//设置广播模式,以控制广播的功率和延迟。
.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
//发射功率级别
.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
//不得超过180000毫秒。值为0将无时间限制广播。
.setTimeout(0)
//设置是否可以连接
.setConnectable(connectable)
.build();
2.广播包设置(AdvertiseData
)
AdvertiseData mAdvertiseData = new AdvertiseData.Builder()
.setIncludeDeviceName(true)
.build();
3.扫描包设置(AdvertiseData
)
//初始化扫描响应包
AdvertiseData mScanResponseData = new AdvertiseData.Builder()
//隐藏广播设备名称
.setIncludeDeviceName(false)
//设置广播的服务UUID
.addServiceUuid(new ParcelUuid(BLE_ADV_SERVICE))
//设置厂商数据
.addManufacturerData(0x11,hexStrToByte(mData))
.build();
4.广播回调设置(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.开启广播
//获取蓝牙设配器
BluetoothManager bluetoothManager = (BluetoothManager)
getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//设置设备蓝牙名称
mBluetoothAdapter.setName("XXXXXX");
BluetoothLeAdvertiser mBluetoothAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
mBluetoothAdvertiser.startAdvertising(mAdvertiseSettings, mAdvertiseData,mScanResponseData , mAdvCallback )