RxGpsService


Source link: https://github.com/miguelbcr/RxGpsService

RxGpsService

An Android service to retrieve GPS locations and route stats using RxJava

Features:

  • Runtime permissions
  • Highly customizable
  • Always alive even if app is closed
  • Provides route stats (time, speeds, distance and waypoints)
  • Navigation mode auto/manual
  • Possibility to stop and resume the chrono at anytime

Setup

Add the JitPack repository in your build.gradle (top level module):

allprojects {

  repositories {

jcenter()

maven {
 url "https://jitpack.io" 
}

  
}
 
}

And add next dependencies in the build.gradle of the module:

dependencies {

  compile "com.github.miguelbcr:RxGpsService:0.1.0"
  compile "io.reactivex:rxjava:1.1.10" 
}

Usage

Starting the service

The basic usage is as follow, it will use the default configuration defined in GpsConfig

RxGpsService.builder(getActivity())

.startService(new RxGpsService.Listener() {

 @Override

 public NotificationCompat.Builder notificationServiceStarted(Context context) {

  return new NotificationCompat.Builder(context)

  .setContentTitle(context.getString(R.string.app_name))

  .setContentText(context.getString(R.string.route_started))

  .setSmallIcon(R.drawable.ic_place);

 
}

  @Override

 public void onServiceAlreadyStarted() {

  // Service is already started. 

  // Now you can listen for location updates

  startListenForLocationUpdates();

 
}

  @Override

 public void onNavigationModeChanged(boolean isAuto) {

  // Called when gps is switched from auto <-> manual

 
}

}
);

But you can start the RxGpsService using your custom config:

RxGpsService.builder(getActivity())

.withDebugMode(true)

.withSpeedMinModeAuto(5 / 3.6f)

.withStageDistance(0)

.withDiscardSpeedsAbove(150 / 3.6f)

.withMinDistanceTraveled(10)

.withPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)

.withInterval(10000)

.withFastestInterval(5000)

.withDetailedWaypoints(false)

.startService(new RxGpsService.Listener() {

 @Override

 public NotificationCompat.Builder notificationServiceStarted(Context context) {

  return new NotificationCompat.Builder(context)

  .setContentTitle(context.getString(R.string.app_name))

  .setContentText(context.getString(R.string.route_started))

  .setSmallIcon(R.drawable.ic_place);

 
}

  @Override

 public void onServiceAlreadyStarted() {

  // Service is already started. 

  // Now you can listen for location updates

  startListenForLocationUpdates();

 
}

  @Override

 public void onNavigationModeChanged(boolean isAuto) {

  // Called when gps is switched from auto <-> manual

 
}

}
);

Additionally for NotificationCompat.Builder you can set extra parameters in order to customize the notification created by RxGpsService:

RxGpsService.builder(getActivity())

.startService(new RxGpsService.Listener() {

 @Override

 public NotificationCompat.Builder notificationServiceStarted(Context context) {

  Bundle extras = new Bundle();

  extras.putBoolean(RxGpsServiceExtras.SHOW_TIME, true);

  extras.putString(RxGpsServiceExtras.TEXT_TIME, context.getString(R.string.time_elapsed));

  extras.putBoolean(RxGpsServiceExtras.SHOW_DISTANCE, true);

  extras.putString(RxGpsServiceExtras.TEXT_DISTANCE, context.getString(R.string.distance_traveled));

  extras.putString(RxGpsServiceExtras.BIG_CONTENT_TITLE, context.getString(R.string.route_details));

return new NotificationCompat.Builder(context)

  .setContentTitle(context.getString(R.string.app_name))

  .setContentText(context.getString(R.string.route_started))

  .setSmallIcon(R.drawable.ic_place)

  .setExtras(extras);

 
}

  @Override

 public void onServiceAlreadyStarted() {

  // Service is already started. 

  // Now you can listen for location updates

  startListenForLocationUpdates();

 
}

  @Override

 public void onNavigationModeChanged(boolean isAuto) {

  // Called when gps is switched from auto <-> manual

 
}

}
);

You can see all available options in RxGpsServiceExtras

Listening for location updates

In order to get the latest updated RouteStats object, you will need to subscribe to the RxGpsService#onRouteStatsUpdates() method, which is called every second, because of the chrono, but the RouteStats could vary depending on the GpsConfig used on the RxGpsService.Builder.

public class RouteFragment extends Fragment {

  private Subscription subscription;
  ....

@Override public void onDestroy() {

super.onDestroy();

unsubscribe();

  
}

private void unsubscribe() {

if (subscription != null) {

 subscription.unsubscribe();

 subscription = null;

}

  
}

private void startListenForLocationUpdates() {

if (RxGpsService.isServiceStarted()) {

 unsubscribe()

 subscription = RxGpsService.instance().onRouteStatsUpdates()

.subscribeOn(Schedulers.io())

.observeOn(AndroidSchedulers.mainThread())

.subscribe(new Action1<RouteStats>() {

 @Override

 public void call(RouteStats routeStats) {

  drawUserPath(routeStats);

 
}

}
, new Action1<Throwable>() {

 @Override

 public void call(Throwable throwable) {

  RxGpsService.stopService(getContext());

  unsubscribe();

 
}

}
);

}

  
}

... 
}
 

Stopping and resuming the route trip

You can stop or resume the route trip by using RxGpsService#stopChrono() or RxGpsService#playChrono() or you can enable the navigation mode to auto by using RxGpsService#setNavigationModeAuto() which will use builder.withSpeedMinModeAuto() to stop/resume the chrono if speed if lower/higher than specified respectively. But even with the navigation in on mode auto you can also use RxGpsService#stopChrono() or RxGpsService#playChrono().

Notice that RxGpsService#onRouteStatsUpdates() method will receive updates every seconds even when the RxGpsService#stopChrono() is called, but the RouteStats object will be the same just before when the chrono was stopped. So if you do not want to receive updates you only have to unsubscribe from the RxGpsService#onRouteStatsUpdates() subscription.

Example

You can see a complete example in sample app

A benchmark case

This is a memory size reference for RouteStats running for 10 hour and emitting 1 meaningful waypoint per second:

  • Using builder.withDetailedWaypoints(false): ~ 3Mb
  • Using builder.withDetailedWaypoints(true): ~ 12Mb

Credits

Authors

Miguel García

Another author's libraries:

  • RxPaparazzo: RxJava extension for Android to take images using camera and gallery.
  • OkAdapters: Wrappers for Android adapters to simply its api at a minimum

Another useful libraries used on the sample app:

  • ReactiveCache: A reactive cache for Android and Java which honors the Observable chain.
  • Jolyglot: Agnostic Json abstraction to perform data binding operations for Android and Java.
  • ACRA: Application Crash Reports for Android

Resources

async-expandable-list contains 2 View classes: CollectionView and AsyncExpandableListView.

AsyncExpandableListView displays a list of headers and loads a sub-list under a header when a header item is clicked. The loading of sub-items can be done asynchronously and there are callbacks to populate the data into the list when it's done loading.

This is a demo project on Flatbuffers. Flatbuffers is an android parsing library which is much faster then GSON.

This project explains how to setup flatbuffers and use them to serialize and deserialize the models.

Gradle script for downsizing graphical assets in development builds

Usually you don't care how big the deployed APK is. However, if you are using metered connection and remote ADB, it would be good idea to build possibly smallest APK file.

Uglyfier for Android is a gradle script which will shrink all image resources in your application during build. It will look ugly, but image files will be 10 times smaller. Ninepatch (9-patch) PNGs are fully supported, with transparency preserved!

Animated Time View like Timely app.

Circle progress view. Can be used as button.

Android Code Highlighter.

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