GithubHelp home page GithubHelp logo

android / location-samples Goto Github PK

View Code? Open in Web Editor NEW
2.7K 237.0 2.8K 1.3 MB

Multiple samples showing the best practices in location APIs on Android.

License: Apache License 2.0

Java 12.30% Kotlin 87.70%

location-samples's Introduction

Warning This sample has been deprecated and is no longer being maintained.

Find the new location samples in the new platform-samples repo.

Google Play Location & Context Samples

The location and context APIs harness the sensors and signals of mobile devices to provide awareness of user actions and their environment, enabling delightful and engaging experiences that simplify user interactions, provide assistance, and help users to better understand themselves.

This repo contains the following samples:

Prerequisites

  • Android API Level >v9
  • Android Build Tools >v21
  • Google Support Repository

Getting Started

These samples use the Gradle build system. To build a sample, use the "gradlew build" command or use "Import Project" in Android Studio.

Support

If you've found an error in these samples, please file an issue: https://github.com/android/location-samples/issues

Patches are encouraged, and may be submitted according to the instructions in CONTRIBUTING.md.

License

These samples are distributed under the terms of the Apache License (Version 2.0). See the license for more information.

location-samples's People

Contributors

carlospuk avatar codingjeremy avatar darioalessandro avatar dturner avatar frankgh avatar jdkoren avatar jfschmakeit avatar kokoro-team avatar marcelpinto avatar naokigoogle avatar owahltinez avatar paulrashidi avatar priebek avatar samtstern avatar shailen avatar tasomaniac avatar tiembo avatar viks178 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

location-samples's Issues

Geofence transitions not triggered on all devices

I have been using the Google Geofencing Service on Android for quite some time now and I just found out that the geofence transitions are not triggered on all devices. I've always tested with my HTC Nexus 5 and HTC Desire 320. But now I can see that the same code does not work on an Asus Zenfone 2 nor a Samsung Galaxy Tab 4.

SETTINGS_CHANGE_UNAVAILABLE when locations are enabled

Steps to reproduce:

  1. Enable Airplane mode (-> cell operator disabled)
  2. Disable Wi-Fi.
  3. Enable locations.
  4. Start "LocationSettings" example from this repositoty.

Expected result:
LocationSettingsStatusCodes.SUCCESS or LocationSettingsStatusCodes.RESOLUTION_REQUIRED in onResult callback, because we're still able to receive updates for the same LocationRequest object.

Actual result:
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE. However, we still can requestLocationUpdates and receive them.

How to enable Location when running app on device emulator

I get the error: "No Location detected. Make sure location is enabled on device."

How do you enable location?

I tried adding android geo api key to AndroidManifest.xml, ran the emulator and went into settings -> Personal -> Location and checked if on is available but it's still not showing anything other than this error message.

App crashes on load

I am using https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates Sample project to test whether app can get coordinates or not with only Wi-Fi enabled on Samsung Tab 4. But app crashes always.

I think app crashes because mCurrentLocation is always null when GPS is disabled and Wi-Fi is enabled and connected to active internet connection. Seems like FusedLocationApi failed to get location with just Wi-Fi enabled. And i think it won't call onLocationChanged() method ever.

It works fine when GPS is enabled.

Device info
Samsung Galaxy Tab® 4 10.1
Android OS: 5.0.2

Stack Trace


FATAL EXCEPTION: main
Process: com.google.android.gms.location.sample.locationupdates, PID: 20866
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.google.android.gms.location.sample.locationupdates.MainActivity.updateUI(MainActivity.java:270)
at com.google.android.gms.location.sample.locationupdates.MainActivity.onConnected(MainActivity.java:344)
at com.google.android.gms.common.internal.zzk.zzh(Unknown Source)
at com.google.android.gms.internal.zzlg.zznU(Unknown Source)
at com.google.android.gms.internal.zzlg.onConnected(Unknown Source)
at com.google.android.gms.internal.zzli$2.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzg.zzpf(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
at com.google.android.gms.common.internal.zzj$zza.zzt(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzc.zzph(Unknown Source)
at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6134)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

LocationAddress - "Address found" but no address shows

I try the project "LocationAddress".
After I push the button "FETCH ADDRESS", "Address found" shows but no address appears.
I find the code in FetchAddressIntentService.java line129

for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
     addressFragments.add(address.getAddressLine(i));
 }

The value of address.getMaxAddressLineIndex() is 0 when there's one element in the HashMap address.mAddressLines [index 0: "some address line value" ], so the program didn't step into the for loop. The ArrayList addressFragments doesn't get the address.

MainActivityTest failing

com.google.android.gms.location.sample.locationupdates.MainActivityTest > testUsingMockLocation[Nexus 4 - 5.1.1] FAILED
    junit.framework.AssertionFailedError: expected:<51.106829> but was:<90.0>
    at com.google.android.gms.location.sample.locationupdates.MainActivityTest.testUsingMockLocation(MainActivityTest.java:92)
:app:connectedAndroidTest FAILED

Actually it seems like I can't receive mock locations while using FusedLocationProviderApi at all. I pulled this repo to check what I'm doing wrong.

Btw it seems like assertEquals parameters in said test are in wrong order (first actual, then expected, should be the other way around).

Giving time out exception

I am getting java.io.IOException: Timed out waiting for response from server, while getting address from Location.

NOTE: There is no connectivity issue in my phone
Given internet permission in manifest file.

Failed to crunch file

Hi there,
I have a problem with samplecode and google-play dependences and drawable icons.
Every time that I compile the project this error happens with icons:

Error: com.android.builder.internal.aapt.AaptException: Failed to crunch file 

C:\Users\Francis\Documents\projects\mobile\android-play-location\Geofencing\Application\build\intermediates\exploded-aar\com.google.android.gms\play-services-base\8.4.0\res\drawable-mdpi\common_google_signin_btn_text_dark_normal.9.png into 

C:\Users\Francis\Documents\projects\mobile\android-play-location\Geofencing\Application\build\intermediates\res\merged\debug\drawable-mdpi\common_google_signin_btn_text_dark_normal.9.png

The icons exists but I not run my project because of that.
What's going wrong?

Running the App

Hi,

Do i need to install this app onto 2 devices to test its functionality?

May i ask developers to provide screenshots of the app running and performing what it is supposed to?
thanks.

GoogleApiClient not yet connected issue

Hi,

When clicking the "request updates" button in the app, I always get the toast "GoogleApiClient not yet connected. TryAgain."
I cloned the repo and installed as is on a Galaxy Note running Marshmallow 5.0. Couldn't find a fix yet, any ideas?

Use WakefulBroadcastReceiver instead of IntentService for handling background triggers to the app

I can't understand why you use IntentService for handling all stuff which happens in background.

Please note that device may go asleep (and it actually does go asleep) during IntentService is doing it's job.

Use WakefulBroadcastReceiver for this purpose which then triggers IntentService.

This issue applies to all examples, in particular GeofenceTransitionsIntentService and DetectedActivitiesIntentService.

Request location updates from Service

All of the samples show location updates being requested from an activity. Can this logic be moved to a IntentService, that way in the background you can monitor a user's location.

Specifically I want to use this so that I can dynamically remove and then add geofences as a users location significantly (the user moves more than 20 miles) changes.

GPS Bug on several older mobile devices

I just tried the BasicLocationSample and it does not work on my Samsung GT-S7562 device. I went to a showroom and tested the same on several devices and it doesn’t work on Xiaomi redmi 2, Galaxy core prime as well. The sample works fine on newer models from these manufacturers. I even tested it on my OnePlus 2 and it works perfectly well.

There appears to be a bug that prevents GPS working on several devices and that needs to be addressed. I’ve been trying to find a solution so I figured trying out this Google Sample hoping that at least this would work coz it’s from the makers of Android but in vain. Basically it shows No location detected. Make sure location is enabled on the device. even with the location enabled.

Testing the LocationUpdates sample on the same devices gave NullPointException at updateUI() function regardless of whether Location is enabled or disabled. On the newer devices like the OP2, the NullPointerException appears only when Location is disabled and shows updates and works fine when Location is enabled.

Cannot run MainActivityTest

I get an error:

FAILURE: Build failed with an exception.

  • What went wrong:
    Task 'cleanTest' not found in project ':app'.
  • Try:
    Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
    BUILD FAILED
    Total time: 1.607 secs
    Task 'cleanTest' not found in project ':app'.

Issues with GMS status codes

When GMS package is disabled (uninstalled all updates and disabled) the error dialog says GMS needs to be updated. When the user chooses to resolve this it opens Play Store app which crashes immediately. Because GMS package is disabled. This check should be performed before checking GMS version.

Head Bang !...Cant use and run them in Eclipse ?

Almost spent an hour trying fixes for the same. ?

Nothing in world seems to be working ? Can't I use them directly with import in eclipse?

05-30 16:19:49.517: E/AndroidRuntime(12302): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.google.android.gms.location.sample.basiclocationsample/com.google.android.gms.location.sample.basiclocationsample.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.location.sample.basiclocationsample.MainActivity" on path: DexPathList[dexElements=[zip file "/data/app/com.google.android.gms.location.sample.basiclocationsample-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.google.android.gms.location.sample.basiclocationsample-1, /vendor/lib, /system/lib]]

location is not working on General Mobile e Tab 3

Hi,

When I run my location code on cell phone I don't have any problem, but When I run it on General Mobile Tablet my location can not founded. Can you help me tihs about issue.

Thanks for your interest.

Google play service's v8.1.0's location listener is leaking the activity or service it is attached to

(Moving this issue from playgames to here on behalf of @youfacepalm)

I am not sure if this is the right place to report this since I could not find any common "Play Services" issue reporting forum anywhere.. If there is such an issue tracker, please give me the link. Thanks

The latest version of Google play service's (8.1.0 as of writing this report) LocationListener is leaking the activity or service it is attached to according to LeakCanary version 1.3.1.

Steps to reproduce

-Download the LocationUpdate Sample from google's repo (https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates)

-Update the gradle to include the latest version of Google play services (8.1.0, the sample contains Google play services version 6.5.87 which had no issues during my testing)

Add a regular activity (name it "TestActivity" for example) to the project

from the MainActivity, after starting the location update, go to the newly added (startActivity()) TestActivity while finishing the MainActivity (it doesn't matter if you stop or did not stop the location updates)

after about 5 seconds you will see LeakCanary reporting that the MainActivity has leaked (if it is added to the project)

Device Info:
Model: Samsung Galaxy S6 edge
OS: Android Lollipop v5.1.1 API 22

Trace:
D/LeakCanary﹕ In com.hammockstudio.myapplication:1.0:1.

com.hammockstudio.myapplication.MainActivity has leaked:
GC ROOT com.google.android.gms.location.internal.zzd$1$1.zzaFg (anonymous class extends com.google.android.gms.location.internal.zzg$zza)
references com.google.android.gms.location.internal.zzd$1.zzaFe (anonymous class extends com.google.android.gms.location.internal.zzd$zza)
leaks com.hammockstudio.myapplication.MainActivity instance [ 10-02 15:32:05.124 20752:21895 D/LeakCanary ]
Reference Key: c3aab681-4124-4c8c-ac2c-97d52fe63e4f
Device: samsung samsung SM-G925I zeroltedv
Android Version: 5.1.1 API: 22 LeakCanary: 1.3.1
Durations: watch=5016ms, gc=133ms, heap dump=2572ms, analysis=17078ms [ 10-02 15:32:05.124 20752:21895 D/LeakCanary ]
Details:
Instance of com.google.android.gms.location.internal.zzd$1$1 | zzaFg = com.google.android.gms.location.internal.zzd$1 [id=0x32e4f380] | mDescriptor = java.lang.String [id=0x32e563a0] | mObject = 547036342800 | mOwner = com.google.android.gms.location.internal.zzd$1$1 [id=0x32e56380]
Instance of com.google.android.gms.location.internal.zzd$1 | zzaFd = com.google.android.gms.location.LocationRequest [id=0x32dedf40] | zzaFe = com.hammockstudio.myapplication.MainActivity [id=0x32c179f0] | zzaFf = com.google.android.gms.location.internal.zzd [id=0x32df8510] | zzZM = com.google.android.gms.common.api.Api$zzc [id=0x32df84d0] | zzabg = java.util.concurrent.atomic.AtomicReference [id=0x32e55150] | zzL = true | zzaaX = com.google.android.gms.common.api.Status [id=0x32cdaf20] | zzabh = java.lang.Object [id=0x32e55130] | zzabi = com.google.android.gms.internal.zzlc$zza [id=0x32e562a0] | zzabj = java.util.ArrayList [id=0x32e56240] | zzabk = null | zzabl = false | zzabm = false | zzabn = null | zzabo = null | zzabp = null | zzoS = java.util.concurrent.CountDownLatch [id=0x32e55140]
Again, this leak did not happen in the Google Play Services version that came with the Location Updates sample!

Is possible to use LocationSettings and Geofencing?

I'm trying to do this since 7 days with no results...

The problem is ResultCallback, for geofencing I need ResultCallback while for LocationSettings I need ResultCallback, is there a way to do this?

I appreciate some tips...

Thanks for your support :)

Geofence Testing

What is the best way to test Geofencing? I wrote a blog article on this subject matter

http://lawloretienne.github.io/blog/

but now am having issues with the Google Maps app on the Genymotion device. Aside from physically going in and out of Geofences, what are the alternatives?

Also, I have set up geofences for stores inside a mall but don't see them triggering a notification. Do geofences still work inside of a mall?

A good example of background service getting location updates

Please I need help.

I'm facing a problem here. It is impossible to find A GOOD EXAMPLE of how create a service that must run in background and receive location updates. Also, all examples on developer.android.com are terrible, any one of them really works.

My app aim is get location updates in background, something which looks like so simple but unfortunately I could not find any good example about how to do it.

GEOFENCE_TOO_MANY_PENDING_INTENTS, GMS officially useless, 5 limit

Please remove the ridiculously low limit of max 5 geofences when using the PendingIntent method. Geofencing in GMS has, a reasonable, limit of 100 geofences, why restrict the use of the more background service friendly PendingIntent method to only 5, it should be 100 as well.

We can no longer justify using the Google Play Services location API, there's just too many issues, even if it claims to be more accurate and battery friendly. Reverting back to the proximity alarm API.

Geofence does not activate on entering or leaving, only activates when another request location

I have used the sample app and also followed the documentation on the Android developer site and i keep getting the same results.

The geofence does not trigger when i enter or leave the area around the geofence. To force the geofence to activate i have to open an app such as maps that polls for location updates then i get the geofence triggering.

I had to open an app that have a Google Places Picker then the geofence triggers. How do i resolve this since i do not need to keep polling for location updates and it looks as if i need to do that for the geofence to trigger?

Moving all location API code inside a helper class

In all samples the location API code is written inside a activity. wouldn't it be better if we move all logic inside a helper class. This way any activity can request the location by calling a function defined in helper class.

FusedLocationApi cannot retrieve satellites number as with android.location.LocationManager

As described in the documentation, I changed my application to use the new FusedLocationApi instead of the old android.location.LocationManager.

Everything works fine, but before, when I was using the android.location.LocationManager listener to retrieve the updates of the locations:

    @Override
    public void onLocationChanged(Location location) {
    }

inside the object "Location" I could see a list of Bundles (extras) like the "satellites", giving me information about the number of satellites used to retrieve that information.

Now, with the new service I cannot retrieve that information because the object Location.getExtras() is null.

I am using the current 9.4 google play services version.

Null Last known location when using a coarse location permission

In my case

  • target SDK: 21
  • build tools version: 21.1.2
  • play-services version: 6.5.87
  • running the sample on a Lollipop physical device

I'm always getting a null last known location with ACCESS_COARSE_LOCATION permission in the manifest file. Only getting a valid object when using ACCESS_FINE_LOCATION.

Geofence issue

Sometime geofence does not provide result after connection established.
Specially when we call action from service.

ActivityRecognition does not work in background on HTC M8 with Android 5.0.1

I'm using compile 'com.google.android.gms:play-services-location:8.1.0'.

It seems that ActivityRecognition sample does not work and is not sending any updates when device goes asleep. It does not work even if I use WakefulBroadcastReceiver mentioned in #28.

I've added notification to be fired from when DetectedActivitiesIntentService is triggered.

It works perfect on Sony C5303 Android 4.3 (notifications are but it does not work on HTC M8 Android 5.0.1 (i.e. notifications stop coming as soon as I press power button).

Issue "getGoogleAppId failed"

I am trying to 'BasicLocationSample' project after importing to Android Studio. The details of the setup are:

Android Studio: v1.4.1
JRE: 1.7.0_79
Android 6.0 (API 23)
Android SDK Tools: 24.4.1
Google Play Services Rev 29
Google Repository Rev 24

Gradle build was successful but while trying to run the app following error is seen in Android Monitor:

01-01 18:34:25.004 8182-8205/com.google.android.gms.location.sample.basiclocationsample I/GMPM: App measurement is starting up
01-01 18:34:25.007 8182-8205/com.google.android.gms.location.sample.basiclocationsample E/GMPM: getGoogleAppId failed with status: 10
01-01 18:34:25.008 8182-8205/com.google.android.gms.location.sample.basiclocationsample E/GMPM: Uploading is not possible. App measurement disabled

I am trying to run the app in Nexus 5 Emulator (in-built AVD). Is it the cause of the problem?

Not able to listen GpsStatus.Listener

I am not able to receive GpsStatus status change event using FusedLocationProviderAPI. How to receive satellite fix event using FusedLocationProviderAPI.

Enter Event is not triggering

I am setting my current lat long in the app but When I am launching this app, events are not triggering accordingly. PendingIntentService is receiving any notification. Please help me into it.

Thanks.

requestLocationUpdates with PendingIntent including extras not working, no Location

When using requestLocationUpdates() with a PendingIntent which include additional extras, the received "location update" Intent contains no Location, neither in the LocationResult or the deprecated FusedLocationProviderApi.KEY_LOCATION_CHANGED extra.

This recently ceased to work, it used to work fine.

All Android version are affected.
com.google.android.gms:play-services-location:8.1.0
Google Play Services 8.3.01

Disable location and Activity Recognizing sample still works

Hi,

In the ActivityRecognition's introduction, there is a sentence "To run this sample, location must be enabled." But when I disable "Android Location" ActivityRecognition sample still works. I just want to know is there any different in application behavior when I turn on or turn off location. Why it still work?
And the last question is which sensors ActivityRecognition API use?

Is there any way to use "Step Detector Sensor" and "Step Counter Sensor" to detect current user activity?

Thank you in advance.

Null

Hi.
I got null at:

public void onConnected(Bundle connectionHint) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

best regards
Rob

Issues with location status codes

After the user selects never to be bothered by LocationSettingsResult dialog again subsequent calls return LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE even when all requirements are satisfied.

How to load dynamically Geofences?

Hi,
I have a problem...in this sample you use geofence from Constant...unfortunately i'm not able to load geofences dynamically :-(

Maybe I wrong something...

In onCreate method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<Geofence>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;

    geofencePointsRequest(this, null, null);
}

Volley request to retrieve data

public void geofencePointsRequest(final Context context, Map<String,String> params, final ProgressDialog pDialog){
webService = new WebService();

CustomArrayRequest jsonObjReq = new CustomArrayRequest(
        Request.Method.GET,
        WebServiceUrl.POINTS,
        params,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                ArrayList<Point> points = webService.getPoints(response);
                populateGeofenceList(points);
            }
        },

        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String errorHandler = webService.getError(error);
                int status = (error.networkResponse.statusCode != 0) ? error.networkResponse.statusCode : 0;
                Toast.makeText(context, "Code : " + status + " - Error : " + errorHandler, Toast.LENGTH_LONG).show();
            }
        }) {

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return webService.getHeaders();
    }
};

VolleySingleton.getInstance(context).addToRequestQueue("pointsRequest", jsonObjReq);
}

Build GoogleApiClient

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mGoogleApiClient.connect();
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) mGoogleApiClient.connect();
}

On connected I load geofences

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    addGeofencesOnLoad();
}

private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

public void addGeofencesOnLoad() {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        logSecurityException(securityException);
    }
}

I create a list of geofences (from data parsed)

public void populateGeofenceList(ArrayList<Point> points) {
    for (int i=0; i<points.size(); i++) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(pins.get(i).getShortId())
                .setCircularRegion(
                        points.get(i).getLocation().getCoordinates().latitude,
                        points.get(i).getLocation().getCoordinates().longitude,
                        points.get(i).getLocation().getRadius()
                )
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                .build());
    }

    buildGoogleApiClient();
}

Thanks in advance :-)

connecting to google play services

I try to connect to google play services using the code of this sample.
But it does n`t connect and return connection result code 8(Internal error occurred.retrying should resolve the problem) and code 2(The installed version of Google Play services is out of date.
The calling activity should pass this error code to getErrorDialog(int, Activity, int) to get a localized error dialog that will resolve the error when shown.).
I cant understand error code 8. and I installed the latest version of google play services but i still receive error code 2.
Can you help me to resolve this problem and connect to google play services?

Why location must be enabled?

Hi all,
I remember in previous google play services version was possible to instantiate a geofence without location enabled (only with Wi-Fi for example).

Why in this sample do not work?

I allready read "To run this sample, location must be enabled.", but in this way the battery becoming low in small time.

Thanks

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.