The 11.0.0 release of the Google Play services SDK includes a new way to access
.
Why not use GoogleApiClient?
The LocationServices APIs allow you to access device location, set up geofences,
prompt the user to enable location on the device and more. In order to access
these services, the app must connect to Google Play services, which can involve
error-prone connection logic. For example, can you spot the crash in the app
below?
Note: we'll assume our app has the
ACCESS_FINE_LOCATION permission, which is required to get the
user's exact location using the LocationServices APIs.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleApiClient client = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(LocationServices.API)
.build();
client.connect();
PendingResultresult =
LocationServices.FusedLocationApi.requestLocationUpdates(
client, LocationRequest.create(), pendingIntent);
result.setResultCallback(new ResultCallback() {
@Override
public void onResult(@NonNull Status status) {
Log.d(TAG, "Result: " + status.getStatusMessage());
}
});
}
// ...
}
If you pointed to the requestLocationUpdates() call, you're right!
That call throws an IllegalStateException, since the
GoogleApiClient is has not yet connected. The call to
connect() is asynchronous.
While the code above looks like it should work, it's missing a
API which makes it easier to compose asynchronous operations.
class or similar.
coding.
What happened to all of the callbacks?
The new API will automatically resolve certain connection failures for you, so
you don't need to write code that for things like prompting the user to update
Google Play services. Rather than exposing connection failures globally in the
:
client.requestLocationUpdates(LocationRequest.create(), pendingIntent)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ApiException) {
Log.w(TAG, ((ApiException) e).getStatusMessage());
} else {
Log.w(TAG, e.getMessage());
}
}
});
Try it for yourself
Try the new LocationServices APIs out for yourself in your own app
or head over to the
SOCIAL SHARE CARD GENERATOR