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

(gtxtreme123) #1
Getting a Location Fix

When you first create a LocationRequest, it will be configured for accuracy within a city block,
with repeated slow updates until the end of time. In your code, you change this to get a single, high-
accuracy location fix by changing the priority and the number of updates. You also set the interval to 0
to signify that you would like a location fix as soon as possible.


The next step is to send off this request and listen for the Locations that come back. You do this by
adding a LocationListener. There are two versions of LocationListener you can import. Choose
com.google.android.gms.location.LocationListener. Add another method call to findImage().


Listing 33.15  Sending LocationRequest (LocatrFragment.java)


public class LocatrFragment extends Fragment {
private static final String TAG = "LocatrFragment";
...
private void findImage() {
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setNumUpdates(1);
request.setInterval(0);
LocationServices.FusedLocationApi
.requestLocationUpdates(mClient, request, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, "Got a fix: " + location);
}
});
}


If this were a longer-lived request, you would need to hold on to your listener and call
removeLocationUpdates(...) later to cancel the request. However, since you called setNumUpdates(1),
all you need to do is send this off and forget about it.


(Your call to requestLocationUpdates(...) will receive a dramatic red error indicator. Will this cause
problems? Yes, it will – but leave it as is for now; you will address those issues in a moment.)


Finally, to send this off you need to hook up your search button. Override onOptionsItemSelected(...)
to call findImage().


Listing 33.16  Hooking up search button (LocatrFragment.java)


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
...
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_locate:
findImage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Free download pdf