I will try to summarize. If you want to understand more deeply every step I quote, I recommend reading this document.
First step - Configuration
Add dependency to Gradle:
dependencies {
compile 'com.google.android.gms:play-services:8.1.0'
}
Add permission to 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, we need to instantiate the Googleapiclient class, because it is through it that we will access the services that exist in Google Services, such as Location Service.
I created a 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 successfully established, we may then use API.
Adding the Location Service API
It is simple to use the Location Service API through the client that we created. Just add the reference of this API during the instantiation of Googleapiclient thus:
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Now we can use the API location when the client establish the connection. We will do this through the class LocationServices.FusedLocationApi:
Capturing the Last Identified Location
Through class LocationServices.FusedLocationApi we can capture the last identified location in this way in our method onConnected()
(because it’s 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);
}
Want latitude and longitude? Just call the methods Location.getLatitude()
and Location.getLongitude()
.
Anything comment!