Chapter 28 Background Services
Looking for New Results
Your service will be polling for new results, so it will need to know what the last result fetched was.
This is a perfect job for another SharedPreferences entry.
Update QueryPreferences to store the ID of the most recently fetched photo.
Listing 28.6 Adding recent ID preference constant (QueryPreferences.java)
public class QueryPreferences {
private static final String PREF_SEARCH_QUERY = "searchQuery";
private static final String PREF_LAST_RESULT_ID = "lastResultId";
public static String getStoredQuery(Context context) {
...
}
public static void setStoredQuery(Context context, String query) {
...
}
public static String getLastResultId(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_LAST_RESULT_ID, null);
}
public static void setLastResultId(Context context, String lastResultId) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_LAST_RESULT_ID, lastResultId)
.apply();
}
}
The next step is to fill out your service. Here is what you need to do:
- Pull out the current query and the last result ID from the default SharedPreferences.
- Fetch the latest result set with FlickrFetchr.
- If there are results, grab the first one.
- Check to see whether it is different from the last result ID.
- Store the first result back in SharedPreferences.