Skip to content

Instantly share code, notes, and snippets.

@udacityandroid
Created February 12, 2015 01:42
Show Gist options
  • Save udacityandroid/e5eb3afa254ca750e083 to your computer and use it in GitHub Desktop.
Save udacityandroid/e5eb3afa254ca750e083 to your computer and use it in GitHub Desktop.
6.06 Notifications Quiz
private void notifyWeather() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
String locationQuery = Utility.getPreferredLocation(context);
Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis());
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
int weatherId = cursor.getInt(INDEX_WEATHER_ID);
double high = cursor.getDouble(INDEX_MAX_TEMP);
double low = cursor.getDouble(INDEX_MIN_TEMP);
String desc = cursor.getString(INDEX_SHORT_DESC);
int iconId = Utility.getIconResourceForWeatherCondition(weatherId);
String title = context.getString(R.string.app_name);
// Define the text of the forecast.
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high),
Utility.formatTemperature(context, low));
//build your notification here.
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
}
}
@cyber2024
Copy link

Instead of declaring a variable for SharedPreferences.Editor(), you can string the methods together from an existing SharedPreferences object.
I've forked for you.

prefs.edit()
    .putLong(lastNotificationKey, System.currentTimeMillis())
    .commit();

@arthur7257
Copy link

Shouldn't the cursor returned by ContentResolver.query( ) be closed?

Copy link

ghost commented Jun 28, 2016

@arthur7257 Yes, it should!

@wubydax
Copy link

wubydax commented Sep 6, 2016

Just a small comment... the line
private static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
can be replaced by convenience static method for getting length of time unit in milliseconds in TimeUnit class:
private final static long DAY_IN_MILLIS = TimeUnit.DAYS.toMillis(1);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment