Skip to content
Ivan Baranov edited this page Apr 24, 2017 · 8 revisions
  1. Download.

    compile 'com.github.ivbaranov:rxbluetooth:0.1.6'
  2. Declare permissions:

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    // If you intend to run on devices with android 6.0+ you also need to declare:
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  3. Create RxBluetooth instance.

    RxBluetooth rxBluetooth = new RxBluetooth(this); // `this` is a context
  4. For android 6.0+ you need location permision.

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
    }
    // And catch the result like this:
     @Override
     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
         if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
             for (String permission : permissions) {
                 if (android.Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                     // Do stuff if permission granted
                 }
             }
         }
     }
  5. Check that bluetooth is available and enabled:

    // check if bluetooth is supported on your hardware
    if  (!rxBluetooth.isBluetoothAvailable()) {
       // handle the lack of bluetooth support
    } else {
       // check if bluetooth is currently enabled and ready for use
       if (!rxBluetooth.isBluetoothEnabled()) { 
          // to enable bluetooth via startActivityForResult()
          rxBluetooth.enableBluetooth(this, REQUEST_ENABLE_BT);
       } else {
          // you are ready
       }
    }
  6. Have fun.

  7. Make sure you are unsubscribing and stopping discovery in OnDestroy():

    if (rxBluetooth != null) {
          rxBluetooth.cancelDiscovery();
        }
    unsubscribe(rxBluetoothSubscription);