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

(gtxtreme123) #1
Controlling Your Alarm

Now delete your old debug code for starting the alarm and add an implementation for the menu item.


Listing 28.13  Implementing toggle menu item (PhotoGalleryFragment.java)


private static final String TAG = "PhotoGalleryFragment";
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
updateItems();


PollService.setServiceAlarm(getActivity(), true);


Handler responseHandler = new Handler();
...
}
...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_clear:
QueryPreferences.setStoredQuery(getActivity(), null);
updateItems();
return true;
case R.id.menu_item_toggle_polling:
boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity());
PollService.setServiceAlarm(getActivity(), shouldStartAlarm);
return true;
default:
return super.onOptionsItemSelected(item);
}
}


With that, you should be able to toggle your alarm on and off. However, you will notice that the menu
item for polling always says Start polling, even if the polling is currently on. You need to toggle the
menu item title as you did for SHOW SUBTITLE in the CriminalIntent app (Chapter 13).

Free download pdf