Java Code Examples for android.bluetooth.le.AdvertiseData

The following are top voted examples for showing how to use android.bluetooth.le.AdvertiseData. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: IBeaconBroadcastDemo   File: MainActivity.java   Source Code and License 7 votes vote down vote up
public AdvertiseData createAdvertiseData(UUID proximityUuid, int major,
                                         int minor, byte txPower) {
    if (proximityUuid == null) {
        throw new IllegalArgumentException("proximitiUuid null");
    }
    byte[] manufacturerData = new byte[23];
    ByteBuffer bb = ByteBuffer.wrap(manufacturerData);
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.put((byte) 0x02);
    bb.put((byte) 0x15);
    bb.putLong(proximityUuid.getMostSignificantBits());
    bb.putLong(proximityUuid.getLeastSignificantBits());
    bb.putShort((short) major);
    bb.putShort((short) minor);
    bb.put(txPower);

    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    builder.addManufacturerData(0x004c, manufacturerData);
    AdvertiseData adv = builder.build();
    return adv;
}
 
Example 2
Project: RangeThings   File: GattServer.java   Source Code and License 7 votes vote down vote up
private void startAdvertising() {
    if (mBluetoothLeAdvertiser == null) 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(GattProfile.SERVICE_UUID))
            .build();

    mBluetoothLeAdvertiser.startAdvertising(settings, data, mAdvertiseCallback);
}
 
Example 3
Project: SweetBlue   File: BleAdvertisingPacket.java   Source Code and License 7 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 4
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 6 votes vote down vote up
public BtError startServer(){
	BtError error = checkBluetooth();
	if(error != BtError.None)
		return error;
	bleAdvertiser = btAdapter.getBluetoothLeAdvertiser();
	gattServer = btManager.openGattServer(context, gattServerCallback);
	for(BluetoothGattService service : services){
		gattServer.addService(service);
	}
	if(bleAdvertiser == null)
		return BtError.NoServer;
	AdvertiseSettings.Builder settings = new AdvertiseSettings.Builder();
	settings.setAdvertiseMode(advertiseMode);
	settings.setConnectable(true);
	settings.setTimeout(0);
	settings.setTxPowerLevel(advertiseTransmitPower);
	AdvertiseData.Builder data = new AdvertiseData.Builder();
	data.setIncludeDeviceName(advertiseDeviceName);
	//data.addServiceUuid(new ParcelUuid(SERVICE_COMMUNICATION));
	bleAdvertiser.startAdvertising(settings.build(), data.build(), advertiseCallback);
	serverRunning = true;
	return BtError.None;
}
 
Example 5
Project: blefun-androidthings   File: GattServer.java   Source Code and License 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
Project: sample-bluetooth-le-gattserver   File: GattServerActivity.java   Source Code and License 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
Project: BleUARTPeripheral   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void startAdvertising() {
    if (mBluetoothLeAdvertiser == null) 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)
            .addServiceUuid(new ParcelUuid(UARTProfile.UART_SERVICE))
            .build();

    mBluetoothLeAdvertiser.startAdvertising(settings, data, mAdvertiseCallback);
}
 
Example 8
Project: AsteroidOSSync   File: BleAdvertisingPacket.java   Source Code and License 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
Project: unity-bluetooth   File: BLEServicePeripheral.java   Source Code and 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 10
Project: Quick-Bluetooth-LE   File: BLEServer.java   Source Code and License 6 votes vote down vote up
public BtError startServer(){
	BtError error = checkBluetooth();
	if(error != BtError.None)
		return error;
	bleAdvertiser = btAdapter.getBluetoothLeAdvertiser();
	gattServer = btManager.openGattServer(context, gattServerCallback);
	for(BluetoothGattService service : services){
		gattServer.addService(service);
	}
	if(bleAdvertiser == null)
		return BtError.NoServer;
	AdvertiseSettings.Builder settings = new AdvertiseSettings.Builder();
	settings.setAdvertiseMode(advertiseMode);
	settings.setConnectable(true);
	settings.setTimeout(0);
	settings.setTxPowerLevel(advertiseTransmitPower);
	AdvertiseData.Builder data = new AdvertiseData.Builder();
	data.setIncludeDeviceName(advertiseDeviceName);
	//data.addServiceUuid(new ParcelUuid(SERVICE_COMMUNICATION));
	bleAdvertiser.startAdvertising(settings.build(), data.build(), advertiseCallback);
	serverRunning = true;
	return BtError.None;
}
 
Example 11
Project: beacons-android   File: EddystoneAdvertiser.java   Source Code and License 6 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 12
Project: physical-web   File: AdvertiseDataUtils.java   Source Code and License 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 13
Project: physical-web   File: AdvertiseDataUtils.java   Source Code and License 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 14
Project: mDL-ILP   File: BLEConnection.java   Source Code and License 5 votes vote down vote up
private void startAdvertising() {
    AdvertiseSettings advSettings = new AdvertiseSettings.Builder()
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
            .setConnectable(true)
            .build();

    AdvertiseData advData = new AdvertiseData.Builder()
            .setIncludeTxPowerLevel(true)
            .addServiceUuid(Constants.SERVICE_pUUID)
            .addServiceData(Constants.SERVICE_pUUID, serviceData)
            .build();

    AdvertiseData advScanResponse = new AdvertiseData.Builder()
            .setIncludeDeviceName(true)
            .build();

    if (mAdvertiser != null) {
        gattService.startAdvertising();
        mAdvertiser.startAdvertising(advSettings, advData, advScanResponse, advCallback);
        Log.d(TAG, "Started advertisement of mDL service with data " + new String(serviceData));
    } else {
        Log.e(TAG, "mAdvertiser not available!");
    }
}
 
Example 15
Project: Udhari   File: BTEndPoint.java   Source Code and License 5 votes vote down vote up
public BTEndPoint(String id, String content, String details) {
    super(id);
    this.content = content;
    this.details = details;
    this.type=this.getClass().getSimpleName();
    AdvertiseData data;
}
 
Example 16
Project: mobly-bundled-snippets   File: JsonDeserializer.java   Source Code and License 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 17
Project: noise   File: BluetoothSyncService.java   Source Code and License 5 votes vote down vote up
private AdvertiseData buildAdvertiseData() {
    AdvertiseData.Builder builder = new AdvertiseData.Builder();

    // We are including this device's physical MAC address in the advertisement to enable higher bandwidth pair-free communication over Bluetooth Classic sockets.
    // While our communications will always be anonymous by design, this still has privacy implications:
    // If an attacker manages to associate an address with a person, they will be able to determine if that person is nearby as long as the app is installed on that phone.
    builder.addServiceUuid(new ParcelUuid(serviceUuidAndAddress));
    // TODO: Include some portion of the sync bit string/Bloom filter from the database
    builder.setIncludeDeviceName(false);
    return builder.build();
}
 
Example 18
Project: BLE-HID-Peripheral-for-Android   File: HidPeripheral.java   Source Code and License 5 votes vote down vote up
/**
 * Starts advertising
 */
public final void startAdvertising() {
    handler.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 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 Builder()
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_DEVICE_INFORMATION.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BLE_HID.toString()))
                    .addServiceUuid(ParcelUuid.fromString(SERVICE_BATTERY.toString()))
                    .build();

            Log.d(TAG, "advertiseData: " + advertiseData + ", scanResult: " + scanResult);
            bluetoothLeAdvertiser.startAdvertising(advertiseSettings, advertiseData, scanResult, advertiseCallback);
        }
    });
}
 
Example 19
Project: mesh-core-on-android   File: JniCallbacks.java   Source Code and License 5 votes vote down vote up
private AdvertiseData createAdvertiseData(ParcelUuid uuid, byte[] serviceData){		 
	AdvertiseData.Builder mDataBuilder = new AdvertiseData.Builder();
	mDataBuilder.addServiceUuid(uuid);
mDataBuilder.addServiceData(uuid, serviceData);
AdvertiseData mAdvertiseData = mDataBuilder.build();

if(mAdvertiseData==null){
	Log.e(TAG, "mAdvertiseSettings == null");
}
return mAdvertiseData;
  }
 
Example 20
Project: BLEServerSimple   File: AdvertiseAdaptor.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private AdvertiseData makeAdvertiseData() {

    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    //加入自定的service uuid
    builder.addServiceUuid(new ParcelUuid(UUID.fromString(SERVICE_UUID)));

    //設定用device name顯示為ble的local name
    builder.setIncludeDeviceName(true);

    return builder.build();
}
 
Example 21
Project: coinblesk-client-gui   File: BluetoothLEServer.java   Source Code and License 5 votes vote down vote up
private void startAdvertisingService(final UUID uuid) {
    if (bluetoothLeAdvertiseCallbacks == null) {
        bluetoothLeAdvertiseCallbacks = new ArrayList<>();
    }

    AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            Log.d(TAG, "BLE advertising - uuid: " + uuid.toString()
                    + " - onStartSuccess - settings: " + settingsInEffect.toString());
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.w(TAG, "BLE advertising - uuid: " + uuid.toString()
                    + " - onStartFailure - errorCode=" + errorCode);
        }
    };
    bluetoothLeAdvertiseCallbacks.add(advertiseCallback);

    bluetoothAdapter.getBluetoothLeAdvertiser().startAdvertising(
            new AdvertiseSettings.Builder()
                    .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                    .setConnectable(true)
                    .setTimeout(0)
                    .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
                    .build(),
            new AdvertiseData.Builder()
                    .setIncludeDeviceName(false)
                    .addServiceUuid(new ParcelUuid(uuid))
                    .build(),
            advertiseCallback
    );
}
 
Example 22
Project: AsteroidOSSync   File: P_AndroidBluetoothManager.java   Source Code and License 5 votes vote down vote up
@Override
public final void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, AdvertiseCallback callback)
{
    final BluetoothLeAdvertiser ad = L_Util.getBluetoothLeAdvertiser(m_adaptor);
    if (ad != null)
    {
        ad.startAdvertising(settings, adData, callback);
    }
    else
    {
        m_bleManager.getLogger().e("Tried to start advertising, but the BluetoothLeAdvertiser was null!");
    }
}
 
Example 23
Project: BLE-Mesh   File: BLEPeripheral.java   Source Code and License 5 votes vote down vote up
private AdvertiseData createAdvData() {
        AdvertiseData.Builder builder = new AdvertiseData.Builder();
        builder.addServiceUuid(new ParcelUuid(serviceUUID));
        builder.setIncludeTxPowerLevel(false);
//        builder.setManufacturerData(0x1234578, manufacturerData);
        return builder.build();
    }
 
Example 24
Project: beacons-android   File: iBeaconAdvertiser.java   Source Code and License 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 25
Project: beacons-android   File: GenericAdvertiser.java   Source Code and License 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 26
Project: DeviceConnect-Android   File: AbstractHOGPServer.java   Source Code and 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 27
Project: ble-android-sdk   File: LBleAdvertiser.java   Source Code and License 5 votes vote down vote up
@Override
public void startAdvertising(String uuid, List<ScanResult> closestBeaconId, String fallbackUrl) {
    stopAdvertising();
    advertiser.startAdvertising(
            new AdvertiseSettings.Builder().setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED).build(),
            new AdvertiseData.Builder().addServiceUuid(ParcelUuid.fromString(uuid)).build(),
            callback
    );
}
 
Example 28
Project: swan-sense-studio   File: BLEManager.java   Source Code and License 5 votes vote down vote up
private void advertise() throws ExpressionParseException {
    final BluetoothLeAdvertiser bleAdvertiser = btAdapter.getBluetoothLeAdvertiser();
    AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder().setIncludeDeviceName(true);

    for(Map.Entry<String, String> expressionEntry : registeredExpressions.entrySet()) {
        SensorValueExpression svExpression = (SensorValueExpression) ExpressionFactory.parse(expressionEntry.getValue());
        String sensorValuePath = svExpression.getEntity() + ":" + svExpression.getValuePath();
        UUID serviceUuid = getUuidForSensorValuePath(sensorValuePath);
        dataBuilder.addServiceUuid(new ParcelUuid(serviceUuid));
    }

    bleAdvertiser.startAdvertising(advertiseSettings, dataBuilder.build(), advertisingCallback);
}
 
Example 29
Project: Scatterbrain   File: BleUtil.java   Source Code and License 5 votes vote down vote up
public static AdvertiseData makeAdvertiseData(String message) {
    while (message.length() < 9)
    {
        message += " ";
    }
    byte[] data = message.substring(2).getBytes();
    ParcelUuid pu = ParcelUuid.fromString("0000" + asHex(message.substring(0,2).getBytes()) + "-0000-1000-8000-00805F9B34FB");
    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    builder.addServiceData(pu, data);
    builder.addServiceUuid(pu);

    return builder.build();
}
 
Example 30
Project: SweetBlue   File: L_Util.java   Source Code and License 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 31
Project: SweetBlue   File: P_AndroidBluetoothManager.java   Source Code and License 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 32
Project: physical-web   File: FatBeaconBroadcastService.java   Source Code and License 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 33
Project: physical-web   File: PhysicalWebBroadcastService.java   Source Code and License 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 34
Project: mobly-bundled-snippets   File: BluetoothLeAdvertiserSnippet.java   Source Code and License 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 35
Project: AsteroidOSSync   File: UnitTestManagerLayer.java   Source Code and License 4 votes vote down vote up
@Override
public void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, AdvertiseCallback callback)
{
}
 
Example 36
Project: AndroidBluttoothMasterAndSlave   File: BLEAdvertiser.java   Source Code and License 4 votes vote down vote up
private void initAdvertiseData() {
    //初始化Advertise的设定
    Context mContext = contextWeakReference.get();
    if (mContext == null) {
        prepared = false;
        return;
    }
    BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
    advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
    advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.d(TAG, "["+
                    Thread.currentThread().getStackTrace()[2].getFileName() + "_" +
                    Thread.currentThread().getStackTrace()[2].getLineNumber() + "_" +
                    Thread.currentThread().getStackTrace()[2].getMethodName() + "]");
            Log.i(TAG, "onStartSuccess success");

            advertiseResultListener.onAdvertiseSuccess();

            if (settingsInEffect != null) {
                Log.d(TAG, "onStartSuccess TxPowerLv=" + settingsInEffect.getTxPowerLevel() + " mode=" + settingsInEffect.getMode()
                        + " timeout=" + settingsInEffect.getTimeout());
            } else {
                Log.e(TAG, "onStartSuccess, settingInEffect is null");
            }
            Log.i(TAG, "onStartSuccess settingsInEffect" + settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.e(TAG, "Advertise failed.Error code: " + errorCode);
            advertiseResultListener.onAdvertiseFailed(errorCode);
        }
    };
    AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
    settingsBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY);//ADVERTISE_MODE_BALANCED origin
    settingsBuilder.setConnectable(true);
    settingsBuilder.setTimeout(0);
    settingsBuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);// ADVERTISE_TX_POWER_MEDIUM origin
    advertiseSettings = settingsBuilder.build();
    AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
    dataBuilder.setIncludeDeviceName(true);
    dataBuilder.addServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE));
    advertiseData = dataBuilder.build();
    prepared = true;
}
 
Example 37
Project: Android-BLE-Library   File: BLEAdvertiser.java   Source Code and License 4 votes vote down vote up
private void initAdvertiseData() {
    //初始化Advertise的设定
    Context mContext = contextWeakReference.get();
    if (mContext == null) {
        prepared = false;
        return;
    }
    BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
    advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
    advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.i(TAG, "Advertise success");

            advertiseResultListener.onAdvertiseSuccess();

            if (settingsInEffect != null) {
                Log.d(TAG, "onStartSuccess TxPowerLv=" + settingsInEffect.getTxPowerLevel() + " mode=" + settingsInEffect.getMode()
                        + " timeout=" + settingsInEffect.getTimeout());
            } else {
                Log.e(TAG, "onStartSuccess, settingInEffect is null");
            }
            Log.i(TAG, "onStartSuccess settingsInEffect" + settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.e(TAG, "Advertise failed.Error code: " + errorCode);
            advertiseResultListener.onAdvertiseFailed(errorCode);
        }
    };
    AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
    settingsBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
    settingsBuilder.setConnectable(true);
    settingsBuilder.setTimeout(0);
    settingsBuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM);
    advertiseSettings = settingsBuilder.build();
    AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
    dataBuilder.setIncludeDeviceName(true);
    dataBuilder.addServiceUuid(ParcelUuid.fromString(BLEProfile.UUID_SERVICE));
    advertiseData = dataBuilder.build();
    prepared = true;
}
 
Example 38
Project: beacons-android   File: iBeaconAdvertiser.java   Source Code and License 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseData() {
    return mAdvertiseData;
}
 
Example 39
Project: beacons-android   File: Advertiser.java   Source Code and License 4 votes vote down vote up
public AdvertiseData getAdvertiseScanResponse() {
    return null;
}
 
Example 40
Project: beacons-android   File: GenericAdvertiser.java   Source Code and License 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseData() {
    return mAdvertiseData;
}
 
Example 41
Project: beacons-android   File: GenericAdvertiser.java   Source Code and License 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseScanResponse() {
    return mAdvertiseScanResponse;
}
 
Example 42
Project: beacons-android   File: EddystoneAdvertiser.java   Source Code and License 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseData() {
    return mAdvertiseData;
}
 
Example 43
Project: beacons-android   File: EddystoneAdvertiser.java   Source Code and License 4 votes vote down vote up
@Override
public AdvertiseData getAdvertiseScanResponse() {
    return mAdvertiseScanResponse;
}
 
Example 44
Project: ble-test-peripheral-android   File: Peripheral.java   Source Code and License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_peripherals);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  mAdvStatus = (TextView) findViewById(R.id.textView_advertisingStatus);
  mConnectionStatus = (TextView) findViewById(R.id.textView_connectionStatus);
  mBluetoothDevices = new HashSet<>();
  mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  mBluetoothAdapter = mBluetoothManager.getAdapter();

  // If we are not being restored from a previous state then create and add the fragment.
  if (savedInstanceState == null) {
    int peripheralIndex = getIntent().getIntExtra(Peripherals.EXTRA_PERIPHERAL_INDEX,
        /* default */ -1);
    if (peripheralIndex == 0) {
      mCurrentServiceFragment = new BatteryServiceFragment();
    } else if (peripheralIndex == 1) {
      mCurrentServiceFragment = new HeartRateServiceFragment();
    } else if (peripheralIndex == 2) {
      mCurrentServiceFragment = new HealthThermometerServiceFragment();
    } else {
      Log.wtf(TAG, "Service doesn't exist");
    }
    getFragmentManager()
        .beginTransaction()
        .add(R.id.fragment_container, mCurrentServiceFragment, CURRENT_FRAGMENT_TAG)
        .commit();
  } else {
    mCurrentServiceFragment = (ServiceFragment) getFragmentManager()
        .findFragmentByTag(CURRENT_FRAGMENT_TAG);
  }
  mBluetoothGattService = mCurrentServiceFragment.getBluetoothGattService();

  mAdvSettings = new AdvertiseSettings.Builder()
      .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED)
      .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
      .setConnectable(true)
      .build();
  mAdvData = new AdvertiseData.Builder()
      .setIncludeTxPowerLevel(true)
      .addServiceUuid(mCurrentServiceFragment.getServiceUUID())
      .build();
  mAdvScanResponse = new AdvertiseData.Builder()
      .setIncludeDeviceName(true)
      .build();
}
 
Example 45
Project: SweetBlue   File: UnitTestManagerLayer.java   Source Code and License 4 votes vote down vote up
@Override
public void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, L_Util.AdvertisingCallback callback)
{
    NativeUtil.setToAdvertising(BleManager.s_instance, settings, callback);
}
 
Example 46
Project: android-beacon-library   File: BeaconTransmitter.java   Source Code and License 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(false);

        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");
    }
}
 
Example 47
Project: AsteroidOSSync   File: P_NativeManagerLayer.java   Source Code and License votes vote down vote up
void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, AdvertiseCallback callback); 
Example 48
Project: beacons-android   File: Advertiser.java   Source Code and License votes vote down vote up
public abstract AdvertiseData getAdvertiseData(); 
Example 49
Project: SweetBlue   File: P_NativeManagerLayer.java   Source Code and License votes vote down vote up
void startAdvertising(AdvertiseSettings settings, AdvertiseData adData, L_Util.AdvertisingCallback callback);