code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Parcelable; import android.util.Log; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.AppUtils; import ru.gelin.android.weather.notification.IntentParameters; import ru.gelin.android.weather.notification.skin.Tag; /** * Broadcast receiver which receives the weather updates. * <p> * The receiver should: * <ul> * <li>display the Weather passed in the start intent extra using {@link NotificationManager}</li> * <li>hide the weather notification if necessary</li> * </ul> * The intent, passed to the receiver, has action {@link IntentParameters#ACTION_WEATHER_UPDATE}. * The Weather Notification finds the broadcast receivers which accepts this intent type * as weather notification skins. * <p> * The intent contains the extras: * <ul> * <li>{@link IntentParameters#EXTRA_WEATHER} holds updated {@link Weather}</li> * <li>{@link IntentParameters#EXTRA_ENABLE_NOTIFICATION} holds boolean flag about notification state, * if false the weather notification should be hidden.</li> * </ul> * The intent is sent to the receiver each time the weather notification * should be updated or cleared. This can happen not on weather update, * but also when the specified skin is enabled or disabled. */ public abstract class WeatherNotificationReceiver extends BroadcastReceiver { /** * Verifies the intent, extracts extras, calls {@link #notify} or {@link #cancel} methods. */ @Override public void onReceive(Context context, Intent intent) { Log.d(Tag.TAG, "received: " + intent); if (intent == null) { return; } if (!IntentParameters.ACTION_WEATHER_UPDATE_2.equals(intent.getAction())) { return; } Log.d(Tag.TAG, "extras: " + intent.getExtras().size()); boolean enabled = intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, true); Log.d(Tag.TAG, "extra weather: " + intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER)); if (enabled) { Parcelable weather = intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER); if (!(weather instanceof Weather)) { return; } notify(context, (Weather)weather); } else { cancel(context); } } /** * Is called when a new weather value is received. * @param context current context * @param weather weather value to be displayed */ protected abstract void notify(Context context, Weather weather); /** * Is called when a weather notification should be canceled. * @param context current context */ protected abstract void cancel(Context context); /** * Returns notification manager, selected from the context. * @param context current context */ protected static NotificationManager getNotificationManager(Context context) { return (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); } /** * Returns the PendingIntent which starts the main WeatherNotification activity. * You can use it as {@link Notification#contentIntent}. * @param context current context */ protected static PendingIntent getMainActivityPendingIntent(Context context) { Intent intent = AppUtils.getMainActivityIntent(); return PendingIntent.getActivity(context, 0, intent, 0); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; /** * Enumeration with notification styles. */ public enum NotificationTextStyle { BLACK_TEXT(0xff000000), WHITE_TEXT(0xffffffff); int textColor; private NotificationTextStyle(int textColor) { this.textColor = textColor; } /** * Returns color of the text for this notification style. */ public int getTextColor() { return this.textColor; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import android.app.Notification; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.RemoteViews; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.WeatherCondition; import ru.gelin.android.weather.WeatherConditionType; import ru.gelin.android.weather.notification.ParcelableWeather2; import ru.gelin.android.weather.notification.WeatherStorage; import ru.gelin.android.weather.notification.skin.Tag; import java.util.List; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.STRING; /** * Weather notification receiver built into basic application. */ abstract public class BaseWeatherNotificationReceiver extends WeatherNotificationReceiver { /** Key to store the weather in the bundle */ static final String WEATHER_KEY = "weather"; /** Handler to receive the weather */ static Handler handler; /** * Registers the handler to receive the new weather. * The handler is owned by activity which have initiated the update. * The handler is used to update the weather displayed by the activity. */ static synchronized void registerWeatherHandler(Handler handler) { BaseWeatherNotificationReceiver.handler = handler; } /** * Unregisters the weather update handler. */ static synchronized void unregisterWeatherHandler() { BaseWeatherNotificationReceiver.handler = null; } @Override protected void cancel(Context context) { Log.d(Tag.TAG, "cancelling weather"); getNotificationManager(context).cancel(getNotificationId()); } @Override protected void notify(Context context, Weather weather) { Log.d(Tag.TAG, "displaying weather: " + weather); WeatherStorage storage = new WeatherStorage(context); storage.save(weather); WeatherFormatter formatter = getWeatherFormatter(context, weather); NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setSmallIcon(getNotificationIconId(weather)); if (weather.isEmpty() || weather.getConditions().size() <= 0) { builder.setTicker(context.getString(formatter.getIds().id(STRING, "unknown_weather"))); } else { builder.setTicker(formatter.formatTicker()); builder.setSmallIcon(getNotificationIconId(weather), getNotificationIconLevel(weather, formatter.getStyler().getTempType().getTemperatureUnit())); } builder.setWhen(weather.getQueryTime().getTime()); builder.setOngoing(true); builder.setAutoCancel(false); builder.setContentIntent(getContentIntent(context)); //Lollipop notification on lock screen builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); Notification notification = builder.build(); switch (formatter.getStyler().getNotifyStyle()) { case CUSTOM_STYLE: RemoteViews views = new RemoteViews(context.getPackageName(), formatter.getStyler().getLayoutId()); RemoteWeatherLayout layout = getRemoteWeatherLayout(context, views, formatter.getStyler()); layout.bind(weather); notification.contentView = views; break; case STANDARD_STYLE: builder.setContentTitle(formatter.formatContentTitle()); builder.setContentText(formatter.formatContentText()); Bitmap largeIcon = formatter.formatLargeIcon(); if (largeIcon != null) { builder.setLargeIcon(largeIcon); } notification = builder.build(); break; } getNotificationManager(context).notify(getNotificationId(), notification); notifyHandler(weather); } /** * Returns the notification ID for the skin. * Different skins withing the same application must return different results here. */ protected int getNotificationId() { return this.getClass().getName().hashCode(); } /** * Returns the pending intent called on click on notification. * This intent starts the weather info activity. */ protected PendingIntent getContentIntent(Context context) { Intent intent = new Intent(); intent.setComponent(getWeatherInfoActivityComponentName()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return PendingIntent.getActivity(context, 0, intent, 0); } protected void notifyHandler(Weather weather) { synchronized (BaseWeatherNotificationReceiver.class) { //monitor of static methods if (handler == null) { return; } Message message = handler.obtainMessage(); Bundle bundle = message.getData(); bundle.putParcelable(WEATHER_KEY, new ParcelableWeather2(weather)); message.sendToTarget(); } } /** * Returns the component name of the weather info activity */ abstract protected ComponentName getWeatherInfoActivityComponentName(); /** * Returns the ID of the notification icon based on the current weather. */ protected int getNotificationIconId(Weather weather) { List<WeatherCondition> conditions = weather.getConditions(); if (conditions == null || conditions.isEmpty()) { return WeatherConditionFormat.getDrawableId(WeatherConditionType.CLOUDS_CLEAR); } return WeatherConditionFormat.getDrawableId(weather.getConditions().iterator().next()); } /** * Returns the notification icon level. */ protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return 24; //24dp for notification icon size } /** * Creates the remove view layout for the notification. */ protected RemoteWeatherLayout getRemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { return new RemoteWeatherLayout(context, views, styler); } /** * Creates the weather formatter. */ protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, weather); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.notification.skin.impl; import android.content.Context; import ru.gelin.android.weather.Wind; import ru.gelin.android.weather.WindDirection; import ru.gelin.android.weather.WindSpeedUnit; public class WindFormat { Context context; ResourceIdFactory ids; public WindFormat(Context context) { this.context = context; this.ids = ResourceIdFactory.getInstance(context); } public String format(Wind wind) { if (wind == null) { return ""; } if (wind.getSpeed() == Wind.UNKNOWN) { return ""; } String format = getString("wind_caption"); return String.format(format, valueOf(wind.getDirection()), wind.getSpeed(), valueOf(wind.getSpeedUnit())); } String getString(String resource) { return this.context.getString(this.ids.id(ResourceIdFactory.STRING, resource)); } String valueOf(WindSpeedUnit unit){ switch (unit){ case MPH: return getString("wind_speed_unit_mph"); case KMPH: return getString("wind_speed_unit_kmph"); case MPS: return getString("wind_speed_unit_mps"); } return ""; } String valueOf(WindDirection dir){ switch (dir){ case E: return getString("wind_dir_e"); case ENE: return getString("wind_dir_ene"); case ESE: return getString("wind_dir_ese"); case N: return getString("wind_dir_n"); case NE: return getString("wind_dir_ne"); case NNE: return getString("wind_dir_nne"); case NNW: return getString("wind_dir_nnw"); case NW: return getString("wind_dir_nw"); case S: return getString("wind_dir_s"); case SE: return getString("wind_dir_se"); case SSE: return getString("wind_dir_sse"); case SSW: return getString("wind_dir_ssw"); case SW: return getString("wind_dir_sw"); case W: return getString("wind_dir_w"); case WNW: return getString("wind_dir_wnw"); case WSW: return getString("wind_dir_wsw"); } return ""; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import ru.gelin.android.weather.UnitSystem; @Deprecated public enum TemperatureUnit { C(UnitSystem.SI), F(UnitSystem.US), CF(UnitSystem.SI), FC(UnitSystem.US); UnitSystem unit; TemperatureUnit(UnitSystem unit) { this.unit = unit; } public UnitSystem getUnitSystem() { return this.unit; } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import ru.gelin.android.weather.Temperature; public class TemperatureFormat { public String format(int temp) { if (temp == Temperature.UNKNOWN) { return ""; } return signedValue(temp) + "\u00B0"; } public String format(int temp, TemperatureType unit) { if (temp == Temperature.UNKNOWN) { return ""; } switch (unit) { case C: return signedValue(temp) + "\u00B0C"; case F: return signedValue(temp) + "\u00B0F"; case CF: return signedValue(temp) + "\u00B0C"; case FC: return signedValue(temp) + "\u00B0F"; } return ""; } public String format(int tempC, int tempF, TemperatureType unit) { if (tempC == Temperature.UNKNOWN || tempF == Temperature.UNKNOWN) { return ""; } switch (unit) { case C: return signedValue(tempC) + "\u00B0C"; case F: return signedValue(tempF) + "\u00B0F"; case CF: return signedValue(tempC) + "\u00B0C(" + signedValue(tempF) + "\u00B0F)"; case FC: return signedValue(tempF) + "\u00B0F(" + signedValue(tempC) + "\u00B0C)"; } return ""; } /** * Returns the int value with a sign. * This implementation returns only minus sign for negative values. */ protected String signedValue(int value) { return String.valueOf(value); } }
Java
/* * Android Weather Notification. * Copyright (C) 2014 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; /** * Enumeration with notification styles. */ public enum NotificationStyle { STANDARD_STYLE, CUSTOM_STYLE; }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import ru.gelin.android.weather.TemperatureUnit; /** * Maps user's preferences into actual temperature unit. */ public enum TemperatureType { C(TemperatureUnit.C), F(TemperatureUnit.F), CF(TemperatureUnit.C), FC(TemperatureUnit.F); TemperatureUnit unit; TemperatureType(TemperatureUnit unit) { this.unit = unit; } public TemperatureUnit getTemperatureUnit() { return this.unit; } /** * Converts from deprecated class. */ @SuppressWarnings("deprecation") public static TemperatureType valueOf(ru.gelin.android.weather.notification.skin.impl.TemperatureUnit unit) { switch (unit) { case C: return TemperatureType.C; case CF: return TemperatureType.CF; case F: return TemperatureType.F; case FC: return TemperatureType.FC; } return TemperatureType.C; } }
Java
package ru.gelin.android.weather.notification.skin.impl; import android.content.Context; import android.graphics.drawable.LevelListDrawable; import ru.gelin.android.weather.WeatherCondition; import ru.gelin.android.weather.WeatherConditionType; import ru.gelin.android.weather.notification.skin.R; import java.util.*; import static ru.gelin.android.weather.WeatherConditionType.*; /** * Formats weather condition text. */ public class WeatherConditionFormat { static final String SEPARATOR = ", "; static Map<WeatherConditionType, Integer> STR_MAP = new EnumMap<WeatherConditionType, Integer>(WeatherConditionType.class); static { STR_MAP.put(THUNDERSTORM_RAIN_LIGHT, R.string.condition_thunderstorm_rain_light); STR_MAP.put(THUNDERSTORM_RAIN, R.string.condition_thunderstorm_rain); STR_MAP.put(THUNDERSTORM_RAIN_HEAVY, R.string.condition_thunderstorm_rain_heavy); STR_MAP.put(THUNDERSTORM_LIGHT, R.string.condition_thunderstorm_light); STR_MAP.put(THUNDERSTORM, R.string.condition_thunderstorm); STR_MAP.put(THUNDERSTORM_HEAVY, R.string.condition_thunderstorm_heavy); STR_MAP.put(THUNDERSTORM_RAGGED, R.string.condition_thunderstorm_ragged); STR_MAP.put(THUNDERSTORM_DRIZZLE_LIGHT, R.string.condition_thunderstorm_drizzle_light); STR_MAP.put(THUNDERSTORM_DRIZZLE, R.string.condition_thunderstorm_drizzle); STR_MAP.put(THUNDERSTORM_DRIZZLE_HEAVY, R.string.condition_thunderstorm_drizzle_heavy); STR_MAP.put(DRIZZLE_LIGHT, R.string.condition_drizzle_light); STR_MAP.put(DRIZZLE, R.string.condition_drizzle); STR_MAP.put(DRIZZLE_HEAVY, R.string.condition_drizzle_heavy); STR_MAP.put(DRIZZLE_RAIN_LIGHT, R.string.condition_drizzle_rain_light); STR_MAP.put(DRIZZLE_RAIN, R.string.condition_drizzle_rain); STR_MAP.put(DRIZZLE_RAIN_HEAVY, R.string.condition_drizzle_rain_heavy); STR_MAP.put(DRIZZLE_SHOWER, R.string.condition_drizzle_shower); STR_MAP.put(RAIN_LIGHT, R.string.condition_rain_light); STR_MAP.put(RAIN, R.string.condition_rain); STR_MAP.put(RAIN_HEAVY, R.string.condition_rain_heavy); STR_MAP.put(RAIN_VERY_HEAVY, R.string.condition_rain_very_heavy); STR_MAP.put(RAIN_EXTREME, R.string.condition_rain_extreme); STR_MAP.put(RAIN_FREEZING, R.string.condition_rain_freezing); STR_MAP.put(RAIN_SHOWER_LIGHT, R.string.condition_rain_shower_light); STR_MAP.put(RAIN_SHOWER, R.string.condition_rain_shower); STR_MAP.put(RAIN_SHOWER_HEAVY, R.string.condition_rain_shower_heavy); STR_MAP.put(SNOW_LIGHT, R.string.condition_snow_light); STR_MAP.put(SNOW, R.string.condition_snow); STR_MAP.put(SNOW_HEAVY, R.string.condition_snow_heavy); STR_MAP.put(SLEET, R.string.condition_sleet); STR_MAP.put(SNOW_SHOWER, R.string.condition_snow_shower); STR_MAP.put(MIST, R.string.condition_mist); STR_MAP.put(SMOKE, R.string.condition_smoke); STR_MAP.put(HAZE, R.string.condition_haze); STR_MAP.put(SAND_WHIRLS, R.string.condition_sand_whirls); STR_MAP.put(FOG, R.string.condition_fog); STR_MAP.put(CLOUDS_CLEAR, R.string.condition_clouds_clear); STR_MAP.put(CLOUDS_FEW, R.string.condition_clouds_few); STR_MAP.put(CLOUDS_SCATTERED, R.string.condition_clouds_scattered); STR_MAP.put(CLOUDS_BROKEN, R.string.condition_clouds_broken); STR_MAP.put(CLOUDS_OVERCAST, R.string.condition_clouds_overcast); STR_MAP.put(TORNADO, R.string.condition_tornado); STR_MAP.put(TROPICAL_STORM, R.string.condition_tropical_storm); STR_MAP.put(HURRICANE, R.string.condition_hurricane); STR_MAP.put(COLD, R.string.condition_cold); STR_MAP.put(HOT, R.string.condition_hot); STR_MAP.put(WINDY, R.string.condition_windy); STR_MAP.put(HAIL, R.string.condition_hail); } static Map<WeatherConditionType, Integer> IMG_MAP = new EnumMap<WeatherConditionType, Integer>(WeatherConditionType.class); static { IMG_MAP.put(THUNDERSTORM_RAIN_LIGHT, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_RAIN, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_RAIN_HEAVY, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_LIGHT, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_HEAVY, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_RAGGED, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_DRIZZLE_LIGHT, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_DRIZZLE, R.drawable.condition_storm); IMG_MAP.put(THUNDERSTORM_DRIZZLE_HEAVY, R.drawable.condition_storm); IMG_MAP.put(DRIZZLE_LIGHT, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE_HEAVY, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE_RAIN_LIGHT, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE_RAIN, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE_RAIN_HEAVY, R.drawable.condition_rain); IMG_MAP.put(DRIZZLE_SHOWER, R.drawable.condition_shower); IMG_MAP.put(RAIN_LIGHT, R.drawable.condition_rain); IMG_MAP.put(RAIN, R.drawable.condition_rain); IMG_MAP.put(RAIN_HEAVY, R.drawable.condition_rain); IMG_MAP.put(RAIN_VERY_HEAVY, R.drawable.condition_rain); IMG_MAP.put(RAIN_EXTREME, R.drawable.condition_rain); IMG_MAP.put(RAIN_FREEZING, R.drawable.condition_rain); IMG_MAP.put(RAIN_SHOWER_LIGHT, R.drawable.condition_shower); IMG_MAP.put(RAIN_SHOWER, R.drawable.condition_shower); IMG_MAP.put(RAIN_SHOWER_HEAVY, R.drawable.condition_shower); IMG_MAP.put(SNOW_LIGHT, R.drawable.condition_snow); IMG_MAP.put(SNOW, R.drawable.condition_snow); IMG_MAP.put(SNOW_HEAVY, R.drawable.condition_snow); IMG_MAP.put(SLEET, R.drawable.condition_snow); IMG_MAP.put(SNOW_SHOWER, R.drawable.condition_snow); IMG_MAP.put(MIST, R.drawable.condition_mist); IMG_MAP.put(SMOKE, R.drawable.condition_mist); IMG_MAP.put(HAZE, R.drawable.condition_mist); IMG_MAP.put(SAND_WHIRLS, R.drawable.condition_mist); IMG_MAP.put(FOG, R.drawable.condition_mist); IMG_MAP.put(CLOUDS_CLEAR, R.drawable.condition_clear); IMG_MAP.put(CLOUDS_FEW, R.drawable.condition_clouds); IMG_MAP.put(CLOUDS_SCATTERED, R.drawable.condition_clouds); IMG_MAP.put(CLOUDS_BROKEN, R.drawable.condition_overcast); IMG_MAP.put(CLOUDS_OVERCAST, R.drawable.condition_overcast); IMG_MAP.put(TORNADO, R.drawable.condition_alert); IMG_MAP.put(TROPICAL_STORM, R.drawable.condition_alert); IMG_MAP.put(HURRICANE, R.drawable.condition_alert); IMG_MAP.put(COLD, R.drawable.condition_alert); IMG_MAP.put(HOT, R.drawable.condition_alert); IMG_MAP.put(WINDY, R.drawable.condition_alert); IMG_MAP.put(HAIL, R.drawable.condition_alert); } Context context; public WeatherConditionFormat(Context context) { this.context = context; } public String getText(WeatherCondition condition) { int maxPriority = 0; List<WeatherConditionType> resultTypes = new ArrayList<WeatherConditionType>(); for (WeatherConditionType type : condition.getConditionTypes()) { if (type.getPriority() > maxPriority) { maxPriority = type.getPriority(); } } for (WeatherConditionType type : condition.getConditionTypes()) { if (type.getPriority() == maxPriority) { resultTypes.add(type); } } if (resultTypes.isEmpty()) { return this.context.getString(getStringId(WeatherConditionType.CLOUDS_CLEAR)); } StringBuilder result = new StringBuilder(); for (WeatherConditionType type : resultTypes) { Integer id = getStringId(type); if (id != null) { result.append(this.context.getString(id)); result.append(SEPARATOR); } } if (result.length() > 0) { result.delete(result.length() - SEPARATOR.length(), result.length()); } return result.toString(); } /** * Returns the LevelListDrawable, suitable for this weather condition. * The level of the drawable defines the desired drawable size in dp. */ public LevelListDrawable getDrawable(WeatherCondition condition) { return (LevelListDrawable)this.context.getResources().getDrawable(getDrawableId(condition)); } /** * Returns the ID of the drawable icon, suitable for this weather condition. * It's the LevelListDrawable, where the level defines the desired drawable size in dp. */ public static int getDrawableId(WeatherCondition condition) { Collection<WeatherConditionType> types = condition.getConditionTypes(); if (types == null || types.isEmpty()) { return getDrawableId(WeatherConditionType.CLOUDS_CLEAR); } return getDrawableId(types.iterator().next()); } static Integer getStringId(WeatherConditionType type) { return STR_MAP.get(type); } static Integer getDrawableId(WeatherConditionType type) { return IMG_MAP.get(type); } }
Java
/* * Android Weather Notification. * Copyright (C) 2014 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static ru.gelin.android.weather.notification.skin.impl.PreferenceKeys.*; /** * The class to get layout data based on the skin preferences. */ public class NotificationStyler { private static class LayoutKey { private final boolean showIcon; private final boolean showForecasts; private final boolean showUpdateTime; public LayoutKey(boolean showIcon, boolean showForecasts, boolean showUpdateTime) { this.showIcon = showIcon; this.showForecasts = showForecasts; this.showUpdateTime = showUpdateTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LayoutKey layoutKey = (LayoutKey) o; if (showForecasts != layoutKey.showForecasts) return false; if (showIcon != layoutKey.showIcon) return false; if (showUpdateTime != layoutKey.showUpdateTime) return false; return true; } @Override public int hashCode() { int result = (showIcon ? 1 : 0); result = 31 * result + (showForecasts ? 1 : 0); result = 31 * result + (showUpdateTime ? 1 : 0); return result; } } public enum Layout { CUSTOM_ICON_FORECASTS("notification_icon_forecasts"), CUSTOM_ICON_FORECASTS_UPDATE("notification_icon_forecasts_update"), CUSTOM_ICON("notification_icon"), CUSTOM_ICON_UPDATE("notification_icon_update"), CUSTOM_FORECASTS("notification_forecasts"), CUSTOM_FORECASTS_UPDATE("notification_forecasts_update"), CUSTOM("notification"), CUSTOM_UPDATE("notification_update"); public final String name; private Layout(String name) { this.name = name; } private static final Map<LayoutKey, Layout> MAP = new HashMap<LayoutKey, Layout>(); static { MAP.put(new LayoutKey(false, false, false), Layout.CUSTOM); MAP.put(new LayoutKey(false, false, true), Layout.CUSTOM_UPDATE); MAP.put(new LayoutKey(false, true, false), Layout.CUSTOM_FORECASTS); MAP.put(new LayoutKey(false, true, true), Layout.CUSTOM_FORECASTS_UPDATE); MAP.put(new LayoutKey(true, false, false), Layout.CUSTOM_ICON); MAP.put(new LayoutKey(true, false, true), Layout.CUSTOM_ICON_UPDATE); MAP.put(new LayoutKey(true, true, false), Layout.CUSTOM_ICON_FORECASTS); MAP.put(new LayoutKey(true, true, true), Layout.CUSTOM_ICON_FORECASTS_UPDATE); } public static Layout get(boolean showIcon, boolean showForecasts, boolean showUpdateTime) { LayoutKey key = new LayoutKey(showIcon, showForecasts, showUpdateTime); return MAP.get(key); } } private final Context context; private final TemperatureType tempType; private final WindUnit windUnit; private final NotificationStyle notifyStyle; private final NotificationTextStyle textStyle; private final boolean showIcon; private final boolean showForecasts; /** Type of the notification layout */ final Layout layout; /** Ids of layout views. */ final Set<Integer> ids = new HashSet<Integer>(); public NotificationStyler(Context context) { this.context = context; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); this.tempType = TemperatureType.valueOf(prefs.getString( TEMP_UNIT, TEMP_UNIT_DEFAULT)); this.windUnit = WindUnit.valueOf(prefs.getString( WS_UNIT, WS_UNIT_DEFAULT)); this.notifyStyle = NotificationStyle.valueOf(prefs.getString( NOTIFICATION_STYLE, NOTIFICATION_STYLE_DEFAULT)); this.textStyle = NotificationTextStyle.valueOf(prefs.getString( NOTIFICATION_TEXT_STYLE, NOTIFICATION_TEXT_STYLE_DEFAULT)); this.showIcon = prefs.getBoolean( NOTIFICATION_ICON_STYLE, NOTIFICATION_ICON_STYLE_DEFAULT); this.showForecasts = prefs.getBoolean( NOTIFICATION_FORECASTS_STYLE, NOTIFICATION_FORECASTS_STYLE_DEFAULT); this.layout = Layout.get(isShowIcon(), isShowForecasts(), isShowUpdateTime()); initLayoutIds(); } public TemperatureType getTempType() { return this.tempType; } public WindUnit getWindUnit() { return this.windUnit; } public NotificationStyle getNotifyStyle() { return this.notifyStyle; } public NotificationTextStyle getTextStyle() { return this.textStyle; } public boolean isShowIcon() { return this.showIcon; } public boolean isShowForecasts() { return this.showForecasts; } /** * Returns the notification layout id. */ public int getLayoutId() { if (this.layout == null) { return 0; //unknown resource } ResourceIdFactory ids = ResourceIdFactory.getInstance(this.context); return ids.id(ResourceIdFactory.LAYOUT, this.layout.name); } /** * Returns true if this layout contains view with this id */ public boolean isViewInLayout(int viewId) { return this.ids.contains(viewId); } private boolean isShowUpdateTime() { switch (getTempType()) { case C: case F: default: return true; case CF: case FC: return false; } } private void initLayoutIds() { ResourceIdFactory ids = ResourceIdFactory.getInstance(this.context); //basic set of ids this.ids.add(ids.id("condition")); this.ids.add(ids.id("wind")); this.ids.add(ids.id("humidity")); this.ids.add(ids.id("temp")); this.ids.add(ids.id("current_temp")); this.ids.add(ids.id("high_temp")); this.ids.add(ids.id("low_temp")); switch(this.layout) { case CUSTOM_ICON_FORECASTS: case CUSTOM_ICON: case CUSTOM_FORECASTS: case CUSTOM: this.ids.add(ids.id("current_temp_alt")); break; case CUSTOM_ICON_FORECASTS_UPDATE: case CUSTOM_ICON_UPDATE: case CUSTOM_FORECASTS_UPDATE: case CUSTOM_UPDATE: this.ids.add(ids.id("update_time_short")); break; } switch(this.layout) { case CUSTOM_ICON_FORECASTS: case CUSTOM_ICON_FORECASTS_UPDATE: case CUSTOM_FORECASTS: case CUSTOM_FORECASTS_UPDATE: this.ids.add(ids.id("forecasts")); // this.ids.add(ids.id("forecast_1")); this.ids.add(ids.id("forecast_day_1")); this.ids.add(ids.id("forecast_condition_icon_1")); this.ids.add(ids.id("forecast_high_temp_1")); this.ids.add(ids.id("forecast_low_temp_1")); // this.ids.add(ids.id("forecast_2")); this.ids.add(ids.id("forecast_day_2")); this.ids.add(ids.id("forecast_condition_icon_2")); this.ids.add(ids.id("forecast_high_temp_2")); this.ids.add(ids.id("forecast_low_temp_2")); // this.ids.add(ids.id("forecast_3")); this.ids.add(ids.id("forecast_day_3")); this.ids.add(ids.id("forecast_condition_icon_3")); this.ids.add(ids.id("forecast_high_temp_3")); this.ids.add(ids.id("forecast_low_temp_3")); break; } switch(this.layout) { case CUSTOM_ICON_FORECASTS: case CUSTOM_ICON_FORECASTS_UPDATE: case CUSTOM_ICON: case CUSTOM_ICON_UPDATE: this.ids.add(ids.id("condition_icon")); break; } } }
Java
package ru.gelin.android.weather.notification.skin.impl; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import ru.gelin.android.weather.*; import ru.gelin.android.weather.TemperatureUnit; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.STRING; /** * A class which holds together: Context, Weather, NotificationStyler - * and provides formatting methods for many aspects of the weather representation. */ public class WeatherFormatter { /** Large icon size */ static final int LARGE_ICON = 48; private final Context context; private final Weather weather; private final NotificationStyler styler; private final ResourceIdFactory ids; public WeatherFormatter(Context context, Weather weather) { this.context = context; this.weather = weather; this.styler = new NotificationStyler(context); this.ids = ResourceIdFactory.getInstance(context); } protected Context getContext() { return this.context; } protected Weather getWeather() { return this.weather; } protected NotificationStyler getStyler() { return this.styler; } protected ResourceIdFactory getIds() { return this.ids; } protected String formatTicker() { WeatherCondition condition = getWeather().getConditions().get(0); Temperature tempC = condition.getTemperature(TemperatureUnit.C); Temperature tempF = condition.getTemperature(TemperatureUnit.F); return getContext().getString( getIds().id(STRING, "notification_ticker"), getWeather().getLocation().getText(), getTemperatureFormat().format( tempC.getCurrent(), tempF.getCurrent(), getStyler().getTempType())); } protected String formatContentTitle() { WeatherCondition condition = getWeather().getConditions().get(0); Temperature tempC = condition.getTemperature(TemperatureUnit.C); Temperature tempF = condition.getTemperature(TemperatureUnit.F); return getContext().getString( getIds().id(STRING, "notification_content_title"), getTemperatureFormat().format( tempC.getCurrent(), tempF.getCurrent(), getStyler().getTempType()), getWeatherConditionFormat().getText(condition)); } protected String formatContentText() { WeatherCondition condition = getWeather().getConditions().get(0); TemperatureFormat tempFormat = getTemperatureFormat(); TemperatureUnit tempUnit = getStyler().getTempType().getTemperatureUnit(); Temperature temp = condition.getTemperature(tempUnit); Wind wind = condition.getWind(getStyler().getWindUnit().getWindSpeedUnit()); Humidity humidity = condition.getHumidity(); return getContext().getString(getIds().id(STRING, "notification_content_text"), tempFormat.format(temp.getHigh()), tempFormat.format(temp.getLow()), getWindFormat().format(wind), getHumidityFormat().format(humidity)); } protected Bitmap formatLargeIcon() { WeatherCondition condition = getWeather().getConditions().get(0); WeatherConditionFormat format = getWeatherConditionFormat(); Drawable drawable = format.getDrawable(condition); drawable.setLevel(LARGE_ICON); return Drawable2Bitmap.convert(drawable); } /** * Creates the temperature formatter. */ protected TemperatureFormat getTemperatureFormat() { return new TemperatureFormat(); } /** * Creates the weather condition format. */ protected WeatherConditionFormat getWeatherConditionFormat() { return new WeatherConditionFormat(getContext()); } /** * Creates the wind format. */ protected WindFormat getWindFormat() { return new WindFormat(getContext()); } /** * Creates the humidity format. */ protected HumidityFormat getHumidityFormat() { return new HumidityFormat(getContext()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.LAYOUT; import static ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver.WEATHER_KEY; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.WeatherStorage; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.ImageButton; import ru.gelin.android.weather.notification.AppUtils; /** * Base class for weather info activity. */ abstract public class BaseWeatherInfoActivity extends Activity { ResourceIdFactory ids; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ids = ResourceIdFactory.getInstance(this); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(ids.id(LAYOUT, "weather_info")); final ImageButton refreshButton = (ImageButton)findViewById(ids.id("refresh_button")); refreshButton.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { startProgress(); AppUtils.startUpdateService(BaseWeatherInfoActivity.this, true, true); } }); ImageButton preferencesButton = (ImageButton)findViewById(ids.id("preferences_button")); preferencesButton.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { finish(); AppUtils.startMainActivity(BaseWeatherInfoActivity.this); } }); View wholeActivity = findViewById(ids.id("weather_info")); wholeActivity.setOnClickListener(new OnClickListener() { //@Override public void onClick(View v) { finish(); } }); } @Override protected void onResume() { super.onResume(); BaseWeatherNotificationReceiver.registerWeatherHandler(weatherHandler); WeatherStorage storage = new WeatherStorage(this); WeatherLayout layout = createWeatherLayout(this, findViewById(ids.id("weather_info"))); Weather weather = storage.load(); layout.bind(weather); //Location location = weather.getLocation(); //setTitle(location == null ? "" : location.getText()); } @Override protected void onPause() { super.onPause(); BaseWeatherNotificationReceiver.unregisterWeatherHandler(); } final Handler weatherHandler = new Handler() { @Override public void handleMessage(Message msg) { stopProgress(); Weather weather = (Weather)msg.getData().getParcelable(WEATHER_KEY); if (weather == null) { return; } WeatherLayout layout = createWeatherLayout( BaseWeatherInfoActivity.this, findViewById( BaseWeatherInfoActivity.this.ids.id("weather_info"))); layout.bind(weather); }; }; void startProgress() { View refreshButton = findViewById(ids.id("refresh_button")); refreshButton.setEnabled(false); //Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate); //refreshButton.startAnimation(rotate); } void stopProgress() { View refreshButton = findViewById(ids.id("refresh_button")); refreshButton.setEnabled(true); } /** * Creates the weather layout to render activity. */ protected WeatherLayout createWeatherLayout(Context context, View view) { return new WeatherLayout(context, view); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.notification.skin.impl; import ru.gelin.android.weather.WindSpeedUnit; /** * Maps user's settings to the actual wind speed unit. */ public enum WindUnit { MPH(WindSpeedUnit.MPH), MPS(WindSpeedUnit.MPS), KMPH(WindSpeedUnit.KMPH); WindSpeedUnit unit; WindUnit(WindSpeedUnit unit) { this.unit = unit; } public WindSpeedUnit getWindSpeedUnit() { return this.unit; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import java.util.List; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceChangeListener; public class SkinsActivity extends UpdateNotificationActivity implements OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SkinManager sm = new SkinManager(this); List<SkinInfo> skins = sm.getInstalledSkins(); PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this); setPreferenceScreen(screen); for (SkinInfo skin : skins) { CheckBoxPreference checkboxPref = skin.getCheckBoxPreference(this); checkboxPref.setOnPreferenceChangeListener(this); screen.addPreference(checkboxPref); Preference configPref = skin.getConfigPreference(this); if (configPref != null) { screen.addPreference(configPref); configPref.setDependency(checkboxPref.getKey()); //disabled if skin is disabled } } } public boolean onPreferenceChange(Preference preference, Object newValue) { updateNotification(); return true; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.IntentParameters; import ru.gelin.android.weather.notification.ParcelableWeather; import ru.gelin.android.weather.notification.ParcelableWeather2; import ru.gelin.android.weather.notification.WeatherStorage; import static ru.gelin.android.weather.notification.PreferenceKeys.ENABLE_NOTIFICATION; import static ru.gelin.android.weather.notification.PreferenceKeys.ENABLE_NOTIFICATION_DEFAULT; /** * Managers the broadcast receivers to receive the weather notification. */ @SuppressWarnings("deprecation") public class WeatherNotificationManager { Context context; SkinManager sm; /** * Updates the notification. */ public static void update(Context context) { WeatherNotificationManager manager = new WeatherNotificationManager(context); if (!manager.isEnabled()) { manager.cancelAll(); return; } manager.cancelDisabled(); manager.sendWeather(); } WeatherNotificationManager(Context context) { this.context = context; this.sm = new SkinManager(context); } /** * Returns true if the notification is enabled. */ boolean isEnabled() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context); return prefs.getBoolean(ENABLE_NOTIFICATION, ENABLE_NOTIFICATION_DEFAULT); } /** * Cancels the notification */ void cancelAll() { Intent intent = new Intent(IntentParameters.ACTION_WEATHER_UPDATE); //cancel sends to all intent.putExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false); this.context.sendBroadcast(intent); Intent intent2 = new Intent(IntentParameters.ACTION_WEATHER_UPDATE_2); intent2.putExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false); this.context.sendBroadcast(intent2); } /** * Cancels notification for the disabled skins */ void cancelDisabled() { for (SkinInfo skin : this.sm.getDisabledSkins()) { Intent intent = createIntent(skin, false, null); intent.setClassName(skin.getPackageName(), skin.getBroadcastReceiverClass()); context.sendBroadcast(intent); } } /** * Notifies with new weather value. */ void sendWeather() { WeatherStorage storage = new WeatherStorage(this.context); Weather weather = storage.load(); for (SkinInfo skin : this.sm.getEnabledSkins()) { Intent intent = createIntent(skin, true, weather); intent.setClassName(skin.getPackageName(), skin.getBroadcastReceiverClass()); context.sendBroadcast(intent); } } /** * Creates the intents with the weather. * Returns two intents with different Action and Weather object type for backward compatibility. */ static Intent createIntent(SkinInfo skin, boolean enableNotification, Weather weather) { switch (skin.getVersion()) { case V1: return createIntent(enableNotification, weather); case V2: return createIntent2(enableNotification, weather); } throw new RuntimeException("unknown skin version"); } static Intent createIntent(boolean enableNotification, Weather weather) { Intent intent = new Intent(IntentParameters.ACTION_WEATHER_UPDATE); intent.putExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, enableNotification); if (enableNotification) { ParcelableWeather oldParcel = new ParcelableWeather(weather); intent.putExtra(IntentParameters.EXTRA_WEATHER, oldParcel); } return intent; } static Intent createIntent2(boolean enableNotification, Weather weather) { Intent intent = new Intent(IntentParameters.ACTION_WEATHER_UPDATE_2); intent.putExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, enableNotification); if (enableNotification) { ParcelableWeather2 parcel = new ParcelableWeather2(weather); intent.putExtra(IntentParameters.EXTRA_WEATHER, parcel); } return intent; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import android.content.Context; import android.content.Intent; import android.preference.Preference; import android.preference.TwoStatePreference; import ru.gelin.android.preference.SwitchPreference; import static ru.gelin.android.weather.notification.IntentParameters.ACTION_WEATHER_SKIN_PREFERENCES; import static ru.gelin.android.weather.notification.skin.PreferenceKeys.SKIN_ENABLED_PATTERN; /** * Information about skin * A version which is used in Android 4.x */ public class SkinInfo4 extends SkinInfo { protected SkinInfo4(String id) { super(id); } @Override public Preference getSwitchPreference(Context context) { TwoStatePreference pref = new SwitchPreference(context); pref.setKey(String.format(SKIN_ENABLED_PATTERN, getId())); pref.setTitle(getBroadcastReceiverLabel()); pref.setSummary(R.string.skin_tap_to_config); pref.setChecked(isEnabled()); pref.setOrder(this.order); Intent intent = new Intent(ACTION_WEATHER_SKIN_PREFERENCES); intent.setClassName(getPackageName(), getConfigActivityClass()); pref.setIntent(intent); pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { TwoStatePreference switchPreference = (TwoStatePreference)preference; switchPreference.setChecked(!switchPreference.isChecked()); //to avoid changing of the state by clicking not to the switch return false; } }); return pref; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import android.content.Context; import android.content.Intent; import android.os.Build; import android.preference.CheckBoxPreference; import android.preference.Preference; import static ru.gelin.android.weather.notification.IntentParameters.ACTION_WEATHER_SKIN_PREFERENCES; import static ru.gelin.android.weather.notification.skin.PreferenceKeys.SKIN_CONFIG_PATTERN; import static ru.gelin.android.weather.notification.skin.PreferenceKeys.SKIN_ENABLED_PATTERN; /** * Information about skin */ public class SkinInfo { /** * Versions of the skin. * Skin V1 receives notifications with {@link ru.gelin.android.weather.notification.IntentParameters#ACTION_WEATHER_UPDATE}. * Skin V2 receives notifications with {@link ru.gelin.android.weather.notification.IntentParameters#ACTION_WEATHER_UPDATE_2}. */ public enum Version { V1, V2; } String id; String packageName; Version version; boolean enabled; String broadcastReceiverClass; String broadcastReceiverLabel; String configActivityClass; String configActivityLabel; int order = 0; static SkinInfo getInstance(String id) { SkinInfo info = new SkinInfo(id); try { if (Integer.parseInt(Build.VERSION.SDK) >= 14) { //info = SkinInfo4.class.getConstructor(String.class).newInstance(id); info = new SkinInfo4(id); } } catch (Exception e) { //pass to old SkinInfo } return info; } protected SkinInfo(String id) { this.id = id; } public String getId() { return this.id; } public String getPackageName() { return this.packageName; } public Version getVersion() { return this.version; } public boolean isEnabled() { return this.enabled; } public String getBroadcastReceiverClass() { return this.broadcastReceiverClass; } public String getBroadcastReceiverLabel() { return this.broadcastReceiverLabel; } public String getConfigActivityClass() { return this.configActivityClass; } public String getConfigActivityLabel() { return this.configActivityLabel; } /** * Creates checkbox preference to enable/disable the skin. */ public CheckBoxPreference getCheckBoxPreference(Context context) { CheckBoxPreference checkBox = new CheckBoxPreference(context); checkBox.setKey(String.format(SKIN_ENABLED_PATTERN, getId())); checkBox.setTitle(getBroadcastReceiverLabel()); checkBox.setChecked(isEnabled()); checkBox.setOrder(this.order); return checkBox; } /** * Creates preference to open skin settings. * Can return null if the skin has no configuraion. */ public Preference getConfigPreference(Context context) { if (getConfigActivityClass() == null) { return null; } Preference pref = new Preference(context); pref.setKey(String.format(SKIN_CONFIG_PATTERN, getId())); pref.setTitle(getConfigActivityLabel() == null ? getBroadcastReceiverLabel() : getConfigActivityLabel()); Intent intent = new Intent(ACTION_WEATHER_SKIN_PREFERENCES); intent.setClassName(getPackageName(), getConfigActivityClass()); pref.setIntent(intent); pref.setOrder(this.order + 1); return pref; } /** * Creates SwitchPreference to enable/disable the skin and open skin settings. */ public Preference getSwitchPreference(Context context) { CheckBoxPreference pref = new CheckBoxPreference(context); pref.setKey(String.format(SKIN_ENABLED_PATTERN, getId())); pref.setTitle(getBroadcastReceiverLabel()); pref.setSummary(R.string.skin_tap_to_config); pref.setChecked(isEnabled()); pref.setOrder(this.order); Intent intent = new Intent(ACTION_WEATHER_SKIN_PREFERENCES); intent.setClassName(getPackageName(), getConfigActivityClass()); pref.setIntent(intent); pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { CheckBoxPreference switchPreference = (CheckBoxPreference)preference; switchPreference.setChecked(!switchPreference.isChecked()); //to avoid changing of the state by clicking not to the switch return false; } }); return pref; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.preference.PreferenceManager; import ru.gelin.android.weather.notification.IntentParameters; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import static ru.gelin.android.weather.notification.IntentParameters.ACTION_WEATHER_UPDATE; import static ru.gelin.android.weather.notification.IntentParameters.ACTION_WEATHER_UPDATE_2; import static ru.gelin.android.weather.notification.skin.PreferenceKeys.SKIN_ENABLED_PATTERN; /** * Contains methods to handle list of installed skins. * The BroadcastReceivers which handles ACTION_WEATHER_UPDATE and ACTION_WEATHER_UPDATE_2 * intents are tracked. * The activity which handles ACTION_WEATHER_SKIN_PREFERENCES intent and is placed in the same * Android AND Java package as the received is treated as a configuration activity for the skin. */ public class SkinManager { Context context; /** Map of the skin Android package name + Java package name to the skin info. Sorted by package name. */ Map<String, SkinInfo> skins = new TreeMap<String, SkinInfo>(); //sorted by the package name /** * Creates the manager. Updates the list of installed skins. */ public SkinManager(Context context) { this.context = context; querySkinReceivers(); updateEnabledFlag(); querySkinConfigs(); } /** * Returns the list of installed skins. */ public List<SkinInfo> getInstalledSkins() { List<SkinInfo> result = new ArrayList<SkinInfo>(); result.addAll(this.skins.values()); return result; } /** * Returns the list of enabled skins. */ public List<SkinInfo> getEnabledSkins() { List<SkinInfo> result = new ArrayList<SkinInfo>(); for (SkinInfo skin : this.skins.values()) { if (skin.isEnabled()) { result.add(skin); } } return result; } /** * Returns the list of installed, but disabled skins. */ public List<SkinInfo> getDisabledSkins() { List<SkinInfo> result = new ArrayList<SkinInfo>(); for (SkinInfo skin : this.skins.values()) { if (!skin.isEnabled()) { result.add(skin); } } return result; } /** * Queries PackageManager for broadcast receivers which handles * ACTION_WEATHER_UPDATE and ACTION_WEATHER_UPDATE_2. * Puts found data (skin package, receiver class and label) into skins map. */ void querySkinReceivers() { querySkinReceivers(ACTION_WEATHER_UPDATE, SkinInfo.Version.V1); //TODO: join intent action names and versions... querySkinReceivers(ACTION_WEATHER_UPDATE_2, SkinInfo.Version.V2); } /** * Queries PackageManager for broadcast receivers which handles specified Action. * Puts found data (skin package, receiver class and labed) into skins map. */ void querySkinReceivers(String action, SkinInfo.Version version) { PackageManager pm = context.getPackageManager(); Intent intent = new Intent(action); List<ResolveInfo> search = pm.queryBroadcastReceivers(intent, 0); //without flags for (ResolveInfo info : search) { //Log.d(TAG, String.valueOf(info)); String packageName = info.activityInfo.packageName; String label = String.valueOf(info.loadLabel(pm)); String receiverClass = info.activityInfo.name; //Log.d(TAG, "package: " + packageName); //Log.d(TAG, "class: " + receiverClass); SkinInfo skin = SkinInfo.getInstance(getSkinId(info)); skin.packageName = packageName; skin.version = version; skin.broadcastReceiverLabel = label; skin.broadcastReceiverClass = receiverClass; this.skins.put(skin.getId(), skin); } int order = 0; for (SkinInfo skin : this.skins.values()) { skin.order = order; order += 2; } } /** * Checks preferences to found which skin is enabled. */ void updateEnabledFlag() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context); for (Map.Entry<String, SkinInfo> skin : this.skins.entrySet()) { String key = String.format(SKIN_ENABLED_PATTERN, skin.getKey()); boolean enabled = prefs.getBoolean(key, isBuiltinSkin(skin.getKey())); //builtin skin is enabled by default skin.getValue().enabled = enabled; } } boolean isBuiltinSkin(String packageName) { return packageName.startsWith(this.context.getPackageName()) && packageName.endsWith("builtin"); } /** * Queries PackageManager for activities which handles ACTION_WEATHER_SKIN_PREFERENCES actions. * Updates the skin map according the package name. */ void querySkinConfigs() { PackageManager pm = context.getPackageManager(); Intent intent = new Intent(IntentParameters.ACTION_WEATHER_SKIN_PREFERENCES); List<ResolveInfo> search = pm.queryIntentActivities(intent, 0); //without flags for (ResolveInfo info : search) { //Log.d(TAG, String.valueOf(info)); String label = String.valueOf(info.loadLabel(pm)); String activityClass = info.activityInfo.name; //Log.d(TAG, "package: " + packageName); //Log.d(TAG, "class: " + activityClass); SkinInfo skin = this.skins.get(getSkinId(info)); if (skin == null) { continue; } skin.configActivityLabel = label; skin.configActivityClass = activityClass; } } String getSkinId(ResolveInfo info) { String androidPackageName = info.activityInfo.packageName; String className = info.activityInfo.name; String javaPackageName = className.substring(0, className.lastIndexOf('.')); return androidPackageName + "/" + javaPackageName; } }
Java
/* * Android helper classes. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.preference; import android.content.Context; import android.preference.EditTextPreference; import android.util.AttributeSet; /** * Edit text preference which displays the entered value as Summary. */ public class SummaryTextPreference extends EditTextPreference { public SummaryTextPreference(Context context) { super(context); } public SummaryTextPreference(Context context, AttributeSet attrs) { super(context, attrs); } public SummaryTextPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { super.onSetInitialValue(restoreValue, defaultValue); setSummary(getText()); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); setSummary(getText()); } }
Java
/* * Android helper classes. * Copyright (C) 2012 caoyachao@hotmail.com, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.preference; import android.content.Context; import android.preference.TwoStatePreference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.Checkable; import android.widget.CompoundButton; import android.widget.Switch; /** * The correct version of SwitchPreference which fixes this issue: * http://code.google.com/p/android/issues/detail?id=26194 * Also has not-words, but some characters for on/off states of the switch. */ public class SwitchPreference extends TwoStatePreference { private final Listener mListener = new Listener(); private class Listener implements CompoundButton.OnCheckedChangeListener { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!callChangeListener(isChecked)) { // Listener didn't like it, change it back. // CompoundButton will make sure we don't recurse. buttonView.setChecked(!isChecked); return; } SwitchPreference.this.setChecked(isChecked); } } /** * Construct a new SwitchPreference with the given style options. * * @param context The Context that will style this preference * @param attrs Style attributes that differ from the default * @param defStyle Theme attribute defining the default style options */ public SwitchPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setWidgetLayoutResource(R.layout.preference_widget_switch); } /** * Construct a new SwitchPreference with the given style options. * * @param context The Context that will style this preference * @param attrs Style attributes that differ from the default */ public SwitchPreference(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.switchPreferenceStyle); setWidgetLayoutResource(R.layout.preference_widget_switch); } /** * Construct a new SwitchPreference with default style options. * * @param context The Context that will style this preference */ public SwitchPreference(Context context) { this(context, null); setWidgetLayoutResource(R.layout.preference_widget_switch); } @Override protected void onBindView(View view) { ViewGroup viewGroup= (ViewGroup)view; clearListenerInViewGroup(viewGroup); super.onBindView(view); View checkableView = view.findViewById(R.id.switchWidget); if (checkableView != null && checkableView instanceof Checkable) { ((Checkable) checkableView).setChecked(isChecked()); if (checkableView instanceof Switch) { final Switch switchView = (Switch) checkableView; // switchView.setAccessibilityDelegate(); switchView.setOnCheckedChangeListener(mListener); } } } /** * Clear listener in Switch for specify ViewGroup. * * @param viewGroup The ViewGroup that will need to clear the listener. */ private void clearListenerInViewGroup(ViewGroup viewGroup) { if (null == viewGroup) { return; } int count = viewGroup.getChildCount(); for(int n = 0; n < count; ++n) { View childView = viewGroup.getChildAt(n); if(childView instanceof Switch) { final Switch switchView = (Switch) childView; switchView.setOnCheckedChangeListener(null); return; } else if (childView instanceof ViewGroup){ ViewGroup childGroup = (ViewGroup)childView; clearListenerInViewGroup(childGroup); } } } }
Java
/* * Android helper classes. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.preference; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; /** * List preference which displays the selected value as Summary. */ public class SummaryListPreference extends ListPreference { public SummaryListPreference(Context context) { super(context); } public SummaryListPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { super.onSetInitialValue(restoreValue, defaultValue); setSummary(getEntry()); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); setSummary(getEntry()); } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.google; import android.location.Address; import ru.gelin.android.weather.Location; /** * Wrapper for Android location to query Google weather API with geo coordinates. */ public class AndroidGoogleLocation implements Location { /** Query template */ static final String QUERY = "%s,%s,%s,%d,%d"; /** Android location */ android.location.Location location; /** Android address */ Address address; /** * Creates the location from Android location. */ public AndroidGoogleLocation(android.location.Location location) { this.location = location; } /** * Creates the location from Android location and address. */ public AndroidGoogleLocation(android.location.Location location, Address address) { this.location = location; this.address = address; } /** * Creates the query with geo coordinates. * For example: ",,,30670000,104019996" */ //@Override public String getQuery() { if (location == null) { return ""; } if (address == null) { return String.format(QUERY, "", "", "", convertGeo(location.getLatitude()), convertGeo(location.getLongitude())); } return String.format(QUERY, stringOrEmpty(address.getLocality()), stringOrEmpty(address.getAdminArea()), stringOrEmpty(address.getCountryName()), convertGeo(location.getLatitude()), convertGeo(location.getLongitude())); } //@Override public String getText() { if (location == null) { return ""; } if (address == null) { return android.location.Location.convert(location.getLatitude(), android.location.Location.FORMAT_DEGREES) + " " + android.location.Location.convert(location.getLongitude(), android.location.Location.FORMAT_DEGREES); } StringBuilder result = new StringBuilder(); result.append(stringOrEmpty(address.getLocality())); if (result.length() > 0) { result.append(", "); } result.append(stringOrEmpty(address.getAdminArea())); if (result.length() == 0) { result.append(stringOrEmpty(address.getCountryName())); } return result.toString(); } //@Override public boolean isEmpty() { return this.location == null; } @Override public boolean isGeo() { return true; } int convertGeo(double geo) { return (int)(geo * 1000000); } String stringOrEmpty(String string) { if (string == null) { return ""; } return string; } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.google; import java.io.IOException; import java.io.Reader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ru.gelin.android.weather.v_0_2.*; /** * Weather, provided by Google API. */ public class GoogleWeather implements Weather { /** Format for dates in the XML */ static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); /** Format for times in the XML */ static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); Location location = new SimpleLocation(""); Date date = new Date(0); Date time = new Date(0); UnitSystem unit = UnitSystem.SI; List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); /** * Creates the weather from the input stream with XML * received from API. */ public GoogleWeather(Reader xml) throws WeatherException { try { parse(xml); } catch (Exception e) { throw new WeatherException("cannot parse xml", e); } } //@Override public Location getLocation() { return this.location; } //@Override public Date getTime() { if (this.time.after(this.date)) { //sometimes time is 0, but the date has correct value return this.time; } else { return this.date; } } //@Override public UnitSystem getUnitSystem() { return this.unit; } //@Override public List<WeatherCondition> getConditions() { return this.conditions; } //@Override public boolean isEmpty() { return this.conditions.isEmpty(); } void parse(Reader xml) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //WTF??? Harmony's Expat is so... //factory.setFeature("http://xml.org/sax/features/namespaces", false); //factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); //explicitly decoding from UTF-8 because Google misses encoding in XML preamble parser.parse(new InputSource(xml), new ApiXmlHandler()); } /** * Sets the location. * Used by the weather source if the location, returned from API is empty. */ void setLocation(Location location) { this.location = location; } static enum HandlerState { CURRENT_CONDITIONS, FIRST_FORECAST, NEXT_FORECAST; } class ApiXmlHandler extends DefaultHandler { HandlerState state; SimpleWeatherCondition condition; SimpleTemperature temperature; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String data = attributes.getValue("data"); if ("city".equals(localName)) { GoogleWeather.this.location = new SimpleLocation(data); } else if ("forecast_date".equals(localName)) { try { GoogleWeather.this.date = DATE_FORMAT.parse(data); } catch (ParseException e) { throw new SAXException("invalid 'forecast_date' format: " + data, e); } } else if ("current_date_time".equals(localName)) { try { GoogleWeather.this.time = TIME_FORMAT.parse(data); } catch (ParseException e) { throw new SAXException("invalid 'current_date_time' format: " + data, e); } } else if ("unit_system".equals(localName)) { GoogleWeather.this.unit = UnitSystem.valueOf(data); } else if ("current_conditions".equals(localName)) { state = HandlerState.CURRENT_CONDITIONS; addCondition(); } else if ("forecast_conditions".equals(localName)) { switch (state) { case CURRENT_CONDITIONS: state = HandlerState.FIRST_FORECAST; break; case FIRST_FORECAST: state = HandlerState.NEXT_FORECAST; addCondition(); break; default: addCondition(); } } else if ("condition".equals(localName)) { switch (state) { case FIRST_FORECAST: //skipping update of condition, because the current conditions are already set break; default: condition.setConditionText(data); } } else if ("temp_f".equalsIgnoreCase(localName)) { if (UnitSystem.US.equals(GoogleWeather.this.unit)) { try { temperature.setCurrent(Integer.parseInt(data), UnitSystem.US); } catch (NumberFormatException e) { throw new SAXException("invalid 'temp_f' format: " + data, e); } } } else if ("temp_c".equals(localName)) { if (UnitSystem.SI.equals(GoogleWeather.this.unit)) { try { temperature.setCurrent(Integer.parseInt(data), UnitSystem.SI); } catch (NumberFormatException e) { throw new SAXException("invalid 'temp_c' format: " + data, e); } } } else if ("humidity".equals(localName)) { condition.setHumidityText(data); } else if ("wind_condition".equals(localName)) { condition.setWindText(data); } else if ("low".equals(localName)) { try { temperature.setLow(Integer.parseInt(data), GoogleWeather.this.unit); } catch (NumberFormatException e) { throw new SAXException("invalid 'low' format: " + data, e); } } else if ("high".equals(localName)) { try { temperature.setHigh(Integer.parseInt(data), GoogleWeather.this.unit); } catch (NumberFormatException e) { throw new SAXException("invalid 'high' format: " + data, e); } } } //@Override //public void endElement(String uri, String localName, String qName) // throws SAXException { // boolean dummy = true; //} void addCondition() { condition = new SimpleWeatherCondition(); temperature = new SimpleTemperature(GoogleWeather.this.unit); condition.setTemperature(temperature); GoogleWeather.this.conditions.add(condition); } } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.google; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Locale; import ru.gelin.android.weather.v_0_2.Location; import ru.gelin.android.weather.v_0_2.Weather; import ru.gelin.android.weather.v_0_2.WeatherException; import ru.gelin.android.weather.v_0_2.WeatherSource; /** * Weather source which takes weather from the Google API. */ public class GoogleWeatherSource implements WeatherSource { /** API URL */ static final String API_URL = "http://www.google.com/ig/api?weather=%s&hl=%s"; /** Main encoding */ static final String ENCODING = "UTF-8"; /** Charset pattern */ static final String CHARSET = "charset="; //@Override public Weather query(Location location) throws WeatherException { return query(location, Locale.getDefault()); } //@Override public Weather query(Location location, Locale locale) throws WeatherException { String fullUrl; try { fullUrl = String.format(API_URL, URLEncoder.encode(location.getQuery(), ENCODING), URLEncoder.encode(locale.getLanguage(), ENCODING)); } catch (UnsupportedEncodingException uee) { throw new RuntimeException(uee); //should never happen } URL url; try { url = new URL(fullUrl); } catch (MalformedURLException mue) { throw new WeatherException("invalid URL: " + fullUrl, mue); } String charset = ENCODING; try { URLConnection connection = url.openConnection(); //connection.addRequestProperty("Accept-Charset", "UTF-8"); //connection.addRequestProperty("Accept-Language", locale.getLanguage()); charset = getCharset(connection); GoogleWeather weather = new GoogleWeather(new InputStreamReader( connection.getInputStream(), charset)); if (weather.getLocation().isEmpty()) { weather.setLocation(location); //set original location } return weather; } catch (UnsupportedEncodingException uee) { throw new WeatherException("unsupported charset: " + charset, uee); } catch (IOException ie) { throw new WeatherException("cannot read URL: " + fullUrl, ie); } } static String getCharset(URLConnection connection) { return getCharset(connection.getContentType()); } static String getCharset(String contentType) { if (contentType == null) { return ENCODING; } int charsetPos = contentType.indexOf(CHARSET); if (charsetPos < 0) { return ENCODING; } charsetPos += CHARSET.length(); int endPos = contentType.indexOf(';', charsetPos); if (endPos < 0) { endPos = contentType.length(); } return contentType.substring(charsetPos, endPos); } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; //import java.net.URL; /** * Common weather conditions. */ public interface WeatherCondition { /** * Returns condition as a human readable text. */ String getConditionText(); /** * Returns URL to condition icon. */ //URL getConditionIcon(); /** * Returns the temperature in default units. */ Temperature getTemperature(); /** * Returns the temperature in specified units. */ Temperature getTemperature(UnitSystem units); /** * Returns humidity as a human readable text. * Can return null. */ String getHumidityText(); /** * Returns wind conditions as a human readable text. * Can return null. */ String getWindText(); }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Holds temperature values. * Allows to set the values in different unit systems. * Automatically calculates high and low temps when current temp is set. * Automatically calculates current temp when high and low are set. */ public class SimpleTemperature implements Temperature { UnitSystem unit; int current = UNKNOWN; int low = UNKNOWN; int high = UNKNOWN; /** * Constructs the temperature. * The stored values will be returned in the specified unit system. */ public SimpleTemperature(UnitSystem unit) { this.unit = unit; } /** * Sets the current temperature in specified unit system. */ public void setCurrent(int temp, UnitSystem unit) { if (this.unit.equals(unit)) { this.current = temp; } else { this.current = convertValue(temp, unit); } } /** * Sets the low temperature in specified unit system. */ public void setLow(int temp, UnitSystem unit) { if (this.unit.equals(unit)) { this.low = temp; } else { this.low = convertValue(temp, unit); } } /** * Sets the high temperature in specified unit system. */ public void setHigh(int temp, UnitSystem unit) { if (this.unit.equals(unit)) { this.high = temp; } else { this.high = convertValue(temp, unit); } } //@Override public int getCurrent() { if (this.current == UNKNOWN) { return Math.round((getLow() + getHigh()) / 2f); } return this.current; } //@Override public int getHigh() { if (this.high == UNKNOWN) { if (this.current == UNKNOWN) { return this.low; } else { return this.current; } } return this.high; } //@Override public int getLow() { if (this.low == UNKNOWN) { if (this.current == UNKNOWN) { return this.high; } else { return this.current; } } return this.low; } //@Override public UnitSystem getUnitSystem() { return this.unit; } /** * Creates new temperature in another unit system. */ public SimpleTemperature convert(UnitSystem unit) { SimpleTemperature result = new SimpleTemperature(unit); result.setCurrent(this.getCurrent(), this.getUnitSystem()); result.setLow(this.getLow(), this.getUnitSystem()); result.setHigh(this.getHigh(), this.getUnitSystem()); return result; } /** * Converts the value from provided unit system into this temperature set unit system. */ int convertValue(int value, UnitSystem unit) { if (this.unit.equals(unit)) { return value; } if (UnitSystem.SI.equals(unit)) { //SI -> US return Math.round(value * 9f / 5f + 32); } else { //US -> SI return Math.round((value - 32) * 5f / 9f); } } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Contains current, high and low temperature values. */ public interface Temperature { /** Unknown temperature value */ static int UNKNOWN = Integer.MIN_VALUE; /** * Current temperature. */ int getCurrent(); /** * High forecast temperature. */ int getHigh(); /** * Low forecast temperature. */ int getLow(); /** * Units of this weather. */ UnitSystem getUnitSystem(); }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; import java.util.Locale; /** * Source of the weather forecasts. */ public interface WeatherSource { /** * Searches the weather for specified location. * @throws WeatherException if the weather cannot be found */ Weather query(Location location) throws WeatherException; /** * Searches the weather for specified location and locale. * @throws WeatherException if the weather cannot be found */ Weather query(Location location, Locale locale) throws WeatherException; }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; import java.util.Date; import java.util.List; /** * Interface which contains the weather query results. */ public interface Weather { /** * Returns the weather location (original, passed to {@link WeatherSource#query}, * or modified by the weather source implementation) */ Location getLocation(); /** * Returns the current weather timestamp. */ Date getTime(); /** * Returns default unit system (SI or US). */ UnitSystem getUnitSystem(); /** * Returns weather conditions starting from the current weather * and following some forecasts. */ List<WeatherCondition> getConditions(); /** * Returns true if this weather doesn't contains any actual values. */ boolean isEmpty(); }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Simple location which query and text are equal and are set in constructor. */ public class SimpleLocation implements Location { String text; /** * Create the location. * @param locationText query and the text value. */ public SimpleLocation(String text) { this.text = text; } //@Override public String getQuery() { return this.text; } //@Override public String getText() { return this.text; } //@Override public boolean isEmpty() { return this.text == null || this.text.length() == 0; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.notification; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.CONDITION_TEXT; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.CURRENT_TEMP; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.HIGH_TEMP; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.HUMIDITY_TEXT; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.LOCATION; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.LOW_TEMP; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.TIME; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.UNIT_SYSTEM; import static ru.gelin.android.weather.v_0_2.notification.WeatherStorageKeys.WIND_TEXT; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.weather.v_0_2.Location; import ru.gelin.android.weather.v_0_2.SimpleLocation; import ru.gelin.android.weather.v_0_2.SimpleTemperature; import ru.gelin.android.weather.v_0_2.SimpleWeather; import ru.gelin.android.weather.v_0_2.SimpleWeatherCondition; import ru.gelin.android.weather.v_0_2.Temperature; import ru.gelin.android.weather.v_0_2.UnitSystem; import ru.gelin.android.weather.v_0_2.Weather; import ru.gelin.android.weather.v_0_2.WeatherCondition; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; /** * Stores and retrieves the weather objects to SharedPreferences. * The exact classes of the retrieved Weather can differ from the classes * of the saved weather. */ public class WeatherStorage { /** Preference name for weather (this fake preference is updated * to call preference change listeners) */ static final String WEATHER = "weather"; /** SharedPreferences to store weather. */ SharedPreferences preferences; /** * Creates the storage for context. */ public WeatherStorage(Context context) { this.preferences = PreferenceManager.getDefaultSharedPreferences(context); //Log.d(TAG, "storage for " + context.getPackageName()); } /** * Saves the weather. */ public void save(Weather weather) { Editor editor = preferences.edit(); editor.putLong(WEATHER, System.currentTimeMillis()); //just current time editor.putString(LOCATION, weather.getLocation().getText()); editor.putLong(TIME, weather.getTime().getTime()); editor.putString(UNIT_SYSTEM, weather.getUnitSystem().toString()); int i = 0; for (WeatherCondition condition : weather.getConditions()) { putOrRemove(editor, String.format(CONDITION_TEXT, i), condition.getConditionText()); Temperature temp = condition.getTemperature(); putOrRemove(editor, String.format(CURRENT_TEMP, i), temp.getCurrent()); putOrRemove(editor, String.format(LOW_TEMP, i), temp.getLow()); putOrRemove(editor, String.format(HIGH_TEMP, i), temp.getHigh()); putOrRemove(editor, String.format(HUMIDITY_TEXT, i), condition.getHumidityText()); putOrRemove(editor, String.format(WIND_TEXT, i), condition.getWindText()); i++; } editor.commit(); } /** * Loads the weather. * The values of the saved weather are restored, not exact classes. */ public Weather load() { SimpleWeather weather = new ParcelableWeather(); Location location = new SimpleLocation( preferences.getString(LOCATION, "")); weather.setLocation(location); weather.setTime(new Date(preferences.getLong(TIME, 0))); weather.setUnitSystem(UnitSystem.valueOf( preferences.getString(UNIT_SYSTEM, "SI"))); int i = 0; List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); while (preferences.contains(String.format(CONDITION_TEXT, i))) { SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.setConditionText(preferences.getString( String.format(CONDITION_TEXT, i), "")); SimpleTemperature temp = new SimpleTemperature(weather.getUnitSystem()); temp.setCurrent(preferences.getInt(String.format(CURRENT_TEMP, i), Temperature.UNKNOWN), weather.getUnitSystem()); temp.setLow(preferences.getInt(String.format(LOW_TEMP, i), Temperature.UNKNOWN), weather.getUnitSystem()); temp.setHigh(preferences.getInt(String.format(HIGH_TEMP, i), Temperature.UNKNOWN), weather.getUnitSystem()); condition.setTemperature(temp); condition.setHumidityText(preferences.getString( String.format(HUMIDITY_TEXT, i), "")); condition.setWindText(preferences.getString( String.format(WIND_TEXT, i), "")); conditions.add(condition); i++; } weather.setConditions(conditions); return weather; } /** * Updates just "weather" preference to signal that the weather update is performed, * but nothing is changed. */ public void updateTime() { Editor editor = preferences.edit(); editor.putLong(WEATHER, System.currentTimeMillis()); //just current time editor.commit(); } void putOrRemove(Editor editor, String key, String value) { if (value == null || "".equals(value)) { editor.remove(key); } else { editor.putString(key, value); } } void putOrRemove(Editor editor, String key, int temp) { if (temp == Temperature.UNKNOWN) { editor.remove(key); } else { editor.putInt(key, temp); } } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.notification; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.weather.v_0_2.Location; import ru.gelin.android.weather.v_0_2.SimpleLocation; import ru.gelin.android.weather.v_0_2.SimpleTemperature; import ru.gelin.android.weather.v_0_2.SimpleWeather; import ru.gelin.android.weather.v_0_2.SimpleWeatherCondition; import ru.gelin.android.weather.v_0_2.Temperature; import ru.gelin.android.weather.v_0_2.UnitSystem; import ru.gelin.android.weather.v_0_2.Weather; import ru.gelin.android.weather.v_0_2.WeatherCondition; import android.os.Parcel; import android.os.Parcelable; public class ParcelableWeather extends SimpleWeather implements Parcelable { public ParcelableWeather() { } /** * Copy constructor. */ public ParcelableWeather(Weather weather) { Location location = weather.getLocation(); if (location == null) { setLocation(new SimpleLocation(null)); } else { setLocation(new SimpleLocation(location.getText())); } Date time = weather.getTime(); if (time == null) { setTime(new Date(0)); } else { setTime(time); } UnitSystem unit = weather.getUnitSystem(); if (unit == null) { setUnitSystem(UnitSystem.SI); } else { setUnitSystem(unit); } List<WeatherCondition> conditions = weather.getConditions(); if (conditions == null) { return; } List<WeatherCondition> copyConditions = new ArrayList<WeatherCondition>(); for (WeatherCondition condition : conditions) { SimpleWeatherCondition copyCondition = new SimpleWeatherCondition(); copyCondition.setConditionText(condition.getConditionText()); Temperature temp = condition.getTemperature(); SimpleTemperature copyTemp = new SimpleTemperature(unit); if (temp != null) { copyTemp.setCurrent(temp.getCurrent(), unit); copyTemp.setLow(temp.getLow(), unit); copyTemp.setHigh(temp.getHigh(), unit); } copyCondition.setTemperature(copyTemp); copyCondition.setHumidityText(condition.getHumidityText()); copyCondition.setWindText(condition.getWindText()); copyConditions.add(copyCondition); } setConditions(copyConditions); } //@Override public int describeContents() { return 0; } //@Override public void writeToParcel(Parcel dest, int flags) { Location location = getLocation(); if (location == null) { dest.writeString(null); } else { dest.writeString(location.getText()); } Date time = getTime(); if (time == null) { dest.writeLong(0); } else { dest.writeLong(time.getTime()); } UnitSystem unit = getUnitSystem(); if (unit == null) { dest.writeString(null); } else { dest.writeString(unit.toString()); } if (getConditions() == null) { return; } for (WeatherCondition condition : getConditions()) { dest.writeString(condition.getConditionText()); Temperature temp = condition.getTemperature(); if (temp == null) { continue; } dest.writeInt(temp.getCurrent()); dest.writeInt(temp.getLow()); dest.writeInt(temp.getHigh()); dest.writeString(condition.getHumidityText()); dest.writeString(condition.getWindText()); } } private ParcelableWeather(Parcel in) { setLocation(new SimpleLocation(in.readString())); setTime(new Date(in.readLong())); String unit = in.readString(); try { setUnitSystem(UnitSystem.valueOf(unit)); } catch (Exception e) { setUnitSystem(UnitSystem.SI); } List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); while (in.dataAvail() > 6) { //each condition takes 6 positions SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.setConditionText(in.readString()); SimpleTemperature temp = new SimpleTemperature(getUnitSystem()); temp.setCurrent(in.readInt(), getUnitSystem()); temp.setLow(in.readInt(), getUnitSystem()); temp.setHigh(in.readInt(), getUnitSystem()); condition.setTemperature(temp); condition.setHumidityText(in.readString()); condition.setWindText(in.readString()); conditions.add(condition); } setConditions(conditions); } public static final Parcelable.Creator<ParcelableWeather> CREATOR = new Parcelable.Creator<ParcelableWeather>() { public ParcelableWeather createFromParcel(Parcel in) { return new ParcelableWeather(in); } public ParcelableWeather[] newArray(int size) { return new ParcelableWeather[size]; } }; }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2.notification; public interface WeatherStorageKeys { /** Preference name for location. */ static final String LOCATION = "weather_location"; /** Preference name for time. */ static final String TIME = "weather_time"; /** Preference name for unit system. */ static final String UNIT_SYSTEM = "weather_unit_system"; /** Preference name pattern for condition text. */ static final String CONDITION_TEXT = "weather_%d_condition_text"; /** Preference name pattern for current temp. */ static final String CURRENT_TEMP = "weather_%d_current_temp"; /** Preference name pattern for low temp. */ static final String LOW_TEMP = "weather_%d_low_temp"; /** Preference name pattern for high temp. */ static final String HIGH_TEMP = "weather_%d_high_temp"; /** Preference name pattern for humidity text. */ static final String HUMIDITY_TEXT = "weather_%d_humidity_text"; /** Preference name pattern for wind text. */ static final String WIND_TEXT = "weather_%d_wind_text"; }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Identifies location to search weather. */ public interface Location { /** * Returns the query String (for Google Weather API). */ String getQuery(); /** * Returns the location in a human readable form. */ String getText(); /** * Returns true if this location is empty * (i.e.) doesn't contains any useful data. */ boolean isEmpty(); }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Common exception for weather getting errors. */ @SuppressWarnings("serial") public class WeatherException extends Exception { public WeatherException() { super(); } public WeatherException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public WeatherException(String detailMessage) { super(detailMessage); } public WeatherException(Throwable throwable) { super(throwable); } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; public enum UnitSystem { SI, US; }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Simple weather realization. Just holds the values. */ public class SimpleWeather implements Weather { /** Location */ Location location; /** Time */ Date time; /** Unit system */ UnitSystem unit; /** List of conditions */ List<WeatherCondition> conditions; /** * Sets the location. */ public void setLocation(Location location) { this.location = location; } /** * Sets the time. */ public void setTime(Date time) { this.time = time; } /** * Sets the unit system. */ public void setUnitSystem(UnitSystem unit) { this.unit = unit; } /** * Sets the weather conditions list. */ public void setConditions(List<WeatherCondition> conditions) { this.conditions = conditions; } //@Override public Location getLocation() { return this.location; } //@Override public Date getTime() { return this.time; } //@Override public UnitSystem getUnitSystem() { return this.unit; } //@Override public List<WeatherCondition> getConditions() { if (this.conditions == null) { return new ArrayList<WeatherCondition>(); } return this.conditions; } //@Override public boolean isEmpty() { if (this.time == null || this.time.getTime() == 0) { return true; } if (this.conditions == null || this.conditions.size() == 0) { return true; } return false; } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.v_0_2; /** * Simple weather condition implementation which just holds * the values. */ public class SimpleWeatherCondition implements WeatherCondition { String conditionText; SimpleTemperature temperature; String windText; String humidityText; /** * Sets the condition text. */ public void setConditionText(String text) { this.conditionText = text; } /** * Sets the temperature. */ public void setTemperature(SimpleTemperature temp) { this.temperature = temp; } /** * Sets the wind text. */ public void setWindText(String text) { this.windText = text; } /** * Sets the humidity text. */ public void setHumidityText(String text) { this.humidityText = text; } //@Override public String getConditionText() { return this.conditionText; } //@Override public Temperature getTemperature() { return this.temperature; } //@Override public Temperature getTemperature(UnitSystem unit) { if (this.temperature == null) { return null; } if (this.temperature.getUnitSystem().equals(unit)) { return this.temperature; } return this.temperature.convert(unit); } //@Override public String getWindText() { return this.windText; } //@Override public String getHumidityText() { return this.humidityText; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import android.content.res.AssetManager; import android.test.InstrumentationTestCase; import ru.gelin.android.weather.*; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Calendar; import java.util.TimeZone; @SuppressWarnings("deprecation") public class GoogleWeatherTest extends InstrumentationTestCase { AssetManager assets; @Override protected void setUp() throws Exception { this.assets = getInstrumentation().getContext().getAssets(); } public void testXmlParseEn() throws Exception { InputStream xml1 = this.assets.open("google_weather_api_en.xml"); InputStream xml2 = this.assets.open("google_weather_api_en.xml"); GoogleWeather weather = GoogleWeather.parse( new InputStreamReader(xml1, "UTF-8"), new InputStreamReader(xml2, "UTF-8")); assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2010, Calendar.DECEMBER, 28, 6, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); assertEquals(UnitSystem.US, weather.getUnitSystem()); //assertEquals(TemperatureUnit.F, weather.getTemperatureUnit()); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Clear", condition0.getConditionText()); Temperature temp0old = condition0.getTemperature(); assertEquals(-11, temp0old.getCurrent()); assertEquals(-10, temp0old.getLow()); assertEquals(-4, temp0old.getHigh()); Temperature temp0new = condition0.getTemperature(TemperatureUnit.F); assertEquals(-11, temp0new.getCurrent()); assertEquals(-10, temp0new.getLow()); assertEquals(-4, temp0new.getHigh()); assertEquals("Humidity: 66%", condition0.getHumidityText()); assertEquals("Wind: SW at 2 mph", condition0.getWindText()); assertEquals(66, condition0.getHumidity().getValue()); Wind wind = condition0.getWind(WindSpeedUnit.MPH); assertEquals(WindDirection.SW, wind.getDirection()); assertEquals(2, wind.getSpeed()); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Snow Showers", condition1.getConditionText()); Temperature temp1old = condition1.getTemperature(); assertEquals(7, temp1old.getCurrent()); assertEquals(-7, temp1old.getLow()); assertEquals(20, temp1old.getHigh()); Temperature temp1new = condition1.getTemperature(TemperatureUnit.F); assertEquals(7, temp1new.getCurrent()); assertEquals(-7, temp1new.getLow()); assertEquals(20, temp1new.getHigh()); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Partly Sunny", condition2.getConditionText()); Temperature temp2old = condition2.getTemperature(); assertEquals(-10, temp2old.getCurrent()); assertEquals(-14, temp2old.getLow()); assertEquals(-6, temp2old.getHigh()); Temperature temp2new = condition2.getTemperature(TemperatureUnit.F); assertEquals(-10, temp2new.getCurrent()); assertEquals(-14, temp2new.getLow()); assertEquals(-6, temp2new.getHigh()); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Partly Sunny", condition3.getConditionText()); Temperature temp3old = condition3.getTemperature(); assertEquals(-22, temp3old.getCurrent()); assertEquals(-29, temp3old.getLow()); assertEquals(-15, temp3old.getHigh()); Temperature temp3new = condition3.getTemperature(TemperatureUnit.F); assertEquals(-22, temp3new.getCurrent()); assertEquals(-29, temp3new.getLow()); assertEquals(-15, temp3new.getHigh()); } public void testTempConvertUS2SI() throws Exception { InputStream xml = this.assets.open("google_weather_api_en.xml"); GoogleWeather weather = new GoogleWeather(); GoogleWeatherParser parser = new GoogleWeatherParser(weather); parser.parse(new InputStreamReader(xml, "UTF-8"), new ParserHandler(weather)); WeatherCondition condition0 = weather.getConditions().get(0); Temperature temp0old = condition0.getTemperature(UnitSystem.SI); assertEquals(-24, temp0old.getCurrent()); assertEquals(-23, temp0old.getLow()); //(-10 - 32) * 5 / 9 assertEquals(-20, temp0old.getHigh()); //(-4 - 32) * 5 / 9 Temperature temp0new = condition0.getTemperature(TemperatureUnit.C); assertEquals(-24, temp0new.getCurrent()); assertEquals(-23, temp0new.getLow()); //(-10 - 32) * 5 / 9 assertEquals(-20, temp0new.getHigh()); //(-4 - 32) * 5 / 9 } public void testXmlParseRu() throws Exception { InputStream xmlru = this.assets.open("google_weather_api_ru.xml"); InputStream xmlus = this.assets.open("google_weather_api_en.xml"); GoogleWeather weather = GoogleWeather.parse( new InputStreamReader(xmlus, "UTF-8"), new InputStreamReader(xmlru, "UTF-8")); assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2010, Calendar.DECEMBER, 28, 6, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); assertEquals(UnitSystem.SI, weather.getUnitSystem()); //assertEquals(TemperatureUnit.C, weather.getTemperatureUnit()); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Ясно", condition0.getConditionText()); Temperature temp0 = condition0.getTemperature(); assertEquals(TemperatureUnit.C, temp0.getTemperatureUnit()); assertEquals(-24, temp0.getCurrent()); assertEquals(-23, temp0.getLow()); assertEquals(-20, temp0.getHigh()); assertEquals("Влажность: 66 %", condition0.getHumidityText()); assertEquals("Ветер: ЮЗ, 1 м/с", condition0.getWindText()); assertEquals(66, condition0.getHumidity().getValue()); Wind wind = condition0.getWind(WindSpeedUnit.MPH); assertEquals(WindDirection.SW, wind.getDirection()); assertEquals(2, wind.getSpeed()); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Ливневый снег", condition1.getConditionText()); Temperature temp1 = condition1.getTemperature(); assertEquals(TemperatureUnit.C, temp1.getTemperatureUnit()); assertEquals(-14, temp1.getCurrent()); assertEquals(-21, temp1.getLow()); assertEquals(-7, temp1.getHigh()); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Местами солнечно", condition2.getConditionText()); Temperature temp2 = condition2.getTemperature(); assertEquals(TemperatureUnit.C, temp2.getTemperatureUnit()); assertEquals(-23, temp2.getCurrent()); assertEquals(-26, temp2.getLow()); assertEquals(-21, temp2.getHigh()); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Местами солнечно", condition3.getConditionText()); Temperature temp3 = condition3.getTemperature(); assertEquals(TemperatureUnit.C, temp3.getTemperatureUnit()); assertEquals(-30, temp3.getCurrent()); assertEquals(-34, temp3.getLow()); assertEquals(-26, temp3.getHigh()); } public void testTempConvertSI2US() throws Exception { InputStream xml = this.assets.open("google_weather_api_ru.xml"); GoogleWeather weather = new GoogleWeather(); GoogleWeatherParser parser = new GoogleWeatherParser(weather); parser.parse(new InputStreamReader(xml, "UTF-8"), new ParserHandler(weather)); WeatherCondition condition0 = weather.getConditions().get(0); Temperature temp0 = condition0.getTemperature(UnitSystem.US); assertEquals(-11, temp0.getCurrent()); assertEquals(-9, temp0.getLow()); //-23 * 9 / 5 + 32 assertEquals(-4, temp0.getHigh()); //-20 * 9 / 5 + 32 } public void testTempConvertC2F() throws Exception { InputStream xml = this.assets.open("google_weather_api_ru.xml"); GoogleWeather weather = new GoogleWeather(); GoogleWeatherParser parser = new GoogleWeatherParser(weather); parser.parse(new InputStreamReader(xml, "UTF-8"), new ParserHandler(weather)); WeatherCondition condition0 = weather.getConditions().get(0); Temperature temp0 = condition0.getTemperature(TemperatureUnit.F); assertEquals(-11, temp0.getCurrent()); assertEquals(-9, temp0.getLow()); //-23 * 9 / 5 + 32 assertEquals(-4, temp0.getHigh()); //-20 * 9 / 5 + 32 } public void testTempConvertMPH2MPSKMPS() throws Exception { InputStream xmlru = this.assets.open("google_weather_api_ru.xml"); InputStream xmlus = this.assets.open("google_weather_api_en.xml"); GoogleWeather weather = GoogleWeather.parse( new InputStreamReader(xmlus, "UTF-8"), new InputStreamReader(xmlru, "UTF-8")); WeatherCondition condition0 = weather.getConditions().get(0); Wind windKMPH = condition0.getWind(WindSpeedUnit.KMPH); assertEquals(3, windKMPH.getSpeed()); //2 mph * 1.6 Wind windMPS = condition0.getWind(WindSpeedUnit.MPS); assertEquals(1, windMPS.getSpeed()); //2 mph * 0.44 } public void testUnknownWeather() throws Exception { InputStream xmlun = this.assets.open("google_weather_api_ru_2011-03.xml"); InputStream xmlus = this.assets.open("google_weather_api_en.xml"); GoogleWeather weather = GoogleWeather.parse( new InputStreamReader(xmlus, "UTF-8"), new InputStreamReader(xmlun, "UTF-8")); assertFalse(weather.isEmpty()); assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2011, Calendar.MARCH, 22, 0, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); assertEquals(UnitSystem.SI, weather.getUnitSystem()); //assertEquals(TemperatureUnit.C, weather.getTemperatureUnit()); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Преимущественно облачно", condition0.getConditionText()); Temperature temp0 = condition0.getTemperature(); assertEquals(TemperatureUnit.C, temp0.getTemperatureUnit()); assertEquals(-5, temp0.getCurrent()); assertEquals(-9, temp0.getLow()); assertEquals(-1, temp0.getHigh()); assertEquals("Влажность: 83 %", condition0.getHumidityText()); assertEquals("Ветер: Ю, 4 м/с", condition0.getWindText()); assertEquals(66, condition0.getHumidity().getValue()); //value from EN XML Wind wind = condition0.getWind(WindSpeedUnit.MPH); assertEquals(WindDirection.SW, wind.getDirection()); //value from EN XML assertEquals(2, wind.getSpeed()); //value from EN XML assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Переменная облачность", condition1.getConditionText()); Temperature temp1 = condition1.getTemperature(); assertEquals(-7, temp1.getLow()); assertEquals(-2, temp1.getHigh()); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Преимущественно облачно", condition2.getConditionText()); Temperature temp2 = condition2.getTemperature(); assertEquals(-7, temp2.getLow()); assertEquals(3, temp2.getHigh()); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Ливневый снег", condition3.getConditionText()); Temperature temp3 = condition3.getTemperature(); assertEquals(-3, temp3.getLow()); assertEquals(2, temp3.getHigh()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import android.test.AndroidTestCase; import ru.gelin.android.weather.Humidity; public class GoogleHumidityTest extends AndroidTestCase { public void testParseText() { GoogleHumidity humidity = new GoogleHumidity(); humidity.parseText("Humidity: 48%"); assertEquals(48, humidity.getValue()); assertEquals("Humidity: 48%", humidity.getText()); } public void testParseTextWrong() { GoogleHumidity humidity = new GoogleHumidity(); humidity.parseText("Humidity: non-number"); assertEquals(Humidity.UNKNOWN, humidity.getValue()); assertEquals("Humidity: non-number", humidity.getText()); } public void testParseTextFloat() { GoogleHumidity humidity = new GoogleHumidity(); humidity.parseText("Humidity: 3.14%"); assertEquals(3, humidity.getValue()); assertEquals("Humidity: 3.14%", humidity.getText()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import android.test.InstrumentationTestCase; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import ru.gelin.android.weather.*; import ru.gelin.android.weather.notification.WeatherUtils; import ru.gelin.android.weather.source.HttpUtils; import java.io.InputStreamReader; import java.io.Reader; import java.net.URLEncoder; import java.util.Date; import java.util.Locale; @SuppressWarnings("deprecation") public class GoogleWeatherSourceTest extends InstrumentationTestCase { //ignoring test because Google API is not available now public void ignoretestQueryRu() throws Exception { WeatherSource source = new GoogleWeatherSource(); Location location = new SimpleLocation("Омск"); Weather weather = source.query(location, new Locale("ru")); assertTrue(weather.getLocation().getText().contains("Omsk")); assertEquals(4, weather.getConditions().size()); System.out.println(weather.getConditions().get(0).getHumidityText()); assertTrue(weather.getConditions().get(0).getHumidityText().startsWith("Влажность")); System.out.println(weather.getConditions().get(0).getWindText()); assertTrue(weather.getConditions().get(0).getWindText().startsWith("Ветер")); } //ignoring test because Google API is not available now public void ignoretestRawQueryRu() throws Exception { String apiUrl = "http://www.google.com/ig/api?weather=%s&hl=%s"; String fullUrl = String.format(apiUrl, URLEncoder.encode("Омск", "UTF-8"), URLEncoder.encode("ru", "UTF-8")); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(fullUrl); request.setHeader("User-Agent", "Google Weather/1.0 (Linux; Android)"); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { assertTrue(false); } HttpEntity entity = response.getEntity(); String charset = HttpUtils.getCharset(entity); System.out.println(response.getAllHeaders()); Reader in = new InputStreamReader(entity.getContent(), charset); int c; while ((c = in.read()) >= 0) { System.out.print((char)c); } assertTrue(true); } //ignoring test because Google API is not available now public void ignoretestQueryTime() throws WeatherException { Date now = new Date(); WeatherSource source = new GoogleWeatherSource(); Location location = new SimpleLocation("Омск"); Weather weather = source.query(location, new Locale("ru")); assertNotNull(weather.getQueryTime()); assertTrue(!weather.getQueryTime().before(now)); } public void testDefaultTemperatureUnit() throws Exception { Weather weather = WeatherUtils.createWeather(getInstrumentation().getContext()); assertEquals(TemperatureUnit.F, weather.getConditions().get(0).getTemperature().getTemperatureUnit()); } public void testDefaultWindSpeedUnit() throws Exception { Weather weather = WeatherUtils.createWeather(getInstrumentation().getContext()); assertEquals(WindSpeedUnit.MPH, weather.getConditions().get(0).getWind().getSpeedUnit()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import android.test.AndroidTestCase; import ru.gelin.android.weather.Wind; import ru.gelin.android.weather.WindDirection; import ru.gelin.android.weather.WindSpeedUnit; public class GoogleWindTest extends AndroidTestCase { public void testParseText() { GoogleWind wind = new GoogleWind(); wind.parseText("Wind: SW at 2 mph"); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); assertEquals(2, wind.getSpeed()); assertEquals(WindDirection.SW, wind.getDirection()); assertEquals("Wind: SW at 2 mph", wind.getText()); } public void testParseText2() { GoogleWind wind = new GoogleWind(); wind.parseText("Wind: SSW at 42 mph"); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); assertEquals(42, wind.getSpeed()); assertEquals(WindDirection.SSW, wind.getDirection()); assertEquals("Wind: SSW at 42 mph", wind.getText()); } public void testParseTextWrong() { GoogleWind wind = new GoogleWind(); wind.parseText("Wind: Is it a wind?"); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); assertEquals(Wind.UNKNOWN, wind.getSpeed()); assertEquals("Wind: Is it a wind?", wind.getText()); } public void testParseTextWrongDirection() { GoogleWind wind = new GoogleWind(); wind.parseText("Wind: XYZ at 42 mph"); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); assertEquals(Wind.UNKNOWN, wind.getSpeed()); assertEquals("Wind: XYZ at 42 mph", wind.getText()); } public void testParseTextFloatSpeed() { GoogleWind wind = new GoogleWind(); wind.parseText("Wind: SW at 3.14 mph"); assertEquals(WindSpeedUnit.MPH, wind.getSpeedUnit()); assertEquals(3, wind.getSpeed()); assertEquals(WindDirection.SW, wind.getDirection()); assertEquals("Wind: SW at 3.14 mph", wind.getText()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; @SuppressWarnings("deprecation") public class SimplePrecipitationTest extends AndroidTestCase { public void testSetGetValue() { SimplePrecipitation precipitation = new SimplePrecipitation(PrecipitationUnit.MM); precipitation.setValue(3.0f, PrecipitationPeriod.PERIOD_3H); assertEquals(1.0f, precipitation.getValue(PrecipitationPeriod.PERIOD_1H)); } public void testUnknownValue() { SimplePrecipitation precipitation = new SimplePrecipitation(PrecipitationUnit.MM); assertEquals(Precipitation.UNKNOWN, precipitation.getValue(PrecipitationPeriod.PERIOD_1H)); assertEquals(Precipitation.UNKNOWN, precipitation.getValue(PrecipitationPeriod.PERIOD_3H)); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; @SuppressWarnings("deprecation") public class SimpleTemperatureTest extends AndroidTestCase { public void testConstructor() { SimpleTemperature temp1 = new SimpleTemperature(UnitSystem.SI); assertEquals(UnitSystem.SI, temp1.getUnitSystem()); SimpleTemperature temp2 = new SimpleTemperature(UnitSystem.US); assertEquals(UnitSystem.US, temp2.getUnitSystem()); } public void testSetLowHigh() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setCurrent(25, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(25, temp.getHigh()); } public void testSetLowCurrent() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setHigh(25, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(25, temp.getHigh()); assertEquals(25, temp.getCurrent()); } public void testSetHighCurrent() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setLow(25, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(25, temp.getHigh()); assertEquals(25, temp.getCurrent()); } public void testSetCurrent() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setLow(25, UnitSystem.SI); temp.setHigh(35, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(35, temp.getHigh()); assertEquals(30, temp.getCurrent()); } public void testSetCurrent2() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setLow(25, UnitSystem.SI); temp.setHigh(28, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(28, temp.getHigh()); assertEquals(27, temp.getCurrent()); } public void testSetAll() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setLow(25, UnitSystem.SI); temp.setHigh(35, UnitSystem.SI); temp.setCurrent(32, UnitSystem.SI); assertEquals(25, temp.getLow()); assertEquals(35, temp.getHigh()); assertEquals(32, temp.getCurrent()); } public void testConvertSI2US() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.US); temp.setLow(25, UnitSystem.SI); temp.setHigh(35, UnitSystem.SI); temp.setCurrent(32, UnitSystem.SI); assertEquals(77, temp.getLow()); assertEquals(95, temp.getHigh()); assertEquals(90, temp.getCurrent()); } public void testConvertUS2SI() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setLow(77, UnitSystem.US); temp.setHigh(95, UnitSystem.US); temp.setCurrent(90, UnitSystem.US); assertEquals(25, temp.getLow()); assertEquals(35, temp.getHigh()); assertEquals(32, temp.getCurrent()); } public void testConvert() { SimpleTemperature temp1 = new SimpleTemperature(UnitSystem.SI); temp1.setLow(25, UnitSystem.SI); temp1.setHigh(35, UnitSystem.SI); temp1.setCurrent(32, UnitSystem.SI); SimpleTemperature temp2 = temp1.convert(UnitSystem.US); assertEquals(UnitSystem.US, temp2.getUnitSystem()); assertEquals(77, temp2.getLow()); assertEquals(95, temp2.getHigh()); assertEquals(90, temp2.getCurrent()); } public void testConvertUnknownValue() { SimpleTemperature temp1 = new SimpleTemperature(TemperatureUnit.C); assertEquals(Temperature.UNKNOWN, temp1.getCurrent()); assertEquals(Temperature.UNKNOWN, temp1.getHigh()); assertEquals(Temperature.UNKNOWN, temp1.getLow()); SimpleTemperature temp2 = temp1.convert(TemperatureUnit.F); assertEquals(Temperature.UNKNOWN, temp2.getCurrent()); assertEquals(Temperature.UNKNOWN, temp2.getHigh()); assertEquals(Temperature.UNKNOWN, temp2.getLow()); SimpleTemperature temp3 = temp2.convert(TemperatureUnit.C); assertEquals(Temperature.UNKNOWN, temp3.getCurrent()); assertEquals(Temperature.UNKNOWN, temp3.getHigh()); assertEquals(Temperature.UNKNOWN, temp3.getLow()); } public void testConvertKtoC() { SimpleTemperature temp = new SimpleTemperature(TemperatureUnit.K); temp.setLow(288, TemperatureUnit.K); temp.setHigh(288 + 15, TemperatureUnit.K); temp.setCurrent(288 + 5, TemperatureUnit.K); SimpleTemperature temp2 = temp.convert(TemperatureUnit.C); assertEquals(15, temp2.getLow()); assertEquals(30, temp2.getHigh()); assertEquals(20, temp2.getCurrent()); } public void testConvertKtoF() { SimpleTemperature temp = new SimpleTemperature(TemperatureUnit.K); temp.setLow(273 + 25, TemperatureUnit.K); temp.setHigh(273 + 35, TemperatureUnit.K); temp.setCurrent(273 + 32, TemperatureUnit.K); SimpleTemperature temp2 = temp.convert(TemperatureUnit.F); assertEquals(77, temp2.getLow()); assertEquals(95, temp2.getHigh()); assertEquals(89, temp2.getCurrent()); } // demonstration to avoid multiple convertions /* public void testMultipleConvert() { SimpleTemperature temp1 = new SimpleTemperature(TemperatureUnit.F); temp1.setCurrent(-10, TemperatureUnit.F); SimpleTemperature temp2 = temp1.convert(TemperatureUnit.C); assertEquals(-23, temp2.getCurrent()); SimpleTemperature temp3 = temp2.convert(TemperatureUnit.F); assertEquals(-10, temp3.getCurrent()); } */ }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; public class SimpleHumidityTest extends AndroidTestCase { public void testDefaultValues() { Humidity humidity = new SimpleHumidity(); assertEquals(Humidity.UNKNOWN, humidity.getValue()); assertNull(humidity.getText()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; public class WindDirectionTest extends AndroidTestCase { public void testConvertWindDirection() { assertEquals(WindDirection.NW, WindDirection.valueOf(-45 - 360)); assertEquals(WindDirection.NW, WindDirection.valueOf(-45)); assertEquals(WindDirection.N, WindDirection.valueOf(0)); assertEquals(WindDirection.NNE, WindDirection.valueOf(22)); assertEquals(WindDirection.NE, WindDirection.valueOf(45)); assertEquals(WindDirection.E, WindDirection.valueOf(90)); assertEquals(WindDirection.SE, WindDirection.valueOf(135)); assertEquals(WindDirection.S, WindDirection.valueOf(180)); assertEquals(WindDirection.SW, WindDirection.valueOf(225)); assertEquals(WindDirection.W, WindDirection.valueOf(270)); assertEquals(WindDirection.NW, WindDirection.valueOf(315)); assertEquals(WindDirection.N, WindDirection.valueOf(360)); assertEquals(WindDirection.NE, WindDirection.valueOf(405)); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import java.util.ArrayList; import java.util.Date; import android.test.AndroidTestCase; public class SimpleWeatherTest extends AndroidTestCase { public void testIsEmpty() { SimpleWeather weather = new SimpleWeather(); assertTrue(weather.isEmpty()); weather.time = new Date(); assertTrue(weather.isEmpty()); weather.conditions = new ArrayList<WeatherCondition>(); assertTrue(weather.isEmpty()); weather.conditions.add(new SimpleWeatherCondition()); assertFalse(weather.isEmpty()); //???? } public void testNullConditions() { SimpleWeather weather = new SimpleWeather(); assertNotNull(weather.getConditions()); weather.setConditions(null); assertNotNull(weather.getConditions()); assertEquals(0, weather.getConditions().size()); assertTrue(weather.isEmpty()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; @SuppressWarnings("deprecation") public class SimpleCloudinessTest extends AndroidTestCase { public void testConvertOkta2Percent() { internalTestOkta2Percent(0, 0); internalTestOkta2Percent(1, 12); internalTestOkta2Percent(2, 25); internalTestOkta2Percent(3, 37); internalTestOkta2Percent(4, 50); internalTestOkta2Percent(5, 62); internalTestOkta2Percent(6, 75); internalTestOkta2Percent(7, 87); internalTestOkta2Percent(8, 100); } void internalTestOkta2Percent(int okta, int percent) { SimpleCloudiness cloud1 = new SimpleCloudiness(CloudinessUnit.OKTA); cloud1.setValue(okta, CloudinessUnit.OKTA); SimpleCloudiness cloud2 = cloud1.convert(CloudinessUnit.PERCENT); assertEquals(CloudinessUnit.PERCENT, cloud2.getCloudinessUnit()); assertEquals(percent, cloud2.getValue()); } public void testConvertPercent2Okta() { internalTestPercent2Okta(0, 0); internalTestPercent2Okta(15, 1); internalTestPercent2Okta(25, 2); internalTestPercent2Okta(40, 3); internalTestPercent2Okta(50, 4); internalTestPercent2Okta(65, 5); internalTestPercent2Okta(75, 6); internalTestPercent2Okta(88, 7); internalTestPercent2Okta(98, 8); } void internalTestPercent2Okta(int percent, int okta) { SimpleCloudiness cloud1 = new SimpleCloudiness(CloudinessUnit.PERCENT); cloud1.setValue(percent, CloudinessUnit.PERCENT); SimpleCloudiness cloud2 = cloud1.convert(CloudinessUnit.OKTA); assertEquals(CloudinessUnit.OKTA, cloud2.getCloudinessUnit()); assertEquals(okta, cloud2.getValue()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; public class PrecipitationPeriodTest extends AndroidTestCase { public void testValueOfInt1() { PrecipitationPeriod period = PrecipitationPeriod.valueOf(1); assertEquals(PrecipitationPeriod.PERIOD_1H, period); } public void testValueOfInt3() { PrecipitationPeriod period = PrecipitationPeriod.valueOf(3); assertEquals(PrecipitationPeriod.PERIOD_3H, period); } public void testValueOfInt2() { try { PrecipitationPeriod.valueOf(2); fail(); } catch (IllegalArgumentException e) { //pass } } }
Java
package ru.gelin.android.weather.notification.skin.impl; import android.test.AndroidTestCase; import ru.gelin.android.weather.SimpleWeatherCondition; import ru.gelin.android.weather.WeatherConditionType; import ru.gelin.android.weather.notification.skin.R; public class WeatherConditionFormatTest extends AndroidTestCase { WeatherConditionFormat format; public void setUp() { format = new WeatherConditionFormat(getContext()); } public void testGetStringId() { assertEquals(R.string.condition_rain_light, (int)WeatherConditionFormat.getStringId(WeatherConditionType.RAIN_LIGHT)); assertEquals(R.string.condition_tornado, (int)WeatherConditionFormat.getStringId(WeatherConditionType.TORNADO)); } public void testGetText() { testConditionText("Rain", new WeatherConditionType[]{WeatherConditionType.RAIN, WeatherConditionType.CLOUDS_BROKEN}); testConditionText("Tornado", new WeatherConditionType[]{WeatherConditionType.RAIN, WeatherConditionType.TORNADO}); testConditionText("Tornado, Hurricane", new WeatherConditionType[]{WeatherConditionType.TORNADO, WeatherConditionType.HURRICANE}); } private void testConditionText(String expected, WeatherConditionType[] types) { SimpleWeatherCondition condition = new SimpleWeatherCondition(); for (WeatherConditionType type : types) { condition.addConditionType(type); } WeatherConditionFormat format = new WeatherConditionFormat(getContext()); assertEquals(expected, format.getText(condition)); } public void testEmptyCondition() { SimpleWeatherCondition condition = new SimpleWeatherCondition(); WeatherConditionFormat format = new WeatherConditionFormat(getContext()); assertEquals("Sky is clear", format.getText(condition)); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.impl; import android.test.AndroidTestCase; import java.text.MessageFormat; import java.util.Calendar; import java.util.Date; public class UpdateTimeFormatTest extends AndroidTestCase { //static final String FORMAT = "{0,choice,15#<15m|30#<30m|60#<1h|120#<2h|180#<3h|240#<4h|300#<5h|360#<6h|720#<12h|1440#<1d|2880#<2d|2880<>2d}"; static final String FORMAT = "{0,choice,0#'<'15m|15#'<'30m|30#'<'1h|60#'<'2h|120#'<'3h|180#'<'4h|240#'<'5h|300#'<'6h|360#'<'12h|720#'<'1d|1440#'<'2d|2880#'>'2d}"; Date now; public void setUp() { this.now = new Date(); } public void test15Min() { assertEquals("<15m", format(addMinutes(this.now, -10))); assertEquals("<15m", format(addMinutes(this.now, -14))); assertEquals("<30m", format(addMinutes(this.now, -15))); } public void test30Min() { assertEquals("<30m", format(addMinutes(this.now, -29))); } public void test2Hours() { assertEquals("<2h", format(addMinutes(this.now, -2 * 60 + 1))); } public void test3Hours() { assertEquals("<3h", format(addMinutes(this.now, -3 * 60 + 1))); } public void test4Hours() { assertEquals("<4h", format(addMinutes(this.now, -4 * 60 + 1))); } public void test5Hours() { assertEquals("<5h", format(addMinutes(this.now, -5 * 60 + 1))); } public void test6Hours() { assertEquals("<6h", format(addMinutes(this.now, -6 * 60 + 1))); } public void test12Hours() { assertEquals("<12h", format(addMinutes(this.now, -12 * 60 + 1))); } public void test1Day() { assertEquals("<1d", format(addMinutes(this.now, -24 * 60 + 1))); } public void test2Days() { assertEquals("<2d", format(addMinutes(this.now, -2 * 24 * 60 + 1))); } public void testMore2Days() { assertEquals(">2d", format(addMinutes(this.now, -2 * 24 * 60))); } String format(Date updated) { return MessageFormat.format(FORMAT, getMinutes(updated)); } long getMinutes(Date updated) { return (this.now.getTime() - updated.getTime()) / 60000; } Date addMinutes(Date date, int minutes) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MINUTE, minutes); return calendar.getTime(); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin; import android.content.Intent; import android.os.Parcel; import android.test.InstrumentationTestCase; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.IntentParameters; import ru.gelin.android.weather.notification.WeatherUtils; @SuppressWarnings("deprecation") public class WeatherNotificationManagerTest extends InstrumentationTestCase { public void testCreateIntentDisableNotification() { Intent intent = WeatherNotificationManager.createIntent(false, null); Parcel parcel = Parcel.obtain(); intent.writeToParcel(parcel, 0); parcel.setDataPosition(0); intent.readFromParcel(parcel); assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION)); assertFalse(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, true)); assertFalse(intent.hasExtra(IntentParameters.EXTRA_WEATHER)); } public void testCreateIntent() throws Exception { Weather weather = WeatherUtils.createWeather(getInstrumentation().getContext()); Intent intent = WeatherNotificationManager.createIntent(true, weather); //Parcel parcel = Parcel.obtain(); //parcel.writeParcelable(intent, 0); //parcel.setDataPosition(0); //intent = (Intent)parcel.readParcelable(getContext().getClassLoader()); //intent.setExtrasClassLoader(getContext().getClassLoader()); //TODO: Why the serialization fails? System.out.println(intent); System.out.println("extras: " + intent.getExtras().keySet()); System.out.println("enabled: " + intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); System.out.println("extra weather: " + intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER)); assertEquals(IntentParameters.ACTION_WEATHER_UPDATE, intent.getAction()); assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION)); assertTrue(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); assertTrue(intent.hasExtra(IntentParameters.EXTRA_WEATHER)); WeatherUtils.checkWeather((Weather)intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER), WeatherUtils.Version.V_0_2); } public void testCreateIntent2() throws Exception { Weather weather = WeatherUtils.createWeather(getInstrumentation().getContext()); Intent intent = WeatherNotificationManager.createIntent2(true, weather); Parcel parcel = Parcel.obtain(); parcel.writeParcelable(intent, 0); parcel.setDataPosition(0); intent = (Intent)parcel.readParcelable(getInstrumentation().getTargetContext().getClassLoader()); intent.setExtrasClassLoader(getInstrumentation().getTargetContext().getClassLoader()); System.out.println(intent); System.out.println("extras: " + intent.getExtras().keySet()); System.out.println("enabled: " + intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); System.out.println("extra weather: " + intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER)); assertEquals(IntentParameters.ACTION_WEATHER_UPDATE_2, intent.getAction()); assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION)); assertTrue(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); assertTrue(intent.hasExtra(IntentParameters.EXTRA_WEATHER)); WeatherUtils.checkWeather((Weather)intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER), WeatherUtils.Version.V_0_3); } public void testCreateIntent3() throws Exception { Weather weather = WeatherUtils.createOpenWeather(getInstrumentation()); Intent intent = WeatherNotificationManager.createIntent2(true, weather); Parcel parcel = Parcel.obtain(); parcel.writeParcelable(intent, 0); parcel.setDataPosition(0); intent = (Intent)parcel.readParcelable(getInstrumentation().getTargetContext().getClassLoader()); intent.setExtrasClassLoader(getInstrumentation().getTargetContext().getClassLoader()); System.out.println(intent); System.out.println("extras: " + intent.getExtras().keySet()); System.out.println("enabled: " + intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); System.out.println("extra weather: " + intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER)); assertEquals(IntentParameters.ACTION_WEATHER_UPDATE_2, intent.getAction()); assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION)); assertTrue(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false)); assertTrue(intent.hasExtra(IntentParameters.EXTRA_WEATHER)); WeatherUtils.checkOpenWeather((Weather)intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER)); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification; import android.os.Parcel; import android.test.InstrumentationTestCase; import ru.gelin.android.weather.Weather; @SuppressWarnings("deprecation") public class ParcelableWeatherTest extends InstrumentationTestCase { public void testCopyConstructor() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Weather weather2 = new ParcelableWeather(weather1); WeatherUtils.checkWeather(weather2, WeatherUtils.Version.V_0_2); } public void testWriteRead() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Parcel parcel = Parcel.obtain(); ParcelableWeather weather2 = new ParcelableWeather(weather1); weather2.writeToParcel(parcel, 0); int position = parcel.dataPosition(); parcel.setDataPosition(0); Weather weather3 = ParcelableWeather.CREATOR.createFromParcel(parcel); assertEquals(position, parcel.dataPosition()); //read the same data as write WeatherUtils.checkWeather(weather3, WeatherUtils.Version.V_0_2); } public void testBackwardCompatibility() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Parcel parcel = Parcel.obtain(); ParcelableWeather weather2 = new ParcelableWeather(weather1); weather2.writeToParcel(parcel, 0); parcel.setDataPosition(0); ru.gelin.android.weather.v_0_2.Weather weather3 = ru.gelin.android.weather.v_0_2.notification.ParcelableWeather.CREATOR.createFromParcel(parcel); WeatherUtils.checkWeather(weather3); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification; import android.content.Context; import android.test.InstrumentationTestCase; import ru.gelin.android.weather.Weather; public class WeatherStorageTest extends InstrumentationTestCase { private Context getContext() { return getInstrumentation().getContext(); } public void testSaveLoad() throws Exception { Weather weather1 = WeatherUtils.createWeather(getContext()); WeatherStorage storage = new WeatherStorage(getContext()); storage.save(weather1); Weather weather2 = storage.load(); WeatherUtils.checkWeather(weather2); } public void testSaveLoad2() throws Exception { Weather weather1 = WeatherUtils.createWeather(getContext()); Weather weather2 = new ParcelableWeather2(weather1); WeatherStorage storage = new WeatherStorage(getContext()); storage.save(weather2); Weather weather3 = storage.load(); WeatherUtils.checkWeather(weather3); } public void testSaveLoad3() throws Exception { Weather weather1 = WeatherUtils.createOpenWeather(getInstrumentation()); WeatherStorage storage = new WeatherStorage(getContext()); storage.save(weather1); Weather weather2 = storage.load(); WeatherUtils.checkOpenWeather(weather2); } public void testSaveLoad4() throws Exception { Weather weather1 = WeatherUtils.createOpenWeather(getInstrumentation()); Weather weather2 = new ParcelableWeather2(weather1); WeatherStorage storage = new WeatherStorage(getContext()); storage.save(weather2); Weather weather3 = storage.load(); WeatherUtils.checkOpenWeather(weather3); } public void testBackwardCompatibility() throws Exception { Weather weather1 = WeatherUtils.createWeather(getContext()); WeatherStorage newStorage = new WeatherStorage(getContext()); newStorage.save(weather1); ru.gelin.android.weather.v_0_2.notification.WeatherStorage storage = new ru.gelin.android.weather.v_0_2.notification.WeatherStorage(getContext()); ru.gelin.android.weather.v_0_2.Weather weather2 = storage.load(); WeatherUtils.checkWeather(weather2); } /* Don't want to support saving of the old weather by the new storage public void testBackwardCompatibility2() throws Exception { ru.gelin.android.weather.v_0_2.Weather weather1 = WeatherUtils.createWeather_v_0_2(); WeatherStorage newStorage = new WeatherStorage(getContext()); newStorage.save(WeatherUtils.convert(weather1)); Weather weather2 = newStorage.load(); WeatherUtils.checkWeather(weather2); } */ public void testBackwardCompatibility3() throws Exception { Weather weather1 = WeatherUtils.createWeather(getContext()); ru.gelin.android.weather.v_0_2.notification.WeatherStorage oldStorage = new ru.gelin.android.weather.v_0_2.notification.WeatherStorage(getContext()); oldStorage.save(WeatherUtils.convert(weather1)); ru.gelin.android.weather.v_0_2.Weather weather2 = oldStorage.load(); WeatherUtils.checkWeather(weather2); } public void testRemoveOldConditions() throws Exception { WeatherStorage storage = new WeatherStorage(getContext()); Weather weather1 = WeatherUtils.createWeather(getContext()); storage.save(weather1); assertEquals(4, storage.load().getConditions().size()); Weather weather2 = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); storage.save(weather2); assertEquals(1, storage.load().getConditions().size()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification; import android.os.Parcel; import android.test.InstrumentationTestCase; import ru.gelin.android.weather.Weather; public class ParcelableWeather2Test extends InstrumentationTestCase { public void testCopyConstructor() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Weather weather2 = new ParcelableWeather2(weather1); WeatherUtils.checkWeather(weather2); } public void testCopyConstructor2() throws Exception { Weather weather1 = WeatherUtils.createOpenWeather(getInstrumentation()); Weather weather2 = new ParcelableWeather2(weather1); WeatherUtils.checkOpenWeather(weather2); } public void testWriteRead() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Parcel parcel = Parcel.obtain(); ParcelableWeather2 weather2 = new ParcelableWeather2(weather1); //weather2.writeToParcel(parcel, 0); parcel.writeParcelable(weather2, 0); int position = parcel.dataPosition(); parcel.setDataPosition(0); //Weather weather3 = ParcelableWeather2.CREATOR.createFromParcel(parcel); Weather weather3 = (Weather)parcel.readParcelable(getInstrumentation().getTargetContext().getClassLoader()); assertEquals(position, parcel.dataPosition()); //read the same data as wrote WeatherUtils.checkWeather(weather3); } public void testWriteRead2() throws Exception { Weather weather1 = WeatherUtils.createOpenWeather(getInstrumentation()); Parcel parcel = Parcel.obtain(); ParcelableWeather2 weather2 = new ParcelableWeather2(weather1); //weather2.writeToParcel(parcel, 0); parcel.writeParcelable(weather2, 0); int position = parcel.dataPosition(); parcel.setDataPosition(0); //Weather weather3 = ParcelableWeather2.CREATOR.createFromParcel(parcel); Weather weather3 = (Weather)parcel.readParcelable(getInstrumentation().getTargetContext().getClassLoader()); assertEquals(position, parcel.dataPosition()); //read the same data as wrote WeatherUtils.checkOpenWeather(weather3); } /* Not compatible, ParcelableWeather is compatible public void testBackwardCompatibility() throws Exception { Weather weather1 = WeatherUtils.createWeather(); Parcel parcel = Parcel.obtain(); ParcelableWeather2 weather2 = new ParcelableWeather2(weather1); weather2.writeToParcel(parcel, 0); parcel.setDataPosition(0); ru.gelin.android.weather.v_0_2.Weather weather3 = ru.gelin.android.weather.v_0_2.notification.ParcelableWeather2.CREATOR.createFromParcel(parcel); WeatherUtils.checkWeather(weather3); } */ @SuppressWarnings("deprecation") public void testOldVersionRead() throws Exception { Weather weather1 = WeatherUtils.createWeather(getInstrumentation().getContext()); Parcel parcel = Parcel.obtain(); ParcelableWeather weather2 = new ParcelableWeather(weather1); weather2.writeToParcel(parcel, 0); parcel.setDataPosition(0); Weather weather3 = ParcelableWeather2.CREATOR.createFromParcel(parcel); //WeatherUtils.checkWeather(weather3, WeatherUtils.Version.V_0_2); //ideal :( assertTrue(weather3.isEmpty()); } public void testParcel() { Parcel parcel = Parcel.obtain(); parcel.writeString("test"); parcel.setDataPosition(0); assertEquals("test", parcel.readString()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification; import android.content.res.AssetManager; import android.test.InstrumentationTestCase; import java.util.Arrays; public class AssetsTest extends InstrumentationTestCase { public void testAssetsExists() throws Exception { AssetManager assets = getInstrumentation().getContext().getAssets(); String[] files = assets.list(""); System.out.println(Arrays.asList(files)); assertTrue(files.length > 0); } }
Java
package ru.gelin.android.weather.notification; import android.app.Instrumentation; import android.content.Context; import android.content.res.AssetManager; import android.os.Parcel; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import ru.gelin.android.weather.*; import ru.gelin.android.weather.google.GoogleWeather; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import java.util.TimeZone; import static android.test.AndroidTestCase.assertEquals; import static android.test.AndroidTestCase.assertTrue; public class WeatherUtils { public static enum Version { V_0_2, V_0_3 } private WeatherUtils() { //avoid instantiation } public static Weather createWeather(Context context) throws Exception { AssetManager assets = context.getAssets(); InputStream xml1 = assets.open("google_weather_api_en.xml"); InputStream xml2 = assets.open("google_weather_api_en.xml"); GoogleWeather weather = GoogleWeather.parse( new InputStreamReader(xml1, "UTF-8"), new InputStreamReader(xml2, "UTF-8")); return weather; } public static Weather createOpenWeather(Instrumentation instrumentation) throws Exception { return ru.gelin.android.weather.openweathermap.WeatherUtils.createOpenWeather(instrumentation); } public static Weather createIncompleteOpenWeather(Instrumentation instrumentation) throws Exception { return ru.gelin.android.weather.openweathermap.WeatherUtils.createIncompleteOpenWeather(instrumentation); } public static ru.gelin.android.weather.v_0_2.Weather createWeather_v_0_2(Context context) throws Exception { return new ru.gelin.android.weather.v_0_2.google.GoogleWeather( new InputStreamReader(context.getAssets().open("google_weather_api_en.xml"))); } public static ru.gelin.android.weather.v_0_2.Weather convert(Weather weather) { Parcel parcel = Parcel.obtain(); ParcelableWeather parcelable = new ParcelableWeather(weather); parcelable.writeToParcel(parcel, 0); parcel.setDataPosition(0); return ru.gelin.android.weather.v_0_2.notification.ParcelableWeather.CREATOR.createFromParcel(parcel); } public static Weather convert(ru.gelin.android.weather.v_0_2.Weather weather) { Parcel parcel = Parcel.obtain(); ru.gelin.android.weather.v_0_2.notification.ParcelableWeather parcelable = new ru.gelin.android.weather.v_0_2.notification.ParcelableWeather(weather); parcelable.writeToParcel(parcel, 0); parcel.setDataPosition(0); return ParcelableWeather.CREATOR.createFromParcel(parcel); } public static void checkWeather(Weather weather, Version version) throws MalformedURLException { switch (version) { case V_0_2: checkWeather_v_0_2(weather); break; default: checkWeather(weather); } } public static void checkWeather(Weather weather) throws MalformedURLException { assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2010, Calendar.DECEMBER, 28, 6, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.MINUTE, -1); assertTrue(weather.getQueryTime().after(calendar.getTime())); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Clear", condition0.getConditionText()); Temperature temp0 = condition0.getTemperature(TemperatureUnit.F); assertEquals(-11, temp0.getCurrent()); assertEquals(-10, temp0.getLow()); assertEquals(-4, temp0.getHigh()); Humidity humidity = condition0.getHumidity(); assertEquals("Humidity: 66%", humidity.getText()); assertEquals(66, humidity.getValue()); Wind wind = condition0.getWind(WindSpeedUnit.MPH); assertEquals("Wind: SW at 2 mph", wind.getText()); assertEquals(WindDirection.SW, wind.getDirection()); assertEquals(2, wind.getSpeed()); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Snow Showers", condition1.getConditionText()); Temperature temp1 = condition1.getTemperature(TemperatureUnit.F); assertEquals(7, temp1.getCurrent()); assertEquals(-7, temp1.getLow()); assertEquals(20, temp1.getHigh()); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Partly Sunny", condition2.getConditionText()); Temperature temp2 = condition2.getTemperature(TemperatureUnit.F); assertEquals(-10, temp2.getCurrent()); assertEquals(-14, temp2.getLow()); assertEquals(-6, temp2.getHigh()); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Partly Sunny", condition3.getConditionText()); Temperature temp3 = condition3.getTemperature(TemperatureUnit.F); assertEquals(-22, temp3.getCurrent()); assertEquals(-29, temp3.getLow()); assertEquals(-15, temp3.getHigh()); } public static void checkOpenWeather(Weather weather) throws MalformedURLException { assertEquals("Omsk", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.set(2013, Calendar.AUGUST, 15, 14, 00, 00); calendar.set(Calendar.MILLISECOND, 0); assertEquals(calendar.getTime(), weather.getTime()); calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.add(Calendar.MINUTE, -1); assertTrue(weather.getQueryTime().after(calendar.getTime())); assertEquals(new URL("http://m.openweathermap.org/city/1496153#forecast"), weather.getForecastURL()); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Sky is clear", condition0.getConditionText()); Temperature temp0 = condition0.getTemperature(TemperatureUnit.K); assertEquals(294, temp0.getCurrent()); assertEquals(287, temp0.getLow()); assertEquals(294, temp0.getHigh()); Humidity humidity = condition0.getHumidity(); assertEquals("Humidity: 56%", humidity.getText()); assertEquals(56, humidity.getValue()); Wind wind = condition0.getWind(WindSpeedUnit.MPS); assertEquals("Wind: N, 4 m/s", wind.getText()); assertEquals(WindDirection.N, wind.getDirection()); assertEquals(4, wind.getSpeed()); Cloudiness cloudiness = condition0.getCloudiness(CloudinessUnit.PERCENT); assertEquals(0, cloudiness.getValue()); assertEquals(0f, condition0.getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(1, condition0.getConditionTypes().size()); assertTrue(condition0.getConditionTypes().contains(WeatherConditionType.CLOUDS_CLEAR)); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Light rain", condition1.getConditionText()); Temperature temp1 = condition1.getTemperature(TemperatureUnit.K); assertEquals(289, temp1.getCurrent()); assertEquals(284, temp1.getLow()); assertEquals(293, temp1.getHigh()); assertEquals(98, condition1.getHumidity().getValue()); assertEquals(WindDirection.N, condition1.getWind().getDirection()); assertEquals(2, condition1.getWind().getSpeed()); assertEquals(18, condition1.getCloudiness().getValue()); assertEquals(1f, condition1.getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(2, condition1.getConditionTypes().size()); assertTrue(condition1.getConditionTypes().contains(WeatherConditionType.CLOUDS_FEW)); assertTrue(condition1.getConditionTypes().contains(WeatherConditionType.RAIN_LIGHT)); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Rain", condition2.getConditionText()); Temperature temp2 = condition2.getTemperature(TemperatureUnit.K); assertEquals(288, temp2.getCurrent()); assertEquals(282, temp2.getLow()); assertEquals(293, temp2.getHigh()); assertEquals(93, condition2.getHumidity().getValue()); assertEquals(WindDirection.SW, condition2.getWind().getDirection()); assertEquals(2, condition2.getWind().getSpeed()); assertEquals(0, condition2.getCloudiness().getValue()); assertEquals(2f, condition2.getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(2, condition2.getConditionTypes().size()); assertTrue(condition2.getConditionTypes().contains(WeatherConditionType.CLOUDS_BROKEN)); assertTrue(condition2.getConditionTypes().contains(WeatherConditionType.RAIN)); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Shower rain", condition3.getConditionText()); Temperature temp3 = condition3.getTemperature(TemperatureUnit.K); assertEquals(289, temp3.getCurrent()); assertEquals(283, temp3.getLow()); assertEquals(295, temp3.getHigh()); assertEquals(90, condition3.getHumidity().getValue()); assertEquals(WindDirection.SW, condition3.getWind().getDirection()); assertEquals(2, condition3.getWind().getSpeed()); assertEquals(22, condition3.getCloudiness().getValue()); assertEquals(3f, condition3.getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(2, condition3.getConditionTypes().size()); assertTrue(condition3.getConditionTypes().contains(WeatherConditionType.CLOUDS_OVERCAST)); assertTrue(condition3.getConditionTypes().contains(WeatherConditionType.RAIN_SHOWER)); } public static void checkWeather(ru.gelin.android.weather.v_0_2.Weather weather) { assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2010, Calendar.DECEMBER, 28, 6, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); assertEquals(ru.gelin.android.weather.v_0_2.UnitSystem.US, weather.getUnitSystem()); assertEquals(4, weather.getConditions().size()); ru.gelin.android.weather.v_0_2.WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Clear", condition0.getConditionText()); ru.gelin.android.weather.v_0_2.Temperature temp0 = condition0.getTemperature(ru.gelin.android.weather.v_0_2.UnitSystem.US); assertEquals(-11, temp0.getCurrent()); assertEquals(-10, temp0.getLow()); assertEquals(-4, temp0.getHigh()); assertEquals("Humidity: 66%", condition0.getHumidityText()); assertEquals("Wind: SW at 2 mph", condition0.getWindText()); ru.gelin.android.weather.v_0_2.WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Snow Showers", condition1.getConditionText()); ru.gelin.android.weather.v_0_2.Temperature temp1 = condition1.getTemperature(ru.gelin.android.weather.v_0_2.UnitSystem.US); assertEquals(7, temp1.getCurrent()); assertEquals(-7, temp1.getLow()); assertEquals(20, temp1.getHigh()); ru.gelin.android.weather.v_0_2.WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Partly Sunny", condition2.getConditionText()); ru.gelin.android.weather.v_0_2.Temperature temp2 = condition2.getTemperature(ru.gelin.android.weather.v_0_2.UnitSystem.US); assertEquals(-10, temp2.getCurrent()); assertEquals(-14, temp2.getLow()); assertEquals(-6, temp2.getHigh()); ru.gelin.android.weather.v_0_2.WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Partly Sunny", condition3.getConditionText()); ru.gelin.android.weather.v_0_2.Temperature temp3 = condition3.getTemperature(ru.gelin.android.weather.v_0_2.UnitSystem.US); assertEquals(-22, temp3.getCurrent()); assertEquals(-29, temp3.getLow()); assertEquals(-15, temp3.getHigh()); } @SuppressWarnings("deprecation") public static void checkWeather_v_0_2(Weather weather) { assertEquals("Omsk, Omsk Oblast", weather.getLocation().getText()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.set(Calendar.MILLISECOND, 0); calendar.set(2010, Calendar.DECEMBER, 28, 6, 0, 0); assertEquals(calendar.getTime(), weather.getTime()); assertEquals(4, weather.getConditions().size()); WeatherCondition condition0 = weather.getConditions().get(0); assertEquals("Clear", condition0.getConditionText()); Temperature temp0 = condition0.getTemperature(); assertEquals(-11, temp0.getCurrent()); assertEquals(-10, temp0.getLow()); assertEquals(-4, temp0.getHigh()); assertEquals("Humidity: 66%", condition0.getHumidityText()); assertEquals("Wind: SW at 2 mph", condition0.getWindText()); WeatherCondition condition1 = weather.getConditions().get(1); assertEquals("Snow Showers", condition1.getConditionText()); Temperature temp1 = condition1.getTemperature(); assertEquals(7, temp1.getCurrent()); assertEquals(-7, temp1.getLow()); assertEquals(20, temp1.getHigh()); WeatherCondition condition2 = weather.getConditions().get(2); assertEquals("Partly Sunny", condition2.getConditionText()); Temperature temp2 = condition2.getTemperature(); assertEquals(-10, temp2.getCurrent()); assertEquals(-14, temp2.getLow()); assertEquals(-6, temp2.getHigh()); WeatherCondition condition3 = weather.getConditions().get(3); assertEquals("Partly Sunny", condition3.getConditionText()); Temperature temp3 = condition3.getTemperature(); assertEquals(-22, temp3.getCurrent()); assertEquals(-29, temp3.getLow()); assertEquals(-15, temp3.getHigh()); } public static JSONObject readJSON(Context context, String assetName) throws IOException, JSONException { Reader reader = new InputStreamReader(context.getAssets().open(assetName)); StringBuilder buffer = new StringBuilder(); int c = reader.read(); while (c >= 0) { buffer.append((char)c); c = reader.read(); } JSONTokener parser = new JSONTokener(buffer.toString()); return (JSONObject)parser.nextValue(); } }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; public class SimpleWindTest extends AndroidTestCase { public void testDefaultValues() { Wind wind = new SimpleWind(WindSpeedUnit.MPS); assertEquals(Wind.UNKNOWN, wind.getSpeed()); assertEquals(WindSpeedUnit.MPS, wind.getSpeedUnit()); assertNull(wind.getText()); } public void testSetSpeedMPS() { SimpleWind wind = new SimpleWind(WindSpeedUnit.MPS); wind.setSpeed(10, WindSpeedUnit.MPS); assertEquals(10, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.KMPH); assertEquals(3, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.MPH); assertEquals(4, wind.getSpeed()); } public void testSetSpeedKMPH() { SimpleWind wind = new SimpleWind(WindSpeedUnit.KMPH); wind.setSpeed(10, WindSpeedUnit.MPS); assertEquals(36, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.KMPH); assertEquals(10, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.MPH); assertEquals(16, wind.getSpeed()); } public void testSetSpeedMPH() { SimpleWind wind = new SimpleWind(WindSpeedUnit.MPH); wind.setSpeed(10, WindSpeedUnit.MPS); assertEquals(22, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.KMPH); assertEquals(6, wind.getSpeed()); wind.setSpeed(10, WindSpeedUnit.MPH); assertEquals(10, wind.getSpeed()); } public void testConvertMPS() { SimpleWind wind = new SimpleWind(WindSpeedUnit.MPS); wind.setSpeed(10, WindSpeedUnit.MPS); Wind kmph = wind.convert(WindSpeedUnit.KMPH); assertEquals(WindSpeedUnit.KMPH, kmph.getSpeedUnit()); assertEquals(36, kmph.getSpeed()); Wind mph = wind.convert(WindSpeedUnit.MPH); assertEquals(WindSpeedUnit.MPH, mph.getSpeedUnit()); assertEquals(22, mph.getSpeed()); } public void testConvertKMPH() { SimpleWind wind = new SimpleWind(WindSpeedUnit.KMPH); wind.setSpeed(10, WindSpeedUnit.KMPH); Wind mps = wind.convert(WindSpeedUnit.MPS); assertEquals(WindSpeedUnit.MPS, mps.getSpeedUnit()); assertEquals(3, mps.getSpeed()); Wind mph = wind.convert(WindSpeedUnit.MPH); assertEquals(WindSpeedUnit.MPH, mph.getSpeedUnit()); assertEquals(6, mph.getSpeed()); } public void testConvertMPH() { SimpleWind wind = new SimpleWind(WindSpeedUnit.MPH); wind.setSpeed(10, WindSpeedUnit.MPH); Wind mps = wind.convert(WindSpeedUnit.MPS); assertEquals(WindSpeedUnit.MPS, mps.getSpeedUnit()); assertEquals(4, mps.getSpeed()); Wind kmph = wind.convert(WindSpeedUnit.KMPH); assertEquals(WindSpeedUnit.KMPH, kmph.getSpeedUnit()); assertEquals(16, kmph.getSpeed()); } public void testConvertText() { SimpleWind wind = new SimpleWind(WindSpeedUnit.MPH); wind.setText("text"); SimpleWind wind2 = wind.convert(WindSpeedUnit.MPS); assertEquals("text", wind2.getText()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather; import android.test.AndroidTestCase; @SuppressWarnings("deprecation") public class SimpleWeatherConditionTest extends AndroidTestCase { SimpleWeatherCondition condition; public void setUp() { condition = new SimpleWeatherCondition(); } public void testTempInUnits() { SimpleTemperature temp = new SimpleTemperature(UnitSystem.SI); temp.setCurrent(25, UnitSystem.SI); condition.setTemperature(temp); Temperature temp1 = condition.getTemperature(); assertEquals(25, temp1.getCurrent()); Temperature temp2 = condition.getTemperature(UnitSystem.US); assertEquals(77, temp2.getCurrent()); } public void testConditionTypePriority() { SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.addConditionType(WeatherConditionType.CLOUDS_BROKEN); condition.addConditionType(WeatherConditionType.RAIN); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.CLOUDS_BROKEN)); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.RAIN)); } public void testConditionTypeStrength() { SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.addConditionType(WeatherConditionType.RAIN); condition.addConditionType(WeatherConditionType.RAIN_EXTREME); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.RAIN_EXTREME)); assertFalse(condition.getConditionTypes().contains(WeatherConditionType.RAIN)); } public void testConditionTypeStrengthAndPriority() { SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.addConditionType(WeatherConditionType.CLOUDS_BROKEN); condition.addConditionType(WeatherConditionType.RAIN_EXTREME); condition.addConditionType(WeatherConditionType.RAIN); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.CLOUDS_BROKEN)); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.RAIN_EXTREME)); assertFalse(condition.getConditionTypes().contains(WeatherConditionType.RAIN)); } public void testConditionTypeSameStrength() { SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.addConditionType(WeatherConditionType.TORNADO); condition.addConditionType(WeatherConditionType.HURRICANE); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.TORNADO)); assertTrue(condition.getConditionTypes().contains(WeatherConditionType.HURRICANE)); } }
Java
package ru.gelin.android.weather.source; import android.test.AndroidTestCase; public class HttpUtilsTest extends AndroidTestCase { public void testGetCharset() { assertEquals("UTF-8", HttpUtils.getCharset("text/xml; charset=UTF-8")); assertEquals("windows-1251", HttpUtils.getCharset("text/xml; charset=windows-1251")); assertEquals("UTF-8", HttpUtils.getCharset("text/xml")); assertEquals("windows-1251", HttpUtils.getCharset("text/xml; charset=windows-1251; something more")); assertEquals("UTF-8", HttpUtils.getCharset("")); assertEquals("UTF-8", HttpUtils.getCharset((String) null)); } }
Java
package ru.gelin.android.weather.source; import android.test.AndroidTestCase; import java.util.Date; public class DebugDumperTest extends AndroidTestCase { private DebugDumper dumper; private String now; public void setUp() { this.dumper = new DebugDumper(getContext(), "http://openweathermap.org/data/2.5"); this.now = DebugDumper.DATE_FORMAT.format(new Date()); } public void testGetDumpFile1() { String url = "http://openweathermap.org/data/2.5/weather?q=test"; String fileName = this.dumper.getDumpFile(url).getName(); assertTrue(this.now.compareTo(fileName) < 0); assertEquals("_weather_q_test.txt", fileName.substring(20)); } public void testGetDumpFile2() { String url = "http://openweathermap.org/data/2.5/weather?q=omsk&lat=54.96&lon=73.38"; String fileName = this.dumper.getDumpFile(url).getName(); assertTrue(this.now.compareTo(fileName) < 0); assertEquals("_weather_q_omsk_lat_54.96_lon_73.38.txt", fileName.substring(20)); } public void testGetDumpFile3() { String url = "http://openweathermap.org/data/2.5/forecast/daily?cnt=4&id=123456"; String fileName = this.dumper.getDumpFile(url).getName(); assertTrue(this.now.compareTo(fileName) < 0); assertEquals("_forecast_daily_cnt_4_id_123456.txt", fileName.substring(20)); } }
Java
package ru.gelin.android.weather.openweathermap; import android.test.AndroidTestCase; import org.json.JSONException; import org.json.JSONObject; import ru.gelin.android.weather.*; public class OpenWeatherMapSourceTest extends AndroidTestCase { public void testQueryOmsk() throws WeatherException { WeatherSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("lat=54.96&lon=73.38", true); Weather weather = source.query(location); assertNotNull(weather); assertFalse(weather.isEmpty()); } public void testQueryOmskJSON() throws WeatherException, JSONException { OpenWeatherMapSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("lat=54.96&lon=73.38", true); JSONObject json = source.queryCurrentWeather(location); assertNotNull(json); assertEquals("Omsk", json.getString("name")); } public void testQueryOmskName() throws WeatherException { WeatherSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("q=omsk", false); Weather weather = source.query(location); assertNotNull(weather); assertFalse(weather.isEmpty()); } public void testQueryOmskNameJSON() throws WeatherException, JSONException { OpenWeatherMapSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("q=omsk", false); JSONObject json = source.queryCurrentWeather(location); assertNotNull(json); assertEquals("Omsk", json.getString("name")); } public void testQueryOmskForecasts() throws WeatherException { WeatherSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("lat=54.96&lon=73.38&cnt=4", true); Weather weather = source.query(location); assertNotNull(weather); assertFalse(weather.isEmpty()); assertEquals(4, weather.getConditions().size()); } public void testQueryTestLocationPlus() throws WeatherException { WeatherSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("+25", false); Weather weather = source.query(location); assertNotNull(weather); assertFalse(weather.isEmpty()); assertEquals("Test location", weather.getLocation().getText()); assertEquals(25, weather.getConditions().get(0).getTemperature(TemperatureUnit.C).getCurrent()); } public void testQueryTestLocationMinus() throws WeatherException { WeatherSource source = new OpenWeatherMapSource(getContext()); Location location = new SimpleLocation("-25", false); Weather weather = source.query(location); assertNotNull(weather); assertFalse(weather.isEmpty()); assertEquals("Test location", weather.getLocation().getText()); assertEquals(-25, weather.getConditions().get(0).getTemperature(TemperatureUnit.C).getCurrent()); } // In API 2.5 the city name is not localized // // public void testQueryOmskJSON_RU() throws WeatherException, JSONException { // OpenWeatherMapSource source = new OpenWeatherMapSource(getContext()); // Location location = new SimpleLocation("lat=54.96&lon=73.38&lang=ru", true); // JSONObject json = source.queryCurrentWeather(location); // assertNotNull(json); // assertEquals("Омск", json.getString("name")); // } // // public void testQueryOmskNameJSON_RU() throws WeatherException, JSONException { // OpenWeatherMapSource source = new OpenWeatherMapSource(getContext()); // Location location = new SimpleLocation("q=omsk&lang=ru", false); // JSONObject json = source.queryCurrentWeather(location); // assertNotNull(json); // assertEquals("Омск", json.getString("name")); // } // // public void testQueryOmskNameJSON_EO() throws WeatherException, JSONException { // OpenWeatherMapSource source = new OpenWeatherMapSource(getContext()); // Location location = new SimpleLocation("q=omsk&lang=eo", false); //unsupported language // JSONObject json = source.queryCurrentWeather(location); // assertNotNull(json); // assertEquals("Omsk", json.getString("name")); // } }
Java
package ru.gelin.android.weather.openweathermap; import android.test.AndroidTestCase; import ru.gelin.android.weather.WeatherException; public class NameOpenWeatherMapLocationTest extends AndroidTestCase { public void testNullLocation() throws WeatherException { NameOpenWeatherMapLocation location = new NameOpenWeatherMapLocation("test", null); assertEquals("test", location.getText()); assertEquals("q=test", location.getQuery()); } }
Java
package ru.gelin.android.weather.openweathermap; import android.test.AndroidTestCase; import ru.gelin.android.weather.SimpleTemperature; import ru.gelin.android.weather.Temperature; import ru.gelin.android.weather.TemperatureUnit; public class AppendableTemperatureTest extends AndroidTestCase { public void testAppendLowTemperature() { AppendableTemperature temperature = new AppendableTemperature(TemperatureUnit.C); assertEquals(Temperature.UNKNOWN, temperature.getLow()); SimpleTemperature append1 = new SimpleTemperature(TemperatureUnit.C); append1.setLow(-5, TemperatureUnit.C); temperature.append(append1); assertEquals(-5, temperature.getLow()); SimpleTemperature append2 = new SimpleTemperature(TemperatureUnit.C); append2.setLow(-10, TemperatureUnit.C); temperature.append(append2); assertEquals(-10, temperature.getLow()); SimpleTemperature append3 = new SimpleTemperature(TemperatureUnit.C); append3.setLow(-3, TemperatureUnit.C); temperature.append(append3); assertEquals(-10, temperature.getLow()); } public void testAppendHighTemperature() { AppendableTemperature temperature = new AppendableTemperature(TemperatureUnit.C); assertEquals(Temperature.UNKNOWN, temperature.getHigh()); SimpleTemperature append1 = new SimpleTemperature(TemperatureUnit.C); append1.setHigh(5, TemperatureUnit.C); temperature.append(append1); assertEquals(5, temperature.getHigh()); SimpleTemperature append2 = new SimpleTemperature(TemperatureUnit.C); append2.setHigh(10, TemperatureUnit.C); temperature.append(append2); assertEquals(10, temperature.getHigh()); SimpleTemperature append3 = new SimpleTemperature(TemperatureUnit.C); append3.setHigh(3, TemperatureUnit.C); temperature.append(append3); assertEquals(10, temperature.getHigh()); } public void testAppendTemperatureConvert() { AppendableTemperature temperature = new AppendableTemperature(TemperatureUnit.C); assertEquals(Temperature.UNKNOWN, temperature.getLow()); SimpleTemperature append1 = new SimpleTemperature(TemperatureUnit.K); append1.setLow(273, TemperatureUnit.K); temperature.append(append1); assertEquals(0, temperature.getLow()); assertEquals(0, temperature.getHigh()); } }
Java
package ru.gelin.android.weather.openweathermap; import android.test.InstrumentationTestCase; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import ru.gelin.android.weather.*; import java.io.IOException; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import static ru.gelin.android.weather.notification.WeatherUtils.readJSON; public class OpenWeatherMapWeatherTest extends InstrumentationTestCase { public void testNotEmpty() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); assertNotNull(weather); assertFalse(weather.isEmpty()); } public void testNotNullLocation() { OpenWeatherMapWeather weather = new OpenWeatherMapWeather(getInstrumentation().getTargetContext()); assertNotNull(weather.getLocation()); assertTrue(weather.isEmpty()); } public void testGetTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(21, condition.getTemperature(TemperatureUnit.C).getCurrent()); } public void testParseEmptyJSON() throws JSONException { JSONTokener parser = new JSONTokener("{}"); try { new OpenWeatherMapWeather(getInstrumentation().getTargetContext(), (JSONObject)parser.nextValue()); fail(); } catch (WeatherException e) { //passed } } public void testGetLocation() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); Location location = weather.getLocation(); assertNotNull(location); assertEquals("Omsk", location.getText()); } public void testGetTime() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); Date time = weather.getTime(); assertNotNull(time); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.set(2013, Calendar.AUGUST, 15, 14, 00, 00); calendar.set(Calendar.MILLISECOND, 0); assertEquals(calendar.getTime(), time); } public void testGetQueryTime() throws Exception { long now = System.currentTimeMillis(); OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); assertTrue(now < weather.getQueryTime().getTime()); } public void testGetConditionText() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); String text = condition.getConditionText(); assertEquals("Sky is clear", text); } public void testGetLowTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(21, condition.getTemperature(TemperatureUnit.C).getLow()); } public void testGetHighTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(21, condition.getTemperature(TemperatureUnit.C).getHigh()); } public void testGetWind() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); Wind wind = condition.getWind(WindSpeedUnit.MPS); assertNotNull(wind); assertEquals(4, wind.getSpeed()); assertEquals(WindDirection.N, wind.getDirection()); } public void testGetHumidity() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); Humidity humidity = condition.getHumidity(); assertNotNull(humidity); assertEquals(56, humidity.getValue()); } public void testGetTemperatureUnit() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(TemperatureUnit.K, condition.getTemperature().getTemperatureUnit()); } public void testGetCityID() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); assertEquals(1496153, weather.getCityId()); } public void testGetForecastURL() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createIncompleteOpenWeather(getInstrumentation()); assertEquals(new URL("http://m.openweathermap.org/city/1496153#forecast"), weather.getForecastURL()); } public void testForecastsNulls() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); assertEquals(4, weather.getConditions().size()); assertNotNull(weather.getConditions().get(3).getHumidity()); assertNotNull(weather.getConditions().get(3).getWind()); } public void testForecastGetLowTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); assertEquals(287, conditions.get(0).getTemperature(TemperatureUnit.K).getLow()); assertEquals(284, conditions.get(1).getTemperature(TemperatureUnit.K).getLow()); assertEquals(282, conditions.get(2).getTemperature(TemperatureUnit.K).getLow()); assertEquals(283, conditions.get(3).getTemperature(TemperatureUnit.K).getLow()); } public void testForecastGetHighTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); assertEquals(294, conditions.get(0).getTemperature(TemperatureUnit.K).getHigh()); assertEquals(293, conditions.get(1).getTemperature(TemperatureUnit.K).getHigh()); assertEquals(293, conditions.get(2).getTemperature(TemperatureUnit.K).getHigh()); assertEquals(295, conditions.get(3).getTemperature(TemperatureUnit.K).getHigh()); } public void testForecastGetTemperature() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); //the current temp should come from the city JSON assertEquals(294, conditions.get(0).getTemperature(TemperatureUnit.K).getCurrent()); } public void testForecastGetPrecipitations() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<SimpleWeatherCondition> conditions = weather.getOpenWeatherMapConditions(); assertEquals(4, conditions.size()); assertEquals(0f, conditions.get(0).getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H)); //current assertEquals(1f, conditions.get(1).getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(2f, conditions.get(2).getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); assertEquals(3f, conditions.get(3).getPrecipitation().getValue(PrecipitationPeriod.PERIOD_1H), 0.01f); } public void testForecastGetCloudiness() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<SimpleWeatherCondition> conditions = weather.getOpenWeatherMapConditions(); assertEquals(4, conditions.size()); assertEquals(0, conditions.get(0).getCloudiness().getValue()); //current assertEquals(18, conditions.get(1).getCloudiness().getValue()); assertEquals(0, conditions.get(2).getCloudiness().getValue()); assertEquals(22, conditions.get(3).getCloudiness().getValue()); } public void testForecastGetConditionTypes() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<SimpleWeatherCondition> conditions = weather.getOpenWeatherMapConditions(); assertEquals(4, conditions.size()); assertEquals(1, conditions.get(0).getConditionTypes().size()); assertTrue(conditions.get(0).getConditionTypes().contains(WeatherConditionType.CLOUDS_CLEAR)); assertEquals(2, conditions.get(1).getConditionTypes().size()); assertTrue(conditions.get(1).getConditionTypes().contains(WeatherConditionType.CLOUDS_FEW)); assertTrue(conditions.get(1).getConditionTypes().contains(WeatherConditionType.RAIN_LIGHT)); assertEquals(2, conditions.get(2).getConditionTypes().size()); assertTrue(conditions.get(2).getConditionTypes().contains(WeatherConditionType.CLOUDS_BROKEN)); assertTrue(conditions.get(2).getConditionTypes().contains(WeatherConditionType.RAIN)); assertEquals(2, conditions.get(3).getConditionTypes().size()); assertTrue(conditions.get(3).getConditionTypes().contains(WeatherConditionType.CLOUDS_OVERCAST)); assertTrue(conditions.get(3).getConditionTypes().contains(WeatherConditionType.RAIN_SHOWER)); } public void testForecastGetConditionText() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); assertEquals("Sky is clear", conditions.get(0).getConditionText()); assertEquals("Light rain", conditions.get(1).getConditionText()); assertEquals("Rain", conditions.get(2).getConditionText()); assertEquals("Shower rain", conditions.get(3).getConditionText()); } public void testParseNoHumidity() throws IOException, JSONException, WeatherException { OpenWeatherMapWeather weather = new OpenWeatherMapWeather(getInstrumentation().getTargetContext(), readJSON(getInstrumentation().getContext(), "omsk_name_no_humidity_2.5.json")); assertNotNull(weather); assertFalse(weather.isEmpty()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(21, condition.getTemperature(TemperatureUnit.C).getCurrent()); } public void testParseMinimalJSON() throws IOException, JSONException, WeatherException { JSONTokener parser = new JSONTokener("{\"id\": 1496153,\"cod\": 200}"); OpenWeatherMapWeather weather = new OpenWeatherMapWeather(getInstrumentation().getTargetContext(), (JSONObject)parser.nextValue()); assertNotNull(weather); assertFalse(weather.isEmpty()); assertEquals(1496153, weather.getCityId()); assertEquals("", weather.getLocation().getText()); WeatherCondition condition = weather.getConditions().get(0); assertEquals(Temperature.UNKNOWN, condition.getTemperature(TemperatureUnit.C).getCurrent()); } public void testParseBadResultCodeJSON() throws JSONException, WeatherException { JSONTokener parser = new JSONTokener("{ \"cod\": \"404\"}"); OpenWeatherMapWeather weather = new OpenWeatherMapWeather(getInstrumentation().getTargetContext(), (JSONObject)parser.nextValue()); assertNotNull(weather); assertTrue(weather.isEmpty()); } public void testForecastGetWind() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); assertEquals(4, conditions.get(0).getWind().getSpeed()); assertEquals(WindDirection.N, conditions.get(0).getWind().getDirection()); assertEquals(2, conditions.get(1).getWind().getSpeed()); assertEquals(WindDirection.N, conditions.get(1).getWind().getDirection()); assertEquals(2, conditions.get(2).getWind().getSpeed()); assertEquals(WindDirection.SW, conditions.get(2).getWind().getDirection()); assertEquals(2, conditions.get(3).getWind().getSpeed()); assertEquals(WindDirection.SW, conditions.get(3).getWind().getDirection()); } public void testForecastGetHumidity() throws Exception { OpenWeatherMapWeather weather = WeatherUtils.createOpenWeather(getInstrumentation()); List<WeatherCondition> conditions = weather.getConditions(); assertEquals(4, conditions.size()); assertEquals(56, conditions.get(0).getHumidity().getValue()); assertEquals(98, conditions.get(1).getHumidity().getValue()); assertEquals(93, conditions.get(2).getHumidity().getValue()); assertEquals(90, conditions.get(3).getHumidity().getValue()); } }
Java
package ru.gelin.android.weather.openweathermap; import android.app.Instrumentation; import static ru.gelin.android.weather.notification.WeatherUtils.readJSON; public class WeatherUtils { public static OpenWeatherMapWeather createOpenWeather(Instrumentation instrumentation) throws Exception { OpenWeatherMapWeather weather = new OpenWeatherMapWeather(instrumentation.getTargetContext(), readJSON(instrumentation.getContext(), "omsk_name_2.5.json")); weather.parseDailyForecast(readJSON(instrumentation.getContext(), "omsk_name_forecast_2.5.json")); return weather; } public static OpenWeatherMapWeather createIncompleteOpenWeather(Instrumentation instrumentation) throws Exception { OpenWeatherMapWeather weather = new OpenWeatherMapWeather(instrumentation.getTargetContext(), readJSON(instrumentation.getContext(), "omsk_name_2.5.json")); return weather; } }
Java
/* * Weather API. * Copyright (C) 2011 Denis Nelubin, Vladimir Kubyshev * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ru.gelin.android.weather.Weather; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.IOException; import java.io.Reader; class GoogleWeatherParser { GoogleWeather weather; public GoogleWeatherParser(Weather weather) { this.weather = (GoogleWeather)weather; } //@Override public void parse(Reader xml, DefaultHandler handler) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //WTF??? Harmony's Expat is so... //factory.setFeature("http://xml.org/sax/features/namespaces", false); //factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); //explicitly decoding from UTF-8 because Google misses encoding in XML preamble parser.parse(new InputSource(xml), handler); } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import android.location.Address; import ru.gelin.android.weather.Location; /** * Wrapper for Android location to query Google weather API with geo coordinates. */ public class AndroidGoogleLocation implements Location { /** Query template */ static final String QUERY = "%s,%s,%s,%d,%d"; /** Android location */ android.location.Location location; /** Android address */ Address address; /** * Creates the location from Android location. */ public AndroidGoogleLocation(android.location.Location location) { this.location = location; } /** * Creates the location from Android location and address. */ public AndroidGoogleLocation(android.location.Location location, Address address) { this.location = location; this.address = address; } /** * Creates the query with geo coordinates. * For example: ",,,30670000,104019996" */ //@Override public String getQuery() { if (location == null) { return ""; } if (address == null) { return String.format(QUERY, "", "", "", convertGeo(location.getLatitude()), convertGeo(location.getLongitude())); } return String.format(QUERY, stringOrEmpty(address.getLocality()), stringOrEmpty(address.getAdminArea()), stringOrEmpty(address.getCountryName()), convertGeo(location.getLatitude()), convertGeo(location.getLongitude())); } //@Override public String getText() { if (location == null) { return ""; } if (address == null) { return android.location.Location.convert(location.getLatitude(), android.location.Location.FORMAT_DEGREES) + " " + android.location.Location.convert(location.getLongitude(), android.location.Location.FORMAT_DEGREES); } StringBuilder result = new StringBuilder(); result.append(stringOrEmpty(address.getLocality())); if (result.length() > 0) { result.append(", "); } result.append(stringOrEmpty(address.getAdminArea())); if (result.length() == 0) { result.append(stringOrEmpty(address.getCountryName())); } return result.toString(); } //@Override public boolean isEmpty() { return this.location == null; } @Override public boolean isGeo() { return true; } int convertGeo(double geo) { return (int)(geo * 1000000); } String stringOrEmpty(String string) { if (string == null) { return ""; } return string; } }
Java
/* * Weather API. * Copyright (C) 2010 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import ru.gelin.android.weather.UnitSystem; @SuppressWarnings("deprecation") class EnglishParserHandler extends ParserHandler { public EnglishParserHandler(GoogleWeather weather) { super(weather); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String data = attributes.getValue("data"); if ("unit_system".equals(localName)) { if (data.equalsIgnoreCase("si")) { this.weather.unit = UnitSystem.SI; } else { this.weather.unit = UnitSystem.US; } } else if ("current_conditions".equals(localName)) { this.state = HandlerState.CURRENT_CONDITIONS; addCondition(); } else if ("forecast_conditions".equals(localName)) { switch (state) { case CURRENT_CONDITIONS: this.state = HandlerState.FIRST_FORECAST; break; case FIRST_FORECAST: this.state = HandlerState.NEXT_FORECAST; addCondition(); break; default: addCondition(); } } else if ("humidity".equals(localName)) { this.humidity.parseText(data); } else if ("wind_condition".equals(localName)) { this.wind.parseText(data); } } }
Java
/* * Weather API. * Copyright (C) 2011 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; import ru.gelin.android.weather.SimpleWind; import ru.gelin.android.weather.WindDirection; import ru.gelin.android.weather.WindSpeedUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Wind speed and direction which can parse the text string returned by Goolge Weather API. */ public class GoogleWind extends SimpleWind { private static final Pattern PARSE_PATTERN = Pattern.compile("(N|NNE|NE|ENE|E|ESE|SE|SSE|S|SSW|SW|WSW|W|WNW|NW|NNW)\\s+at\\s+(\\d+)"); /** * Constructs the wind. * The MPH is implied as speed unit. */ public GoogleWind() { super(WindSpeedUnit.MPH); } /** * Extract wind speed and direction value from string. */ public void parseText(String text) { this.text = text; Matcher matcher = PARSE_PATTERN.matcher(text); if (matcher.find()) { this.direction = WindDirection.valueOf(matcher.group(1)); //regexp gurantees that the value is valid enum value this.speed = Integer.parseInt(matcher.group(2)); //regexp guarantees that the value is valid integer } } }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import org.xml.sax.SAXException; import ru.gelin.android.weather.*; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.Reader; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Weather, provided by Google API. */ @SuppressWarnings("deprecation") public class GoogleWeather implements Weather { Location location = new SimpleLocation(""); Date date = new Date(0); Date time = new Date(0); Date queryTime = new Date(); UnitSystem unit = UnitSystem.US; List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); //@Override public Location getLocation() { return this.location; } //@Override public Date getTime() { if (this.time.after(this.date)) { //sometimes time is 0, but the date has correct value return this.time; } else { return this.date; } } public Date getQueryTime() { return this.queryTime; } //@Override @Deprecated public UnitSystem getUnitSystem() { return this.unit; } //@Override public List<WeatherCondition> getConditions() { return new ArrayList<WeatherCondition>(this.conditions); } //@Override public boolean isEmpty() { return this.conditions.isEmpty(); } public URL getForecastURL() { return null; } /** * Sets the location. * Used by the weather source if the location, returned from API is empty. */ void setLocation(Location location) { this.location = location; } /** * Test method, creates the weather from two readers: english and localized XMLs. */ public static GoogleWeather parse(Reader enXml, Reader xml) throws IOException, SAXException, ParserConfigurationException { GoogleWeather weather = new GoogleWeather(); GoogleWeatherParser parser = new GoogleWeatherParser(weather); parser.parse(enXml, new EnglishParserHandler(weather)); parser.parse(xml, new ParserHandler(weather)); return weather; } }
Java
/* * Weather API. * Copyright (C) 2010 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ru.gelin.android.weather.*; import java.text.ParseException; import java.text.SimpleDateFormat; @SuppressWarnings("deprecation") class ParserHandler extends DefaultHandler { protected GoogleWeather weather; protected SimpleWeatherCondition condition; protected SimpleTemperature temperature; protected GoogleHumidity humidity; protected GoogleWind wind; protected HandlerState state; protected int conditionCounter = 0; /** Format for dates in the XML */ static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); /** Format for times in the XML */ static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); public ParserHandler(GoogleWeather weather) { this.weather = weather; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String data = attributes.getValue("data"); if ("city".equals(localName)) { this.weather.location = new SimpleLocation(data); } else if ("forecast_date".equals(localName)) { try { this.weather.date = DATE_FORMAT.parse(data); } catch (ParseException e) { throw new SAXException("invalid 'forecast_date' format: " + data, e); } } else if ("current_date_time".equals(localName)) { try { this.weather.time = TIME_FORMAT.parse(data); } catch (ParseException e) { throw new SAXException("invalid 'current_date_time' format: " + data, e); } } else if ("unit_system".equals(localName)) { if (data.equalsIgnoreCase("si")) { this.weather.unit = UnitSystem.SI; } else { this.weather.unit = UnitSystem.US; } } else if ("current_conditions".equals(localName)) { this.state = HandlerState.CURRENT_CONDITIONS; addCondition(); } else if ("forecast_conditions".equals(localName)) { switch (state) { case CURRENT_CONDITIONS: this.state = HandlerState.FIRST_FORECAST; break; case FIRST_FORECAST: this.state = HandlerState.NEXT_FORECAST; addCondition(); break; default: addCondition(); } } else if ("condition".equals(localName)) { switch (this.state) { case FIRST_FORECAST: //skipping update of condition, because the current conditions are already set break; default: this.condition.setConditionText(data); } } else if ("temp_f".equalsIgnoreCase(localName)) { if (UnitSystem.US.equals(weather.unit)) { try { this.temperature.setCurrent(Integer.parseInt(data), TemperatureUnit.F); } catch (NumberFormatException e) { throw new SAXException("invalid 'temp_f' format: " + data, e); } } } else if ("temp_c".equals(localName)) { if (UnitSystem.SI.equals(weather.unit)) { try { this.temperature.setCurrent(Integer.parseInt(data), TemperatureUnit.C); } catch (NumberFormatException e) { throw new SAXException("invalid 'temp_c' format: " + data, e); } } } else if ("low".equals(localName)) { try { this.temperature.setLow(Integer.parseInt(data), this.weather.unit); } catch (NumberFormatException e) { throw new SAXException("invalid 'low' format: " + data, e); } } else if ("high".equals(localName)) { try { this.temperature.setHigh(Integer.parseInt(data), this.weather.unit); } catch (NumberFormatException e) { throw new SAXException("invalid 'high' format: " + data, e); } } else if ("humidity".equals(localName)) { this.humidity.setText(data); //sets translated text, for backward compatibility } else if ("wind_condition".equals(localName)) { this.wind.setText(data); //sets translated text, for backward compatibility } } protected void addCondition() { if (this.weather.conditions.size() <= this.conditionCounter) { this.condition = new SimpleWeatherCondition(); this.temperature = new SimpleTemperature(weather.unit); this.humidity = new GoogleHumidity(); this.wind = new GoogleWind(); this.condition.setTemperature(this.temperature); this.condition.setHumidity(this.humidity); this.condition.setWind(this.wind); this.weather.conditions.add(this.condition); } else { this.condition = (SimpleWeatherCondition) this.weather.conditions.get(this.conditionCounter); //convert the temperature to the new unit this.temperature = (SimpleTemperature)this.condition.getTemperature(weather.unit); this.condition.setTemperature(this.temperature); this.humidity = (GoogleHumidity)this.condition.getHumidity(); //by default parse in mph this.wind = (GoogleWind)this.condition.getWind(WindSpeedUnit.MPH); //this.condition.setHumidity(this.humidity); //this.condition.setWind(this.wind); } this.conditionCounter++; } }
Java
/* * Weather API. * Copyright (C) 2011 Vladimir Kubyshev, Denis Nelubin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; import ru.gelin.android.weather.SimpleHumidity; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Humidity which parses the string provided by Google Weather API. */ public class GoogleHumidity extends SimpleHumidity { private static final Pattern PARSE_PATTERN = Pattern.compile("(\\d++)"); /** * Sets the current humidity from the unparsed text. */ public void parseText(String text) { this.text = text; if (text == null || text.length() == 0) { this.value = UNKNOWN; return; } Matcher matcher = PARSE_PATTERN.matcher(text); if (matcher.find()) { this.value = Integer.parseInt(matcher.group(1)); //this group selects integers, so parsing is safe } } }
Java
/* * Weather API. * Copyright (C) 2010 Vladimir Kubyshev * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package ru.gelin.android.weather.google; enum HandlerState { CURRENT_CONDITIONS, FIRST_FORECAST, NEXT_FORECAST; }
Java
/* * Weather API. * Copyright (C) 2010 Denis Nelubin, Vladimir Kubyshev * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.google; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ru.gelin.android.weather.Location; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.WeatherException; import ru.gelin.android.weather.WeatherSource; import ru.gelin.android.weather.source.HttpWeatherSource; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Locale; /** * Weather source which takes weather from the Google API. */ public class GoogleWeatherSource extends HttpWeatherSource implements WeatherSource { /** API URL */ static final String API_URL = "http://www.google.com/ig/api?weather=%s&hl=%s"; GoogleWeatherParser weatherParser; GoogleWeather weather; //@Override public Weather query(Location location) throws WeatherException { return query(location, Locale.getDefault()); } void parseContent(Location location, String locale, DefaultHandler handler) throws WeatherException, SAXException, ParserConfigurationException, IOException { String fullUrl; try { fullUrl = String.format(API_URL, URLEncoder.encode(location.getQuery(), ENCODING), URLEncoder.encode(locale, ENCODING)); } catch (UnsupportedEncodingException uee) { throw new RuntimeException(uee); //should never happen } InputStreamReader reader = getReaderForURL(fullUrl); GoogleWeatherParser weatherParser = new GoogleWeatherParser(weather); weatherParser.parse(reader, handler); } //@Override public Weather query(Location location, Locale locale) throws WeatherException { try { weather = new GoogleWeather(); weatherParser = new GoogleWeatherParser(weather); parseContent(location, "us", new EnglishParserHandler(weather)); parseContent(location, locale.getLanguage(), new ParserHandler(weather)); if (weather.getLocation().isEmpty()) { weather.setLocation(location); //set original location } return weather; } catch (Exception e) { throw new WeatherException("create weather error", e); } } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.builtin; /** * Silently extends the basic config activity. * Adds no more functionality. * Used to declare a new class name to be inserted into manifest. */ public class SkinConfigActivity extends ru.gelin.android.weather.notification.skin.impl.BaseConfigActivity { }
Java
/* * Android Weather Notification. * Copyright (C) 2011 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ /** * Built-in skin. */ package ru.gelin.android.weather.notification.skin.builtin;
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.builtin; import android.content.ComponentName; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; import static ru.gelin.android.weather.notification.Tag.TAG; /** * Extends the basic notification receiver. * Always displays the same notification icon. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(TAG, WeatherInfoActivity.class.getName()); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.skin.builtin; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherInfoActivity; /** * Silently extends the basic weather info activity. * Adds no more functionality. * Used to declare a new class name to be inserted into manifest. */ public class WeatherInfoActivity extends BaseWeatherInfoActivity { }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; public class Tag { private Tag() { //avoiding instantiation } /** This application tag for logging. */ public static final String TAG = Tag.class.getPackage().getName(); }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import ru.gelin.android.weather.notification.AppUtils; /** * Broadcast receiver which receives event about boot complete. * Starts UpdateService. */ public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive (Context context, Intent intent) { AppUtils.startUpdateService(context); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; /** * Represents the refresh interval. * Handles interval value (in milliseconds). */ public enum RefreshInterval { REFRESH_15M(900 * 1000), REFRESH_30M(1800 * 1000), REFRESH_1H(3600 * 1000), REFRESH_2H(2 * 3600 * 1000), REFRESH_3H(3 * 3600 * 1000), REFRESH_4H(4 * 3600 * 1000), REFRESH_6H(6 * 3600 * 1000), REFRESH_12H(12 * 3600 * 1000), REFRESH_1D(24 * 3600 * 1000); long interval; RefreshInterval(long interval) { this.interval = interval; } /** * Returns refresh interval value (in milliseconds). */ public long getInterval() { return this.interval; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; /** * Constants for preference keys. */ public class PreferenceKeys { private PreferenceKeys() { //avoid instantiation } /** Preference key for special preference which displays the weather */ public static final String WEATHER = "weather"; /** Refresh interval preference key */ public static final String REFRESH_INTERVAL = "refresh_interval"; /** Refresh interval default value */ public static final String REFRESH_INTERVAL_DEFAULT = RefreshInterval.REFRESH_1H.toString(); /** Location type preferences key */ static final String LOCATION_TYPE = "location_type"; /** Location type default value */ static final String LOCATION_TYPE_DEFAULT = LocationType.LOCATION_NETWORK.toString(); /** Manual location preferences key */ static final String LOCATION = "location"; /** Manual location default value */ static final String LOCATION_DEFAULT = ""; /** Skins preferences category */ static final String SKINS_CATEGORY = "skins_category"; /** Skins install preferences key */ static final String SKINS_INSTALL = "skins_install"; /** API Debug preference key */ static final String API_DEBUG = "api_debug"; /** API Debug default value */ static final boolean API_DEBUG_DEFAULT = false; }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.preference.Preference; import android.preference.PreferenceCategory; import ru.gelin.android.weather.notification.skin.SkinInfo; import java.util.List; import static ru.gelin.android.weather.notification.app.PreferenceKeys.SKINS_CATEGORY; /** * Main activity for ICS and later Androids. */ public class MainActivity4 extends BaseMainActivity { protected void fillSkinsPreferences(List<SkinInfo> skins) { PreferenceCategory skinsCategory = (PreferenceCategory)findPreference(SKINS_CATEGORY); for (SkinInfo skin : skins) { Preference switchPref = skin.getSwitchPreference(this); switchPref.setOnPreferenceChangeListener(this); skinsCategory.addPreference(switchPref); } } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import ru.gelin.android.weather.notification.skin.SkinInfo; import java.util.List; import static ru.gelin.android.weather.notification.app.PreferenceKeys.SKINS_CATEGORY; /** * Main activity for old Androids. */ public class MainActivity2 extends BaseMainActivity { protected void fillSkinsPreferences(List<SkinInfo> skins) { PreferenceCategory skinsCategory = (PreferenceCategory)findPreference(SKINS_CATEGORY); for (SkinInfo skin : skins) { CheckBoxPreference checkboxPref = skin.getCheckBoxPreference(this); checkboxPref.setOnPreferenceChangeListener(this); skinsCategory.addPreference(checkboxPref); Preference configPref = skin.getConfigPreference(this); if (configPref != null) { skinsCategory.addPreference(configPref); configPref.setDependency(checkboxPref.getKey()); //disabled if skin is disabled } } } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.preference.Preference; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.View; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.AppUtils; import ru.gelin.android.weather.notification.R; import ru.gelin.android.weather.notification.WeatherStorage; import ru.gelin.android.weather.notification.skin.impl.WeatherLayout; public class WeatherPreference extends Preference implements OnSharedPreferenceChangeListener { public WeatherPreference(Context context) { super(context); setLayoutResource(R.layout.weather); } public WeatherPreference(Context context, AttributeSet attrs) { super(context, attrs); setLayoutResource(R.layout.weather); } public WeatherPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setLayoutResource(R.layout.weather); } @Override protected void onBindView(View view) { super.onBindView(view); Context context = getContext(); WeatherStorage storage = new WeatherStorage(context); WeatherLayout layout = new WeatherLayout(context, view); Weather weather = storage.load(); layout.bind(weather); } @Override protected void onClick() { super.onClick(); AppUtils.startUpdateService(getContext(), true, true); } @Override protected void onAttachedToHierarchy(PreferenceManager preferenceManager) { super.onAttachedToHierarchy(preferenceManager); getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } //@Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (!getKey().equals(key)) { return; } callChangeListener(sharedPreferences.getAll().get(key)); notifyChanged(); } }
Java
package ru.gelin.android.weather.notification.app; import android.location.LocationManager; /** * Location types. * Location can be defined by GPS (fine), by Wi-Fi or cellular network signal (coarse) or manually (search string). */ public enum LocationType { LOCATION_GPS(LocationManager.GPS_PROVIDER), LOCATION_NETWORK(LocationManager.NETWORK_PROVIDER), LOCATION_MANUAL(null); String locationProvider; private LocationType(String locationProvider) { this.locationProvider = locationProvider; } /** * Returns the name of the Android location provider to use. */ public String getLocationProvider() { return this.locationProvider; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import ru.gelin.android.weather.notification.AppUtils; /** * Broadcast receiver which receives event about changes of network connectivity. * Starts UpdateService if the network goes up. */ public class NetworkConnectivityReceiver extends BroadcastReceiver { @Override public void onReceive (Context context, Intent intent) { boolean noConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (noConnection) { return; } NetworkInfo info = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (info == null) { return; } if (!info.isAvailable()) { return; } Log.d(Tag.TAG, "network is up"); AppUtils.startUpdateService(context); } }
Java
/* * Android Weather Notification. * Copyright (C) 2012 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import ru.gelin.android.weather.notification.AppUtils; /** * Broadcast receiver which receives event about availability of new applicatons installed on SD card. * Starts UpdateService to update weather information for skins installed on SD card. */ public class ExternalAppsAvailableReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { AppUtils.startUpdateService(context); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import java.io.File; /** * A class to check global debug settings. */ public class DebugSettings { private final Context context; public DebugSettings(Context context) { this.context = context; } /** * Returns the directory on the filesystem to store debug data into it. * It's the application's directory on the SD card. * May return null if the external storage is not available. */ public File getDebugDir() { if (Integer.parseInt(Build.VERSION.SDK) >= 8) { return this.context.getExternalFilesDir("debug"); } else { File android = new File(Environment.getExternalStorageDirectory(), "Android"); File data = new File(android, "data"); File pkg = new File(data, this.context.getPackageName()); File debug = new File(pkg, "debug"); return debug; } } /** * Returns true if the debug for API is enabled. */ public boolean isAPIDebug() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context); return prefs.getBoolean(PreferenceKeys.API_DEBUG, PreferenceKeys.API_DEBUG_DEFAULT); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import ru.gelin.android.weather.notification.AppUtils; /** * Broadcast receiver which receives event about new package is updated. * Starts UpdateService to process possible skin update. */ public class PackageChangedReceiver extends BroadcastReceiver { @Override public void onReceive (Context context, Intent intent) { AppUtils.startUpdateService(context); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import ru.gelin.android.weather.notification.R; /** * The activity with debug preferences. */ public class DebugActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.debug_preferences); DebugSettings settings = new DebugSettings(this); Preference apiDebugPref = findPreference(PreferenceKeys.API_DEBUG); apiDebugPref.setSummary(getString(R.string.api_debug_summary, settings.getDebugDir())); } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import ru.gelin.android.weather.Location; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.WeatherSource; import ru.gelin.android.weather.notification.R; import ru.gelin.android.weather.notification.WeatherStorage; import ru.gelin.android.weather.notification.skin.WeatherNotificationManager; import ru.gelin.android.weather.openweathermap.AndroidOpenWeatherMapLocation; import ru.gelin.android.weather.openweathermap.NameOpenWeatherMapLocation; import ru.gelin.android.weather.openweathermap.OpenWeatherMapSource; import java.util.Date; import static ru.gelin.android.weather.notification.AppUtils.EXTRA_FORCE; import static ru.gelin.android.weather.notification.AppUtils.EXTRA_VERBOSE; import static ru.gelin.android.weather.notification.PreferenceKeys.ENABLE_NOTIFICATION; import static ru.gelin.android.weather.notification.PreferenceKeys.ENABLE_NOTIFICATION_DEFAULT; import static ru.gelin.android.weather.notification.app.PreferenceKeys.*; import static ru.gelin.android.weather.notification.app.Tag.TAG; /** * Service to update weather. * Just start it. The new weather values will be wrote to SharedPreferences * (use {@link ru.gelin.android.weather.notification.WeatherStorage} to extract them). */ public class UpdateService extends Service implements Runnable { /** Success update message */ static final int SUCCESS = 0; /** Failure update message */ static final int FAILURE = 1; /** Update message when location is unknown */ static final int UNKNOWN_LOCATION = 2; /** Update message when querying new location */ static final int QUERY_LOCATION = 3; /** * Lock used when maintaining update thread. */ private static Object staticLock = new Object(); /** * Flag if there is an update thread already running. We only launch a new * thread if one isn't already running. */ static boolean threadRunning = false; /** Verbose flag */ boolean verbose = false; /** Force flag */ boolean force = false; /** Queried location */ Location location; /** Updated weather */ Weather weather; /** Weather update error */ Exception updateError; /** Intent which starts the service */ Intent startIntent; @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); synchronized(this) { this.startIntent = intent; if (intent != null) { this.verbose = intent.getBooleanExtra(EXTRA_VERBOSE, false); this.force = intent.getBooleanExtra(EXTRA_FORCE, false); } } removeLocationUpdates(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); WeatherStorage storage = new WeatherStorage(UpdateService.this); Weather weather = storage.load(); long lastUpdate = weather.getTime().getTime(); boolean notificationEnabled = preferences.getBoolean( ENABLE_NOTIFICATION, ENABLE_NOTIFICATION_DEFAULT); scheduleNextRun(lastUpdate); synchronized(staticLock) { if (threadRunning) { return; // only start processing thread if not already running } if (!force && !notificationEnabled) { skipUpdate(storage, "skipping update, notification disabled"); return; } if (!force && !isExpired(lastUpdate)) { skipUpdate(storage, "skipping update, not expired"); return; } if (!isNetworkAvailable()) { //no network skipUpdate(storage, "skipping update, no network"); if (verbose) { Toast.makeText(UpdateService.this, getString(R.string.weather_update_no_network), Toast.LENGTH_LONG).show(); } return; } if (!threadRunning) { threadRunning = true; new Thread(this).start(); } } } void skipUpdate(WeatherStorage storage, String logMessage) { stopSelf(); Log.d(TAG, logMessage); storage.updateTime(); WeatherNotificationManager.update(this); } //@Override public void run() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); Location location = null; LocationType locationType = getLocationType(); if (LocationType.LOCATION_MANUAL.equals(locationType)) { location = createSearchLocation(preferences.getString(LOCATION, LOCATION_DEFAULT)); } else { location = queryLocation(locationType.getLocationProvider()); if (location == null) { internalHandler.sendEmptyMessage(QUERY_LOCATION); return; } } synchronized(this) { this.location = location; } if (location == null || location.isEmpty()) { internalHandler.sendEmptyMessage(UNKNOWN_LOCATION); return; } WeatherSource source = new OpenWeatherMapSource(this); try { Weather weather = source.query(location); synchronized(this) { this.weather = weather; } internalHandler.sendEmptyMessage(SUCCESS); } catch (Exception e) { synchronized(this) { this.updateError = e; } internalHandler.sendEmptyMessage(FAILURE); } } /** * Handles weather update result. */ final Handler internalHandler = new Handler() { @Override public void handleMessage(Message msg) { synchronized(staticLock) { threadRunning = false; } WeatherStorage storage = new WeatherStorage(UpdateService.this); switch (msg.what) { case SUCCESS: synchronized(UpdateService.this) { Log.i(TAG, "received weather: " + weather.getLocation().getText() + " " + weather.getTime()); if (weather.isEmpty()) { storage.updateTime(); } else { storage.save(weather); //saving only non-empty weather } scheduleNextRun(weather.getTime().getTime()); if (verbose && weather.isEmpty()) { Toast.makeText(UpdateService.this, getString(R.string.weather_update_empty, location.getText()), Toast.LENGTH_LONG).show(); } } break; case FAILURE: synchronized(UpdateService.this) { Log.w(TAG, "failed to update weather", updateError); storage.updateTime(); if (verbose) { Toast.makeText(UpdateService.this, getString(R.string.weather_update_failed, updateError.getMessage()), Toast.LENGTH_LONG).show(); } } break; case UNKNOWN_LOCATION: synchronized(UpdateService.this) { Log.w(TAG, "failed to get location"); storage.updateTime(); if (verbose) { Toast.makeText(UpdateService.this, getString(R.string.weather_update_unknown_location), Toast.LENGTH_LONG).show(); } } break; case QUERY_LOCATION: synchronized(UpdateService.this) { Log.d(TAG, "quering new location"); //storage.updateTime(); //don't signal about update } break; } WeatherNotificationManager.update(UpdateService.this); stopSelf(); } }; /** * Check availability of network connections. * Returns true if any network connection is available. */ boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null) { return false; } return info.isAvailable(); } /** * Returns true if the last update time is expired. * @param timestamp timestamp value to check */ boolean isExpired(long timestamp) { long now = System.currentTimeMillis(); RefreshInterval interval = getRefreshInterval(); return timestamp + interval.getInterval() < now; } void scheduleNextRun(long lastUpdate) { long now = System.currentTimeMillis(); RefreshInterval interval = getRefreshInterval(); long nextUpdate = lastUpdate + interval.getInterval(); if (nextUpdate <= now) { nextUpdate = now + interval.getInterval(); } PendingIntent pendingIntent = getPendingIntent(null); //don't inherit extra flags boolean notificationEnabled = PreferenceManager.getDefaultSharedPreferences(this). getBoolean(ENABLE_NOTIFICATION, ENABLE_NOTIFICATION_DEFAULT); AlarmManager alarmManager = (AlarmManager)getSystemService( Context.ALARM_SERVICE); if (notificationEnabled) { Log.d(TAG, "scheduling update to " + new Date(nextUpdate)); alarmManager.set(AlarmManager.RTC, nextUpdate, pendingIntent); } else { Log.d(TAG, "cancelling update schedule"); alarmManager.cancel(pendingIntent); } } RefreshInterval getRefreshInterval() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); return RefreshInterval.valueOf(preferences.getString( REFRESH_INTERVAL, REFRESH_INTERVAL_DEFAULT)); } LocationType getLocationType() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); return LocationType.valueOf(preferences.getString( LOCATION_TYPE, LOCATION_TYPE_DEFAULT)); } /** * Queries current location using android services. */ Location queryLocation(String locationProvider) { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); if (manager == null) { return null; } android.location.Location androidLocation = manager.getLastKnownLocation(locationProvider); if (androidLocation == null || isExpired(androidLocation.getTime())) { try { Log.d(TAG, "requested location update from " + locationProvider); manager.requestLocationUpdates(locationProvider, 0, 0, getPendingIntent(this.startIntent)); //try to update immediately return null; } catch (IllegalArgumentException e) { return null; //no location provider } } return new AndroidOpenWeatherMapLocation(androidLocation); } /** * Creates the location to search the location by the entered string. */ Location createSearchLocation(String query) { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); if (manager == null) { return new NameOpenWeatherMapLocation(query, null); } android.location.Location androidLocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); return new NameOpenWeatherMapLocation(query, androidLocation); } /** * Unsubscribes from location updates. */ void removeLocationUpdates() { if (this.startIntent != null && this.startIntent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)) { Log.d(TAG, "location updated"); } LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); manager.removeUpdates(getPendingIntent(this.startIntent)); } /** * Returns pending intent to start the service. * @param intent to wrap into the pending intent or null */ PendingIntent getPendingIntent(Intent intent) { Intent serviceIntent; if (intent == null) { serviceIntent = new Intent(this, UpdateService.class); } else { serviceIntent = new Intent(intent); } return PendingIntent.getService(this, 0, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT); } @Override public IBinder onBind(Intent intent) { return null; } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.app.AlertDialog; import android.content.*; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.provider.Settings; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.Toast; import ru.gelin.android.weather.notification.AppUtils; import ru.gelin.android.weather.notification.R; import ru.gelin.android.weather.notification.skin.SkinInfo; import ru.gelin.android.weather.notification.skin.SkinManager; import ru.gelin.android.weather.notification.skin.UpdateNotificationActivity; import java.util.List; import static ru.gelin.android.weather.notification.PreferenceKeys.ENABLE_NOTIFICATION; import static ru.gelin.android.weather.notification.app.PreferenceKeys.*; /** * Main activity for old Androids. */ public abstract class BaseMainActivity extends UpdateNotificationActivity implements OnPreferenceClickListener, OnPreferenceChangeListener { static final Uri SKIN_SEARCH_URI=Uri.parse("market://search?q=WNS"); static final String SKIN_PREFERENCE_PREFIX = "skin_enabled_"; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); //before super()! super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.main_preferences); /* TODO: why this doesn't work? PreferenceScreen screen = getPreferenceScreen(); screen.setOnPreferenceClickListener(this); screen.setOnPreferenceChangeListener(this); */ Preference weatherPreference = findPreference(WEATHER); weatherPreference.setOnPreferenceClickListener(this); weatherPreference.setOnPreferenceChangeListener(this); Preference notificationPreference = findPreference(ENABLE_NOTIFICATION); notificationPreference.setOnPreferenceChangeListener(this); Preference refreshInterval = findPreference(REFRESH_INTERVAL); refreshInterval.setOnPreferenceChangeListener(this); Preference locationTypePreference = findPreference(LOCATION_TYPE); locationTypePreference.setOnPreferenceChangeListener(this); Preference locationPreference = findPreference(LOCATION); locationPreference.setOnPreferenceChangeListener(this); Preference skinsInstallPreference = findPreference(SKINS_INSTALL); Intent skinsInstallIntent = new Intent(Intent.ACTION_VIEW, SKIN_SEARCH_URI); skinsInstallPreference.setIntent(skinsInstallIntent); ComponentName marketActivity = skinsInstallIntent.resolveActivity(getPackageManager()); if (marketActivity == null) { PreferenceCategory skinsCategory = (PreferenceCategory)findPreference(SKINS_CATEGORY); skinsCategory.removePreference(skinsInstallPreference); } SkinManager sm = new SkinManager(this); List<SkinInfo> skins = sm.getInstalledSkins(); fillSkinsPreferences(skins); if (skins.size() <= 1) { Toast.makeText(this, marketActivity == null ? R.string.skins_install_notice_no_market : R.string.skins_install_notice, Toast.LENGTH_LONG).show(); } startUpdate(false); } @Override protected void onResume() { super.onResume(); SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); boolean isManual = LocationType.LOCATION_MANUAL.toString().equals( prefs.getString(LOCATION_TYPE, LOCATION_TYPE_DEFAULT)); //Toast.makeText(this, prefs.getString(LOCATION_TYPE, LOCATION_TYPE_DEFAULT), Toast.LENGTH_LONG).show(); findPreference(LOCATION).setEnabled(isManual); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.debug_menu_item: Intent intent = new Intent(this, DebugActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } protected abstract void fillSkinsPreferences(List<SkinInfo> skins); //@Override public boolean onPreferenceClick(Preference preference) { String key = preference.getKey(); if (WEATHER.equals(key)) { setProgressBarIndeterminateVisibility(true); return true; } return false; } //@Override public boolean onPreferenceChange(Preference preference, Object newValue) { String key = preference.getKey(); if (WEATHER.equals(key)) { setProgressBarIndeterminateVisibility(false); return true; } if (ENABLE_NOTIFICATION.equals(key) || REFRESH_INTERVAL.equals(key)) { //force reschedule service start startUpdate(false); return true; } if (LOCATION_TYPE.equals(key)) { LocationType locationType = LocationType.valueOf(String.valueOf(newValue)); boolean isManual = LocationType.LOCATION_MANUAL.equals(locationType); findPreference(LOCATION).setEnabled(isManual); checkLocationProviderEnabled(locationType.getLocationProvider()); startUpdate(true); return true; } if (LOCATION.equals(key)) { startUpdate(true); return true; } if (key.startsWith(SKIN_PREFERENCE_PREFIX)) { updateNotification(); return true; } return true; } void startUpdate(boolean force) { setProgressBarIndeterminateVisibility(true); AppUtils.startUpdateService(this, true, force); } void checkLocationProviderEnabled(String locationProvider) { if (locationProvider == null) { return; } LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); if (!manager.isProviderEnabled(locationProvider)) { final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); boolean hasSettings = intent.resolveActivity(getPackageManager()) != null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.location_disabled) .setCancelable(true) .setPositiveButton(R.string.open_settings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { startActivity(intent); } }) .setNegativeButton(android.R.string.cancel, null); builder.show(); } } }
Java
/* * Android Weather Notification. * Copyright (C) 2010 Denis Nelubin aka Gelin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://gelin.ru * mailto:den@gelin.ru */ package ru.gelin.android.weather.notification.app; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(getIntent()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setClass(this, MainActivity2.class); try { if (Integer.parseInt(Build.VERSION.SDK) >= 14) { intent.setClass(this, MainActivity4.class); } } catch (NumberFormatException e) { //pass to MainActivity2 } startActivity(intent); finish(); } }
Java
package ru.gelin.android.weather.notification; /** * MainActivity class for backward compatibility. */ @Deprecated public class MainActivity extends ru.gelin.android.weather.notification.app.MainActivity { }
Java
package ru.gelin.android.weather.source; import org.apache.http.HttpEntity; /** * Some utilities to work with HTTP requests. */ public class HttpUtils { private HttpUtils() { //avoid instatiation } public static String getCharset(HttpEntity entity) { return getCharset(entity.getContentType().toString()); } static String getCharset(String contentType) { if (contentType == null) { return HttpWeatherSource.ENCODING; } int charsetPos = contentType.indexOf(HttpWeatherSource.CHARSET); if (charsetPos < 0) { return HttpWeatherSource.ENCODING; } charsetPos += HttpWeatherSource.CHARSET.length(); int endPos = contentType.indexOf(';', charsetPos); if (endPos < 0) { endPos = contentType.length(); } return contentType.substring(charsetPos, endPos); } }
Java
package ru.gelin.android.weather.source; import android.content.Context; import android.util.Log; import ru.gelin.android.weather.notification.app.DebugSettings; import ru.gelin.android.weather.notification.app.Tag; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.TimeZone; /** * Saves the query result to a file. */ public class DebugDumper { static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss'Z'"); static final Set<Character> BAD_CHARS = new HashSet<Character>(); static final char REPLACEMENT = '_'; static { DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); BAD_CHARS.add('/'); BAD_CHARS.add('?'); BAD_CHARS.add('<'); BAD_CHARS.add('>'); BAD_CHARS.add('\\'); BAD_CHARS.add(':'); BAD_CHARS.add('*'); BAD_CHARS.add('|'); BAD_CHARS.add('"'); BAD_CHARS.add('&'); BAD_CHARS.add('='); } private final DebugSettings settings; private final File path; private final String prefix; public DebugDumper(Context context, String prefix) { this.settings = new DebugSettings(context); this.path = settings.getDebugDir(); this.prefix = prefix; } public void dump(String url, String content) { if (!this.settings.isAPIDebug()) { return; } File dumpFile = getDumpFile(url); File dir = dumpFile.getParentFile(); if (!(dir.mkdirs() || dir.isDirectory())) { Log.w(Tag.TAG, "cannot create dir " + dir); return; } try { Log.d(Tag.TAG, "dumping to " + dumpFile); Writer out = new FileWriter(dumpFile); out.write(content); out.close(); } catch (Exception e) { Log.w(Tag.TAG, "cannot create debug dump", e); } } File getDumpFile(String url) { StringBuilder fileName = new StringBuilder(); fileName.append(DATE_FORMAT.format(new Date())); fileName.append(url.replace(this.prefix, "")); for (int i = 0; i < fileName.length(); i++) { if (BAD_CHARS.contains(fileName.charAt(i))) { fileName.setCharAt(i, REPLACEMENT); } } fileName.append(".txt"); return new File(this.path, fileName.toString()); } }
Java
package ru.gelin.android.weather.source; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import ru.gelin.android.weather.WeatherException; import ru.gelin.android.weather.notification.app.Tag; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; /** * Abstract class for a weather source which uses HTTP for transport */ public class HttpWeatherSource { /** Main encoding */ public static final String ENCODING = "UTF-8"; /** Charset pattern */ static final String CHARSET = "charset="; /** OK HTTP status */ private static final int HTTP_STATUS_OK = 200; /** User Agent of the Weather Source */ static final String USER_AGENT = "Weather Notification (Linux; Android)"; /** HTTP client */ private HttpClient client; /** * Reads the content of the specified URL. */ protected InputStreamReader getReaderForURL(String url) throws WeatherException { Log.d(Tag.TAG, "requesting " + url); HttpGet request; try { request = new HttpGet(url); request.setHeader("User-Agent", USER_AGENT); prepareRequest(request); } catch (Exception e) { throw new WeatherException("Can't prepare http request", e); } String charset = ENCODING; try { HttpResponse response = getClient().execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { throw new WeatherException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); charset = HttpUtils.getCharset(entity); InputStreamReader inputStream = new InputStreamReader(entity.getContent(), charset); return inputStream; } catch (UnsupportedEncodingException uee) { throw new WeatherException("unsupported charset: " + charset, uee); } catch (IOException e) { throw new WeatherException("Problem communicating with API", e); } } /** * Add necessary headers to the GET request. */ protected void prepareRequest(HttpGet request) { //void implementation } /** * Creates client with specific user-agent string */ HttpClient getClient() throws WeatherException { if (this.client == null) { try { this.client = new DefaultHttpClient(); } catch (Exception e) { throw new WeatherException("Can't prepare http client", e); } } return this.client; } }
Java
package ru.gelin.android.weather.openweathermap; import ru.gelin.android.weather.SimpleTemperature; import ru.gelin.android.weather.Temperature; import ru.gelin.android.weather.TemperatureUnit; /** * The temperature, which values can be appended by some another temperature, parsed from the forecasts, for example. * This temperature is updated after the append operation. * The Low temperature is updated by the lowest of the current and appending Low temperatures. * The High temperature is updated by the highest of the current and appending High temperatures. */ public class AppendableTemperature extends SimpleTemperature { public AppendableTemperature(TemperatureUnit unit) { super(unit); } public void append(Temperature temperature) { if (getLow() == Temperature.UNKNOWN) { setLow(temperature.getLow(), temperature.getTemperatureUnit()); } else { setLow(Math.min( getLow(), convertValue(temperature.getLow(), temperature.getTemperatureUnit())), getTemperatureUnit()); } if (getHigh() == Temperature.UNKNOWN) { setHigh(temperature.getHigh(), temperature.getTemperatureUnit()); } else { setHigh(Math.max( getHigh(), convertValue(temperature.getHigh(), temperature.getTemperatureUnit())), getTemperatureUnit()); } } }
Java