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

    compile 'com.github.ivbaranov:rxbluetooth2:2.0.1'
  2. Create RxBluetooth instance.

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

    if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_PERMISSION_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 == REQUEST_PERMISSION_COARSE_LOCATION) {
           for (String permission : permissions) {
             if (android.Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission)) {
               // Do stuff if permission granted
             }
           }
         }
       }
  4. 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
       }
    }
  5. Have fun.

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

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