Java Code Examples for android.bluetooth.le.AdvertiseData

The following examples show how to use android.bluetooth.le.AdvertiseData. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: connectivity-samples   Source File: AdvertiserService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts BLE Advertising.
 */
private void startAdvertising() {
    goForeground();

    Log.d(TAG, "Service: Starting Advertising");

    if (mAdvertiseCallback == null) {
        AdvertiseSettings settings = buildAdvertiseSettings();
        AdvertiseData data = buildAdvertiseData();
        mAdvertiseCallback = new SampleAdvertiseCallback();

        if (mBluetoothLeAdvertiser != null) {
            mBluetoothLeAdvertiser.startAdvertising(settings, data,
                mAdvertiseCallback);
        }
    }
}
 
Example 2
Source Project: connectivity-samples   Source File: AdvertiserService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an AdvertiseData object which includes the Service UUID and Device Name.
 */
private AdvertiseData buildAdvertiseData() {

    /**
     * Note: There is a strict limit of 31 Bytes on packets sent over BLE Advertisements.
     *  This includes everything put into AdvertiseData including UUIDs, device info, &
     *  arbitrary service or manufacturer data.
     *  Attempting to send packets over this limit will result in a failure with error code
     *  AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE. Catch this error in the
     *  onStartFailure() method of an AdvertiseCallback implementation.
     */

    AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
    dataBuilder.addServiceUuid(Constants.Service_UUID);
    dataBuilder.setIncludeDeviceName(true);

    /* For example - this will cause advertising to fail (exceeds size limit) */
    //String failureData = "asdghkajsghalkxcjhfa;sghtalksjcfhalskfjhasldkjfhdskf";
    //dataBuilder.addServiceData(Constants.Service_UUID, failureData.getBytes());

    return dataBuilder.build();
}
 
Example 3
Source Project: blefun-androidthings   Source File: GattServer.java    License: Apache License 2.0 6 votes vote down vote up
private void startAdvertising() {
    BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter();
    mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
    if (mBluetoothLeAdvertiser == null) {
        Log.w(TAG, "Failed to create advertiser");
        return;
    }

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

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

    mBluetoothLeAdvertiser
            .startAdvertising(settings, data, mAdvertiseCallback);
}
 
Example 4
/**
 * Begin advertising over Bluetooth that this device is connectable
 * and supports the Current Time Service.
 */
private void startAdvertising() {
    BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter();
    mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
    if (mBluetoothLeAdvertiser == null) {
        Log.w(TAG, "Failed to create advertiser");
        return;
    }

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

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

    mBluetoothLeAdvertiser
            .startAdvertising(settings, data, mAdvertiseCallback);
}
 
Example 5
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
/*package*/ AdvertiseData getNativeData() {
    AdvertiseData.Builder data = new AdvertiseData.Builder();
    for (UUID id : serviceUuids)
    {
        data.addServiceUuid(new ParcelUuid(id));
    }
    if (m_manufacturerId != 0 && m_manData != null)
    {
        data.addManufacturerData(m_manufacturerId, m_manData);
    }
    if (serviceData != null && serviceData.size() > 0)
    {
        for (UUID dataUuid : serviceData.keySet())
        {
            data.addServiceData(new ParcelUuid(dataUuid), serviceData.get(dataUuid));
        }
    }
    data.setIncludeDeviceName(includeDeviceName());
    data.setIncludeTxPowerLevel(includeTxPowerLevel());
    return data.build();
}
 
Example 6
Source Project: unity-bluetooth   Source File: BLEServicePeripheral.java    License: MIT License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void start(String uuidString) {
    mServiceUUID = UUID.fromString(uuidString);
    if (mBtAdvertiser == null) {
        return;
    }

    BluetoothGattService btGattService = new BluetoothGattService(mServiceUUID, BluetoothGattService.SERVICE_TYPE_PRIMARY);
    btGattService.addCharacteristic(mBtGattCharacteristic);
    BluetoothGattServerCallback btGattServerCallback = createGattServerCallback(mServiceUUID, UUID.fromString(CHARACTERISTIC_UUID));
    mBtGattServer = mBtManager.openGattServer(mActivity.getApplicationContext(), btGattServerCallback);
    mBtGattServer.addService(btGattService);

    mDataBuilder = new AdvertiseData.Builder();
    mDataBuilder.setIncludeTxPowerLevel(false);
    mDataBuilder.addServiceUuid(new ParcelUuid(mServiceUUID));

    mSettingsBuilder=new AdvertiseSettings.Builder();
    mSettingsBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
    mSettingsBuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);

    mBleAdvertiser = mBtAdapter.getBluetoothLeAdvertiser();
    mBleAdvertiser.startAdvertising(mSettingsBuilder.build(), mDataBuilder.build(), mAdvertiseCallback);
}
 
Example 7
Source Project: Android-BLE   Source File: AdvertiserRequest.java    License: Apache License 2.0 6 votes vote down vote up
public void startAdvertising(final byte[] payload, final AdvertiseSettings advertiseSettings){
    if (bluetoothAdapter.isEnabled()){
        mHandler.removeCallbacks(stopAvertiseRunnable);
        if(mAdvertiser != null){
            ThreadUtils.asyn(new Runnable() {
                @Override
                public void run() {
                    mAdvertiser.stopAdvertising(mAdvertiseCallback);
                    myAdvertiseData = new AdvertiseData.Builder()
                            .addManufacturerData(65520, payload)
                            .setIncludeDeviceName(true)
                            .build();
                    mAdvertiser.startAdvertising(advertiseSettings, myAdvertiseData, mAdvertiseCallback);
                }
            });
        }
    }
}
 
Example 8
/**
 * Starts BLE Advertising.
 */
private void startAdvertising() {
    goForeground();

    Log.d(TAG, "Service: Starting Advertising");

    if (mAdvertiseCallback == null) {
        AdvertiseSettings settings = buildAdvertiseSettings();
        AdvertiseData data = buildAdvertiseData();
        mAdvertiseCallback = new SampleAdvertiseCallback();

        if (mBluetoothLeAdvertiser != null) {
            mBluetoothLeAdvertiser.startAdvertising(settings, data,
                mAdvertiseCallback);
        }
    }
}
 
Example 9
/**
 * Returns an AdvertiseData object which includes the Service UUID and Device Name.
 */
private AdvertiseData buildAdvertiseData() {

    /**
     * Note: There is a strict limit of 31 Bytes on packets sent over BLE Advertisements.
     *  This includes everything put into AdvertiseData including UUIDs, device info, &
     *  arbitrary service or manufacturer data.
     *  Attempting to send packets over this limit will result in a failure with error code
     *  AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE. Catch this error in the
     *  onStartFailure() method of an AdvertiseCallback implementation.
     */

    AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
    dataBuilder.addServiceUuid(Constants.Service_UUID);
    dataBuilder.setIncludeDeviceName(true);

    /* For example - this will cause advertising to fail (exceeds size limit) */
    //String failureData = "asdghkajsghalkxcjhfa;sghtalksjcfhalskfjhasldkjfhdskf";
    //dataBuilder.addServiceData(Constants.Service_UUID, failureData.getBytes());

    return dataBuilder.build();
}
 
Example 10
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
/*package*/ AdvertiseData getNativeData() {
    AdvertiseData.Builder data = new AdvertiseData.Builder();
    for (UUID id : serviceUuids)
    {
        data.addServiceUuid(new ParcelUuid(id));
    }
    if (m_manufacturerId != 0 && m_manData != null)
    {
        data.addManufacturerData(m_manufacturerId, m_manData);
    }
    if (serviceData != null && serviceData.size() > 0)
    {
        for (UUID dataUuid : serviceData.keySet())
        {
            data.addServiceData(new ParcelUuid(dataUuid), serviceData.get(dataUuid));
        }
    }
    data.setIncludeDeviceName(includeDeviceName());
    data.setIncludeTxPowerLevel(includeTxPowerLevel());
    return data.build();
}
 
Example 11
Source Project: physical-web   Source File: AdvertiseDataUtils.java    License: Apache License 2.0 6 votes vote down vote up
@TargetApi(21)
public static AdvertiseData getAdvertisementData(byte[] urlData) {
  AdvertiseData.Builder builder = new AdvertiseData.Builder();
  builder.setIncludeTxPowerLevel(false); // reserve advertising space for URI

  // Manually build the advertising info
  // See https://github.com/google/eddystone/tree/master/eddystone-url
  if (urlData == null || urlData.length == 0) {
    return null;
  }

  byte[] beaconData = new byte[urlData.length + 2];
  System.arraycopy(urlData, 0, beaconData, 2, urlData.length);
  beaconData[0] = URL_FRAME_TYPE; // frame type: url
  beaconData[1] = (byte) 0xBA; // calibrated tx power at 0 m

  builder.addServiceData(EDDYSTONE_BEACON_UUID, beaconData);

  // Adding 0xFEAA to the "Service Complete List UUID 16" (0x3) for iOS compatibility
  builder.addServiceUuid(EDDYSTONE_BEACON_UUID);

  return builder.build();
}
 
Example 12
Source Project: physical-web   Source File: AdvertiseDataUtils.java    License: Apache License 2.0 6 votes vote down vote up
@TargetApi(21)
public static AdvertiseData getFatBeaconAdvertisementData(byte[] fatBeaconAdvertisement) {

  // Manually build the advertising info
  int length = Math.min(fatBeaconAdvertisement.length, 17);
  byte[] beaconData = new byte[length + 3];
  System.arraycopy(fatBeaconAdvertisement, 0, beaconData, 3, length);
  beaconData[0] = URL_FRAME_TYPE;
  beaconData[1] = (byte) 0xBA;
  beaconData[2] = FAT_BEACON;
  return new AdvertiseData.Builder()
      .setIncludeTxPowerLevel(false) // reserve advertising space for URI
      .addServiceData(EDDYSTONE_BEACON_UUID, beaconData)
      // Adding 0xFEAA to the "Service Complete List UUID 16" (0x3) for iOS compatibility
      .addServiceUuid(EDDYSTONE_BEACON_UUID)
      .build();
}
 
Example 13
Source Project: attach   Source File: DalvikBleService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void startBroadcast(String uuid, int major, int minor, String id) {
    Log.v(TAG, "Start broadcasting for uuid = "+uuid+", major = "+major+", minor = "+minor+", id = "+id);
    BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    AdvertiseSettings parameters = new AdvertiseSettings.Builder()
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
            .setConnectable(false)
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
            .build();

    byte[] payload = getPayload(uuid, major, minor);
    AdvertiseData data = new AdvertiseData.Builder()
            .addManufacturerData(0x004C, payload)
            .build();
    callback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.v(TAG, "onStartSuccess");
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.e(TAG, "Advertising onStartFailure: " + errorCode);
            super.onStartFailure(errorCode);
        }
    };

    Log.v(TAG, "Advertise with payload = " + Arrays.toString(payload));
    advertiser.startAdvertising(parameters, data, callback);
}
 
Example 14
Source Project: mobly-bundled-snippets   Source File: JsonDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static AdvertiseData jsonToBleAdvertiseData(JSONObject jsonObject) throws JSONException {
    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    if (jsonObject.has("IncludeDeviceName")) {
        builder.setIncludeDeviceName(jsonObject.getBoolean("IncludeDeviceName"));
    }
    if (jsonObject.has("IncludeTxPowerLevel")) {
        builder.setIncludeTxPowerLevel(jsonObject.getBoolean("IncludeTxPowerLevel"));
    }
    if (jsonObject.has("ServiceData")) {
        JSONArray serviceData = jsonObject.getJSONArray("ServiceData");
        for (int i = 0; i < serviceData.length(); i++) {
            JSONObject dataSet = serviceData.getJSONObject(i);
            ParcelUuid parcelUuid = ParcelUuid.fromString(dataSet.getString("UUID"));
            builder.addServiceUuid(parcelUuid);
            if (dataSet.has("Data")) {
                byte[] data = Base64.decode(dataSet.getString("Data"), Base64.DEFAULT);
                builder.addServiceData(parcelUuid, data);
            }
        }
    }
    if (jsonObject.has("ManufacturerData")) {
        JSONObject manufacturerData = jsonObject.getJSONObject("ManufacturerData");
        int manufacturerId = manufacturerData.getInt("ManufacturerId");
        byte[] manufacturerSpecificData =
                Base64.decode(jsonObject.getString("ManufacturerSpecificData"), Base64.DEFAULT);
        builder.addManufacturerData(manufacturerId, manufacturerSpecificData);
    }
    return builder.build();
}
 
Example 15
Source Project: AsteroidOSSync   Source File: L_Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean startAdvertising(BluetoothAdapter adapter, AdvertiseSettings settings, AdvertiseData adData, AdvertisingCallback callback)
{
    final BluetoothLeAdvertiser adv = adapter.getBluetoothLeAdvertiser();
    if (adv == null)
        return false;

    m_userAdvCallback = callback;
    adv.startAdvertising(settings, adData, m_nativeAdvertiseCallback);
    return true;
}
 
Example 16
@Override
public final void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, L_Util.AdvertisingCallback callback)
{
    if (!L_Util.startAdvertising(m_adaptor, settings, adData, callback))
    {
        m_bleManager.ASSERT(false, "Unable to start advertising!");
        m_bleManager.getLogger().e("Failed to start advertising!");
    }
}
 
Example 17
Source Project: beacons-android   Source File: iBeaconAdvertiser.java    License: Apache License 2.0 5 votes vote down vote up
public iBeaconAdvertiser(SettingsProvider provider, byte[] proximityUUID, int major, int minor, int flags) {
    super(provider);

    byte measuredPower = AdvertisersManager.getZeroDistanceTxPower(provider.getTxPowerLevel());
    measuredPower -= 41;

    int indicator = FLAG_APPLE == flags ? IBEACON_INDICATOR : ALTBEACON_INDICATOR;

    byte[] manufacturerData = new byte[] {
            (byte) (indicator >>> 8),
            (byte) (indicator & 0xFF),

            // ProximityUUID, 16 bytes
            0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,

            // Major
            (byte) (major >>> 8), (byte) major,

            // Minor
            (byte) (minor >>> 8), (byte) minor,

            // Measured Power
            measuredPower
    };

    // set the proximity uuid bytes
    System.arraycopy(proximityUUID, 0, manufacturerData, 2, 16);

    // an advertisement packet can have at most 31 bytes; iBeacon uses 30
    mAdvertiseData = new AdvertiseData.Builder()
            .setIncludeTxPowerLevel(false)
            .setIncludeDeviceName(false)
            .addManufacturerData(COMPANY_ID_APPLE, manufacturerData)
            .build();
}
 
Example 18
Source Project: beacons-android   Source File: GenericAdvertiser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a BLE advertiser. It does not start any actual transmission.
 */
public GenericAdvertiser(SettingsProvider provider, AdvertiseData advertiseData,
                         AdvertiseData scanResponse, String advertiseName) {
    super(provider);

    mAdvertiseData = advertiseData;
    mAdvertiseScanResponse = scanResponse;
    mAdvertiseName = advertiseName;
}
 
Example 19
Source Project: beacons-android   Source File: EddystoneAdvertiser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an Eddystone BLE advertiser. It does not start any actual transmission.
 * @param frameData              Frame data (without service data frame type or TX power bytes)
 * @param pos                    Frame data offset
 * @param len                    Frame data size
 */
public EddystoneAdvertiser(SettingsProvider provider, byte frameType, byte[] frameData,
                           int pos, int len)
{
    super(provider);

    mServiceData = new byte[2 + len];

    mServiceData[0] = frameType;
    mServiceData[1] = FRAME_TLM == frameType ? 0
            : AdvertisersManager.getZeroDistanceTxPower(provider.getTxPowerLevel());
    System.arraycopy(frameData, pos, mServiceData, 2, len);

    // an advertisement packet can have at most 31 bytes
    mAdvertiseData = new AdvertiseData.Builder()
            .setIncludeDeviceName(false)
            .setIncludeTxPowerLevel(false)
            .addServiceData(EDDYSTONE_SERVICE_UUID, mServiceData)
            .addServiceUuid(EDDYSTONE_SERVICE_UUID)
            .build();

    if (provider.isConnectable()) {
        mAdvertiseScanResponse = new AdvertiseData.Builder()
                .setIncludeDeviceName(true)
                .setIncludeTxPowerLevel(false)  // allows 3 more bytes for device name
                .addServiceUuid(new ParcelUuid(EddystoneGattService.UUID_EDDYSTONE_GATT_SERVICE))
                .build();
    }
}
 
Example 20
Source Project: DeviceConnect-Android   Source File: AbstractHOGPServer.java    License: MIT License 5 votes vote down vote up
/**
 * アドバタイジングを開始します.
 */
private void startAdvertising() {
    if (DEBUG) {
        Log.d(TAG, "startAdvertising");
    }

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            // set up advertising setting
            final AdvertiseSettings advertiseSettings = new AdvertiseSettings.Builder()
                    .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                    .setConnectable(true)
                    .setTimeout(0)
                    .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                    .build();

            // set up advertising data
            final AdvertiseData advertiseData = new AdvertiseData.Builder()
                    .setIncludeTxPowerLevel(false)
                    .setIncludeDeviceName(true)
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_DEVICE_INFORMATION.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BLE_HID.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BATTERY.toString()))
                    .build();

            // set up scan result
            final AdvertiseData scanResult = new AdvertiseData.Builder()
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_DEVICE_INFORMATION.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BLE_HID.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BATTERY.toString()))
                    .build();

            mBluetoothLeAdvertiser.startAdvertising(advertiseSettings, advertiseData, scanResult, mAdvertiseCallback);
        }
    });
}
 
Example 21
Source Project: SweetBlue   Source File: L_Util.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static boolean startAdvertising(BluetoothAdapter adapter, AdvertiseSettings settings, AdvertiseData adData, AdvertisingCallback callback)
{
    final BluetoothLeAdvertiser adv = adapter.getBluetoothLeAdvertiser();
    if (adv == null)
        return false;

    m_userAdvCallback = callback;
    adv.startAdvertising(settings, adData, m_nativeAdvertiseCallback);
    return true;
}
 
Example 22
@Override
public final void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, L_Util.AdvertisingCallback callback)
{
    if (!L_Util.startAdvertising(m_adaptor, settings, adData, callback))
    {
        m_bleManager.ASSERT(false, "Unable to start advertising!");
        m_bleManager.getLogger().e("Failed to start advertising!");
    }
}
 
Example 23
Source Project: bluetooth   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
void advertise() {
    BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
    //define the power settings  could use ADVERTISE_MODE_LOW_POWER, ADVERTISE_MODE_BALANCED too.
    AdvertiseSettings settings = new AdvertiseSettings.Builder()
        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
        .setConnectable(false)
        .build();

    ParcelUuid pUuid = new ParcelUuid(UUID.fromString(getString(R.string.ble_uuid)));

    AdvertiseData data = new AdvertiseData.Builder()
        .setIncludeDeviceName(false)
        .addServiceUuid(pUuid)
        .addServiceData(pUuid, "LE Demo".getBytes(Charset.forName("UTF-8")))
        .build();
    AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.e("BLE", "Advertising onStartFailure: " + errorCode);
            super.onStartFailure(errorCode);
        }
    };

    advertiser.startAdvertising(settings, data, advertisingCallback);
    //advertiser.stopAdvertising(advertisingCallback);
}
 
Example 24
Source Project: bluetooth   Source File: AdvertiseFragment.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * start advertise
 * setup the power levels, the UUID, and the data
 * which is used the callback then call start advertising.
 */
private void start_advertise() {

    //define the power settings  could use ADVERTISE_MODE_LOW_POWER, ADVERTISE_MODE_BALANCED too.
    AdvertiseSettings settings = new AdvertiseSettings.Builder()
        .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
        .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
        .setConnectable(false)
        .build();
    //get the UUID needed.
    ParcelUuid pUuid = new ParcelUuid(UUID.fromString(getString(R.string.blue_uuid)));
    //build
    AdvertiseData data = new AdvertiseData.Builder()
        .setIncludeDeviceName(false)  //should be true, but we are bigger then 31bytes in the name?
        .addServiceUuid(pUuid)
        //this is where the text is added.
        .addServiceData(pUuid, text.getText().toString().getBytes(Charset.forName("UTF-8")))
        .build();
    advertisingCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            logthis("Advertising has started");
            logthis("message is " + text.getText().toString());
            advertising = true;
            advertise.setText("Stop Advertising");
            super.onStartSuccess(settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            logthis("Advertising onStartFailure: " + errorCode);
            advertising = false;
            advertise.setText("Start Advertising");
            super.onStartFailure(errorCode);
        }
    };

    advertiser.startAdvertising(settings, data, advertisingCallback);

}
 
Example 25
Source Project: physical-web   Source File: FatBeaconBroadcastService.java    License: Apache License 2.0 5 votes vote down vote up
private void broadcastUrl() {
  byte[] bytes = null;
  try {
    bytes = mDisplayInfo.getBytes("UTF-8");
  } catch (UnsupportedEncodingException e) {
    Log.e(TAG, "Could not encode URL", e);
    return;
  }
  AdvertiseData advertiseData = AdvertiseDataUtils.getFatBeaconAdvertisementData(bytes);
  AdvertiseSettings advertiseSettings = AdvertiseDataUtils.getAdvertiseSettings(true);
  mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
  mBluetoothLeAdvertiser.startAdvertising(advertiseSettings, advertiseData, mAdvertiseCallback);
}
 
Example 26
Source Project: physical-web   Source File: PhysicalWebBroadcastService.java    License: Apache License 2.0 5 votes vote down vote up
private void broadcastUrl(byte[] url) {
    final AdvertiseData advertisementData = AdvertiseDataUtils.getAdvertisementData(url);
    final AdvertiseSettings advertiseSettings = AdvertiseDataUtils.getAdvertiseSettings(false);
    mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
    mBluetoothLeAdvertiser.startAdvertising(advertiseSettings,
        advertisementData, mAdvertiseCallback);
}
 
Example 27
Source Project: AndroidDemoProjects   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void advertise() {
        BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();

        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode( AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY )
                .setTxPowerLevel( AdvertiseSettings.ADVERTISE_TX_POWER_HIGH )
                .setConnectable(false)
                .build();

        ParcelUuid pUuid = new ParcelUuid( UUID.fromString( getString( R.string.ble_uuid ) ) );

        AdvertiseData data = new AdvertiseData.Builder()
                .setIncludeDeviceName( true )
                .addServiceUuid( pUuid )
                .addServiceData( pUuid, "Data".getBytes(Charset.forName("UTF-8") ) )
                .build();

        AdvertiseCallback advertisingCallback = new AdvertiseCallback() {
            @Override
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                super.onStartSuccess(settingsInEffect);
            }

            @Override
            public void onStartFailure(int errorCode) {
                Log.e( "BLE", "Advertising onStartFailure: " + errorCode );
                super.onStartFailure(errorCode);
            }
        };

        advertiser.startAdvertising( settings, data, advertisingCallback );
}
 
Example 28
/**
 * Start Bluetooth LE advertising.
 *
 * <p>This can be called multiple times, and each call is associated with a {@link
 * AdvertiseCallback} object, which is used to stop the advertising.
 *
 * @param callbackId
 * @param advertiseSettings A JSONObject representing a {@link AdvertiseSettings object}. E.g.
 *     <pre>
 *          {
 *            "AdvertiseMode": "ADVERTISE_MODE_BALANCED",
 *            "Timeout": (int, milliseconds),
 *            "Connectable": (bool),
 *            "TxPowerLevel": "ADVERTISE_TX_POWER_LOW"
 *          }
 *     </pre>
 *
 * @param advertiseData A JSONObject representing a {@link AdvertiseData} object. E.g.
 *     <pre>
 *          {
 *            "IncludeDeviceName": (bool),
 *            # JSON list, each element representing a set of service data, which is composed of
 *            # a UUID, and an optional string.
 *            "ServiceData": [
 *                      {
 *                        "UUID": (A string representation of {@link ParcelUuid}),
 *                        "Data": (Optional, The string representation of what you want to
 *                                 advertise, base64 encoded)
 *                        # If you want to add a UUID without data, simply omit the "Data"
 *                        # field.
 *                      }
 *                ]
 *          }
 *     </pre>
 *
 * @throws BluetoothLeAdvertiserSnippetException
 * @throws JSONException
 */
@RpcMinSdk(Build.VERSION_CODES.LOLLIPOP_MR1)
@AsyncRpc(description = "Start BLE advertising.")
public void bleStartAdvertising(
        String callbackId, JSONObject advertiseSettings, JSONObject advertiseData)
        throws BluetoothLeAdvertiserSnippetException, JSONException {
    if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
        throw new BluetoothLeAdvertiserSnippetException(
                "Bluetooth is disabled, cannot start BLE advertising.");
    }
    AdvertiseSettings settings = JsonDeserializer.jsonToBleAdvertiseSettings(advertiseSettings);
    AdvertiseData data = JsonDeserializer.jsonToBleAdvertiseData(advertiseData);
    AdvertiseCallback advertiseCallback = new DefaultAdvertiseCallback(callbackId);
    mAdvertiser.startAdvertising(settings, data, advertiseCallback);
    mAdvertiseCallbacks.put(callbackId, advertiseCallback);
}
 
Example 29
Source Project: beacons-android   Source File: iBeaconAdvertiser.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseData() {
    return mAdvertiseData;
}
 
Example 30
Source Project: beacons-android   Source File: Advertiser.java    License: Apache License 2.0 4 votes vote down vote up
public AdvertiseData getAdvertiseScanResponse() {
    return null;
}