omaraflak / Bluetooth-Library

Bluetooth client library for Android.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

function refactor: connectToDevice(...)

root-ansh opened this issue · comments

The function connectToDevice(...) is not calling bluetoothAdapter.cancelDiscovery(); which according to android's default , is unrecommended.

/*

  • Start the remote device discovery process. The discovery process usually involves an inquiry scan
  • of about 12 seconds, followed by a page scan.....
  • .....
  • .....
  • Device discovery is a heavyweight procedure. New connections to

  • remote Bluetooth devices should not be attempted while discovery is in
  • progress, and existing connections will experience limited bandwidth
  • and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
  • discovery. Discovery is not managed by the Activity,
  • but is run as a system service, so an application should always call
  • {@link BluetoothAdapter#cancelDiscovery()} even if it
  • did not directly request a discovery, just to be sure.
  • Device discovery ....

  • ....
  • ....
    */
    @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
    public boolean startDiscovery() {
    if (getState() != STATE_ON) return false;
    try {
    mServiceLock.readLock().lock();
    if (mService != null) return mService.startDiscovery();
    } catch (RemoteException e) {
    Log.e(TAG, "", e);
    } finally {
    mServiceLock.readLock().unlock();
    }
    return false;
    }

Therefore , I will recommend the following snippet:

public void connectToDevice(BluetoothDevice device, boolean insecureConnection){
        if(bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        new ConnectThread(device, insecureConnection).start();
    }

<PS:I know this will be awkward and public and since i don't know of any other medium of discussions on this site, but can I connect with you on some social media platform like facebook or linkedIn? I am an intermediate android developer looking for guidance and funtalks with more experienced people like you :bowtie: 😅 >

You are right. But I'm actually doing the cancelDiscovery later in ConnectThread.
I've sent you an invitation on a slack channel ;)

You should clone the repo and see how I coded the app module. It shows how you can use the library.

Also, feel free to make a pull request to suggest some code modification to the library.