Google Play Services Location tutorial
"One of the unique features of mobile applications is location awareness. Mobile users take their devices with them everywhere, and adding location awareness to your app offers users a more contextual experience. The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking, geofencing, and activity recognition."How to do that? Never been so simple:
Create a Google Api Client that use the api you need
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Implements
- GoogleApiClientConnectionCallbacks
- GoogleApiClient.onConnectionFailedListener
- LocationListener
Wait for a onConnected callback and ask for updates on location
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
Wait for an other callback OnLocationChanged
@Override
public void onLocationChanged(Location location) {
Log.d(LOG_TAG,"location: "+location.toString());
}
!NB: rembember to set:
- the permission on the manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
2.Add the play services library in the manifest like this
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
3. Add the lib to build gradle
compile 'com.google.android.gms:play-services:8.4.0'
Do not forget to call the appropiate method in order to deal with the activity lifecycle:
Do not forget to call the appropiate method in order to deal with the activity lifecycle:
@Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); }
Happy coding!
0 commenti