All Projects → IvBaranov → Rxbluetooth

IvBaranov / Rxbluetooth

Licence: apache-2.0
Android reactive bluetooth

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Rxbluetooth

Freezer
A simple & fluent Android ORM, how can it be easier ? RxJava2 compatible
Stars: ✭ 326 (-19.51%)
Mutual labels:  rxjava, rxjava2, rxandroid, rx
Reactivebeacons
Android library scanning BLE beacons nearby with RxJava
Stars: ✭ 171 (-57.78%)
Mutual labels:  rxjava, rxjava2, rxandroid, bluetooth
Swipe
👉 detects swipe events on Android
Stars: ✭ 324 (-20%)
Mutual labels:  rxjava, rxjava2, rxandroid
Androidbasemvp
🚀一个快速搭建MVP+RxJava2+Retrofit 基础框架,主要是封装有Http网络请求、日志、缓存、加载等待、toast、页面状态布局管理、权限、RxBus、Glide图片加载等组件,方便快速开发新项目、减少开发成本。
Stars: ✭ 184 (-54.57%)
Mutual labels:  rxjava, rxjava2, rxandroid
Rxgps
Finding current location cannot be easier on Android !
Stars: ✭ 307 (-24.2%)
Mutual labels:  rxjava, rxjava2, rx
Reactivesensors
Android library monitoring device hardware sensors with RxJava
Stars: ✭ 161 (-60.25%)
Mutual labels:  rxjava, rxjava2, rxandroid
Mvvm Architecture Android Beginners
This repository contains a sample app that implements MVVM architecture using Kotlin, ViewModel, LiveData, and etc.
Stars: ✭ 176 (-56.54%)
Mutual labels:  rxjava, rxjava2, rxandroid
Rxbus
Event Bus By RxJava.
Stars: ✭ 2,126 (+424.94%)
Mutual labels:  rxjava, rxjava2, rxandroid
Reactivenetwork
Android library listening network connection state and Internet connectivity with RxJava Observables
Stars: ✭ 2,484 (+513.33%)
Mutual labels:  rxjava, rxjava2, rxandroid
Prefser
Wrapper for Android SharedPreferences with object serialization and RxJava Observables
Stars: ✭ 228 (-43.7%)
Mutual labels:  rxjava, rxjava2, rxandroid
Rxbus
🚌 The RxBus as steady as an old dog.
Stars: ✭ 334 (-17.53%)
Mutual labels:  rxjava, rxjava2, rxandroid
Android Clean Architecture Boilerplate
Apply clean architecture on Android
Stars: ✭ 141 (-65.19%)
Mutual labels:  rxjava, rxjava2, rxandroid
RxAnimator
An RxJava2 binding for android Animator
Stars: ✭ 80 (-80.25%)
Mutual labels:  rxjava, rx, rxjava2
Rxbiometric
☝️ RxJava and RxKotlin bindings for Biometric Prompt (Fingerprint Scanner) on Android
Stars: ✭ 295 (-27.16%)
Mutual labels:  rxjava, rxjava2, rxandroid
Rxjavapriorityscheduler
RxPS - RxJavaPriorityScheduler - A RxJava Priority Scheduler library for Android and Java applications
Stars: ✭ 138 (-65.93%)
Mutual labels:  rxjava, rxjava2, rxandroid
Mvpframes
整合大量主流开源项目并且可高度配置化的 Android MVP 快速集成框架,支持 AndroidX
Stars: ✭ 100 (-75.31%)
Mutual labels:  rxjava, rxjava2, rxandroid
Rxjava2 Operators Magician
你用不惯 RxJava,只因缺了这把钥匙 🔑 You are not used to RxJava, just because of the lack of this key.
Stars: ✭ 868 (+114.32%)
Mutual labels:  rxjava, rxjava2, rxandroid
Aiyagirl
🔥 爱吖妹纸(含 Kotlin 分支版本)——Retrofit + RxJava + MVP 架构 APP 体验代码家的干货集中营 Gank.io,福利多多,不容错过
Stars: ✭ 1,109 (+173.83%)
Mutual labels:  rxjava, rxjava2, rxandroid
Reactivewifi
Android library listening available WiFi Access Points and related information with RxJava Observables
Stars: ✭ 186 (-54.07%)
Mutual labels:  rxjava, rxjava2, rxandroid
RxPagination
Implement pagination in just few lines with RxPagination
Stars: ✭ 20 (-95.06%)
Mutual labels:  rxandroid, rx, rxjava2

RxBluetooth

Build Status

Android reactive bluetooth library. Basically, RxBluetooth is just wrapper around android BluetoothAdapter, so first of all the Bluetooth developer guide should be read.

RxBluetooth for RxJava 1 is available in respective branch.

Full documentation

Usage

  1. Create RxBluetooth instance.

    RxBluetooth rxBluetooth = new RxBluetooth(this); // `this` is a context
    
  2. 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
             }
           }
         }
       }
    
  3. 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
       }
    }
    
  4. Have fun.

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

    if (rxBluetooth != null) {
          rxBluetooth.cancelDiscovery();
        }
    unsubscribe(rxBluetoothSubscription);
    
Observing devices
rxBluetooth.observeDevices()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .subscribe(new Consumer<BluetoothDevice>() {
      @Override public void accept(@NonNull BluetoothDevice bluetoothDevice) throws Exception {
        //
      }
    }));
Create connection between devices
// Use 00001101-0000-1000-8000-00805F9B34FB for SPP service
// (ex. Arduino) or use your own generated UUID.
// UUID uuid = UUID.fromString("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

rxBluetooth.connectAsServer("servername", uuid).subscribe(
    new Consumer<BluetoothSocket>() {
      @Override public void accept(BluetoothSocket bluetoothSocket) throws Exception {
        // Client connected, do anything with the socket
      }
    }, new Consumer<Throwable>() {
      @Override public void accept(Throwable throwable) throws Exception {
        // On error
      }
    });

rxBluetooth.connectAsClient(bluetoothDevice, uuid).subscribe(
    new Consumer<BluetoothSocket>() {
      @Override public void accept(BluetoothSocket bluetoothSocket) throws Exception {
        // Connected to bluetooth device, do anything with the socket
      }
    }, new Consumer<Throwable>() {
      @Override public void accept(Throwable throwable) throws Exception {
        // On error
      }
    });
Observing discovery state

To observe just ACTION_DISCOVERY_STARTED:

rxBluetooth.observeDiscovery()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .filter(BtPredicate.in(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
    .subscribe(new Consumer<String>() {
      @Override public void accept(String action) throws Exception {
        //
      }
    });

To observe both ACTION_DISCOVERY_STARTED and ACTION_DISCOVERY_FINISHED:

rxBluetooth.observeDiscovery()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .filter(BtPredicate.in(BluetoothAdapter.ACTION_DISCOVERY_STARTED, BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
    .subscribe(new Consumer<String>() {
      @Override public void accept(String action) throws Exception {
        //
      }
    });
Observing bluetooth state
rxBluetooth.observeBluetoothState()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .filter(BtPredicate.in(BluetoothAdapter.STATE_ON))
    .subscribe(new Consumer<Integer>() {
      @Override public void accept(Integer integer) throws Exception {
        //
      }
    });

You can observe single or multiple states:

BluetoothAdapter.STATE_OFF
BluetoothAdapter.STATE_TURNING_ON
BluetoothAdapter.STATE_ON
BluetoothAdapter.STATE_TURNING_OFF
Observing scan mode
rxBluetooth.observeScanMode()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .filter(BtPredicate.in(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE))
    .subscribe(new Consumer<Integer>() {
    @Override public void accept(Integer integer) throws Exception {
      //
    }
    });

You can observe single or multiple scan modes:

BluetoothAdapter.SCAN_MODE_NONE
BluetoothAdapter.SCAN_MODE_CONNECTABLE
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE
Getting the profile proxy object
rxBluetooth.observeBluetoothProfile(myProfile)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .subscribe(new Consumer<ServiceEvent>() {
    @Override public void accept(ServiceEvent serviceEvent) throws Exception {
      switch (serviceEvent.getState()) {
       case CONNECTED:
            BluetoothProfile bluetoothProfile = serviceEvent.getBluetoothProfile();
            List<BluetoothDevice> devices = bluetoothProfile.getConnectedDevices();
            for ( final BluetoothDevice dev : devices ) {
              //..
            }
            break;
       case DISCONNECTED:
            //serviceEvent.getBluetoothProfile() returns null
            break;
        }
      }
    });

myProfile can be one of BluetoothProfile.HEALTH, BluetoothProfile.HEADSET, BluetoothProfile.A2DP, BluetoothProfile.GATT or BluetoothProfile.GATT_SERVER

Clients should close profile proxy when they are no longer using the proxy obtained from observeBluetoothProfile:

rxBluetooth.closeProfileProxy(int profile, BluetoothProfile proxy);
Observing device state

To observe the current device state, you can receive the ConnectionStateEvent which provides the state, previous state, and BluetoothDevice.

rxBluetooth.observeConnectionState()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .subscribe(new Consumer<ConnectionStateEvent>() {
    @Override public void accept(ConnectionStateEvent event) throws Exception {
      switch (event.getState()) {
        case BluetoothAdapter.STATE_DISCONNECTED:
            // device disconnected
            break;
        case BluetoothAdapter.STATE_CONNECTING:
            // device connecting
            break;
        case BluetoothAdapter.STATE_CONNECTED:
            // device connected
            break;
        case BluetoothAdapter.STATE_DISCONNECTING:
            // device disconnecting
            break;
      }
    }
    });

Possible states are:

BluetoothAdapter.STATE_DISCONNECTED
BluetoothAdapter.STATE_CONNECTING
BluetoothAdapter.STATE_CONNECTED
BluetoothAdapter.STATE_DISCONNECTING
Observing device bond state

To observe the bond state of devices, you can receive the BondStateEvent which provides the state, previous state, and BluetoothDevice.

rxBluetooth.observeBondState()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .subscribe(new Consumer<BondStateEvent>() {
    @Override public void accept(BondStateEvent event) throws Exception {
      switch (event.getState()) {
        case BluetoothDevice.BOND_NONE:
            // device unbonded
            break;
        case BluetoothDevice.BOND_BONDING:
            // device bonding
            break;
        case BluetoothDevice.BOND_BONDED:
            // device bonded
            break;
      }
    }
    });

Possible states are:

BluetoothDevice.BOND_NONE
BluetoothDevice.BOND_BONDING
BluetoothDevice.BOND_BONDED

Read and Write with BluetoothSocket

After creating a connection to the device, you can use BluetoothConnection class to read and write with its socket.

Read:
BluetoothConnection bluetoothConnection = new BluetoothConnection(bluetoothSocket);

// Observe every byte received
bluetoothConnection.observeByteStream()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe(new Consumer<Byte>() {
      @Override public void accept(Byte aByte) throws Exception {
        // This will be called every single byte received
      }
    }, new Consumer<Throwable>() {
      @Override public void accept(Throwable throwable) throws Exception {
        // Error occured
      }
    });

// Or just observe string
bluetoothConnection.observeStringStream()
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.io())
    .subscribe(new Consumer<String>() {
      @Override public void call(String string) throws Exception {
        // This will be called every string received
      }
    }, new Consumer<Throwable>() {
      @Override public void call(Throwable throwable) throws Exception {
        // Error occured
      }
    });
Write:
bluetoothConnection.send("Hello"); // String
bluetoothConnection.send("There".getBytes()); // Array of bytes
Close:

Remember to close streams and socket once you are done.

bluetoothConnection.closeConnection();

Observe ACL actions

rxBluetooth.observeAclEvent() //
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeOn(Schedulers.computation())
    .subscribe(new Consumer<AclEvent>() {
      @Override public void accept(AclEvent aclEvent) throws Exception {
        switch (aclEvent.getAction()) {
          case BluetoothDevice.ACTION_ACL_CONNECTED:
            //...
            break;
          case BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED:
            //...
            break;
          case BluetoothDevice.ACTION_ACL_DISCONNECTED:
            //...
            break;
        }
      }
    });

Download

Releases are available both in jcenter and mavenCentral repositories.

compile 'com.github.ivbaranov:rxbluetooth2:2.1.1'
Branch Artifact Id Support library version Latest version
rxjava-1.x rxbluetooth 25.3.1 0.1.6
rxjava-2.x rxbluetooth2 25.3.1 2.0.4
rxjava-2.x rxbluetooth2 AndroidX 2.1.1

Snapshots

Snapshots of the development version are available in Sonatype's snapshots repository.

In order to download from snapshot repository add:

repositories {
    maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
}

Contributing

Make sure you use SquareAndroid code style. (https://github.com/square/java-code-styles)

Create a branch for each feature.

Developed By

Ivan Baranov

License

Copyright 2015 Ivan Baranov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].