ReactiveSensors


Source link: https://github.com/pwittchen/ReactiveSensors

ReactiveSensors

Android library monitoring hardware sensors with RxJava.

Current Branch Branch Artifact Id Build Status Maven Central
RxJava1.x reactivesensors
☑? RxJava2.x reactivesensors-rx2

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

min sdk version = 9

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

Contents

Usage

Code sample below demonstrates how to observe Gyroscope sensor.

Please note that we are filtering events occurring when sensor readings change with ReactiveSensorFilter.filterSensorChanged() method. There's also event describing change of sensor's accuracy, which can be filtered with ReactiveSensorFilter.filterAccuracyChanged() method. When we don't apply any filter, we will be notified both about sensor readings and accuracy changes.

new ReactiveSensors(context).observeSensor(Sensor.TYPE_GYROSCOPE)
  .subscribeOn(Schedulers.computation())
  .filter(ReactiveSensorFilter.filterSensorChanged())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Consumer<ReactiveSensorEvent>() {

 @Override public void call(ReactiveSensorEvent reactiveSensorEvent) {

SensorEvent event = reactiveSensorEvent.getSensorEvent();

 float x = event.values[0];

float y = event.values[1];

float z = event.values[2];

 String message = String.format("x = %f, y = %f, z = %f", x, y, z);

 Log.d("gyroscope readings", message);

 
}

  
}
);
 
}

We can observe any hardware sensor in the same way. You can check list of all sensors in official Android documentation. To get list of all sensors available on the current device, you can use getSensors() method available in ReactiveSensors class.

Setting sampling period

Default sampling period for flowable below is set to SensorManager.SENSOR_DELAY_NORMAL.

Flowable<ReactiveSensorEvent> observeSensor(int sensorType)

We can configure sampling period according to our needs with the following flowable:

Flowable<ReactiveSensorEvent> observeSensor(int sensorType,

  final int samplingPeriodInUs)

We can use predefined values available in SensorManager class from Android SDK:

  • int SENSOR_DELAY_FASTEST - get sensor data as fast as possible
  • int SENSOR_DELAY_GAME - rate suitable for games
  • int SENSOR_DELAY_NORMAL - rate (default) suitable for screen orientation changes
  • int SENSOR_DELAY_UI - rate suitable for the user interface

We can also define our own integer value in microseconds, but it's recommended to use predefined values.

We can customize RxJava 2 Backpressure Strategy for our flowable with method:

Flowable<ReactiveSensorEvent> observeSensor(int sensorType, final int samplingPeriodInUs,

 final Handler handler, final BackpressureStrategy strategy)

Default Backpressure Strategy is BUFFER.

Example

Exemplary application, which gets readings of various sensors is located in app directory of this repository. You can easily change SENSOR_TYPE variable to read values from a different sensor in a given samples.

Good practices

Checking whether sensor exists

We should check whether device has concrete sensor before we start observing it.

We can do it in the following way:

if (reactiveSensors.hasSensor(SENSOR_TYPE)) {

// observe sensor 
}
 else {

// show error message 
}

Letting it crash

We can let our subscription crash and handle situation when device does not have given sensor e.g. in the Consumer<Throwable>() implementation (if we want to return Disposable) or in the onError(throwable) method implementation of the Subscriber. Other types of errors can be handled there as well.

new ReactiveSensors(context).observeSensor(Sensor.TYPE_GYROSCOPE)
  .subscribeOn(Schedulers.computation())
  .filter(ReactiveSensorFilter.filterSensorChanged())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Consumer<ReactiveSensorEvent>() {

 @Override public void accept(ReactiveSensorEvent reactiveSensorEvent) throws Exception {

// handle reactiveSensorEvent

 
}

  
}
, new Consumer<Throwable>() {

 @Override public void accept(Throwable throwable) throws Exception {

if (throwable instanceof SensorNotFoundException) {

  textViewForMessage.setText("Sorry, your device doesn't have required sensor.");

}

 
}

  
}
);

Subscribing and disposing flowables

When we are using Disposables in Activity, we should subscribe them in onResume() method and dispose them in onPause() method.

Filtering stream

When we want to receive only sensor updates, we should use ReactiveSensorFilter.filterSensorChanged() method in filter(...) method from RxJava.

When we want to receive only accuracy updates, we should use ReactiveSensorFilter.filterAccuracyChanged() method in filter(...) method from RxJava.

If we don't apply any filter, we will receive both accuracy and sensor readings updates.

Other practices

See also Best Practices for Accessing and Using Sensors.

Download

You can depend on the library through Maven:

<dependency>
  <groupId>com.github.pwittchen</groupId>
  <artifactId>reactivesensors-rx2</artifactId>
  <version>0.2.0</version> </dependency>

or through Gradle:

dependencies {

compile 'com.github.pwittchen:reactivesensors-rx2:0.2.0' 
}

Tests

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

./gradlew connectedCheck 

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

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. 

Resources

Markwon is a library for Android that renders markdown as system-native Spannables. It gives ability to display markdown in all TextView widgets (TextView, Button, Switch, CheckBox, etc), Notifications, Toasts, etc. No WebView is required. Library provides reasonable defaults for display style of markdown but also gives all the means to tweak the appearance if desired. All markdown features are supported (including limited support for inlined HTML code, markdown tables and images).

Flubber is an elegant solution for making animations in Android. The library is inspired by the Spring library for iOS. It supports all of the animations, curves and properties that are present in Spring. The library provides an interpolator called Spring which is similar to the iOS CASpringAnimation.

Promise library for JVM and Android based on the Promises/A+ specification from JavaScript.

Persian official calendar convertor.

Support shadow with CircleImageView.

This library allows to use customized Rating Dialog inside applications.

Supported features

  • colors for dialog's background, title, description
  • accent color for stars and action buttons
  • custom rating scope (number of stars)
  • note descriptions below rating bar, which describes each note
  • defining custom dialog's title and description
  • enter/exit window animation

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes