Again Google has released a new API but they haven’t updated the documentation :$ After spend some time trying to figure out how it works I got it, here you have a full example using the new/latest Location Service API… Enjoy developing 🙂
import android.location.Location;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final String TAG = "MyAwesomeApp";
private TextView mLocationView;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationView = new TextView(this);
setContentView(mLocationView);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
@Override
protected void onStart() {
super.onStart();
// Connect the client.
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
// Disconnecting the client invalidates it.
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "GoogleApiClient connection has been suspend");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "GoogleApiClient connection has failed");
}
@Override
public void onLocationChanged(Location location) {
mLocationView.setText("Location received: " + location.toString());
}
}
and do not forget to add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Note: if you just need to get the last location (without updates), you can use LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
from OnConnected