Fast Step-by-Step to Get Location

by Philip Barlow / from beautifuldecay.com

Configuration

Add Gradle dependency:

dependencies {
compile 'com.google.android.gms:play-services:8.1.0'
}

view raw
build.gradle
hosted with ❤ by GitHub

Add permission on AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tassioauad.locationexample">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!– AND/OR –>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!––>
</manifest>

view raw
AndroidManifest.xml
hosted with ❤ by GitHub

More about ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

Using the GoogleApiClient

At first, we need to instanciate the GoogleApiClient, because throught this instance we can access any service from Google Services, like the Location Service. It is a client for ALL services of the Google Service API (Location, ActivityRecognition and etc..).

This Activity below shows how it happens:

public class LocationActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this) //Be aware of state of the connection
.addOnConnectionFailedListener(this) //Be aware of failures
.build();
//Trying to connect with Google API. If it works onConnected() will be called, else onConnectionFailed() will be called.
googleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
stopGoogleApiConnection();
}
public void stopGoogleApiConnection() {
//Stopping the Connection
if (googleApiClient.isConnected()) {
googleApiClient.disconnect(); //Closing connection with Google APIs
}
}
/**
* After calling connect(), this method will be invoked asynchronously when the connect request has successfully completed.
* After this callback, the application can make requests on other methods provided by the client and expect that no user intervention
* is required to call methods that use account and scopes provided to the client constructor.
*
* @param bundle
*/
@Override
public void onConnected(Bundle bundle) {
//Google API connection has been done successfully
}
/**
* Called when the client is temporarily in a disconnected state.
* This can happen if there is a problem with the remote service (e.g. a crash or resource problem causes it to be killed by the system).
* When called, all requests have been canceled and no outstanding listeners will be executed.
* GoogleApiClient will automatically attempt to restore the connection.
* Applications should disable UI components that require the service, and wait for a call to onConnected(Bundle) to re-enable them.
*/
@Override
public void onConnectionSuspended(int i) {
//Wait for the GoogleApiClient restores the connection.
}
/**
* Called when there was an error connecting the client to the service.
*
* @param connectionResult
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//Google API connection has been failed! Stop it and warn!
stopGoogleApiConnection();
}
}

When the connection with the API is done, we can use the services of the API.

Adding the Location Service API

It’s easy, just add the API reference during the GoogleApiClient instanciation:

googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

view raw
Example.java
hosted with ❤ by GitHub

Now, when the Google API Client get ready to be used, the Location Service will be ready too and we can call methods of LocationServices.FusedLocationApi:

Getting Last Location

Throught the LocationServices.FusedLocationApi we can get the last location:

@Override
public void onConnected(Bundle bundle) {
//Google API connection has been done successfully
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}

view raw
onConnected.java
hosted with ❤ by GitHub

Requesting Location Updates

If we want to get the location everytime it changes, we can set an listener to receive the current location instance:

Instead of use the getLastLocation() we gonna use the requestLocationUpdates(). We have to set the updates configuration (time interval, min displacement in meter and etc) through an instance of com.google.android.gms.location.LocationRequest and we have to set the listener that will receive the updates.

@Override
public void onConnected(Bundle bundle) {
//Google API connection has been done successfully
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setSmallestDisplacement(5);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
}
});
}

view raw
OnConnected.java
hosted with ❤ by GitHub

Ops! Don’t forget to remove the listener when you close the connection with the Google API. We gonna do it using the method removeLocationUpdates of the class LocationServices.FusedLocationApi.

@Override
public void stopToCaptureLocations() {
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener); //Stopping to get location updates
googleApiClient.disconnect(); //Closing connection with Google APIs
}
}

Now that you have an overview, you can read more about each step sink!

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s