restart bluetooth Advertising - Android Bluetooth

Android examples for Bluetooth:Turn On bluetooth

Description

restart bluetooth Advertising

Demo Code


//package com.java2s;
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);
    }/*from   ww w . j  a  v  a2s.c  o m*/

    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();
    }
}

Related Tutorials