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

(gtxtreme123) #1

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:



  1. Pull out the current query and the last result ID from the default SharedPreferences.

  2. Fetch the latest result set with FlickrFetchr.

  3. If there are results, grab the first one.

  4. Check to see whether it is different from the last result ID.

  5. Store the first result back in SharedPreferences.

Free download pdf