安卓(Android) 怎么重新启动蓝牙广告(Advertising)

2019年10月25日21:53:59安卓(Android) 怎么重新启动蓝牙广告(Advertising)已关闭评论 411 1483字阅读4分56秒

1.简介

安卓(Android) 怎么重新启动蓝牙广告(Advertising)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    public static final int MANUFACTURER_GOOGLE = 0x00E0;

    public static void restartAdvertising(BluetoothLeAdvertiser advertiser,
            AdvertiseCallback callback, float newTempValue) {
        stopAdvertising(advertiser, callback);
        startAdvertising(advertiser, callback, newTempValue);
    }

    public static void stopAdvertising(BluetoothLeAdvertiser advertiser,
            AdvertiseCallback callback) {
        if (advertiser == null)
            return;

        advertiser.stopAdvertising(callback);
    }

    public static void startAdvertising(BluetoothLeAdvertiser advertiser,
            AdvertiseCallback callback, float tempValue) {
        if (advertiser == null)
            return;

        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                .setConnectable(false)
                .setTimeout(0)
                .setTxPowerLevel(
                        AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
                .build();

        AdvertiseData data = new AdvertiseData.Builder()
                .setIncludeDeviceName(true)
                .setIncludeTxPowerLevel(true)
                .addManufacturerData(MANUFACTURER_GOOGLE,
                        buildPayload(tempValue)).build();

        advertiser.startAdvertising(settings, data, callback);
    }

    private static byte[] buildPayload(float value) {
        byte flags = (byte) 0x80;
        return ByteBuffer.allocate(5)
                .order(ByteOrder.LITTLE_ENDIAN)
                .put(flags)
                .putFloat(value).array();
    }
}

 
继续阅读
编程十万个怎么办