I'll try to summarize. If you want to understand more about each step I quote, I recommend reading this document . >.
First step - Configuration
Add the dependency in Gradle:
dependencies {
compile 'com.google.android.gms:play-services:8.1.0'
}
Add permission on AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and / or
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Making use of GoogleApiClient
First, you need to instantiate the GoogleApiClient class, because it will be through it that we will access services that exist in Google Services, such as the Location Service.
I created an activity to demonstrate how this 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();
//Tentando conexão com o Google API. Se a tentativa for bem sucessidade, o método onConnected() será chamado, senão, o método onConnectionFailed() será chamado.
googleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
pararConexaoComGoogleApi();
}
public void pararConexaoComGoogleApi() {
//Verificando se está conectado para então cancelar a conexão!
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
/**
* Depois que o método connect() for chamado, esse método será chamado de forma assíncrona caso a conexão seja bem sucedida.
*
* @param bundle
*/
@Override
public void onConnected(Bundle bundle) {
//Conexão com o serviços do Google Service API foi estabelecida!
}
/**
* Esse método é chamado quando o client está temporariamente desconectado. Isso pode acontecer quando houve uma falha ou problema com o serviço que faça com que o client seja desligado.
* Nesse estado, todas as requisições e listeners são cancelados.
* Não se preocupe em tentar reestabelecer a conexão, pois isso acontecerá automaticamente.
* As aplicações devem desabilitar recursos visuais que estejam relacionados com o uso dos serviços e habilitá-los novamente quando o método onConnected() for chamado, indicando reestabelecimento da conexão.
*/
@Override
public void onConnectionSuspended(int i) {
// Aguardando o GoogleApiClient reestabelecer a conexão.
}
/**
* Método chamado quando um erro de conexão acontece e não é possível acessar os serviços da Google Service.
*
* @param connectionResult
*/
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//A conexão com o Google API falhou!
pararConexaoComGoogleApi();
}
}
If the connection is established successfully, then we can use API services.
Adding the Location Service API
It's simple to start using the Location Service API through the client we created. Just add the API reference during instantiation of GoogleApiClient like this:
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Now we can use the location API when the client establishes the connection. We will do this through the LocationServices.FusedLocationApi class:
Capturing Last Known Location
In the LocationServices.FusedLocationApi class, we can capture the last location identified in this way in our onConnected()
method (since it is the method called when the connection was established):
@Override
public void onConnected(Bundle bundle) {
//Google API connection has been done successfully
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
Do you want latitude and longitude? Just call the methods Location.getLatitude()
and Location.getLongitude()
.
Anything to say!