android.bluetooth.le.AdvertiseData Java Examples

The following examples show how to use android.bluetooth.le.AdvertiseData. 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 File: AdvertiserService.java    From connectivity-samples with 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 #2
Source File: AdvertiserService.java    From connectivity-samples with 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 #3
Source File: AdvertiseDataUtils.java    From physical-web with 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 #4
Source File: AdvertiseDataUtils.java    From physical-web with 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 #5
Source File: GattServer.java    From blefun-androidthings with 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 #6
Source File: GattServerActivity.java    From sample-bluetooth-le-gattserver with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: AdvertiserService.java    From android-BluetoothAdvertisements with 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 #8
Source File: BleAdvertisingPacket.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
@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 #9
Source File: AdvertiserService.java    From android-BluetoothAdvertisements with 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 #10
Source File: BLEServicePeripheral.java    From unity-bluetooth with 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 #11
Source File: AdvertiserRequest.java    From Android-BLE with 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 #12
Source File: BleAdvertisingPacket.java    From SweetBlue with GNU General Public License v3.0 6 votes vote down vote up
@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 #13
Source File: AbstractHOGPServer.java    From DeviceConnect-Android with 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 #14
Source File: MainActivity.java    From AndroidDemoProjects with 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 #15
Source File: L_Util.java    From SweetBlue with 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
Source File: P_AndroidBluetoothManager.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@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 File: MainActivity.java    From bluetooth with 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 #18
Source File: AdvertiseFragment.java    From bluetooth with 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 #19
Source File: FatBeaconBroadcastService.java    From physical-web with 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 #20
Source File: PhysicalWebBroadcastService.java    From physical-web with 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 #21
Source File: EddystoneAdvertiser.java    From beacons-android with 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 #22
Source File: JsonDeserializer.java    From mobly-bundled-snippets with 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 #23
Source File: L_Util.java    From AsteroidOSSync with 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 #24
Source File: GenericAdvertiser.java    From beacons-android with 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 #25
Source File: P_AndroidBluetoothManager.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: iBeaconAdvertiser.java    From beacons-android with 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 #27
Source File: EddystoneAdvertiser.java    From beacons-android with Apache License 2.0 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseData() {
    return mAdvertiseData;
}
 
Example #28
Source File: DalvikBleService.java    From attach with GNU General Public License v3.0 4 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 #29
Source File: BluetoothLeAdvertiserSnippet.java    From mobly-bundled-snippets with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #30
Source File: BeaconTransmitter.java    From android-beacon-library with Apache License 2.0 4 votes vote down vote up
/**
 * Starts this beacon advertising
 */
public void startAdvertising() {
    if (mBeacon == null) {
        throw new NullPointerException("Beacon cannot be null.  Set beacon before starting advertising");
    }
    int manufacturerCode = mBeacon.getManufacturer();
    int serviceUuid = -1;
    if (mBeaconParser.getServiceUuid() != null) {
        serviceUuid = mBeaconParser.getServiceUuid().intValue();
    }

    if (mBeaconParser == null) {
        throw new NullPointerException("You must supply a BeaconParser instance to BeaconTransmitter.");
    }

    byte[] advertisingBytes = mBeaconParser.getBeaconAdvertisementData(mBeacon);
    String byteString = "";
    for (int i= 0; i < advertisingBytes.length; i++) {
        byteString += String.format("%02X", advertisingBytes[i]);
        byteString += " ";
    }
    LogManager.d(TAG, "Starting advertising with ID1: %s ID2: %s ID3: %s and data: %s of size "
                    + "%s", mBeacon.getId1(),
                    mBeacon.getIdentifiers().size() > 1 ? mBeacon.getId2() : "",
                    mBeacon.getIdentifiers().size() > 2 ? mBeacon.getId3() : "", byteString,
            advertisingBytes.length);

    try{
        AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
        if (serviceUuid > 0) {
            byte[] serviceUuidBytes = new byte[] {
                    (byte) (serviceUuid & 0xff),
                    (byte) ((serviceUuid >> 8) & 0xff)};
            ParcelUuid parcelUuid = parseUuidFrom(serviceUuidBytes);
            dataBuilder.addServiceData(parcelUuid, advertisingBytes);
            dataBuilder.addServiceUuid(parcelUuid);
            dataBuilder.setIncludeTxPowerLevel(false);
            dataBuilder.setIncludeDeviceName(false);

        } else {
            dataBuilder.addManufacturerData(manufacturerCode, advertisingBytes);
        }

        AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();

        settingsBuilder.setAdvertiseMode(mAdvertiseMode);
        settingsBuilder.setTxPowerLevel(mAdvertiseTxPowerLevel);
        settingsBuilder.setConnectable(mConnectable);

        mBluetoothLeAdvertiser.startAdvertising(settingsBuilder.build(), dataBuilder.build(), getAdvertiseCallback());
        LogManager.d(TAG, "Started advertisement with callback: %s", getAdvertiseCallback());

    } catch (Exception e){
        LogManager.e(e, TAG, "Cannot start advertising due to exception");
    }
}