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

(gtxtreme123) #1

Using receivers


Using receivers


The fact that broadcast receivers live such short lives restricts the things you can do with them.
You cannot use any asynchronous APIs, for example, or register any listeners, because your
receiver will not be alive any longer than the call to onReceive(Context, Intent). Also, because
onReceive(Context, Intent) runs on your main thread, you cannot do any heavy lifting inside it.
That means no networking or heavy work with permanent storage.


But this does not make receivers useless. They are invaluable for all kinds of little plumbing code, such
as starting an activity or service (so long as you do not expect a result back) or resetting a recurring
alarm when the system finishes rebooting (as you will do in this exercise).


Your receiver will need to know whether the alarm should be on or off. Add a preference constant and
convenience methods to QueryPreferences to store this information in shared preferences.


Listing 29.3  Adding alarm status preference (QueryPreferences.java)


public class QueryPreferences {


private static final String PREF_SEARCH_QUERY = "searchQuery";
private static final String PREF_LAST_RESULT_ID = "lastResultId";
private static final String PREF_IS_ALARM_ON = "isAlarmOn";
...
public static void setLastResultId(Context context, String lastResultId) {
...
}


public static boolean isAlarmOn(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(PREF_IS_ALARM_ON, false);
}


public static void setAlarmOn(Context context, boolean isOn) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(PREF_IS_ALARM_ON, isOn)
.apply();
}
}

Free download pdf