Java Code Examples for android.bluetooth.BluetoothDevice#connectGatt()
The following examples show how to use
android.bluetooth.BluetoothDevice#connectGatt() .
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: BTConnectionManager.java From redalert-android with Apache License 2.0 | 8 votes |
@Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { Log.d(TAG, "onLeScan: name: " + device.getName() + ", uuid: " + device.getUuids() + ", add: " + device.getAddress() + ", type: " + device.getType() + ", bondState: " + device.getBondState() + ", rssi: " + rssi); if (device.getName() != null && device.getAddress() != null && device.getName().equals("MI") && device.getAddress().startsWith("88:0F:10")) { mFound = true; stopDiscovery(); device.connectGatt(context, false, btleGattCallback); } }
Example 2
Source File: BleManager.java From BLEChat with GNU General Public License v3.0 | 6 votes |
public boolean connectGatt(Context c, boolean bAutoReconnect, BluetoothDevice device) { if(c == null || device == null) return false; mGattServices.clear(); mGattCharacteristics.clear(); mWritableCharacteristics.clear(); mBluetoothGatt = device.connectGatt(c, bAutoReconnect, mGattCallback); mDefaultDevice = device; mState = STATE_CONNECTING; mHandler.obtainMessage(MESSAGE_STATE_CHANGE, STATE_CONNECTING, 0).sendToTarget(); return true; }
Example 3
Source File: BLeSerialPortService.java From Android-BLE-Terminal with MIT License | 6 votes |
@Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { List<UUID> uuids = parseUUIDs(scanRecord); // Stop if the device doesn't have the UART service. if (uuids.contains(SERIAL_SERVICE_UUID)) { // Notify registered callbacks of found device. notifyOnDeviceFound(device); // Connect to first found device if required. if (connectFirst) { // Stop scanning for devices. stopScan(); // Prevent connections to future found devices. connectFirst = false; // Connect to device. gatt = device.connectGatt(context, true, mGattCallback); } } }
Example 4
Source File: MyBleService.java From science-journal with Apache License 2.0 | 5 votes |
public boolean connect(String address) { if (btAdapter == null) { // Not sure how we could get here, but it happens (b/36738130), so flag an error // instead of crashing. return false; } BluetoothDevice device = btAdapter.getRemoteDevice(address); // Explicitly check if Ble is enabled, otherwise it attempts a connection // that never timesout even though it should. if (device == null || !isBleEnabled()) { return false; } BluetoothGatt bluetoothGatt = addressToGattClient.get(address); int connectionState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT); if (bluetoothGatt != null && connectionState != BluetoothProfile.STATE_CONNECTED) { return bluetoothGatt.connect(); } if (bluetoothGatt != null && connectionState == BluetoothProfile.STATE_CONNECTED) { sendGattBroadcast(address, BleEvents.GATT_CONNECT, null); return true; } if (bluetoothGatt != null) { bluetoothGatt.close(); } bluetoothGatt = device.connectGatt( this, false, // autoConnect = false gattCallbacks); addressToGattClient.put(address, bluetoothGatt); return true; }
Example 5
Source File: BluetoothLeService.java From IoT-Firstep with GNU General Public License v3.0 | 5 votes |
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; return true; }
Example 6
Source File: BluetoothLeService.java From WheelLogAndroid with GNU General Public License v3.0 | 5 votes |
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect() { //final String address) { disconnectRequested = false; autoConnect = false; mDisconnectTime = null; if (mBluetoothAdapter == null || mBluetoothDeviceAddress == null || mBluetoothDeviceAddress.isEmpty()) { Timber.i("BluetoothAdapter not initialized or unspecified address."); return false; } if (mBluetoothGatt != null && mBluetoothGatt.getDevice().getAddress().equals(mBluetoothDeviceAddress)) { Timber.i("Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; broadcastConnectionUpdate(mConnectionState); return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mBluetoothDeviceAddress); if (device == null) { Timber.i("Device not found. Unable to connect."); return false; } mBluetoothGatt = device.connectGatt(this, autoConnect, mGattCallback); Timber.i("Trying to create a new connection."); mConnectionState = STATE_CONNECTING; broadcastConnectionUpdate(mConnectionState); return true; }
Example 7
Source File: AndroidBleStack.java From awesomesauce-rfduino with GNU Lesser General Public License v2.1 | 5 votes |
/** Connects to a chosen Bluetooth device and registers the callback function to be invoked when we get data from this device. **/ public AndroidBleStack(BluetoothDevice device, android.bluetooth.BluetoothGattCallback customCallbackFunction, Context hostActivity) { hostAndroidActivity = hostActivity; activityGattCallback = customCallbackFunction; rfduinoGattServer = device.connectGatt(hostAndroidActivity, false, activityGattCallback); }
Example 8
Source File: AndroidBle.java From GizwitsBLE with Apache License 2.0 | 5 votes |
@Override public boolean connect(String address) { BluetoothDevice device = mBtAdapter.getRemoteDevice(address); BluetoothGatt gatt = device.connectGatt(mService, false, mGattCallback); if (gatt == null) { mBluetoothGatts.remove(address); return false; } else { // TODO: if state is 141, it can be connected again after about 15 // seconds mBluetoothGatts.put(address, gatt); return true; } }
Example 9
Source File: BluetoothLeService.java From BLEConnect with GNU General Public License v2.0 | 5 votes |
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address * The device address of the destination device. * * @return Return true if the connection is initiated successfully. The * connection result is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter .getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } // We want to directly connect to the device, so we are setting the // autoConnect // parameter to false. mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; }
Example 10
Source File: BLEService.java From Android-nRF-BLE-Joiner with BSD 3-Clause "New" or "Revised" License | 5 votes |
public boolean connect(final String address){ if(mBluetoothAdapter == null || address == null){ Log.v(TAG,"BluetoothAdapter is not initialised or wrong address"); return false; } //Previously connected device. Tru to reconnect. if(address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null){ Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGatt.connect()) { mConnectionState = STATE_CONNECTING; return true; } else { return false; } } final BluetoothDevice bleDevice = mBluetoothAdapter.getRemoteDevice(address); if(bleDevice == null){ Log.v(TAG, "Device not found unable to connect"); return false; } mBluetoothGatt = bleDevice.connectGatt(this, false, mBLEGattCallBack); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; }
Example 11
Source File: BleManager.java From BLEChat with GNU General Public License v3.0 | 5 votes |
public boolean connectGatt(Context c, boolean bAutoReconnect, String address) { if(c == null || address == null) return false; if(mBluetoothGatt != null && mDefaultDevice != null && address.equals(mDefaultDevice.getAddress())) { if (mBluetoothGatt.connect()) { mState = STATE_CONNECTING; return true; } } BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); if (device == null) { Logs.d("# Device not found. Unable to connect."); return false; } mGattServices.clear(); mGattCharacteristics.clear(); mWritableCharacteristics.clear(); mBluetoothGatt = device.connectGatt(c, bAutoReconnect, mGattCallback); mDefaultDevice = device; mState = STATE_CONNECTING; mHandler.obtainMessage(MESSAGE_STATE_CHANGE, STATE_CONNECTING, 0).sendToTarget(); return true; }
Example 12
Source File: DeviceServicesActivity.java From EFRConnect-android with Apache License 2.0 | 5 votes |
@Override public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { Log.d("Scanning", ""); if (device.getAddress().equals(reconnectaddress)) { bluetoothGatt = device.connectGatt(getBaseContext(), false, gattCallback); Log.d("onLeScan", "Device is found" + device.getAddress()); } }
Example 13
Source File: GattClient.java From bean-sdk-android with MIT License | 5 votes |
public void connect(Context context, BluetoothDevice device) { if (mGatt != null) { mGatt.disconnect(); mGatt.close(); mConnected = false; } Log.i(TAG, "Gatt connection started"); mGatt = device.connectGatt(context, false, mBluetoothGattCallback); Log.i(TAG, "Refreshing GATT Cache"); refreshDeviceCache(mGatt); }
Example 14
Source File: BluetoothBackgroundService.java From external-nfc-api with Apache License 2.0 | 4 votes |
private boolean connectReader() { BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { Log.w(TAG, "Unable to initialize BluetoothManager."); setConnectionState(BluetoothReader.STATE_DISCONNECTED); return false; } BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) { Log.w(TAG, "Unable to obtain a BluetoothAdapter."); setConnectionState(BluetoothReader.STATE_DISCONNECTED); return false; } /* * Connect Device. */ /* Clear old GATT connection. */ if (bluetoothGatt != null) { Log.i(TAG, "Clear old GATT connection"); bluetoothGatt.disconnect(); bluetoothGatt.close(); bluetoothGatt = null; } if (mDeviceAddress == null) { Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices(); if (mPairedDevices.size() > 0) { for (BluetoothDevice mDevice : mPairedDevices) { Log.i(TAG, "Connect bonded bluetooth device " + mDevice.getName() + " " + mDevice.getAddress()); mDeviceAddress = mDevice.getAddress(); mDeviceName = mDevice.getName(); } } else { Log.i(TAG, "No connected bluetooth devices and no provided address."); return false; } } else { Log.i(TAG, "Connect bluetooth device " + mDeviceName + " " + mDeviceAddress); } /* Create a new connection. */ final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mDeviceAddress); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } /* Connect to GATT internal_invoker. */ setConnectionState(BluetoothReader.STATE_CONNECTING); bluetoothGatt = device.connectGatt(this, false, acsGattCallback); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { bluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); // https://stackoverflow.com/questions/53726759/xamarin-bluetooth-data-receive-delay // https://stackoverflow.com/questions/31742817/delay-between-writecharacteristic-and-callback-oncharacteristicwrite?noredirect=1&lq=1 // https://punchthrough.com/maximizing-ble-throughput-part-2-use-larger-att-mtu-2/ // When using larger ATT_MTU, the throughput is increased about 0-15% as we eliminate transferring ATT layer overhead bytes and replacing them with data. // Using ATT_MTU sizes that are multiples of 23 bytes or (Link Layer Data Field – L2CAP Header Size(4 bytes)) is ideal. bluetoothGatt.requestMtu(138); } return true; }
Example 15
Source File: BluetoothLeService.java From openvidonn with GNU General Public License v3.0 | 4 votes |
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} * callback. */ public boolean connect(final String address) { if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); // Previously connected device. Try to reconnect. if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if((mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT) != BluetoothProfile.STATE_CONNECTED)) { Log.d(TAG, "ConnectionState = " + mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT)); if (mBluetoothGatt.connect()) { Log.d(TAG, "Reconnecting..."); mConnectionState = STATE_CONNECTING; mHandler.postDelayed(new Runnable() { @Override public void run() { if(mConnectionState == STATE_CONNECTING) { disconnect(); broadcastUpdate(CANT_CONNECT_VIDONN); } } }, RECONNECT_PERIOD); return false; } else { return false; } } else return true; } if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } mBluetoothGatt = device.connectGatt(this, false, mGattCallback); Log.d(TAG, "Trying to create a new connection."); mBluetoothDeviceAddress = address; mConnectionState = STATE_CONNECTING; return true; }
Example 16
Source File: BLEService.java From android_wear_for_ios with MIT License | 4 votes |
@Override public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) { Log.i(TAG_LOG, "onLeScan"); if (!is_connect) { Log.d(TAG_LOG, "is connect"); if (device != null) { Log.d(TAG_LOG, "device "); if (!is_reconnect && device.getName() != null) { // if(device.getName().equals("Blank")) { if(device.getName().equals("BLE Utility")) { Log.d(TAG_LOG, "getname "); iphone_uuid = device.getAddress().toString(); Log.d(TAG_LOG, "iphone_uuid: " + iphone_uuid); is_connect = true; bluetooth_gatt = device.connectGatt(getApplicationContext(), false, bluetooth_gattCallback); } } else if (is_reconnect && device.getAddress().toString().equals(iphone_uuid)) { if(!is_time) { Log.d(TAG_LOG, "-=-=-=-=-=-=-=-=-=- timer start:: -=-==-=-=-=-=-=-==--=-=-=-==-=-=-=-=-=-=-=-"); start_time = System.currentTimeMillis(); is_time = true; }else if(System.currentTimeMillis() - start_time > 5000){ Log.d(TAG_LOG, "-=-=-=-=-=-=-=-=-=- reconnect:: -=-==-=-=-=-=-=-==--=-=-=-==-=-=-=-=-=-=-=-"); is_connect = true; is_reconnect = false; // get paired devices Set<BluetoothDevice> _paired_devices = bluetooth_adapter.getBondedDevices(); for(BluetoothDevice _paired_device: _paired_devices) { Log.d(TAG_LOG, "paired device: " + _paired_device + " :: " + _paired_device.getName()); Log.d(TAG_LOG, "++ " + _paired_device.getAddress() + " :: " + _paired_device.getUuids()); if(_paired_device.getAddress().toString().equals(iphone_uuid)) { Log.d(TAG_LOG, "*=*=8=*+*+8=8+*+8=*+*+*=8+*+*8+*+*=*+*+*=8+*+*+8+*+*+*=*+8=*+8+*+8=8+*="); try { BluetoothSocket bluetooth_socket = _paired_device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); bluetooth_socket.connect(); } catch (IOException e) { e.printStackTrace(); } } } Log.d(TAG_LOG, "connect gatt"); bluetooth_gatt = device.connectGatt(getApplicationContext(), false, bluetooth_gattCallback); } } else { Log.d(TAG_LOG, "skip:: "); skip_count++; } } } }
Example 17
Source File: NukiRequestHandler.java From trigger with GNU General Public License v2.0 | 4 votes |
public void run() { if (bluetooth_in_use.get()) { Log.w(TAG, "Bluetooth busy => abort action"); if (action != Action.fetch_state) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Bluetooth device is busy."); } return; } if (!((Context) this.listener).getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Bluetooth Low Energy is not supported."); return; } BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null || !adapter.isEnabled()) { this.listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Bluetooth is disabled."); return; } if (setup.device_name.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No device name set."); return; } if (setup.user_name.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No user name set."); return; } String address = getAddress(adapter, setup.device_name); if (address == null) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "No Device found."); return; } BluetoothDevice device = adapter.getRemoteDevice(address); if (device == null) { this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Device not found."); return; } if (Utils.isEmpty(setup.shared_key) && action == Action.fetch_state) { // ignore query for door state - not paired yet this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, ""); return; } if (!bluetooth_in_use.compareAndSet(false, true)) { // setting the variable failed return; } NukiCallback callback; if (Utils.isEmpty(setup.shared_key)) { // initiate paring callback = new NukiPairingCallback(setup.getId(), this.listener, setup); this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Start Pairing."); } else switch (action) { case open_door: callback = new NukiLockActionCallback(setup.getId(), this.listener, setup, 0x01 /*unlock*/); break; case ring_door: this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Bell not supported."); return; case close_door: callback = new NukiLockActionCallback(setup.getId(), this.listener, setup, 0x02 /*lock*/); break; default: case fetch_state: callback = new NukiReadLockStateCallback(setup.getId(), this.listener, setup); break; } BluetoothGatt gatt; if (Build.VERSION.SDK_INT >= 23) { gatt = device.connectGatt(this.context, false, callback, TRANSPORT_LE); } else { gatt = device.connectGatt(this.context, false, callback); } if (gatt == null) { // failed to start connection bluetooth_in_use.set(false); } }
Example 18
Source File: BLeSerialPortService.java From Android-BLE-Terminal with MIT License | 4 votes |
public BLeSerialPortService connect(BluetoothDevice device) { gatt = device.connectGatt(context, false, mGattCallback); return this; }
Example 19
Source File: MultipleBleService.java From BleLib with Apache License 2.0 | 4 votes |
/** * Connects to the GATT server hosted on the Bluetooth LE device. * * @param address The device address of the destination device. * @return Return true if the connection is initiated successfully. The connection result * is reported asynchronously through the BluetoothGattCallback#onConnectionStateChange. */ public boolean connect(final String address) { if (isScanning) scanLeDevice(false); if (getConnectDevices().size() > MAX_CONNECT_NUM) return false; if (mConnectedAddressList == null) { mConnectedAddressList = new ArrayList<>(); } if (mConnectedAddressList.contains(address)) { Log.d(TAG, "This is device already connected."); return true; } if (mBluetoothAdapter == null || address == null) { Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); return false; } //Previously connected device. Try to reconnect. if (mBluetoothGattMap == null) { mBluetoothGattMap = new HashMap<>(); } if (mBluetoothGattMap.get(address) != null && mConnectedAddressList.contains(address)) { Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); if (mBluetoothGattMap.get(address).connect()) { return true; } else { return false; } } final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { Log.w(TAG, "Device not found. Unable to connect."); return false; } //We want to directly connect to the device, so we are setting the autoConnect // parameter to false. BluetoothGatt bluetoothGatt = device.connectGatt(this, false, mGattCallback); if (bluetoothGatt != null) { mBluetoothGattMap.put(address, bluetoothGatt); Log.d(TAG, "Trying to create a new connection."); mConnectedAddressList.add(address); return true; } return false; }
Example 20
Source File: BluetoothLEController.java From gilgamesh with GNU General Public License v3.0 | 3 votes |
@Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { mBluetoothGatt = device.connectGatt(mContext, true, mGattCallback); // mLeDeviceListAdapter.addDevice(device); // mLeDeviceListAdapter.notifyDataSetChanged(); }