Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Location Based Reminder / Event?

I'm looking for code samples on how to get an event when a users device is close to a pre defined location. I see here how to get an auto completed list of locations using the Google Places API here:

https://developers.google.com/places/training/autocomplete-android

Using a location based on above, how can my app be notified when the user is close to the location they select. If I create a service that constantly polls location, then the daily usage for Google PLaces API will be way over the allotted amount (you only get 1,000 requests/day)...

like image 700
Mike6679 Avatar asked Oct 20 '22 15:10

Mike6679


1 Answers

Using the Google Play Services, you need to set up the Google API Client first

private void setUpApi() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();
    }

when the client is connected you can set up your reminder, using the coords you already know:

@Override
    public void onConnected(Bundle connectionHint) {
        Log.d(TAG, "connected!!");
         Geofence cinemaFence = new Geofence.Builder()
                    .setRequestId(id) // some id for you
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                    .setCircularRegion(mLatitude, mLongtitude, mRadius)
                    .build();

            GeofencingRequest request = new GeofencingRequest.Builder()
                    .addGeofence(cinemaFence)
                    .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
                    .build();

            // Now we create an intent that will be fired when the user enters the region
            Intent intent = new Intent(mContext, UserTransitionIntentService.class);
            intent.putExtra(UserTransitionIntentService.EXTRA_FEATURES, getFeaturesFlag());
            PendingIntent pi = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, request, pi);
    }

The full project can be found here: https://github.com/alexstyl/Location-Reminder

like image 77
Alex Styl Avatar answered Oct 23 '22 09:10

Alex Styl