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();
}
}
}
@saeedAA
Copy link

saeedAA commented Feb 17, 2015

since buildWeatherLocationWithDate doesn't accept current date as long in milliseconds but accepts a string formatted date. getDbString(use new Date()) instead which will give the current date as a string formatted date.

@anonoz
Copy link

anonoz commented Feb 21, 2015

@saeedAA Somehow mine does, maybe our codes are different?

public static long normalizeDate(long startDate) {
        // normalize the start date to the beginning of the (UTC) day
        Time time = new Time();
        time.setToNow();
        int julianDay = Time.getJulianDay(startDate, time.gmtoff);
        return time.setJulianDay(julianDay);
    }

public static Uri buildWeatherLocationWithStartDate(
                String locationSetting, long startDate) {
            long normalizedDate = normalizeDate(startDate);
            return CONTENT_URI.buildUpon().appendPath(locationSetting)
                    .appendQueryParameter(COLUMN_DATE, Long.toString(normalizedDate)).build();
        }

@Actine
Copy link

Actine commented Feb 21, 2015

@saeedAA they updated the code recently (for all lessons). The date in DB is now stored as integer and not a string (don't actually see much difference in terms of how it solves the problem they named)

@runjara
Copy link

runjara commented Apr 15, 2015

Line 12 is Wrong, use WeatherContract.getDbDateString(new Date()) instead of System.currentTimeMillis()

@ToanNV
Copy link

ToanNV commented Apr 24, 2015

pls add the command line above this line
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high),
Utility.formatTemperature(context, low));

boolean isMetric = Utility.isMetric(context);
and change it like the followings
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high, isMetric),
Utility.formatTemperature(context, low, isMetric));
Lastly, add "public" keyword in font of static method formatTemperature in class Utility
public static String formatTemperature(Context context, double temperature, boolean isMetric)

@Katalune
Copy link

Katalune commented Sep 2, 2015

@ToanNV
or you can only overload this method in Utility class as
public static String formatTemperature(Context context, double temperature) {
return formatTemperature(context, temperature, isMetric(context));
}

@LouisCAD
Copy link

Instead of checking wether the notification has been shown today, I would check if it has been dismissed by using Dismiss PendingIntent, so the notification can be showed again after the phone reboots (which is often needed on Android 5.0 with memory leaks…)

@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