Giter Club home page Giter Club logo

android-reactivelocation's Introduction

ReactiveLocation library for Android

Small library that wraps Google Play Services API in brilliant RxJava Observables reducing boilerplate to minimum.

Current stable version - 2.1

This version works with Google Play Services 11+ and RxJava 2.+

Artifact name: android-reactive-location2

RxJava1 stable version - 1.0

RxJava1 version:

Artifact name: android-reactive-location

What can you do with that?

  • easily connect to Play Services API
  • obtain last known location
  • subscribe for location updates
  • use location settings API
  • manage geofences
  • geocode location to list of addresses
  • activity recognition
  • use current place API
  • fetch place autocomplete suggestions

How does the API look like?

Simple. All you need is to create ReactiveLocationProvider using your context. All observables are already there. Examples are worth more than 1000 words:

Getting last known location

ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
    .subscribe(new Consumer<Location>() {
        @Override
        public void call(Location location) {
            doSthImportantWithObtainedLocation(location);
        }
    });

Yep, Java 8 is not there yet (and on Android it will take a while) but there is absolutely no Google Play Services LocationClient callbacks hell and there is no clean-up you have to do.

Subscribing for location updates

LocationRequest request = LocationRequest.create() //standard GMS LocationRequest
                                  .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                                  .setNumUpdates(5)
                                  .setInterval(100);

ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
Subscription subscription = locationProvider.getUpdatedLocation(request)
    .filter(...)    // you can filter location updates
    .map(...)       // you can map location to sth different
    .flatMap(...)   // or event flat map
    ...             // and do everything else that is provided by RxJava
    .subscribe(new Consumer<Location>() {
        @Override
        public void call(Location location) {
            doSthImportantWithObtainedLocation(location);
        }
    });

When you are done (for example in onStop()) remember to unsubscribe.

subscription.unsubscribe();

Subscribing for Activity Recognition

Getting activity recognition is just as simple

ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
Subscription subscription = locationProvider.getDetectedActivity(0) // detectionIntervalMillis
    .filter(...)    // you can filter location updates
    .map(...)       // you can map location to sth different
    .flatMap(...)   // or event flat map
    ...             // and do everything else that is provided by RxJava
    .subscribe(new Consumer<ActivityRecognitionResult>() {
        @Override
        public void call(ActivityRecognitionResult detectedActivity) {
            doSthImportantWithObtainedActivity(detectedActivity);
        }
    });

Reverse geocode location

Do you need address for location?

Observable<List<Address>> reverseGeocodeObservable = locationProvider
    .getReverseGeocodeObservable(location.getLatitude(), location.getLongitude(), MAX_ADDRESSES);

reverseGeocodeObservable
    .subscribeOn(Schedulers.io())               // use I/O thread to query for addresses
    .observeOn(AndroidSchedulers.mainThread())  // return result in main android thread to manipulate UI
    .subscribe(...);

Geocode location

Do you need address for a text search query?

Observable<List<Address>> geocodeObservable = locationProvider
    .getGeocodeObservable(String userQuery, MAX_ADDRESSES);

geocodeObservable
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(...);

Managing geofences

For geofence management use addGeofences and removeGeofences methods.

Checking location settings though location settings API

To get LocationSettingsResponse for your LocationRequest check out ReactiveLocationProvider.checkLocationSettings() method. Sample usage can be found in sample project in MainActivity class.

Connecting to Google Play Services API

If you just need managed connection to Play Services API use ReactiveLocationProvider.getGoogleApiClientObservable(). On subscription it will connect to the API. Unsubscription will close the connection.

Creating observable from PendingResult

If you are manually using Google Play Services and you are dealing with PendingResult you can easily transform them to observables with ReactiveLocationProvider.fromPendingResult() method.

Transforming buffers to observable

To transform any buffer to observable and autorelease it on unsubscription use DataBufferObservable.from() method. It will let you easily flatMap such data as PlaceLikelihoodBuffer or AutocompletePredictionBuffer from Places API. For usage example see PlacesActivity sample.

Places API

You can fetch current place or place suggestions using:

  • ReactiveLocationProvider.getCurrentPlace()
  • ReactiveLocationProvider.getPlaceAutocompletePredictions()
  • ReactiveLocationProvider.getPlaceById()

For more info see sample project and PlacesActivity.

Cooler examples

Do you need location with certain accuracy but don't want to wait for it more than 4 sec? No problem.

LocationRequest req = LocationRequest.create()
                         .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                         .setExpirationDuration(TimeUnit.SECONDS.toMillis(LOCATION_TIMEOUT_IN_SECONDS))
                         .setInterval(LOCATION_UPDATE_INTERVAL);

Observable<Location> goodEnoughQuicklyOrNothingObservable = locationProvider.getUpdatedLocation(req)
            .filter(new Func1<Location, Boolean>() {
                @Override
                public Boolean call(Location location) {
                    return location.getAccuracy() < SUFFICIENT_ACCURACY;
                }
            })
            .timeout(LOCATION_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS, Observable.just((Location) null), AndroidSchedulers.mainThread())
            .first()
            .observeOn(AndroidSchedulers.mainThread());

goodEnoughQuicklyOrNothingObservable.subscribe(...);

How to use it?

Library is available in maven central.

Gradle

Just use it as dependency in your build.gradle file along with Google Play Services and RxJava.

dependencies {
    ...
    compile 'pl.charmas.android:android-reactive-location2:2.1@aar'
    compile 'com.google.android.gms:play-services-location:11.0.4' //you can use newer GMS version if you need
    compile 'com.google.android.gms:play-services-places:11.0.4'
    compile 'io.reactivex:rxjava:2.0.5' //you can override RxJava version if you need
}

Maven

Ensure you have android-maven-plugin version that support aar archives and add following dependency:

<dependency>
    <groupId>pl.charmas.android</groupId>
    <artifactId>android-reactive-location2</artifactId>
    <version>2.1</version>
    <type>aar</type>
</dependency>

It may be necessary to add google play services and rxanroid dependency as well.

Sample

Sample usage is available in sample directory.

Places API requires API Key. Before running samples you need to create project on API console and obtain API Key using this guide. Obtained key should be exported as gradle property named: REACTIVE_LOCATION_GMS_API_KEY for example in ~/.gradle/gradle.properties.

References

If you need Google Fit library rxified please take a look at RxFit.

License

Copyright (C) 2015 Michał Charmas (http://blog.charmas.pl)

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.

android-reactivelocation's People

Contributors

chris-horner avatar cyrixmorten avatar edenman avatar egor-n avatar gbero avatar intrications avatar mcharmas avatar moskvax avatar niqo01 avatar numan1617 avatar phajduk avatar plackemacher avatar pranaysharma avatar r4md4c avatar rindress avatar rishibaldawa avatar romaniakovlev avatar sebastianmarschall avatar sytolk avatar turbo87 avatar zoltanf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-reactivelocation's Issues

Is it possible to change update interval?

Hi, is it possible to change update location interval dynamically?

For some stage of the app I want it update like every 10 minutes, but some stage i need it to be like close to real- time.

Thank in advance!

GeoFencing not working

I tried to use the geofencing but it is not triggering any event on enter and exit. But with the same code pending intent and geofencing request i used the default google play library then working. So i think geofencing has some problem. Can you please guide?

rx.android... import problem.

I'm exploring your library and Sample project cannot be built.

Import rx.android.whatever in utils/TextObservable.java is invalid. rx.Observable and rx.functions.Func1 are OK, but every import with 'android' in name is with error. I checked RxJava repo and android package is not in the source code O_o.

Is your sample project runnable?

proguard

I have use it with proguard and have this exception from Acra (I cant repeat it).
HUAWEI Y220-U00 Android '2.3.6
Is there some custom proguard configuration or RxJava ?

b.a.e: Error connecting to LocationClient.
at b.a$2.a(Observable.java:5890)
at b.c.a.b(SafeSubscriber.java:125)
at b.c.a.a(SafeSubscriber.java:94)
at b.d.a$1.a(OperatorFilter.java:47)
at a.a.a.a.a.b.a(BaseLocationObservable.java:84)
at com.google.android.gms.internal.cz.a(Unknown Source)
at com.google.android.gms.internal.db.a(Unknown Source)
at com.google.android.gms.internal.da.a(Unknown Source)
at com.google.android.gms.internal.da.a(Unknown Source)
at com.google.android.gms.internal.cv.b(Unknown Source)
at com.google.android.gms.internal.cu.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(Looper.java:384)
at android.app.ActivityThread.main(ActivityThread.java:3975)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732)
at dalvik.system.NativeStart.main(Native Method)
Caused by: a.a.a.a.a.c: Error connecting to LocationClient.
... 15 more
a.a.a.a.a.c: Error connecting to LocationClient.
at a.a.a.a.a.b.a(BaseLocationObservable.java:84)
at com.google.android.gms.internal.cz.a(Unknown Source)
at com.google.android.gms.internal.db.a(Unknown Source)
at com.google.android.gms.internal.da.a(Unknown Source)
at com.google.android.gms.internal.da.a(Unknown Source)
at com.google.android.gms.internal.cv.b(Unknown Source)
at com.google.android.gms.internal.cu.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(Looper.java:384)
at android.app.ActivityThread.main(ActivityThread.java:3975)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732)
at dalvik.system.NativeStart.main(Native Method)

Activity Recognition Subscription question

Hi ,

Im subscribing to activity recognition with this function in a service :

public void activity_subs(){

        activitySubscription=   locationProvider.getDetectedActivity(0) // detectionIntervalMillis

                .subscribe(new Action1<ActivityRecognitionResult>() {
                    @Override
                    public void call(ActivityRecognitionResult detectedActivity) {
                        //doSthImportantWithObtainedActivity(detectedActivity);
}
});
}

Now i've noticed that if i call this function multiple times and then i call to :

 activitySubscription.unsubscribe();

Then Activity Recognition still keeps running even though i want it to stop.

so if im calling to activity_subs() multiple times it does not override but gets new subscription every call??

Thanks.

Multiple Geofences

Hi ,

I've tryied to add two geofences but apperently only the last one is working .
it's like the last one is overriding the first one.
Maybe i dont add them right .

Thats how i add them:

    private void addGeofence() {
        final GeofencingRequest geofencingRequest = createGeofencingRequest();
        if (geofencingRequest == null) return;

        final PendingIntent pendingIntent = createNotificationBroadcastPendingIntent();
        reactiveLocationProvider
                .removeGeofences(pendingIntent)
                .flatMap(new Func1<Status, Observable<Status>>() {
                    @Override
                    public Observable<Status> call(Status pendingIntentRemoveGeofenceResult) {
                        return reactiveLocationProvider.addGeofences(pendingIntent, geofencingRequest);
                    }
                })
                .subscribe(new Action1<Status>() {
                    @Override
                    public void call(Status addGeofenceResult) {
                        toast("Geofence added, success: " + addGeofenceResult.isSuccess());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        toast("Error adding geofence.");
                        Log.d(TAG, "Error adding geofence.", throwable);
                    }
                });
    }

    private GeofencingRequest createGeofencingRequest() {
        try {

            Geofence geofence = new Geofence.Builder()
                    .setRequestId(ID)
                    .setCircularRegion(latitude, longitude, radius)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();
            return new GeofencingRequest.Builder().addGeofence(geofence).build();
        } catch (NumberFormatException ex) {
            toast("Error parsing input.");
            return null;
        }
    }

For every geofence i add different id.

gms DeadObjectException

this Exception is with version 0.2 and play service v. 5.x.x
I have read this:
http://stackoverflow.com/questions/24288685/deadobjectexception-in-gmslocationclient-android

d.a.d: android.os.DeadObjectException
at d.c.a.b(SafeSubscriber.java:184)
at d.c.a.a(SafeSubscriber.java:94)
at d.d.a$1.a(OperatorFilter.java:47)
at c.a.a.a.a.b.a(BaseLocationObservable.java:69)
at com.google.android.gms.internal.il.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ik.b(Unknown Source)
at com.google.android.gms.internal.ij.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4747)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: android.os.DeadObjectException
at com.google.android.gms.location.d.a(Unknown Source)
at c.a.a.a.a.a.a.a(LocationUpdatesObservable.java:42)
at c.a.a.a.a.a$1.a(BaseLocationObservable.java:42)
at d.f.c.b(Subscriptions.java:63)
at d.f.a.a(SubscriptionList.java:86)
at d.f.a.b(SubscriptionList.java:76)
at d.e.b(Subscriber.java:66)
at d.c.a.b(SafeSubscriber.java:177)
... 18 more
Caused by: android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at com.google.android.gms.internal.lw.a(Unknown Source)
at com.google.android.gms.internal.lx.a(Unknown Source)
at com.google.android.gms.internal.ma.a(Unknown Source)
... 26 more
java.lang.IllegalStateException: android.os.DeadObjectException
at com.google.android.gms.location.d.a(Unknown Source)
at c.a.a.a.a.a.a.a(LocationUpdatesObservable.java:42)
at c.a.a.a.a.a$1.a(BaseLocationObservable.java:42)
at d.f.c.b(Subscriptions.java:63)
at d.f.a.a(SubscriptionList.java:86)
at d.f.a.b(SubscriptionList.java:76)
at d.e.b(Subscriber.java:66)
at d.c.a.b(SafeSubscriber.java:177)
at d.c.a.a(SafeSubscriber.java:94)
at d.d.a$1.a(OperatorFilter.java:47)
at c.a.a.a.a.b.a(BaseLocationObservable.java:69)
at com.google.android.gms.internal.il.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ik.b(Unknown Source)
at com.google.android.gms.internal.ij.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4747)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at com.google.android.gms.internal.lw.a(Unknown Source)
at com.google.android.gms.internal.lx.a(Unknown Source)
at com.google.android.gms.internal.ma.a(Unknown Source)
... 26 more
android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at com.google.android.gms.internal.lw.a(Unknown Source)
at com.google.android.gms.internal.lx.a(Unknown Source)
at com.google.android.gms.internal.ma.a(Unknown Source)
at com.google.android.gms.location.d.a(Unknown Source)
at c.a.a.a.a.a.a.a(LocationUpdatesObservable.java:42)
at c.a.a.a.a.a$1.a(BaseLocationObservable.java:42)
at d.f.c.b(Subscriptions.java:63)
at d.f.a.a(SubscriptionList.java:86)
at d.f.a.b(SubscriptionList.java:76)
at d.e.b(Subscriber.java:66)
at d.c.a.b(SafeSubscriber.java:177)
at d.c.a.a(SafeSubscriber.java:94)
at d.d.a$1.a(OperatorFilter.java:47)
at c.a.a.a.a.b.a(BaseLocationObservable.java:69)
at com.google.android.gms.internal.il.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.iq.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ip.a(Unknown Source)
at com.google.android.gms.internal.ik.b(Unknown Source)
at com.google.android.gms.internal.ij.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4747)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

Cannot resolve method: 'Action1<DetectedActivity>'

Im trying to create a service which will receive activity recognition result.

I wrote this in my code:

locationProvider.getDetectedActivity(0) // detectionIntervalMillis
    .subscribe(new Action1<DetectedActivity>() {
        @Override
        public void call(DetectedActivity detectedActivity) {
            doSthImportantWithObtainedActivity(detectedActivity);
        }
    });

But android studio does not recognize
"Action1 DetectedActivity" .

all the others like location updates and geofencing is working great!

Any idea what is going on?

App crashes

on htc 1 with android 4.1.1 i keep getting crashes

logcat

 Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
07-23 17:03:59.747  26391-26391/ E/AndroidRuntime﹕ FATAL EXCEPTION: main
    rx.exceptions.OnErrorNotImplementedException: Error connecting to GoogleApiClient.
            at rx.Observable$30.onError(Observable.java:7334)
            at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154)
            at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111)
            at pl.charmas.android.reactivelocation.observables.BaseObservable$ApiClientConnectionCallbacks.onConnectionFailed(BaseObservable.java:107)
            at com.google.android.gms.common.internal.zzj.zzh(Unknown Source)
            at com.google.android.gms.common.api.zze.zzd(Unknown Source)
            at com.google.android.gms.common.api.zze.zza(Unknown Source)
            at com.google.android.gms.common.api.zze$1.run(Unknown Source)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5454)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: pl.charmas.android.reactivelocation.observables.GoogleAPIConnectionException: Error connecting to GoogleApiClient.
            at pl.charmas.android.reactivelocation.observables.BaseObservable$ApiClientConnectionCallbacks.onConnectionFailed(BaseObservable.java:107)
            at com.google.android.gms.common.internal.zzj.zzh(Unknown Source)
            at com.google.android.gms.common.api.zze.zzd(Unknown Source)
            at com.google.android.gms.common.api.zze.zza(Unknown Source)
            at com.google.android.gms.common.api.zze$1.run(Unknown Source)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5454)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
            at dalvik.system.NativeStart.main(Native Method)

Feature Request: unit tests

Can you please consider adding unit tests to your library or sample? I would like to see stuff similar toMockWebServer, MockResponse, and MockRetrofit. This will explain how to test the networking calls which are being made by this library.

Error connecting to GoogleApiClient

I've tried to use the library but when I started the location update subscription with this code:

I get these errors:

rx.exceptions.OnErrorNotImplementedException: Error connecting to GoogleApiClient.
at rx.Observable$36.onError(Observable.java:8420)
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:128)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:97)
at pl.charmas.android.reactivelocation.observables.BaseObservable$ApiClientConnectionCallbacks.onConnectionFailed(BaseObservable.java:107)
at com.google.android.gms.common.internal.zzj.zzj(Unknown Source)
at com.google.android.gms.common.api.zze.zzf(Unknown Source)
at com.google.android.gms.common.api.zze.zzkP(Unknown Source)
at com.google.android.gms.common.api.zze.zzf(Unknown Source)
at com.google.android.gms.common.api.zze$zzc.zza(Unknown Source)
at com.google.android.gms.common.internal.zzi$zzb.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: pl.charmas.android.reactivelocation.observables.GoogleAPIConnectionException: Error connecting to GoogleApiClient.
            at pl.charmas.android.reactivelocation.observables.BaseObservable$ApiClientConnectionCallbacks.onConnectionFailed(BaseObservable.java:107)
            at com.google.android.gms.common.internal.zzj.zzj(Unknown Source)
            at com.google.android.gms.common.api.zze.zzf(Unknown Source)
            at com.google.android.gms.common.api.zze.zzkP(Unknown Source)
            at com.google.android.gms.common.api.zze.zzf(Unknown Source)
            at com.google.android.gms.common.api.zze$zzc.zza(Unknown Source)
            at com.google.android.gms.common.internal.zzi$zzb.handleMessage(Unknown Source)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3687)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
            at dalvik.system.NativeStart.main(Native Method)

What should I set?

Unimplemented exception

Hi, looks like some exception handling method is not implemented.

Here is my stack:

java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add onError handling.
1 at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:60)
2 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
3 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
4 at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
5 at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
6 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
7 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
8 at java.lang.Thread.run(Thread.java:841)
9Caused by: rx.exceptions.OnErrorNotImplementedException
10 at rx.Observable$27.onError(Observable.java:7535)
11 at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154)
12 at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111)
13 at rx.internal.operators.OperatorSubscribeOn$1$1$1.onError(OperatorSubscribeOn.java:71)
14 at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:197)
15 at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:170)
16 at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
17 ... 7 more
18Caused by: rx.exceptions.MissingBackpressureException
19 at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.onNext(OperatorObserveOn.java:138)
20 at rx.internal.operators.OperatorSubscribeOn$1$1$1.onNext(OperatorSubscribeOn.java:76)
21 at pl.charmas.android.reactivelocation.observables.location.LocationUpdatesObservable$1.onLocationChanged(LocationUpdatesObservable.java:36)
22 at com.google.android.gms.internal.nj$a.handleMessage(Unknown Source)
23 at android.os.Handler.dispatchMessage(Handler.java:102)
24 at android.os.Looper.loop(Looper.java:146)
25 at android.app.ActivityThread.main(ActivityThread.java:5692)
26 at java.lang.reflect.Method.invokeNative(Native Method)
27 at java.lang.reflect.Method.invoke(Method.java:515)
28 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
29 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
30 at dalvik.system.NativeStart.main(Native Method)

Cannot use play services 8.1.0

Hello,
I keep getting a crash:

IllegalStateException: Fatal Exception thrown on Scheduler.Worker thread.
IncompatibleClassChangeError: The method 'void com.google.android.gms.common.api.GoogleApiClient.connect()'

Please advise.

Strange Activity Recognition behaviour

Hi.

I've subscribed activity recognition in two services.

the first service listens to activity recognition with this call :

activitySubscription=   locationProvider.getDetectedActivity(0) // detectionIntervalMillis

                .subscribe(new Action1<ActivityRecognitionResult>() {
                               @Override
                               public void call(ActivityRecognitionResult detectedActivity) {
                                   //doSthImportantWithObtainedActivity(detectedActivity);
}
});

The second service listens to activity recognition with the same variable : activitySubscription

Now , when i call from the first service to

activitySubscription.unsubscribe();

The second subscription on the second service also unsubscribing for some reason.

What can be the result of this issue?
Thanks

Google Play Services 8.1.0 support?

Not sure why, but if I update GPS to 8.1.0 I can't get any fix from my ReactiveLocationProvider... No error thrown, no completion. Any clue?

App always shows high power use after update

I've set up a getUpdatedLocation observable that only requests 1 update using high power. I've noticed the high battery power notification in the status bar hangs around after I get that update. Do I need to remove the subscription for it to remove that bubble?

Is it wise to create a new instance of GoogleApiClient for every Observable?

Great library! It is certainly going to be useful. However, I have one concern. It seems that for every Observable that extends BaseObservable a new instance of GoogleApiClient is created. Is this not a waste of resources? Wouldn't it be better if ReactiveLocationProvider would somehow cache the apiClient?

Mock locations not working

Hello,
I am testing your sample where I am setting a mock location. However, it doesn't do anything. My Google map still shows me at my old location. Please advise.

Igor

getLastKnownLocation() doesn't call next() if GPS is off

The getLastKnownLocation() method defaults to calling "observer.onCompleted()", skipping onNext() if the location is null

https://github.com/mcharmas/Android-ReactiveLocation/blob/master/android-reactive-location/src/main/java/pl/charmas/android/reactivelocation/observables/location/LastKnownLocationObservable.java#L29

This makes it difficult to chain with other observables:

 Subscription subscription = locationProvider.getLastKnownLocation()
            .timeout(LOCATION_TIMEOUT_IN_SECONDS,
                     TimeUnit.SECONDS,
                     Observable.just((Location) null))
            .onErrorResumeNext(Observable.just((Location) null))
            .concatWith(locationProvider.getUpdatedLocation(req))
            .distinctUntilChanged()
            .subscribe(this::updateLocationIfPossible);

In this example, I would like to get a null location so that I can react accordingly, in this case I prompt the user to enable GPS. Then, once GPS is on, the observable will emit the updated location and I can again take action.

updates in the documentation might be necessary

Followed readme instructions and also instructions inside http://developer.android.com/google/play-services/setup.html

Not sure if intellij cannot find the package/classes.

LocationRequest cannot be found
Also from sample the import com.google.android.gms.location.LocationRequest package does not seem to exist (while com.google.android.gms does exist)

Packages rx.android.observables, rx.android.schedulers and rx.schedulers cannot be found (while rx.util, rx.Observable and rx.Subscription are found just fine)

Thanks

Extending library to support others Google Play APIs?

What do you think about extracting from library the base module with the GoogleAPIClientObservable and all related class? So we could build upon one base all API specific modules.

BTW Thanks to all contributors, good work, keep going :)

New feature Tracert

It will be good feature if I can start/stop tracert and after stop to have statistic for mileage, time stay on one place..

does it make sense to support all Places like APIs?

for example if i wanted to search for a place (hotel) at a particular location? i get a sense that most of the current features revolve around the user's current location. if that is the intent, then supporting such a feature doesn't make sense.

was just curious if this would be a feature you're willing to consider (say if a PR was sent your way)

Activity Recognition

I have created this fork adding support for activity recognition: https://github.com/cyrixmorten/Android-ReactiveLocation

The sample has also been updated to demonstrate the new feature. For this, I have had to add a Start/Stop button, allowing the Activity detection to continue running after onStop. All subscriptions are always unsubscribed in onDestroy, though.

Before requesting a merge, I have a problem that I would like to find a solution to. The usage of Activity Recognition requires the DetectedActivity results be handed to an IntentService. This pattern does seemingly not fit well with RxJava, as I would like to feed the results to an observer living outside the IntentService.

My initial attempt was based on passing a ResultReceiver to the intent that is handed to the IntentService by a PendingIntent. This idea is based on the answers to this SO question: http://stackoverflow.com/questions/4510974/using-resultreceiver-in-android
The relevant code is kept but commented out in ActivityUpdatesObservable

Unfortunately it turns out that passing any values to the intent this way makes it 'freeze' in the current state. That is, the values are not updated properly to reflect the detected activity, rather, the passed information is just repeated.

I hope that you, or someone else reading this has more knowledge on the subject and can come up with a way around the problem.
Also added a question on SO on the subject: http://stackoverflow.com/questions/27757437/activityrecognitionresult-hasresultintent-false-when-adding-extras-to-the-inte

Currently, I have simply created a static reference to the observer that the IntentService can grab, calling onNext with the detected activity. This is not an acceptable solution as it allows only one observer at a time. Nonetheless, it is working and is a start.

in sample-app: Internal data leak within a DataBuffer object detected! Be sure to explicitly call release() on all DataBuffer extending objects when you are done with them. (AutocompletePredictionBuffer{status=Status{statusCode=SUCCESS, resolution=null}})

08-21 09:04:26.063 2556-2570/pl.charmas.android.reactivelocation.sample E/DataBuffer﹕ Internal data leak within a DataBuffer object detected! Be sure to explicitly call release() on all DataBuffer extending objects when you are done with them. (AutocompletePredictionBuffer{status=Status{statusCode=SUCCESS, resolution=null}})

Sample Not Working

I tried importing the project to my studio V 0.8.6 but for some reason it shows me this error
screenshot from 2014-08-20 13 37 31
Can you please help me

BaseLocationObservable$LocationConnectionCallbacks:onConnectionFailed:84

Hi, using this awesome lib, but I have couple crashes in Google Analytics:

LocationConnectionException(@BaseLocationObservable$LocationConnectionCallbacks:onConnectionFailed:84) {main}

Using like this:
new ReactiveLocationProvider(getActivity()).getLastKnownLocation().subscribe(new Action1<Location>() { @Override public void call(Location location) { ... } });

Any clue, why I get this exception? Thanks!

How can i get current city with locationProvider.getCurrentPlace() ?

I've tried to pass PlaceFilter.

public static PlaceFilter getPlaceFilter() {
    List<Integer> filterTypes = new ArrayList<>();
    filterTypes.add(Place.TYPE_LOCALITY);
    filterTypes.add(Place.TYPE_ADMINISTRATIVE_AREA_LEVEL_3);
    return new PlaceFilter(filterTypes, false, null, null);
}

locationProvider.getCurrentPlace(getPlaceFilter)

But no result. It always returns a company, registered inside my house.

Geofences get deleted?

Hello ,

I've noticed lately that when users are updating the app , all geofences are deleted?
is that possible to keep them even when app is updating?

Thanks.

Can not get getLastKnownLocation to run as blocking call

Hello,

I am hitting the wall since quite a while. No I try to get a solution here. My problem:

When i use the basic call as shown in the Readme

ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
.subscribe(new Action1() {
@OverRide
public void call(Location location) {
doSthImportantWithObtainedLocation(location);
}
});

the call comes back as expected asynchronously at a later stage. Thats fine. In some areas i really need to wait till the result is already back before proceeding. I tried solutions like:

        locationProvider.getLastKnownLocation()
                .subscribeOn(Schedulers.newThread())  
                .observeOn(Schedulers.newThread())
                .toBlocking()

                .forEach(new Action1<Location>() {
                   @Override
                   public void call(Location location) {
                       setLocation(location);
                       Timber.i(CommonValues.TAG, "jo!");
                   }
               });

This one never comes back - i am getting a threading exception "down under".

The really strange thing is that at yet another area in the code i am using this:

    Observable<Location> locationObservable = LastKnownLocationObservable.createObservable(ctx);
    Iterable<Location> locations = BlockingObservable.from(locationObservable).toIterable();
    Location location = locations.iterator().next();

and it works! (But not in other areas of the code).

Has someone any hint what is wrong here?

Besides that i really like the library and maaaany thanks for it and also the frequent updates.

cheers

Juergen

setinterval(8*1000) not triggering the update on 8 sec but it is triggering each second!

locationProvider.getUpdatedLocation(
LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setNumUpdates(1500)
.setInterval(8*1000);
This code i used but it seems like interval not working with seconds value.

but if i use this .setInterval(6 * 6* 1000) value then it gives me request each 7 seconds.
So may be i am confused setting interval .Can you please guide.

P.S. Thank man for your smart work..!

Location updates not working when WiFi is enabled.

Apologies if i'm doing something wrong here.

I'm subscribing for location updates but I only get the updates when wifi is turned off

My code:

LocationRequest request = LocationRequest.create() //standard GMS LocationRequest
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        .setSmallestDisplacement(0.1f)
        .setNumUpdates(5)
        .setInterval(100);

Subscription subscription = locationProvider.getUpdatedLocation(request)
        .subscribe(new Action1<Location>() {
            @Override
            public void call(Location location) {
              //do stuff
            }
        });

As soon as I disable wifi I start receiving the updates.

NullPointer exception in sample

Hi
Thanks for the great library. Can you change in sample LocationToStringFunc like this, to avoid null pointer exception if its running in emulator:

private static class LocationToStringFunc implements Func1<Location, String> {
@OverRide
public String call(Location location) {
if (location != null)
return location.getLatitude() + " " + location.getLongitude() + " (" + location.getAccuracy() + ")";
return "no location available";
}
}

Dex method count

Hello,
I just ran a dexcount gradle plugin on your repo, and your sample-debug.apk has 25782 methods. That is 40% of the allowed limit in dex on Android! Is there any way to exclude dependencies? I am using your library in my project, and I am afraid it's decimating my dexcount as well.

Thanks,
Igor

Get location using GPS satellites if 'Use wireless networks' options is not checked

Hi,

I'm using following codes and everything is okay if the 'Use wireless networks' options is checked but that's not enough good to get location, because if a user turned that option off, this library will not work and it cannot get location using GPS satellites option. How can I force this library to get location using GPS satellites if 'Use wireless networks' option is not checked?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.