start Bluetooth Advertising - Android Phone

Android examples for Phone:Bluetooth

Description

start 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 startAdvertising(BluetoothLeAdvertiser advertiser,
            AdvertiseCallback callback, float tempValue) {
        if (advertiser == null)
            return;

        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
                .setConnectable(false)//from   w  w  w. ja  v  a 2s. c o  m
                .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