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


Once you do that, you need to connect to the client. Google recommends always connecting to the
client in onStart() and disconnecting in onStop(). Calling connect() on your client will change what
your menu button can do, too, so call invalidateOptionsMenu() to update its visible state. (You will
call it one more time later, after you are told you have been connected.)


Listing 33.9  Connecting and disconnecting (LocatrFragment.java)


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
}


@Override
public void onStart() {
super.onStart();


getActivity().invalidateOptionsMenu();
mClient.connect();
}


@Override
public void onStop() {
super.onStop();


mClient.disconnect();
}


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


If your client is not connected, your app will not be able to do anything. So for the next step, enable or
disable the button depending on whether the client is connected.


Listing 33.10  Updating the menu button (LocatrFragment.java)


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_locatr, menu);


MenuItem searchItem = menu.findItem(R.id.action_locate);
searchItem.setEnabled(mClient.isConnected());
}


Then add another call to getActivity().invalidateOptionsMenu() to update your menu
item when you find out that you are connected. Connection state information is passed through
two callback interfaces: ConnectionCallbacks and OnConnectionFailedListener. Hook up
a ConnectionCallbacks listener in onCreate(Bundle) to invalidate your toolbar when you are
connected.

Free download pdf