android.bluetooth.le.AdvertiseCallback Java Examples
The following examples show how to use
android.bluetooth.le.AdvertiseCallback.
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: BleService.java From beacons-android with Apache License 2.0 | 5 votes |
/** * Start or restart the advertising of an item's BLE beacon. * @param beacon The item to (re)start. * @return True if the beacon was started, false otherwise. */ public boolean startBeaconAdvertiser(Beacon beacon) { if (null == mAdvertisersManager) { return false; } if (!mAdvertisersManager.isBluetoothEnabled()) { return false; } if (!mAdvertisersManager.canAdvertise()) { beacon.onAdvertiseFailed(AdvertiseCallback.ADVERTISE_FAILED_FEATURE_UNSUPPORTED); broadcastBeaconEvent(EVENT_ADVERTISE_UNSUPPORTED, beacon); return false; } // stop current advertiser for this beacon Advertiser existingAdvertiser = beacon.getAdvertiser(); if (null != existingAdvertiser) { mAdvertisersManager.stopAdvertiser(existingAdvertiser); mEstimatedPDUCount += existingAdvertiser.clearPDUCount(); } Advertiser advertiser = beacon.recreateAdvertiser(this); if (null == advertiser) { return false; } advertiser.setManager(mAdvertisersManager); return mAdvertisersManager.startAdvertiser(advertiser); }
Example #2
Source File: MainActivity.java From AndroidDemoProjects with Apache License 2.0 | 5 votes |
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 #3
Source File: AdvertiseFragment.java From bluetooth with Apache License 2.0 | 5 votes |
/** * 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 #4
Source File: MainActivity.java From bluetooth with Apache License 2.0 | 5 votes |
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 #5
Source File: Beacon.java From beacons-android with Apache License 2.0 | 5 votes |
public void onAdvertiseFailed(int errorCode) { if (AdvertiseCallback.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS == errorCode){ // don't stop - we could attempt to start the beacon again if we free a slot pause(); } else { // fatal, no point in keeping the beacon in active state stop(); } mAdvertiser = null; mErrorCode = errorCode; setErrorDetails(Advertiser.getErrorName(errorCode)); }
Example #6
Source File: BeaconSimulatorFragment.java From iBeacon-Android with Apache License 2.0 | 5 votes |
private void transmitIBeacon() { boolean isSupported = false; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { isSupported = btAdapter.isMultipleAdvertisementSupported(); if (isSupported) { Log.v(TAG, "is support advertistment"); if (beaconTransmitter.isStarted()) { beaconTransmitter.stopAdvertising(); beaconIv.setAnimation(null); } else { beaconTransmitter.startAdvertising(beacon, new AdvertiseCallback() { @Override public void onStartFailure(int errorCode) { Log.e(TAG, "Advertisement start failed with code: " + errorCode); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { Log.i(TAG, "Advertisement start succeeded." + settingsInEffect.toString()); } }); beaconIv.startAnimation(anim); } } else { UiHelper.showErrorMessage(getActivity(), "Your device is not support leBluetooth."); } } else { UiHelper.showErrorMessage(getActivity(), "Your device is not support leBluetooth."); } }
Example #7
Source File: BeaconBroadcast.java From react-native-ibeacon-simulator with MIT License | 5 votes |
@ReactMethod public void startSharedAdvertisingBeaconWithString(String uuid, int major, int minor,String identifier) { int manufacturer = 0x4C; Beacon beacon = new Beacon.Builder() .setId1(uuid) .setId2(String.valueOf(major)) .setId3(String.valueOf(minor)) .setManufacturer(manufacturer) .setBluetoothName(identifier) .setTxPower(-59) .build(); BeaconParser beaconParser = new BeaconParser() .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"); this.beaconTransmitter = new BeaconTransmitter(context, beaconParser); this.beaconTransmitter.startAdvertising(beacon, new AdvertiseCallback() { @Override public void onStartFailure(int errorCode) { Log.d("ReactNative", "Error from start advertising " + errorCode); } @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { Log.d("ReactNative", "Success start advertising"); } }); }
Example #8
Source File: BluetoothLeAdvertiserSnippet.java From mobly-bundled-snippets with Apache License 2.0 | 5 votes |
@Override public void shutdown() { for (AdvertiseCallback callback : mAdvertiseCallbacks.values()) { mAdvertiser.stopAdvertising(callback); } mAdvertiseCallbacks.clear(); }
Example #9
Source File: BluetoothLeAdvertiserSnippet.java From mobly-bundled-snippets with Apache License 2.0 | 5 votes |
/** * Stop a BLE advertising. * * @param callbackId The callbackId corresponding to the {@link * BluetoothLeAdvertiserSnippet#bleStartAdvertising} call that started the advertising. * @throws BluetoothLeScannerSnippet.BluetoothLeScanSnippetException */ @RpcMinSdk(Build.VERSION_CODES.LOLLIPOP_MR1) @Rpc(description = "Stop BLE advertising.") public void bleStopAdvertising(String callbackId) throws BluetoothLeAdvertiserSnippetException { AdvertiseCallback callback = mAdvertiseCallbacks.remove(callbackId); if (callback == null) { throw new BluetoothLeAdvertiserSnippetException( "No advertising session found for ID " + callbackId); } mAdvertiser.stopAdvertising(callback); }
Example #10
Source File: L_Util.java From AsteroidOSSync with GNU General Public License v3.0 | 4 votes |
public static AdvertiseCallback getNativeAdvertisingCallback() { return m_nativeAdvertiseCallback; }
Example #11
Source File: AdvertiserFragment.java From connectivity-samples with Apache License 2.0 | 4 votes |
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); advertisingFailureReceiver = new BroadcastReceiver() { /** * Receives Advertising error codes from {@code AdvertiserService} and displays error messages * to the user. Sets the advertising toggle to 'false.' */ @Override public void onReceive(Context context, Intent intent) { int errorCode = intent.getIntExtra(AdvertiserService.ADVERTISING_FAILED_EXTRA_CODE, -1); mSwitch.setChecked(false); String errorMessage = getString(R.string.start_error_prefix); switch (errorCode) { case AdvertiseCallback.ADVERTISE_FAILED_ALREADY_STARTED: errorMessage += " " + getString(R.string.start_error_already_started); break; case AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE: errorMessage += " " + getString(R.string.start_error_too_large); break; case AdvertiseCallback.ADVERTISE_FAILED_FEATURE_UNSUPPORTED: errorMessage += " " + getString(R.string.start_error_unsupported); break; case AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR: errorMessage += " " + getString(R.string.start_error_internal); break; case AdvertiseCallback.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS: errorMessage += " " + getString(R.string.start_error_too_many); break; case AdvertiserService.ADVERTISING_TIMED_OUT: errorMessage = " " + getString(R.string.advertising_timedout); break; default: errorMessage += " " + getString(R.string.start_error_unknown); } Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show(); } }; }
Example #12
Source File: AdvertiserFragment.java From android-BluetoothAdvertisements with Apache License 2.0 | 4 votes |
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); advertisingFailureReceiver = new BroadcastReceiver() { /** * Receives Advertising error codes from {@code AdvertiserService} and displays error messages * to the user. Sets the advertising toggle to 'false.' */ @Override public void onReceive(Context context, Intent intent) { int errorCode = intent.getIntExtra(AdvertiserService.ADVERTISING_FAILED_EXTRA_CODE, -1); mSwitch.setChecked(false); String errorMessage = getString(R.string.start_error_prefix); switch (errorCode) { case AdvertiseCallback.ADVERTISE_FAILED_ALREADY_STARTED: errorMessage += " " + getString(R.string.start_error_already_started); break; case AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE: errorMessage += " " + getString(R.string.start_error_too_large); break; case AdvertiseCallback.ADVERTISE_FAILED_FEATURE_UNSUPPORTED: errorMessage += " " + getString(R.string.start_error_unsupported); break; case AdvertiseCallback.ADVERTISE_FAILED_INTERNAL_ERROR: errorMessage += " " + getString(R.string.start_error_internal); break; case AdvertiseCallback.ADVERTISE_FAILED_TOO_MANY_ADVERTISERS: errorMessage += " " + getString(R.string.start_error_too_many); break; case AdvertiserService.ADVERTISING_TIMED_OUT: errorMessage = " " + getString(R.string.advertising_timedout); break; default: errorMessage += " " + getString(R.string.start_error_unknown); } Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show(); } }; }
Example #13
Source File: L_Util.java From SweetBlue with GNU General Public License v3.0 | 4 votes |
public static AdvertiseCallback getNativeAdvertisingCallback() { return m_nativeAdvertiseCallback; }
Example #14
Source File: BluetoothMedic.java From android-beacon-library with Apache License 2.0 | 4 votes |
/** * Starts up a beacon transmitter with the intent of seeing if it results in an error condition * indicating the bluetooth stack may be in a bad state. * * If the failure error code matches a pattern known to be associated with a bad bluetooth stack * state, then the bluetooth stack is turned off and then back on after a short delay in order * to try to recover. * * @return false if the test indicates a failure indicating a bad state of the bluetooth stack */ @SuppressWarnings({"unused","WeakerAccess"}) @RequiresApi(21) public boolean runTransmitterTest(final Context context) { initializeWithContext(context); this.mTransmitterTestResult = null; long testStartTime = System.currentTimeMillis(); if (mAdapter != null) { final BluetoothLeAdvertiser advertiser = getAdvertiserSafely(mAdapter); if(advertiser != null) { AdvertiseSettings settings = (new Builder()).setAdvertiseMode(0).build(); AdvertiseData data = (new android.bluetooth.le.AdvertiseData.Builder()) .addManufacturerData(0, new byte[]{0}).build(); LogManager.i(TAG, "Starting transmitter test"); advertiser.startAdvertising(settings, data, new AdvertiseCallback() { public void onStartSuccess(AdvertiseSettings settingsInEffect) { super.onStartSuccess(settingsInEffect); LogManager.i(BluetoothMedic.TAG, "Transmitter test succeeded"); advertiser.stopAdvertising(this); BluetoothMedic.this.mTransmitterTestResult = true; } public void onStartFailure(int errorCode) { super.onStartFailure(errorCode); Intent intent = new Intent("onStartFailed"); intent.putExtra("errorCode", errorCode); LogManager.d(BluetoothMedic.TAG, "Sending onStartFailure broadcast with " + BluetoothMedic.this.mLocalBroadcastManager); if (BluetoothMedic.this.mLocalBroadcastManager != null) { BluetoothMedic.this.mLocalBroadcastManager.sendBroadcast(intent); } if(errorCode == 4) { BluetoothMedic.this.mTransmitterTestResult = false; LogManager.w(BluetoothMedic.TAG, "Transmitter test failed in a way we consider a test failure"); BluetoothMedic.this.sendNotification(context, "transmitter failed", "bluetooth not ok"); } else { BluetoothMedic.this.mTransmitterTestResult = true; LogManager.i(BluetoothMedic.TAG, "Transmitter test failed, but not in a way we consider a test failure"); } } }); } else { LogManager.d(TAG, "Cannot get advertiser"); } while(this.mTransmitterTestResult == null) { LogManager.d(TAG, "Waiting for transmitter test to complete..."); try { Thread.sleep(1000L); } catch (InterruptedException e) { /* do nothing */ } if(System.currentTimeMillis() - testStartTime > 5000L) { LogManager.d(TAG, "Timeout running transmitter test"); break; } } } LogManager.d(TAG, "transmitter test complete"); return this.mTransmitterTestResult != null && this.mTransmitterTestResult; }
Example #15
Source File: BeaconTransmitter.java From android-beacon-library with Apache License 2.0 | 4 votes |
/** * Starts advertising with fields from the passed beacon * @param beacon */ public void startAdvertising(Beacon beacon, AdvertiseCallback callback) { mBeacon = beacon; mAdvertisingClientCallback = callback; startAdvertising(); }
Example #16
Source File: BluetoothLeAdvertiserSnippet.java From mobly-bundled-snippets with Apache License 2.0 | 4 votes |
/** * 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 #17
Source File: PeripheralModeFragment.java From Bluefruit_LE_Connect_Android_V2 with MIT License | 4 votes |
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // ViewModel FragmentActivity activity = getActivity(); if (activity != null) { //PeripheralModeViewModel model = new ViewModelProvider(activity).get(PeripheralModeViewModel.class); PeripheralModeViewModel model = new ViewModelProvider(activity, new ViewModelProvider.AndroidViewModelFactory(activity.getApplication())).get(PeripheralModeViewModel.class); model.getStartAdvertisingErrorCode().observe(this, errorCode -> { Log.d(TAG, "Advertising error: " + errorCode); if (errorCode != null) { int messageId = errorCode == AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE ? R.string.peripheral_advertising_starterror_toolarge : R.string.peripheral_advertising_starterror_undefined; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog dialog = builder.setTitle(R.string.dialog_error).setMessage(messageId) .setPositiveButton(android.R.string.ok, null) .show(); DialogUtils.keepDialogOnOrientationChanges(dialog); } }); // RecyclerView Adapter PeripheralModeAdapter adapter = new PeripheralModeAdapter(activity, model, index -> { FragmentActivity activity2 = getActivity(); if (activity2 != null) { FragmentManager fragmentManager = activity2.getSupportFragmentManager(); Fragment fragment = null; String fragmentTag = null; switch (index) { case 0: fragment = DeviceInformationServiceFragment.newInstance(); fragmentTag = "DeviceInformationService"; break; case 1: fragment = UartServiceFragment.newInstance(); fragmentTag = "UartService"; break; } if (fragment != null) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() .setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left) .replace(R.id.contentLayout, fragment, fragmentTag); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } }); mRecyclerView.setAdapter(adapter); } }
Example #18
Source File: DalvikBleService.java From attach with GNU General Public License v3.0 | 4 votes |
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); }