Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 33  Locations and Play Services


Next, you need to verify that Play Services is available. Since the working parts live in another app
on your device, the Play Services library is not always guaranteed to be working. The library makes it
easy to verify this. Update your main activity to perform this check.


Listing 33.6  Adding Play Services check (LocatrActivity.java)


public class LocatrActivity extends SingleFragmentActivity {
private static final int REQUEST_ERROR = 0;


@Override
protected Fragment createFragment() {
return LocatrFragment.newInstance();
}


@Override
protected void onResume() {
super.onResume();


GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int errorCode = apiAvailability.isGooglePlayServicesAvailable(this);


if (errorCode != ConnectionResult.SUCCESS) {
Dialog errorDialog = apiAvailability
.getErrorDialog(this, errorCode, REQUEST_ERROR,
new DialogInterface.OnCancelListener() {


@Override
public void onCancel(DialogInterface dialog) {
// Leave if services are unavailable.
finish();
}
});


errorDialog.show();
}
}
}


Normally you would not use a bare Dialog like this. However, in this case you will receive the same
errorCode every time LocatrActivity starts up, so the Dialog will always be displayed correctly.


Location permissions


You will also need some location permissions for your app to work. There are
two relevant permissions: android.permission.ACCESS_FINE_LOCATION and
android.permission.ACCESS_COARSE_LOCATION. Fine location is the GPS radio; coarse location is
derived from cell towers or WiFi access points.


In this chapter, you will be requesting a high-accuracy location fix, so you will definitely need
ACCESS_FINE_LOCATION. But it is also a good idea to request ACCESS_COARSE_LOCATION. If the fine
location provider is not available, this gives you permission to use the coarse provider as a backup.


Add these permissions to your manifest. Add an internet permission while you are at it, so that you can
query Flickr.

Free download pdf