如何设置BLE广告包的设备名称字段

时间:2017-11-10 19:26:39

标签: android bluetooth-lowenergy

我使用API​​来构建广告包。我将true传递给setIncludeDeviceName

    AdvertiseData data = new AdvertiseData.Builder()
            .setIncludeDeviceName(true)
            .setIncludeTxPowerLevel(false)
            .addServiceUuid(new ParcelUuid(TimeProfile.TIME_SERVICE))
            .build();

API对广告包中的设备型号进行编码。但是对于我的应用程序,广告包的设备名称应该来自硬编码到应用程序中的字符串

private static final String DEVICE_NAME = "My_Device_Name";

有没有办法在广告包中自定义设备名称?我在AdvertiseDataAdvertiseData.Builder

的文档中看不到任何方法

2 个答案:

答案 0 :(得分:0)

非常确定你必须使用BluetoothAdapter.setName(String name);方法。

答案 1 :(得分:0)

您必须从数据 AdvertiseData中删除" setIncludeDeviceName" 对象并定义扫描响应AdvertiseData对象

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

然后使用scanResponse开始广告

bluetoothAdapter.getBluetoothLeAdvertiser()
          .startAdvertising(advSettings, data, scanResponse, advCallback);

完整示例:

AdvertiseSettings advSettings = new AdvertiseSettings.Builder()
    .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
    .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
    .setConnectable(true)
    .build();

AdvertiseData advData = new AdvertiseData.Builder()
    .setIncludeTxPowerLevel(true)
    .addServiceUuid(mCurrentServiceFragment.getServiceUUID())
    .build();

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

AdvertiseCallback advCallback = new AdvertiseCallback() {
    @Override
    public void onStartFailure(int errorCode) {
        super.onStartFailure(errorCode);
        Log.e(TAG, "Not broadcasting: " + errorCode);
        int statusText;
        switch (errorCode) {
            case ADVERTISE_FAILED_ALREADY_STARTED:
                Log.w(TAG, "ADVERTISE_FAILED_ALREADY_STARTED");
                break;
            case ADVERTISE_FAILED_DATA_TOO_LARGE:
                Log.w(TAG, "ADVERTISE_FAILED_DATA_TOO_LARGE");
                break;
            case ADVERTISE_FAILED_FEATURE_UNSUPPORTED:
                Log.w(TAG, "ADVERTISE_FAILED_FEATURE_UNSUPPORTED");
                break;
            case ADVERTISE_FAILED_INTERNAL_ERROR:
                Log.w(TAG, "ADVERTISE_FAILED_INTERNAL_ERROR");
                break;
            case ADVERTISE_FAILED_TOO_MANY_ADVERTISERS:
                Log.w(TAG, "ADVERTISE_FAILED_TOO_MANY_ADVERTISERS");
                break;
            default:
                Log.wtf(TAG, "Unhandled error: " + errorCode);
        }
    }

    @Override
    public void onStartSuccess(AdvertiseSettings settingsInEffect) {
        super.onStartSuccess(settingsInEffect);
        Log.v(TAG, "Advertising started");
    }
};

bluetoothAdapter.getBluetoothLeAdvertiser()
          .startAdvertising(advSettings, advData, advScanResponse, advCallback);