Skip to content Skip to sidebar Skip to footer

How To Receive Location Updates Every 5 Minutes Using The Fusedlocation Api

I am currently working on an app that has to check the user's location every five minutes and send the coordinates to a server. I decided to go with the FusedLocation API in Google

Solution 1:

I am currently working on an app that has to check the user's location every five minutes and send the coordinates to a server. I decided to go with the FusedLocation API in Google Play Services instead of the plain old LocationManager API

Our app has exactly that same requirement, I implemented that a couple of days ago and here is how I did it.

In the launch activity or wherever you want to start, configure a LocationTracker to run every 5 minutes, using an AlarmManager.

privatevoidstartLocationTracker() {
    // Configure the LocationTracker's broadcast receiver to run every 5 minutes.Intentintent=newIntent(this, LocationTracker.class);
    AlarmManageralarmManager= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntentpendingIntent= PendingIntent.getBroadcast(this, 0, intent, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(),
            LocationProvider.FIVE_MINUTES, pendingIntent);
}

LocationTracker.java

publicclassLocationTrackerextendsBroadcastReceiver {

    private PowerManager.WakeLock wakeLock;

    @OverridepublicvoidonReceive(Context context, Intent intent) {
        PowerManagerpow= (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pow.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wakeLock.acquire();

        LocationcurrentLocation= LocationProvider.getInstance().getCurrentLocation();

        // Send new location to backend. // this will be different for you
        UserService.registerLocation(context, newHandlers.OnRegisterLocationRequestCompleteHandler() {
            @OverridepublicvoidonSuccess() {
                Log.d("success", "UserService.RegisterLocation() succeeded");

                wakeLock.release();
            }

            @OverridepublicvoidonFailure(int statusCode, String errorMessage) {
                Log.d("error", "UserService.RegisterLocation() failed");
                Log.d("error", errorMessage);

                wakeLock.release();
            }
        }, currentLocation);
    }
}

LocationProvider.java

publicclassLocationProvider {

    privatestaticLocationProviderinstance=null;
    privatestatic Context context;

    publicstaticfinalintONE_MINUTE=1000 * 60;
    publicstaticfinalintFIVE_MINUTES= ONE_MINUTE * 5;

    privatestatic Location currentLocation;

    privateLocationProvider() {

    }

    publicstatic LocationProvider getInstance() {
        if (instance == null) {
            instance = newLocationProvider();
        }

        return instance;
    }

    publicvoidconfigureIfNeeded(Context ctx) {
        if (context == null) {
            context = ctx;
            configureLocationUpdates();
        }
    }

    privatevoidconfigureLocationUpdates() {
        finalLocationRequestlocationRequest= createLocationRequest();
        finalGoogleApiClientgoogleApiClient=newGoogleApiClient.Builder(context)
                .addApi(LocationServices.API)
                .build();

        googleApiClient.registerConnectionCallbacks(newGoogleApiClient.ConnectionCallbacks() {
            @OverridepublicvoidonConnected(Bundle bundle) {
                startLocationUpdates(googleApiClient, locationRequest);
            }

            @OverridepublicvoidonConnectionSuspended(int i) {

            }
        });
        googleApiClient.registerConnectionFailedListener(newGoogleApiClient.OnConnectionFailedListener() {
            @OverridepublicvoidonConnectionFailed(ConnectionResult connectionResult) {

            }
        });

        googleApiClient.connect();
    }

    privatestatic LocationRequest createLocationRequest() {
        LocationRequestlocationRequest=newLocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(FIVE_MINUTES);
        return locationRequest;
    }

    privatestaticvoidstartLocationUpdates(GoogleApiClient client, LocationRequest request) {
        LocationServices.FusedLocationApi.requestLocationUpdates(client, request, newcom.google.android.gms.location.LocationListener() {
            @OverridepublicvoidonLocationChanged(Location location) {
                currentLocation = location;
            }
        });
    }

    public Location getCurrentLocation() {
        return currentLocation;
    }
}

I first create an instance of the LocationProvider in a class that extends application, creating the instance when the app is launched:

MyApp.java

publicclassMyAppextendsApplication {

    @OverridepublicvoidonCreate() {
        super.onCreate();

        LocationProviderlocationProvider= LocationProvider.getInstance();
        locationProvider.configureIfNeeded(this);
    }
}

The LocationProvider is instantiated and configured for location updates exactly once, because it is a singleton. Every 5 minutes it will update its currentLocation value, which we can retrieve from anywhere we need with

Locationloc= LocationProvider.getInstance().getCurrentLocation();

Running a background service of any kind is not required. The AlarmManager will broadcast to LocationTracker.onReceive() every 5 minutes and the partial wakelock will ensure that the code will finish running even if the device is standby. This is also energy efficient.

Note that you need the following permissions

<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permissionandroid:name="android.permission.INTERNET" /><!-- For keeping the LocationTracker alive while it is doing networking --><uses-permissionandroid:name="android.permission.WAKE_LOCK" />

and don't forget to register the receiver:

<receiverandroid:name=".LocationTracker" />

Solution 2:

About your first method where u are using the Activity to request for location updates, they should not stop unless you disconnect the Location Client in the onPause() method of the activity. So as long as your activity is in the background/foreground you should continue to receive location updates. But if the activity is destroyed then of course you won't get the updates.

Check if you are disconnecting the location Client in your activity lifecycle.

Post a Comment for "How To Receive Location Updates Every 5 Minutes Using The Fusedlocation Api"