• Stars
    star
    167
  • Rank 226,635 (Top 5 %)
  • Language
    Java
  • License
    Apache License 2.0
  • Created about 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Android library scanning BLE beacons nearby with RxJava

ReactiveBeacons

Android Arsenal

Current Branch Branch Artifact Id Build Status Maven Central
RxJava1.x reactivebeacons Build Status for RxJava1.x Maven Central
β˜‘οΈ RxJava2.x reactivebeacons-rx2 Build Status for RxJava2.x Maven Central

This is RxJava2.x branch. To see documentation for RxJava1.x, switch to RxJava1.x branch.

Android library scanning BLE (Bluetooth Low Energy) beacons nearby with RxJava

Library was tested with Estimote and Kontakt beacons.

This library has limited functionality, but its API is simple:

ReactiveBeacons(context)
boolean isBleSupported()
boolean isBluetoothEnabled()
boolean isLocationEnabled(context)
boolean isAtLeastAndroidLollipop()
void requestBluetoothAccess(activity)
void requestLocationAccess(activity)
Observable<Beacon> observe()
Observable<Beacon> observe(ScanStrategy scanStrategy)

JavaDoc is available at: http://pwittchen.github.io/ReactiveBeacons/RxJava2.x

min SDK = 9, but if you are using API level lower than 18, don't forget to check BLE support on the device.

Contents

Usage

Step 1

Initialize ReactiveBeacons object:

private ReactiveBeacons reactiveBeacons;

@Override protected void onCreate(Bundle savedInstanceState) {
  reactiveBeacons = new ReactiveBeacons(this);
}

Step 2

Create subscribtion:

private Disposable subscription;

@Override protected void onResume() {
  super.onResume();
  
  if (!reactiveBeacons.isBleSupported()) { // optional, but recommended step
    // show message for the user that BLE is not supported on the device
    return;
  }
  
  // we should check Bluetooth and Location access here
  // if they're disabled, we can request access
  // if you want to know how to do it, check next sections 
  // of this documentation and sample app

  subscription = reactiveBeacons.observe()
    .subscribeOn(Schedulers.computation())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Consumer<Beacon>() {
      @Override public void call(Beacon beacon) {
        // do something with beacon
      }
    });
}    

Step 3

Unsubscribe subscription in onPause() method to stop BLE scan.

@Override protected void onPause() {
  super.onPause();
  if (subscription != null && !subscription.isDisposed()) {
    subscription.dispose()
  }
}

Please note: Library may emit information about the same beacon multiple times. New emission is created everytime when RSSI changes. We can distinguish several beacons by their MAC addresses with beacon.device.getAddress() method.

Good practices

Updating Manifest

Add <uses-feature .../> tag inside <manifest ...> tag in AndroidManifest.xml file in your application if you support Android devices with API level 18 or higher. You can skip this, if you are supporting lower API levels.

<uses-feature
    android:name="android.hardware.bluetooth_le"
    android:required="true" />

Checking BLE support

Check BLE support if you are supporting devices with API level lower than 18.

if (!reactiveBeacons.isBleSupported()) {
  // show message for the user that BLE is not supported on the device
}

If BLE is not supported, Observable emitting Beacons will be always empty.

Requesting Bluetooth access

Use requestBluetoothAccess(activity) method to ensure that Bluetooth is enabled. If you are supporting devices with API level lower than 18, you don't have to request Bluetooth access every time.

if (!reactiveBeacons.isBluetoothEnabled()) {
  reactiveBeacons.requestBluetoothAccess(activity);
}

Requesting Location access

Since API 23 (Android 6 - Marshmallow), Bluetooth Low Energy scan, requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permissions. Moreover, we need to enable Location services in order to scan BLE beacons. You don't have to worry about that if your apps are targeted to lower APIs than 23. Nevertheless, you have to be aware of that, if you want to detect beacons on the newest versions of Android. Read more at: https://code.google.com/p/android/issues/detail?id=190372. Use requestLocationAccess(activity) method to ensure that Location services are enabled. If you are supporting devices with API level lower than 18, you don't have to request Location access every time.

if (!reactiveBeacons.isLocationEnabled(activity)) {
  reactiveBeacons.requestLocationAccess(activity);
}

Requesting Runtime Permissions

Since Android M (API 23), we need to request Runtime Permissions. If we want to scan for BLE beacons, we need to request for ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission. For more details, check sample app.

Exemplary code snippet

With API methods, we can create the following code snippet:

private boolean canObserveBeacons() {
  if (!reactiveBeacons.isBleSupported()) {
    Toast.makeText(this, "BLE is not supported on this device", Toast.LENGTH_SHORT).show();
    return false;
  }

  if (!reactiveBeacons.isBluetoothEnabled()) {
    reactiveBeacons.requestBluetoothAccess(this);
    return false;
  } else if (!reactiveBeacons.isLocationEnabled(this)) {
    reactiveBeacons.requestLocationAccess(this);
    return false;
  } else if (!isFineOrCoarseLocationPermissionGranted()
             && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    requestCoarseLocationPermission();
    return false;
   }

  return true;
}

You can adjust this snippet to your needs or handle this logic in your own way.

After that, we can perform the following operation:

if(canObserveBeacons()) {
  // observe beacons here
}

Examples

Exemplary application is located in app directory of this repository.

If you want to know, how to use this library with Kotlin, check app-kotlin sample.

Compatibility with different Android versions

BLE scanning is available from Android 4.3 JELLY_BEAN_MR2 (API 18). You can use this library on lower versions of Android, but you won't be able to scan BLE devices, you should handle that situation in your app and notify user about that. See Good practices section. Since Android 5.0 LOLLIPOP (API 21), we have different API for BLE scanning. That's why this library has two different BLE scanning strategies:

  • PreLollipopScanStrategy used for pre-Lollipop devices (from API 18 to 20)
  • LollipopScanStrategy used for Lollipop devices (API 21 or higher)

Library automatically chooses proper strategy with isAtLeastAndroidLollipop() method, which checks version of the system installed on a device and uses selected strategy in Observable<Beacon> observe() method from the library. Moreover, you can force using one of the existing strategies or your own custom scanning strategy with the following method available in the library:

Observable<Beacon> observe(ScanStrategy scanStrategy)

ScanStrategy is an interface with the following method:

Observable<Beacon> observe();

Beacon class

Beacon class represents BLE beacon and has the following attributes:

BluetoothDevice device;
int rssi;
byte[] scanRecord;
int txPower;

All of the elements are assigned dynamically, but txPower has default value equal to -59. It works quite fine for different types of beacons.

Beacon class has also getDistance() method, which returns distance from mobile device to beacon in meters and getProximity() method, which returns Proximity value.

Proximity can be as follows:

  • IMMEDIATE - from 0m to 1m
  • NEAR - from 1m to 3m
  • FAR - more than 3m

Beacon class has also static create(...) method responsible for creating Beacon objects.

Filter class

Filter class provides static filtering methods, which can be used with RxJava filter(...) method inside specific subscription.

Currently the following filters are available:

  • proximityIsEqualTo(Proximity)
  • proximityIsNotEqualTo(Proximity)
  • distanceIsEqualTo(double)
  • distanceIsGreaterThan(double)
  • distanceIsLowerThan(double)
  • hasName(String)
  • hasMacAddress(String)

Of course, we can create our own custom filters, which are not listed above if we need to.

Exemplary usage

In the example below, we are filtering all Beacons with Proximity equal to NEAR value.

reactiveBeacons.observe()
    .filter(Filter.proximityIsEqualTo(Proximity.NEAR))
    .subscribe(new Consumer<Beacon>() {
      @Override public void call(Beacon beacon) {
        beacons.put(beacon.device.getAddress(), beacon);
        refreshBeaconList();
      }
    });

Download

You can depend on the library through Maven:

<dependency>
    <groupId>com.github.pwittchen</groupId>
    <artifactId>reactivebeacons-rx2</artifactId>
    <version>0.6.0</version>
</dependency>

or through Gradle:

dependencies {
  compile 'com.github.pwittchen:reactivebeacons-rx2:0.6.0'
}

Tests

Tests are available in library/src/test/java/ directory and can be executed without emulator or Android device from CLI with the following command:

./gradlew test

Code style

Code style used in the project is called SquareAndroid from Java Code Styles repository by Square available at: https://github.com/square/java-code-styles. Currently, library doesn't have checkstyle verification attached. It can be done in the future.

Static code analysis

Static code analysis runs Checkstyle, FindBugs, PMD and Lint. It can be executed with command:

./gradlew check

Reports from analysis are generated in library/build/reports/ directory.

References

Useful resources

Producers of BLE beacons

Other APIs and libraries

License

Copyright 2015 Piotr Wittchen

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.

More Repositories

1

ReactiveNetwork

Android library listening network connection state and Internet connectivity with RxJava Observables
Java
2,527
star
2

spotify-cli-linux

🎢 A command line interface to Spotify on Linux
Python
637
star
3

NetworkEvents

Android library listening network connection state and change of the WiFi signal strength with event bus
Java
449
star
4

swipe

πŸ‘‰ detects swipe events on Android
Java
328
star
5

RxBiometric

☝️ RxJava and RxKotlin bindings for Biometric Prompt (Fingerprint Scanner) on Android
Kotlin
301
star
6

prefser

Wrapper for Android SharedPreferences with object serialization and RxJava Observables
Java
228
star
7

WeatherIconView

Weather Icon View for Android applications
Java
204
star
8

ReactiveWiFi

Android library listening available WiFi Access Points and related information with RxJava Observables
Java
189
star
9

InfiniteScroll

Infinite Scroll (Endless Scrolling) for RecyclerView in Android
Java
189
star
10

ReactiveSensors

Android library monitoring device hardware sensors with RxJava
Java
166
star
11

learning-linux

learning Linux (Unix) and collecting resources about it
99
star
12

kirai

String formatting library for Java, Android, Web and Unix Terminal
Java
71
star
13

interview-questions

interview questions for the software developer role and related resources
69
star
14

RxBattery

monitors battery state of the Android device
Kotlin
63
star
15

tmux-plugin-spotify

tmux plugin displaying currently played song on Spotify (linux only)
Shell
53
star
16

neurosky-android-sdk

Android SDK for the NeuroSky MindWave Mobile Brainwave Sensing Headset
Java
47
star
17

EEGReader

EEG Reader is an Android mobile application, which reads EEG signal from NeuroSky mobile device connected to smartphone via Bluetooth.
Java
39
star
18

android-quality-starter

setup CheckStyle, FindBugs, PMD and Lint for your Android project easily
Shell
29
star
19

ydocker

[unofficial PoC] get, build, initialize and run SAP Hybris Commerce Suite inside Docker container
Shell
29
star
20

ReactiveBus

🚍 Reactive Event Bus for JVM (1.7+) and Android apps built with RxJava 2
Java
17
star
21

android-looper-sample

Exemplary Android app showing usage of Handler and Looper
Java
15
star
22

SearchTwitter

Android app, which allows to search tweets as user types and scroll them infinitely (Contentful Android Task)
Java
15
star
23

learn-python-the-hard-way

Set of programs written during learning basics of Python and related resources 🐍
Python
13
star
24

dockerfiles-java

various docker images with java
Dockerfile
11
star
25

dotfiles

my dotfiles
Shell
10
star
26

dockerw

docker wrapper bash script template
Shell
10
star
27

android-resource-converter

Scripts converting Android *.xml resources with translations to *.csv file and backwards
Python
9
star
28

ReactiveAirplaneMode

✈️ Android library listening airplane mode with RxJava Observables
Java
8
star
29

money-transfer-api

HTTP server with REST API for money transfer between bank accounts (Revolut Backend Task)
Java
8
star
30

pkup

semi-automated generating of PKUP report
Python
6
star
31

airly-statusbar

bash script for reading AQI from the airly.eu sensors for BitBar (macOS) and Argos (Linux + Gnome) statusbar
Shell
6
star
32

learning-csharp

Set of simple programs written during learning basics of C# language
C#
4
star
33

fix-skype-icon

☎️ shell script to fix the Skype icon in Ubuntu
Shell
4
star
34

tmux-plugin-ip

tmux plugin showing IP number
Shell
4
star
35

voucher-storage-service

microservice developed during "Kyma meets CCV2 Hackathon"
Kotlin
4
star
36

reactive-client-server

An example of reactive client and server apps written for "Hack Your Career" presentation about Reactive Programming at Silesian University of Technology
Java
4
star
37

touch

Android library, which allows to monitor raw touch events on the screen of the device with RxJava
Java
3
star
38

wittchen.io

a source code of my personal website and blog
HTML
3
star
39

learning-cobol

Repository created to learn basics of COBOL language and feel some vintage breeze
COBOL
3
star
40

ydownloader

shell script for downloading SAP Hybris Commerce Suite from Artifactory
Shell
3
star
41

tmux-auto-pane

a tiny tool for creating pre-defined tile layouts in tmux on linux with xdotool
Shell
3
star
42

learning-R

Repository created in order to learn basics of R language
R
2
star
43

serverless-lambda-playground

Playing around with serverless solutions, lambdas, cloud functions, etc.
Java
2
star
44

noti.py

simple script to show system notifications on Linux
Python
2
star
45

git-branch-comparator

Checks if development branch has all changes from master branch in Git repository
Python
2
star
46

HriseyPlayground

Playing with Hrisey to remove boilerplate code from Android projects
Java
2
star
47

java-flow-experiments

Experimenting with Reactive Streams in Java 8 and Java 9. This repository is prepared for my talk "Get ready for java.util.concurrent.Flow!" at JDD 2017 Conference in KrakΓ³w, Poland
Java
2
star
48

wallpapers

wallpapers I use on my desktop
1
star
49

learning-go

learning basics of go language
Go
1
star
50

craplog

verifies whether your git log is a crap or not
Python
1
star
51

nyan-cat-loader

Nyan cat loader made just for fun in HTML5, CSS3 and JavaScript.
CSS
1
star
52

learning-asm-x64-linux

Repository created in order to learn basics of Assembly x64 for Linux
Assembly
1
star
53

tmux-plugin-uptime

tmux plugin showing computer uptime
Shell
1
star
54

java-playground

a repo created for testing and learning different features of java and jvm libraries
Java
1
star
55

cv

my cv/resume as a code in LaTeX
TeX
1
star
56

tmux-plugin-ram

tmux plugin showing RAM usage
Shell
1
star
57

tmux-plugin-battery

tmux plugin showing battery level
Shell
1
star
58

github-actions-playground

a repo for testing GitHub Actions
1
star
59

HelloAndroidKotlin

Hello World Android app written in Kotlin
Kotlin
1
star
60

learning-docker

learning basics of Docker
Makefile
1
star
61

yaas-java-sdk

YaaS (Hybris as a Service) Java SDK
Java
1
star
62

Ant-algorithm

Implementation of the ant algorithm for AI laboratory at my univeristy.
Pascal
1
star
63

kotlin-playground

Repository created in order to learn basics of Kotlin language
Kotlin
1
star