restart bluetooth Advertising - Android Phone

Android examples for Phone: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);
    }// www.  j a va2 s.  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()
        //Necessary to see friendly name in a scanning app
                .setIncludeDeviceName(true)
                //Helpful for proximity calculations
                .setIncludeTxPowerLevel(true)
                //Our custom temp data
                .addManufacturerData(MANUFACTURER_GOOGLE,
                        buildPayload(tempValue)).build();

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

    private static byte[] buildPayload(float value) {
        //Set the MSB to indicate fahrenheit
        byte flags = (byte) 0x80;
        return ByteBuffer.allocate(5)
        //GATT APIs expect LE order
                .order(ByteOrder.LITTLE_ENDIAN)
                //Add the flags byte
                .put(flags)
                //Add the temperature value
                .putFloat(value).array();
    }
}

Related Tutorials