Java Code Examples for android.bluetooth.BluetoothDevice#BOND_BONDED

The following examples show how to use android.bluetooth.BluetoothDevice#BOND_BONDED . 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: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
	final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
	final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);

	// Skip other devices
	if (bluetoothGatt == null || !device.getAddress().equals(bluetoothGatt.getDevice().getAddress()))
		return;

	DebugLogger.i(TAG, "Bond state changed for: " + device.getName() + " new state: " + bondState + " previous: " + previousBondState);

	switch (bondState) {
		case BluetoothDevice.BOND_BONDING:
			callbacks.onBondingRequired(device);
			break;
		case BluetoothDevice.BOND_BONDED:
			callbacks.onBonded(device);

			// Start initializing again.
			// In fact, bonding forces additional, internal service discovery (at least on Nexus devices), so this method may safely be used to start this process again.
			bluetoothGatt.discoverServices();
			break;
	}
}
 
Example 2
Source File: DeviceListActivity.java    From connectivity-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
        // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
    }
}
 
Example 3
Source File: DeviceListActivity.java    From retrowatch with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
        mScanButton.setVisibility(View.VISIBLE);
    }
}
 
Example 4
Source File: BCLServiceClient.java    From unity-bluetooth with MIT License 6 votes vote down vote up
private BroadcastReceiver createBroadcastReceiver(final String pairingAddress) {
    return new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (pairingAddress.equals(device.getAddress())) {
                        mConnectThread = new ConnectThread(device);
                        mConnectThread.start();
                        for (BCLServiceListener listener : listeners) {
                            listener.onDeviceConnect(true);
                        }
                    }
                }
            }
        }
    };
}
 
Example 5
Source File: ShareTest.java    From xDrip-Experimental with GNU General Public License v3.0 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
        final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
        if (state == BluetoothDevice.BOND_BONDED) {
            Log.d(TAG, "CALLBACK RECIEVED Bonded");
            currentGattTask = GATT_SETUP;
            mBluetoothGatt.discoverServices();
        } else if (state == BluetoothDevice.BOND_NONE){
            Log.d(TAG, "CALLBACK RECIEVED: Not Bonded");
            Toast.makeText(getApplicationContext(), "unBonded", Toast.LENGTH_LONG).show();
        } else if (state == BluetoothDevice.BOND_BONDING) {
            Log.d(TAG, "CALLBACK RECIEVED: Trying to bond");
            Toast.makeText(getApplicationContext(), "trying to bond", Toast.LENGTH_LONG).show();
        }
    }
}
 
Example 6
Source File: ShareTest.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
        final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
        if (state == BluetoothDevice.BOND_BONDED) {
            Log.d(TAG, "CALLBACK RECIEVED Bonded");
            currentGattTask = GATT_SETUP;
            mBluetoothGatt.discoverServices();
        } else if (state == BluetoothDevice.BOND_NONE){
            Log.d(TAG, "CALLBACK RECIEVED: Not Bonded");
            Toast.makeText(getApplicationContext(), "unBonded", Toast.LENGTH_LONG).show();
        } else if (state == BluetoothDevice.BOND_BONDING) {
            Log.d(TAG, "CALLBACK RECIEVED: Trying to bond");
            Toast.makeText(getApplicationContext(), "trying to bond", Toast.LENGTH_LONG).show();
        }
    }
}
 
Example 7
Source File: BluetoothDeviceListActivity.java    From DataLogger with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
        // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.ui_dialog_bluetooth_select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.ui_dialog_bluetooth_none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
    }
}
 
Example 8
Source File: DeviceListActivity.java    From BTChat with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    // When discovery finds a device
    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // If it's already paired, skip it, because it's been listed already
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    // When discovery is finished, change the Activity title
    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
        setProgressBarIndeterminateVisibility(false);
        setTitle(R.string.select_device);
        if (mNewDevicesArrayAdapter.getCount() == 0) {
            String noDevices = getResources().getText(R.string.none_found).toString();
            mNewDevicesArrayAdapter.add(noDevices);
        }
        mScanButton.setVisibility(View.VISIBLE);
    }
}
 
Example 9
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * When the device is bonded and has the Generic Attribute service and the Service Changed
 * characteristic this method enables indications on this characteristic.
 * In case one of the requirements is not fulfilled this method returns <code>false</code>.
 *
 * @return <code>true</code> when the request has been sent, <code>false</code> when the device
 * is not bonded, does not have the Generic Attribute service, the GA service does not have
 * the Service Changed characteristic or this characteristic does not have the CCCD.
 */
private boolean ensureServiceChangedEnabled() {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || !connected)
		return false;

	// The Service Changed indications have sense only on bonded devices.
	final BluetoothDevice device = gatt.getDevice();
	if (device.getBondState() != BluetoothDevice.BOND_BONDED)
		return false;

	final BluetoothGattService gaService = gatt.getService(BleManager.GENERIC_ATTRIBUTE_SERVICE);
	if (gaService == null)
		return false;

	final BluetoothGattCharacteristic scCharacteristic =
			gaService.getCharacteristic(BleManager.SERVICE_CHANGED_CHARACTERISTIC);
	if (scCharacteristic == null)
		return false;

	log(Log.INFO, "Service Changed characteristic found on a bonded device");
	return internalEnableIndications(scCharacteristic);
}
 
Example 10
Source File: DeviceListFragment.java    From BluetoothStudy with Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView = getActivity().getLayoutInflater().inflate(R.layout.layout_item_bt_device, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.deviceName = (TextView) convertView.findViewById(R.id.device_name);
        viewHolder.deviceMac = (TextView) convertView.findViewById(R.id.device_mac);
        viewHolder.deviceState = (TextView) convertView.findViewById(R.id.device_state);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    int code = deviceList.get(position).getBondState();
    String name = deviceList.get(position).getName();
    String mac = deviceList.get(position).getAddress();
    String state;
    if (name == null || name.length() == 0) {
        name = "未命名设备";
    }
    if (code == BluetoothDevice.BOND_BONDED) {
        state = "ready";
        viewHolder.deviceState.setTextColor(getResources().getColor(R.color.green));
    } else {
        state = "new";
        viewHolder.deviceState.setTextColor(getResources().getColor(R.color.red));
    }
    if (mac == null || mac.length() == 0) {
        mac = "未知 mac 地址";
    }
    viewHolder.deviceName.setText(name);
    viewHolder.deviceMac.setText(mac);
    viewHolder.deviceState.setText(state);
    return convertView;
}
 
Example 11
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a bond with the device. The device must be first set using {@link #connect(BluetoothDevice)} which will
 * try to connect to the device. If you need to pair with a device before connecting to it you may do it without
 * the use of BleManager object and connect after bond is established.
 * @return true if pairing has started, false if it was already paired or an immediate error occur.
 */
private boolean internalCreateBond() {
	final BluetoothDevice device = bluetoothDevice;
	if (device == null)
		return false;

	if (device.getBondState() == BluetoothDevice.BOND_BONDED)
		return false;

	return device.createBond();
}
 
Example 12
Source File: EasyBLE.java    From easyble-x with Apache License 2.0 5 votes vote down vote up
/**
 * 创建连接
 *
 * @param device        蓝牙设备实例
 * @param configuration 连接配置
 * @param observer      伴生观察者
 * @return 返回创建的连接实例,创建失败则返回null
 */
@Nullable
public synchronized Connection connect(@NonNull final Device device, @Nullable ConnectionConfiguration configuration,
                                       @Nullable final EventObserver observer) {
    if (checkStatus()) {
        Inspector.requireNonNull(device, "device can't be null");
        Connection connection = connectionMap.remove(device.getAddress());
        //如果连接已存在,先释放掉
        if (connection != null) {
            connection.releaseNoEvent();
        }
        Boolean isConnectable = device.isConnectable();
        if (isConnectable == null || isConnectable) {
            int connectDelay = 0;
            if (bondController != null && bondController.accept(device)) {
                BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());
                if (remoteDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
                    connectDelay = createBond(device.getAddress()) ? 1500 : 0;
                }
            }
            connection = new ConnectionImpl(this, bluetoothAdapter, device, configuration, connectDelay, observer);
            connectionMap.put(device.address, connection);
            addressList.add(device.address);
            return connection;
        } else {
            String message = String.format(Locale.US, "connect failed! [type: unconnectable, name: %s, addr: %s]",
                    device.getName(), device.getAddress());
            logger.log(Log.ERROR, Logger.TYPE_CONNECTION_STATE, message);
            if (observer != null) {
                posterDispatcher.post(observer, MethodInfoGenerator.onConnectFailed(device, Connection.CONNECT_FAIL_TYPE_CONNECTION_IS_UNSUPPORTED));
            }
            observable.notifyObservers(MethodInfoGenerator.onConnectFailed(device, Connection.CONNECT_FAIL_TYPE_CONNECTION_IS_UNSUPPORTED));
        }
    }
    return null;
}
 
Example 13
Source File: Helper.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
public static String bondStateToString(final int bs) {
    String bondState;
    if (bs == BluetoothDevice.BOND_NONE) {
        bondState = "Unpaired";
    } else if (bs == BluetoothDevice.BOND_BONDING) {
        bondState = "Pairing";
    } else if (bs == BluetoothDevice.BOND_BONDED) {
        bondState = "Paired";
    } else if (bs == 0) {
        bondState = "Startup";
    } else {
        bondState = "Unknown bond state: " + bs;
    }
    return bondState;
}
 
Example 14
Source File: BluetoothBackgroundService.java    From external-nfc-api with Apache License 2.0 5 votes vote down vote up
private static String getBondingStatusString(int bondingStatus) {
    if (bondingStatus == BluetoothDevice.BOND_BONDED) {
        return "BOND BONDED";
    } else if (bondingStatus == BluetoothDevice.BOND_NONE) {
        return "BOND NONE";
    } else if (bondingStatus == BluetoothDevice.BOND_BONDING) {
        return "BOND BONDING";
    }
    return "BOND UNKNOWN.";
}
 
Example 15
Source File: BluetoothWrapper.java    From phonegap-bluetooth-plugin with MIT License 5 votes vote down vote up
/**
 * Check if the device at given address is bonded with this device.
 *
 * @param address The device we want to check against.
 * @return Flag indicating whether the devices are bonded.
 * @throws Exception If there is a problem deducing the bond state. A wrong address might also cause this. :)
 *
 * @see BluetoothDevice
 */
public boolean isBonded(String address) throws Exception
{
	try
	{
		BluetoothDevice device = _adapter.getRemoteDevice(address);
		return device.getBondState() == BluetoothDevice.BOND_BONDED;
	}
	catch(Exception e)
	{
		throw e;
	}
}
 
Example 16
Source File: BluetoothGlucoseMeter.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        services_discovered = true;
        statusUpdate("Services discovered");

        bondingstate = mBluetoothGatt.getDevice().getBondState();
        if (bondingstate != BluetoothDevice.BOND_BONDED) {
            statusUpdate("Attempting to create pairing bond - device must be in pairing mode!");
            sendDeviceUpdate(gatt.getDevice());
            mBluetoothGatt.getDevice().createBond();
            waitFor(1000);
            bondingstate = mBluetoothGatt.getDevice().getBondState();
            if (bondingstate != BluetoothDevice.BOND_BONDED) {
                statusUpdate("Pairing appeared to fail");
            } else {
                sendDeviceUpdate(gatt.getDevice());
            }
        } else {
            Log.d(TAG, "Device is already bonded - good");
        }

        if (d) {
            List<BluetoothGattService> gatts = getSupportedGattServices();
            for (BluetoothGattService bgs : gatts) {
                Log.d(TAG, "DEBUG: " + bgs.getUuid());
            }
        }

        if (queue.isEmpty()) {
            statusUpdate("Requesting data from meter");
            Bluetooth_CMD.read(DEVICE_INFO_SERVICE, MANUFACTURER_NAME, "get device manufacturer");
            Bluetooth_CMD.read(CURRENT_TIME_SERVICE, TIME_CHARACTERISTIC, "get device time");

            Bluetooth_CMD.notify(GLUCOSE_SERVICE, GLUCOSE_CHARACTERISTIC, "notify new glucose record");
            Bluetooth_CMD.enable_notification_value(GLUCOSE_SERVICE, GLUCOSE_CHARACTERISTIC, "notify new glucose value");

            Bluetooth_CMD.enable_notification_value(GLUCOSE_SERVICE, CONTEXT_CHARACTERISTIC, "notify new context value");
            Bluetooth_CMD.notify(GLUCOSE_SERVICE, CONTEXT_CHARACTERISTIC, "notify new glucose context");

            Bluetooth_CMD.enable_indications(GLUCOSE_SERVICE, RECORDS_CHARACTERISTIC, "readings indication request");
            Bluetooth_CMD.notify(GLUCOSE_SERVICE, RECORDS_CHARACTERISTIC, "notify glucose record");
            Bluetooth_CMD.write(GLUCOSE_SERVICE, RECORDS_CHARACTERISTIC, RecordsCmdTx.getAllRecords(), "request all readings");
            Bluetooth_CMD.notify(GLUCOSE_SERVICE, GLUCOSE_CHARACTERISTIC, "notify new glucose record again"); // dummy

            Bluetooth_CMD.poll_queue();

        } else {
            Log.e(TAG, "Queue is not empty so not scheduling anything..");
        }
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example 17
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
	final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
	final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
	final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);

	// Skip other devices.
	if (bluetoothDevice == null || device == null
			|| !device.getAddress().equals(bluetoothDevice.getAddress()))
		return;

	log(Log.DEBUG, "[Broadcast] Action received: " +
			BluetoothDevice.ACTION_BOND_STATE_CHANGED +
			", bond state changed to: " + ParserUtils.bondStateToString(bondState) +
			" (" + bondState + ")");

	switch (bondState) {
		case BluetoothDevice.BOND_NONE:
			if (previousBondState == BluetoothDevice.BOND_BONDING) {
				postCallback(c -> c.onBondingFailed(device));
				postBondingStateChange(o -> o.onBondingFailed(device));
				log(Log.WARN, "Bonding failed");
				if (request != null) { // CREATE_BOND request
					request.notifyFail(device, FailCallback.REASON_REQUEST_FAILED);
					request = null;
				}
			} else if (previousBondState == BluetoothDevice.BOND_BONDED) {
				if (request != null && request.type == Request.Type.REMOVE_BOND) {
					// The device has already disconnected by now.
					log(Log.INFO, "Bond information removed");
					request.notifySuccess(device);
					request = null;
				}
				// When the bond information has been removed (either with Remove Bond request
				// or in Android Settings), the BluetoothGatt object should be closed, so
				// the library won't reconnect to the device automatically.
				// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/157
				close();
			}
			break;
		case BluetoothDevice.BOND_BONDING:
			postCallback(c -> c.onBondingRequired(device));
			postBondingStateChange(o -> o.onBondingRequired(device));
			return;
		case BluetoothDevice.BOND_BONDED:
			log(Log.INFO, "Device bonded");
			postCallback(c -> c.onBonded(device));
			postBondingStateChange(o -> o.onBonded(device));
			if (request != null && request.type == Request.Type.CREATE_BOND) {
				request.notifySuccess(device);
				request = null;
				break;
			}
			// If the device started to pair just after the connection was
			// established the services were not discovered.
			if (!servicesDiscovered && !serviceDiscoveryRequested) {
				serviceDiscoveryRequested = true;
				post(() -> {
					log(Log.VERBOSE, "Discovering services...");
					log(Log.DEBUG, "gatt.discoverServices()");
					bluetoothGatt.discoverServices();
				});
				return;
			}
			// On older Android versions, after executing a command on secured attribute
			// of a device that is not bonded, let's say a write characteristic operation,
			// the system will start bonding. The BOND_BONDING and BOND_BONDED events will
			// be received, but the command will not be repeated automatically.
			//
			// Test results:
			// Devices that require repeating the last task:
			// - Nexus 4 with Android 5.1.1
			// - Samsung S6 with 5.0.1
			// - Samsung S8 with Android 7.0
			// - Nexus 9 with Android 7.1.1
			// Devices that repeat the request automatically:
			// - Pixel 2 with Android 8.1.0
			// - Samsung S8 with Android 8.0.0
			//
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
				if (request != null) {
					// Repeat the last command in that case.
					enqueueFirst(request);
					break;
				}
			}
			// No need to repeat the request.
			return;
	}
	nextRequest(true);
}
 
Example 18
Source File: BluetoothGlucoseMeter.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isBonded() {
    return (bondingstate == BluetoothDevice.BOND_BONDED);
}
 
Example 19
Source File: DfuBaseService.java    From microbit with Apache License 2.0 4 votes vote down vote up
@Override
        public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
            // Check whether an error occurred
            logi("onConnectionStateChange() :: Start");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    logi("onConnectionStateChange() :: Connected to GATT server");
                    mConnectionState = STATE_CONNECTED;

					/*
                     *  The onConnectionStateChange callback is called just after establishing connection and before sending Encryption Request BLE event in case of a paired device.
					 *  In that case and when the Service Changed CCCD is enabled we will get the indication after initializing the encryption, about 1600 milliseconds later. 
					 *  If we discover services right after connecting, the onServicesDiscovered callback will be called immediately, before receiving the indication and the following 
					 *  service discovery and we may end up with old, application's services instead.
					 *  
					 *  This is to support the buttonless switch from application to bootloader mode where the DFU bootloader notifies the master about service change.
					 *  Tested on Nexus 4 (Android 4.4.4 and 5), Nexus 5 (Android 5), Samsung Note 2 (Android 4.4.2). The time after connection to end of service discovery is about 1.6s 
					 *  on Samsung Note 2.
					 *  
					 *  NOTE: We are doing this to avoid the hack with calling the hidden gatt.refresh() method, at least for bonded devices.
					 */
                    if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) {
                        try {
                            synchronized (this) {
                                logd("onConnectionStateChange() :: Waiting 1600 ms for a possible Service Changed indication...");
                                wait(1600);

                                // After 1.6s the services are already discovered so the following gatt.discoverServices() finishes almost immediately.

                                // NOTE: This also works with shorted waiting time. The gatt.discoverServices() must be called after the indication is received which is
                                // about 600ms after establishing connection. Values 600 - 1600ms should be OK.
                            }
                        } catch (InterruptedException e) {
                            Log.e(TAG, e.toString());
                            // Do nothing
                        }
                    }

                    // Attempts to discover services after successful connection.
                    final boolean success = gatt.discoverServices();
                    logi("onConnectionStateChange() :: Attempting to start service discovery... " + (success ? "succeed" : "failed"));

                    if (!success) {
                        mError = ERROR_SERVICE_DISCOVERY_NOT_STARTED;
                    } else {
                        // Just return here, lock will be notified when service discovery finishes
                        return;
                    }
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    logi("onConnectionStateChange() :: Disconnected from GATT server");
                    mPaused = false;
                    mConnectionState = STATE_DISCONNECTED;
                }
            } else {
                loge("Connection state change error: " + status + " newState: " + newState);
/*				if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    mConnectionState = STATE_DISCONNECTED;
                    if (mServicePhase == PAIRING_REQUEST ){
                        mServicePhase = PAIRING_FAILED ;
                        updateProgressNotification(status);
                    }
                }*/
                mPaused = false;
                mError = ERROR_CONNECTION_STATE_MASK | status;
            }

            // Notify waiting thread
            synchronized (mLock) {
                mLock.notifyAll();
            }
        }
 
Example 20
Source File: P_NativeDeviceWrapper.java    From AsteroidOSSync with GNU General Public License v3.0 4 votes vote down vote up
boolean isNativelyBonded()
{
	return getNativeBondState() == BluetoothDevice.BOND_BONDED;
}