code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * A class representing a (GPS) Track. * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class Track implements Parcelable { /** * Creator for a Track object. */ public static class Creator implements Parcelable.Creator<Track> { public Track createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Track track = new Track(); track.id = source.readLong(); track.name = source.readString(); track.description = source.readString(); track.mapId = source.readString(); track.category = source.readString(); track.startId = source.readLong(); track.stopId = source.readLong(); track.stats = source.readParcelable(classLoader); track.numberOfPoints = source.readInt(); for (int i = 0; i < track.numberOfPoints; ++i) { Location loc = source.readParcelable(classLoader); track.locations.add(loc); } track.tableId = source.readString(); return track; } public Track[] newArray(int size) { return new Track[size]; } } public static final Creator CREATOR = new Creator(); /** * The track points (which may not have been loaded). */ private ArrayList<Location> locations = new ArrayList<Location>(); /** * The number of location points (present even if the points themselves were * not loaded). */ private int numberOfPoints = 0; private long id = -1; private String name = ""; private String description = ""; private String mapId = ""; private String tableId = ""; private long startId = -1; private long stopId = -1; private String category = ""; private TripStatistics stats = new TripStatistics(); public Track() { } public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(mapId); dest.writeString(category); dest.writeLong(startId); dest.writeLong(stopId); dest.writeParcelable(stats, 0); dest.writeInt(numberOfPoints); for (int i = 0; i < numberOfPoints; ++i) { dest.writeParcelable(locations.get(i), 0); } dest.writeString(tableId); } // Getters and setters: //--------------------- public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMapId() { return mapId; } public void setMapId(String mapId) { this.mapId = mapId; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNumberOfPoints() { return numberOfPoints; } public void setNumberOfPoints(int numberOfPoints) { this.numberOfPoints = numberOfPoints; } public void addLocation(Location l) { locations.add(l); } public ArrayList<Location> getLocations() { return locations; } public void setLocations(ArrayList<Location> locations) { this.locations = locations; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.location.Location; /** * This class extends the standard Android location with extra information. * * @author Sandor Dornbush */ public class MyTracksLocation extends Location { private Sensor.SensorDataSet sensorDataSet = null; /** * The id of this location from the provider. */ private int id = -1; public MyTracksLocation(Location location, Sensor.SensorDataSet sd) { super(location); this.sensorDataSet = sd; } public MyTracksLocation(String provider) { super(provider); } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public void setSensorData(Sensor.SensorDataSet sensorData) { this.sensorDataSet = sensorData; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void reset() { super.reset(); sensorDataSet = null; id = -1; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface WaypointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/waypoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.waypoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.waypoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String ICON = "icon"; public static final String TRACKID = "trackid"; public static final String TYPE = "type"; public static final String LENGTH = "length"; public static final String DURATION = "duration"; public static final String STARTTIME = "starttime"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the track points provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TrackPointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/trackpoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.trackpoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.trackpoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String TRACKID = "trackid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String SENSOR = "sensor"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.protobuf.InvalidProtocolBufferException; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * Helper class providing easy access to locations and tracks in the * MyTracksProvider. All static members. * * @author Leif Hendrik Wilden */ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final ContentResolver contentResolver; private int defaultCursorBatchSize = 2000; public MyTracksProviderUtilsImpl(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * Creates the ContentValues for a given location object. * * @param location a given location * @param trackId the id of the track it belongs to * @return a filled in ContentValues object */ private static ContentValues createContentValues( Location location, long trackId) { ContentValues values = new ContentValues(); values.put(TrackPointsColumns.TRACKID, trackId); values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); // This is an ugly hack for Samsung phones that don't properly populate the // time field. values.put(TrackPointsColumns.TIME, (location.getTime() == 0) ? System.currentTimeMillis() : location.getTime()); if (location.hasAltitude()) { values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(TrackPointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(TrackPointsColumns.SPEED, location.getSpeed()); } if (location instanceof MyTracksLocation) { MyTracksLocation mtLocation = (MyTracksLocation) location; if (mtLocation.getSensorDataSet() != null) { values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray()); } } return values; } @Override public ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics stats = track.getStatistics(); // Values id < 0 indicate no id is available: if (track.getId() >= 0) { values.put(TracksColumns._ID, track.getId()); } values.put(TracksColumns.NAME, track.getName()); values.put(TracksColumns.DESCRIPTION, track.getDescription()); values.put(TracksColumns.MAPID, track.getMapId()); values.put(TracksColumns.TABLEID, track.getTableId()); values.put(TracksColumns.CATEGORY, track.getCategory()); values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints()); values.put(TracksColumns.STARTID, track.getStartId()); values.put(TracksColumns.STARTTIME, stats.getStartTime()); values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.STOPID, track.getStopId()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); return values; } private static ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Values id < 0 indicate no id is available: if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); TripStatistics stats = waypoint.getStatistics(); if (stats != null) { values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, stats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade()); values.put(WaypointsColumns.STARTTIME, stats.getStartTime()); } Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } } return values; } @Override public Location createLocation(Cursor cursor) { Location location = new MyTracksLocation(""); fillLocation(cursor, location); return location; } /** * A cache of track column indices. */ private static class CachedTrackColumnIndices { public final int idxId; public final int idxLatitude; public final int idxLongitude; public final int idxAltitude; public final int idxTime; public final int idxBearing; public final int idxAccuracy; public final int idxSpeed; public final int idxSensor; public CachedTrackColumnIndices(Cursor cursor) { idxId = cursor.getColumnIndex(TrackPointsColumns._ID); idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE); idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE); idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE); idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME); idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING); idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY); idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED); idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR); } } private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices, Location location) { location.reset(); if (!cursor.isNull(columnIndices.idxLatitude)) { location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6); } if (!cursor.isNull(columnIndices.idxLongitude)) { location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6); } if (!cursor.isNull(columnIndices.idxAltitude)) { location.setAltitude(cursor.getFloat(columnIndices.idxAltitude)); } if (!cursor.isNull(columnIndices.idxTime)) { location.setTime(cursor.getLong(columnIndices.idxTime)); } if (!cursor.isNull(columnIndices.idxBearing)) { location.setBearing(cursor.getFloat(columnIndices.idxBearing)); } if (!cursor.isNull(columnIndices.idxSpeed)) { location.setSpeed(cursor.getFloat(columnIndices.idxSpeed)); } if (!cursor.isNull(columnIndices.idxAccuracy)) { location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy)); } if (location instanceof MyTracksLocation && !cursor.isNull(columnIndices.idxSensor)) { MyTracksLocation mtLocation = (MyTracksLocation) location; // TODO get the right buffer. Sensor.SensorDataSet sensorData; try { sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor)); mtLocation.setSensorData(sensorData); } catch (InvalidProtocolBufferException e) { Log.w(TAG, "Failed to parse sensor data.", e); } } } @Override public void fillLocation(Cursor cursor, Location location) { CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor); fillLocation(cursor, columnIndicies, location); } @Override public Track createTrack(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID); int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION); int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY); int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID); int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME); int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID); int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS); int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT); int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT); int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON); int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON); int idxTotalDistance = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE); Track track = new Track(); TripStatistics stats = track.getStatistics(); if (!cursor.isNull(idxId)) { track.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { track.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { track.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxMapId)) { track.setMapId(cursor.getString(idxMapId)); } if (!cursor.isNull(idxTableId)) { track.setTableId(cursor.getString(idxTableId)); } if (!cursor.isNull(idxCategory)) { track.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxStartId)) { track.setStartId(cursor.getInt(idxStartId)); } if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); } if (!cursor.isNull(idxStopTime)) { stats.setStopTime(cursor.getLong(idxStopTime)); } if (!cursor.isNull(idxStopId)) { track.setStopId(cursor.getInt(idxStopId)); } if (!cursor.isNull(idxNumPoints)) { track.setNumberOfPoints(cursor.getInt(idxNumPoints)); } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); } if (!cursor.isNull(idxMaxlat) && !cursor.isNull(idxMinlat) && !cursor.isNull(idxMaxlon) && !cursor.isNull(idxMinlon)) { int top = cursor.getInt(idxMaxlat); int bottom = cursor.getInt(idxMinlat); int right = cursor.getInt(idxMaxlon); int left = cursor.getInt(idxMinlon); stats.setBounds(left, top, right, bottom); } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); } return track; } @Override public Waypoint createWaypoint(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID); int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION); int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY); int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON); int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID); int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH); int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION); int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME); int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID); int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID); int idxTotalDistance = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE); int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE); int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE); int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME); int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING); int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY); int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED); Waypoint waypoint = new Waypoint(); if (!cursor.isNull(idxId)) { waypoint.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { waypoint.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { waypoint.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxCategory)) { waypoint.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxIcon)) { waypoint.setIcon(cursor.getString(idxIcon)); } if (!cursor.isNull(idxTrackId)) { waypoint.setTrackId(cursor.getLong(idxTrackId)); } if (!cursor.isNull(idxType)) { waypoint.setType(cursor.getInt(idxType)); } if (!cursor.isNull(idxLength)) { waypoint.setLength(cursor.getDouble(idxLength)); } if (!cursor.isNull(idxDuration)) { waypoint.setDuration(cursor.getLong(idxDuration)); } if (!cursor.isNull(idxStartId)) { waypoint.setStartId(cursor.getLong(idxStartId)); } if (!cursor.isNull(idxStopId)) { waypoint.setStopId(cursor.getLong(idxStopId)); } TripStatistics stats = new TripStatistics(); boolean hasStats = false; if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); hasStats = true; } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); hasStats = true; } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); hasStats = true; } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); hasStats = true; } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); hasStats = true; } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); hasStats = true; } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); hasStats = true; } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); hasStats = true; } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); hasStats = true; } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); hasStats = true; } if (hasStats) { waypoint.setStatistics(stats); } Location location = new Location(""); if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) { location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6); location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6); } if (!cursor.isNull(idxAltitude)) { location.setAltitude(cursor.getFloat(idxAltitude)); } if (!cursor.isNull(idxTime)) { location.setTime(cursor.getLong(idxTime)); } if (!cursor.isNull(idxBearing)) { location.setBearing(cursor.getFloat(idxBearing)); } if (!cursor.isNull(idxSpeed)) { location.setSpeed(cursor.getFloat(idxSpeed)); } if (!cursor.isNull(idxAccuracy)) { location.setAccuracy(cursor.getFloat(idxAccuracy)); } waypoint.setLocation(location); return waypoint; } @Override public void deleteAllTracks() { contentResolver.delete(TracksColumns.CONTENT_URI, null, null); contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); } @Override public void deleteTrack(long trackId) { Track track = getTrack(trackId); if (track != null) { contentResolver.delete(TrackPointsColumns.CONTENT_URI, "_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(), null); } contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=" + trackId, null); contentResolver.delete( TracksColumns.CONTENT_URI, "_id=" + trackId, null); } @Override public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { final Waypoint deletedWaypoint = getWaypoint(waypointId); if (deletedWaypoint != null && deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) { final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(deletedWaypoint); if (nextWaypoint != null) { Log.d(TAG, "Correcting marker " + nextWaypoint.getId() + " after deleted marker " + deletedWaypoint.getId()); nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics()); nextWaypoint.setDescription( descriptionGenerator.generateWaypointDescription(nextWaypoint)); if (!updateWaypoint(nextWaypoint)) { Log.w(TAG, "Update of marker was unsuccessful."); } } else { Log.d(TAG, "No statistics marker after the deleted one was found."); } } contentResolver.delete( WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null); } @Override public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { final String selection = WaypointsColumns._ID + ">" + waypoint.getId() + " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId() + " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; final String sortOrder = WaypointsColumns._ID + " LIMIT 1"; Cursor cursor = null; try { cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, selection, null /*selectionArgs*/, sortOrder); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public boolean updateWaypoint(Waypoint waypoint) { try { final int rows = contentResolver.update( WaypointsColumns.CONTENT_URI, createContentValues(waypoint), "_id=" + waypoint.getId(), null /*selectionArgs*/); return rows == 1; } catch (RuntimeException e) { Log.e(TAG, "Caught unexpected exception.", e); } return false; } /** * Finds a locations from the provider by the given selection. * * @param select a selection argument that identifies a unique location * @return the fist location matching, or null if not found */ private Location findLocationBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createLocation(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpeceted exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } /** * Finds a track from the provider by the given selection. * * @param select a selection argument that identifies a unique track * @return the first track matching, or null if not found */ private Track findTrackBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public Location getLastLocation() { return findLocationBy("_id=(select max(_id) from trackpoints)"); } @Override public Waypoint getFirstWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1"); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public Waypoint getWaypoint(long waypointId) { if (waypointId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "_id=" + waypointId, null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public long getLastLocationId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, projection, "_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")", null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getFirstWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getLastWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, WaypointsColumns.TRACKID + "=" + trackId, null /*selectionArgs*/, "_id DESC LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public Track getLastTrack() { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)", null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public long getLastTrackId() { String[] proj = { TracksColumns._ID }; Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)", null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TracksColumns._ID)); } } finally { cursor.close(); } } return -1; } @Override public Location getLocation(long id) { if (id < 0) { return null; } String selection = TrackPointsColumns._ID + "=" + id; return findLocationBy(selection); } @Override public Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } String selection; if (minTrackPointId >= 0) { selection = String.format("%s=%d AND %s%s%d", TrackPointsColumns.TRACKID, trackId, TrackPointsColumns._ID, descending ? "<=" : ">=", minTrackPointId); } else { selection = String.format("%s=%d", TrackPointsColumns.TRACKID, trackId); } String sortOrder = "_id " + (descending ? "DESC" : "ASC"); if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { if (trackId < 0) { return null; } String selection; String[] selectionArgs; if (minWaypointId > 0) { selection = String.format("%s = ? AND %s >= ?", WaypointsColumns.TRACKID, WaypointsColumns._ID); selectionArgs = new String[] { Long.toString(trackId), Long.toString(minWaypointId) }; } else { selection = String.format("%s=?", WaypointsColumns.TRACKID); selectionArgs = new String[] { Long.toString(trackId) }; } return getWaypointsCursor(selection, selectionArgs, null, maxWaypoints); } @Override public Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints) { if (order == null) { order = "_id ASC"; } if (maxWaypoints > 0) { order += " LIMIT " + maxWaypoints; } return contentResolver.query( WaypointsColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Track getTrack(long id) { if (id < 0) { return null; } String select = TracksColumns._ID + "=" + id; return findTrackBy(select); } @Override public List<Track> getAllTracks() { Cursor cursor = getTracksCursor(null, null, TracksColumns._ID); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while(cursor.moveToNext()); } cursor.close(); } return tracks; } @Override public Cursor getTracksCursor(String selection, String[] selectionArgs, String order) { return contentResolver.query( TracksColumns.CONTENT_URI, null, selection, selectionArgs, order); } @Override public Uri insertTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack"); return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); } @Override public Uri insertTrackPoint(Location location, long trackId) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint"); return contentResolver.insert(TrackPointsColumns.CONTENT_URI, createContentValues(location, trackId)); } @Override public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) { if (length == -1) { length = locations.length; } ContentValues[] values = new ContentValues[length]; for (int i = 0; i < length; i++) { values[i] = createContentValues(locations[i], trackId); } return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); } @Override public Uri insertWaypoint(Waypoint waypoint) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint"); waypoint.setId(-1); return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); } @Override public boolean trackExists(long id) { if (id < 0) { return false; } Cursor cursor = null; try { final String[] projection = { TracksColumns._ID }; cursor = contentResolver.query( TracksColumns.CONTENT_URI, projection, TracksColumns._ID + "=" + id/*selection*/, null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null && cursor.moveToNext()) { return true; } } finally { if (cursor != null) { cursor.close(); } } return false; } @Override public void updateTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack"); contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), "_id=" + track.getId(), null); } @Override public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("Expecting non-null locationFactory"); } return new LocationIterator() { private long lastTrackPointId = startTrackPointId; private Cursor cursor = getCursor(startTrackPointId); private final CachedTrackColumnIndices columnIndices = cursor != null ? new CachedTrackColumnIndices(cursor) : null; private Cursor getCursor(long trackPointId) { return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } private boolean advanceCursorToNextBatch() { long pointId = lastTrackPointId + (descending ? -1 : 1); Log.d(TAG, "Advancing cursor point ID: " + pointId); cursor.close(); cursor = getCursor(pointId); return cursor != null; } @Override public long getLocationId() { return lastTrackPointId; } @Override public boolean hasNext() { if (cursor == null) { return false; } if (cursor.isAfterLast()) { return false; } if (cursor.isLast()) { // If the current batch size was less that max, we can safely return, otherwise // we need to advance to the next batch. return cursor.getCount() == defaultCursorBatchSize && advanceCursorToNextBatch() && !cursor.isAfterLast(); } return true; } @Override public Location next() { if (cursor == null || !(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) { throw new NoSuchElementException(); } lastTrackPointId = cursor.getLong(columnIndices.idxId); Location location = locationFactory.createLocation(); fillLocation(cursor, columnIndices, location); return location; } @Override public void close() { if (cursor != null) { cursor.close(); cursor = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // @VisibleForTesting void setDefaultCursorBatchSize(int defaultCursorBatchSize) { this.defaultCursorBatchSize = defaultCursorBatchSize; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TracksColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/tracks"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.track"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.track"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String STARTTIME = "starttime"; public static final String STOPTIME = "stoptime"; public static final String NUMPOINTS = "numpoints"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; public static final String MINLAT = "minlat"; public static final String MAXLAT = "maxlat"; public static final String MINLON = "minlon"; public static final String MAXLON = "maxlon"; public static final String MAPID = "mapid"; public static final String TABLEID = "tableid"; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import java.util.Iterator; import java.util.List; /** * Utility to access data from the mytracks content provider. * * @author Rodrigo Damazio */ public interface MyTracksProviderUtils { /** * Authority (first part of URI) for the MyTracks content provider: */ public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** * Deletes all tracks (including track points) from the provider. */ void deleteAllTracks(); /** * Deletes a track with the given track id. * * @param trackId the unique track id */ void deleteTrack(long trackId); /** * Deletes a way point with the given way point id. * This will also correct the next statistics way point after the deleted one * to reflect the deletion. * The generator is needed to stitch together statistics waypoints. * * @param waypointId the unique way point id * @param descriptionGenerator the class to generate descriptions */ void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Finds the next statistics waypoint after the given waypoint. * * @param waypoint a given waypoint * @return the next statistics waypoint, or null if none found. */ Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); /** * Updates the waypoint in the provider. * * @param waypoint * @return true if successful */ boolean updateWaypoint(Waypoint waypoint); /** * Finds the last recorded location from the location provider. * * @return the last location, or null if no locations available */ Location getLastLocation(); /** * Finds the first recorded waypoint for a given track from the location * provider. * This is a special waypoint that holds the stats for current segment. * * @param trackId the id of the track the waypoint belongs to * @return the first waypoint, or null if no waypoints available */ Waypoint getFirstWaypoint(long trackId); /** * Finds the given waypoint from the location provider. * * @param waypointId * @return the waypoint, or null if it does not exist */ Waypoint getWaypoint(long waypointId); /** * Finds the last recorded location id from the track points provider. * * @param trackId find last location on this track * @return the location id, or -1 if no locations available */ long getLastLocationId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getFirstWaypointId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getLastWaypointId(long trackId); /** * Finds the last recorded track from the track provider. * * @return the last track, or null if no tracks available */ Track getLastTrack(); /** * Finds the last recorded track id from the tracks provider. * * @return the track id, or -1 if no tracks available */ long getLastTrackId(); /** * Finds a location by given unique id. * * @param id the desired id * @return a Location object, or null if not found */ Location getLocation(long id); /** * Creates a cursor over the locations in the track points provider which * iterates over a given range of unique ids. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minTrackPointId the minimum id for the track points * @param maxLocations maximum number of locations retrieved * @param descending if true the results will be returned in descending id * order (latest location first) * @return A cursor over the selected range of locations */ Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending); /** * Creates a cursor over the waypoints of a track. * Caller owns the returned cursor and is responsible for closing it. * * @param trackId the id of the track for which to get the points * @param minWaypointId the minimum id for the track points * @param maxWaypoints the maximum number of waypoints to return * @return A cursor over the selected range of locations */ Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); /** * Creates a cursor over waypoints with the given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs arguments for the given selection * @param order the order in which to return results * @param maxWaypoints the maximum number of waypoints to return * @return a cursor of the selected waypoints */ Cursor getWaypointsCursor(String selection, String[] selectionArgs, String order, int maxWaypoints); /** * Finds a track by given unique track id. * Note that the returned track object does not have any track points attached. * Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load * the track points. * * @param id desired unique track id * @return a Track object, or null if not found */ Track getTrack(long id); /** * Retrieves all tracks without track points. If no tracks exist, an empty * list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} * to load the track points. * * @return a list of all the recorded tracks */ List<Track> getAllTracks(); /** * Creates a cursor over the tracks provider with a given selection. * Caller owns the returned cursor and is responsible for closing it. * * @param selection a given selection * @param selectionArgs parameters for the given selection * @param order the order to return results in * @return a cursor of the selected tracks */ Cursor getTracksCursor(String selection, String[] selectionArgs, String order); /** * Inserts a track in the tracks provider. * Note: This does not insert any track points. * Use {@link #insertTrackPoint(Location, long)} to insert them. * * @param track the track to insert * @return the content provider URI for the inserted track */ Uri insertTrack(Track track); /** * Inserts a track point in the tracks provider. * * @param location the location to insert * @return the content provider URI for the inserted track point */ Uri insertTrackPoint(Location location, long trackId); /** * Inserts multiple track points in a single operation. * * @param locations an array of locations to insert * @param length the number of locations (from the beginning of the array) * to actually insert, or -1 for all of them * @param trackId the ID of the track to insert the points into * @return the number of points inserted */ int bulkInsertTrackPoints(Location[] locations, int length, long trackId); /** * Inserts a waypoint in the provider. * * @param waypoint the waypoint to insert * @return the content provider URI for the inserted track */ Uri insertWaypoint(Waypoint waypoint); /** * Tests if a track with given id exists. * * @param id the unique id * @return true if track exists */ boolean trackExists(long id); /** * Updates a track in the content provider. * Note: This will not update any track points. * * @param track a given track */ void updateTrack(Track track); /** * Creates a Track object from a given cursor. * * @param cursor a cursor pointing at a db or provider with tracks * @return a new Track object */ Track createTrack(Cursor cursor); /** * Creates the ContentValues for a given Track object. * * Note: If the track has an id<0 the id column will not be filled. * * @param track a given track object * @return a filled in ContentValues object */ ContentValues createContentValues(Track track); /** * Creates a location object from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @return a new location object */ Location createLocation(Cursor cursor); /** * Fill a location object with values from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @param location a location object to be overwritten */ void fillLocation(Cursor cursor, Location location); /** * Creates a waypoint object from a given cursor. * * @param cursor a cursor pointing at a db or provider with waypoints. * @return a new waypoint object */ Waypoint createWaypoint(Cursor cursor); /** * A lightweight wrapper around the original {@link Cursor} with a method to clean up. */ interface LocationIterator extends Iterator<Location> { /** * Returns ID of the most recently retrieved track point through a call to {@link #next()}. * * @return the ID of the most recent track point ID. */ long getLocationId(); /** * Should be called in case the underlying iterator hasn't reached the last record. * Calling it if it has reached the last record is a no-op. */ void close(); } /** * A factory for creating new {@class Location}s. */ interface LocationFactory { /** * Creates a new {@link Location} object to be populated from the underlying database record. * It's up to the implementing class to decide whether to create a new instance or reuse * existing to optimize for speed. * * @return a {@link Location} to be populated from the database. */ Location createLocation(); } /** * The default {@class Location}s factory, which creates a new location of 'gps' type. */ LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() { @Override public Location createLocation() { return new Location("gps"); } }; /** * A location factory which uses two location instances (one for the current location, * and one for the previous), useful when we need to keep the last location. */ public class DoubleBufferedLocationFactory implements LocationFactory { private final Location locs[] = new MyTracksLocation[] { new MyTracksLocation("gps"), new MyTracksLocation("gps") }; private int lastLoc = 0; @Override public Location createLocation() { lastLoc = (lastLoc + 1) % locs.length; return locs[lastLoc]; } } /** * Creates a new read-only iterator over all track points for the given track. It provides * a lightweight way of iterating over long tracks without failing due to the underlying cursor * limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws * {@class UnsupportedOperationException}. * * Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so, * the iterator calls {@link LocationFactory#createLocation()} and populates it with information * retrieved from the record. * * When done with iteration, you must call {@link LocationIterator#close()} to make sure that all * resources are properly deallocated. * * Example use: * <code> * ... * LocationIterator it = providerUtils.getLocationIterator( * 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); * try { * for (Location loc : it) { * ... // Do something useful with the location. * } * } finally { * it.close(); * } * ... * </code> * * @param trackId the ID of a track to retrieve locations for. * @param startTrackPointId the ID of the first track point to load, or -1 to start from * the first point. * @param descending if true the results will be returned in descending ID * order (latest location first). * @param locationFactory the factory for creating new locations. * * @return the read-only iterator over the given track's points. */ LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); /** * A factory which can produce instances of {@link MyTracksProviderUtils}, * and can be overridden in tests (a.k.a. poor man's guice). */ public static class Factory { private static Factory instance = new Factory(); /** * Creates and returns an instance of {@link MyTracksProviderUtils} which * uses the given context to access its data. */ public static MyTracksProviderUtils get(Context context) { return instance.newForContext(context); } /** * Returns the global instance of this factory. */ public static Factory getInstance() { return instance; } /** * Overrides the global instance for this factory, to be used for testing. * If used, don't forget to set it back to the original value after the * test is run. */ public static void overrideInstance(Factory factory) { instance = factory; } /** * Creates an instance of {@link MyTracksProviderUtils}. */ protected MyTracksProviderUtils newForContext(Context context) { return new MyTracksProviderUtilsImpl(context.getContentResolver()); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import java.util.Vector; /** * An interface for an object that can generate descriptions of waypoints. * * @author Sandor Dornbush */ public interface DescriptionGenerator { /** * Generate a description of the waypoint. */ public String generateWaypointDescription(Waypoint waypoint); /** * Generates a description for a track (with information about the * statistics). * * @param track the track * @return a track description */ public String generateTrackDescription(Track track, Vector<Double> distances, Vector<Double> elevations); }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; /** * A way point. It has a location, meta data such as name, description, * category, and icon, plus it can store track statistics for a "sub-track". * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public final class Waypoint implements Parcelable { /** * Creator for a Waypoint object */ public static class Creator implements Parcelable.Creator<Waypoint> { public Waypoint createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Waypoint waypoint = new Waypoint(); waypoint.id = source.readLong(); waypoint.name = source.readString(); waypoint.description = source.readString(); waypoint.category = source.readString(); waypoint.icon = source.readString(); waypoint.trackId = source.readLong(); waypoint.type = source.readInt(); waypoint.startId = source.readLong(); waypoint.stopId = source.readLong(); byte hasStats = source.readByte(); if (hasStats > 0) { waypoint.stats = source.readParcelable(classLoader); } byte hasLocation = source.readByte(); if (hasLocation > 0) { waypoint.location = source.readParcelable(classLoader); } return waypoint; } public Waypoint[] newArray(int size) { return new Waypoint[size]; } } public static final Creator CREATOR = new Creator(); public static final int TYPE_WAYPOINT = 0; public static final int TYPE_STATISTICS = 1; private long id = -1; private String name = ""; private String description = ""; private String category = ""; private String icon = ""; private long trackId = -1; private int type = 0; private Location location; /** Start track point id */ private long startId = -1; /** Stop track point id */ private long stopId = -1; private TripStatistics stats; /** The length of the track, without smoothing. */ private double length; /** The total duration of the track (not from the last waypoint) */ private long duration; public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(category); dest.writeString(icon); dest.writeLong(trackId); dest.writeInt(type); dest.writeLong(startId); dest.writeLong(stopId); dest.writeByte(stats == null ? (byte) 0 : (byte) 1); if (stats != null) { dest.writeParcelable(stats, 0); } dest.writeByte(location == null ? (byte) 0 : (byte) 1); if (location != null) { dest.writeParcelable(location, 0); } } // Getters and setters: //--------------------- public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Location getLocation() { return location; } public void setTrackId(long trackId) { this.trackId = trackId; } public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTrackId() { return trackId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setLocation(Location location) { this.location = location; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } // WARNING: These fields are used for internal state keeping. You probably // want to look at getStatistics instead. public double getLength() { return length; } public void setLength(double length) { this.length = length; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; /** * A helper class that tracks a minimum and a maximum of a variable. * * @author Sandor Dornbush */ public class ExtremityMonitor { /** * The smallest value seen so far. */ private double min; /** * The largest value seen so far. */ private double max; public ExtremityMonitor() { reset(); } /** * Updates the min and the max with the new value. * * @param value the new value for the monitor * @return true if an extremity was found */ public boolean update(double value) { boolean changed = false; if (value < min) { min = value; changed = true; } if (value > max) { max = value; changed = true; } return changed; } /** * Gets the minimum value seen. * * @return The minimum value passed into the update() function */ public double getMin() { return min; } /** * Gets the maximum value seen. * * @return The maximum value passed into the update() function */ public double getMax() { return max; } /** * Resets this object to it's initial state where the min and max are unknown. */ public void reset() { min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; } /** * Sets the minimum and maximum values. */ public void set(double min, double max) { this.min = min; this.max = max; } /** * Sets the minimum value. */ public void setMin(double min) { this.min = min; } /** * Sets the maximum value. */ public void setMax(double max) { this.max = max; } public boolean hasData() { return min != Double.POSITIVE_INFINITY && max != Double.NEGATIVE_INFINITY; } @Override public String toString() { return "Min: " + min + " Max: " + max; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import android.os.Parcel; import android.os.Parcelable; /** * Statistical data about a trip. * The data in this class should be filled out by TripStatisticsBuilder. * * TODO: hashCode and equals * * @author Rodrigo Damazio */ public class TripStatistics implements Parcelable { /** * The start time for the trip. This is system time which might not match gps * time. */ private long startTime = -1L; /** * The stop time for the trip. This is the system time which might not match * gps time. */ private long stopTime = -1L; /** * The total time that we believe the user was traveling in milliseconds. */ private long movingTime; /** * The total time of the trip in milliseconds. * This is only updated when new points are received, so it may be stale. */ private long totalTime; /** * The total distance in meters that the user traveled on this trip. */ private double totalDistance; /** * The total elevation gained on this trip in meters. */ private double totalElevationGain; /** * The maximum speed in meters/second reported that we believe to be a valid * speed. */ private double maxSpeed; /** * The min and max latitude values seen in this trip. */ private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor(); /** * The min and max longitude values seen in this trip. */ private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor(); /** * The min and max elevation seen on this trip in meters. */ private final ExtremityMonitor elevationExtremities = new ExtremityMonitor(); /** * The minimum and maximum grade calculations on this trip. */ private final ExtremityMonitor gradeExtremities = new ExtremityMonitor(); /** * Default constructor. */ public TripStatistics() { } /** * Copy constructor. * * @param other another statistics data object to copy from */ public TripStatistics(TripStatistics other) { this.maxSpeed = other.maxSpeed; this.movingTime = other.movingTime; this.startTime = other.startTime; this.stopTime = other.stopTime; this.totalDistance = other.totalDistance; this.totalElevationGain = other.totalElevationGain; this.totalTime = other.totalTime; this.latitudeExtremities.set(other.latitudeExtremities.getMin(), other.latitudeExtremities.getMax()); this.longitudeExtremities.set(other.longitudeExtremities.getMin(), other.longitudeExtremities.getMax()); this.elevationExtremities.set(other.elevationExtremities.getMin(), other.elevationExtremities.getMax()); this.gradeExtremities.set(other.gradeExtremities.getMin(), other.gradeExtremities.getMax()); } /** * Combines these statistics with those from another object. * This assumes that the time periods covered by each do not intersect. * * @param other the other waypoint */ public void merge(TripStatistics other) { startTime = Math.min(startTime, other.startTime); stopTime = Math.max(stopTime, other.stopTime); totalTime += other.totalTime; movingTime += other.movingTime; totalDistance += other.totalDistance; totalElevationGain += other.totalElevationGain; maxSpeed = Math.max(maxSpeed, other.maxSpeed); latitudeExtremities.update(other.latitudeExtremities.getMax()); latitudeExtremities.update(other.latitudeExtremities.getMin()); longitudeExtremities.update(other.longitudeExtremities.getMax()); longitudeExtremities.update(other.longitudeExtremities.getMin()); elevationExtremities.update(other.elevationExtremities.getMax()); elevationExtremities.update(other.elevationExtremities.getMin()); gradeExtremities.update(other.gradeExtremities.getMax()); gradeExtremities.update(other.gradeExtremities.getMin()); } /** * Gets the time that this track started. * * @return The number of milliseconds since epoch to the time when this track * started */ public long getStartTime() { return startTime; } /** * Gets the time that this track stopped. * * @return The number of milliseconds since epoch to the time when this track * stopped */ public long getStopTime() { return stopTime; } /** * Gets the total time that this track has been active. * This statistic is only updated when a new point is added to the statistics, * so it may be off. If you need to calculate the proper total time, use * {@link #getStartTime} with the current time. * * @return The total number of milliseconds the track was active */ public long getTotalTime() { return totalTime; } /** * Gets the total distance the user traveled. * * @return The total distance traveled in meters */ public double getTotalDistance() { return totalDistance; } /** * Gets the the average speed the user traveled. * This calculation only takes into account the displacement until the last * point that was accounted for in statistics. * * @return The average speed in m/s */ public double getAverageSpeed() { if (totalTime == 0L) { return 0.0; } return totalDistance / ((double) totalTime / 1000.0); } /** * Gets the the average speed the user traveled when they were actively * moving. * * @return The average moving speed in m/s */ public double getAverageMovingSpeed() { if (movingTime == 0L) { return 0.0; } return totalDistance / ((double) movingTime / 1000.0); } /** * Gets the the maximum speed for this track. * * @return The maximum speed in m/s */ public double getMaxSpeed() { return maxSpeed; } /** * Gets the moving time. * * @return The total number of milliseconds the user was moving */ public long getMovingTime() { return movingTime; } /** * Gets the total elevation gain for this trip. This is calculated as the sum * of all positive differences in the smoothed elevation. * * @return The elevation gain in meters for this trip */ public double getTotalElevationGain() { return totalElevationGain; } /** * Returns the leftmost position (lowest longitude) of the track, in signed degrees. */ public double getLeftDegrees() { return longitudeExtremities.getMin(); } /** * Returns the leftmost position (lowest longitude) of the track, in signed millions of degrees. */ public int getLeft() { return (int) (longitudeExtremities.getMin() * 1E6); } /** * Returns the rightmost position (highest longitude) of the track, in signed degrees. */ public double getRightDegrees() { return longitudeExtremities.getMax(); } /** * Returns the rightmost position (highest longitude) of the track, in signed millions of degrees. */ public int getRight() { return (int) (longitudeExtremities.getMax() * 1E6); } /** * Returns the bottommost position (lowest latitude) of the track, in signed degrees. */ public double getBottomDegrees() { return latitudeExtremities.getMin(); } /** * Returns the bottommost position (lowest latitude) of the track, in signed millions of degrees. */ public int getBottom() { return (int) (latitudeExtremities.getMin() * 1E6); } /** * Returns the topmost position (highest latitude) of the track, in signed degrees. */ public double getTopDegrees() { return latitudeExtremities.getMax(); } /** * Returns the topmost position (highest latitude) of the track, in signed millions of degrees. */ public int getTop() { return (int) (latitudeExtremities.getMax() * 1E6); } /** * Returns the mean position (center latitude) of the track, in signed degrees. */ public double getMeanLatitude() { return (getBottomDegrees() + getTopDegrees()) / 2.0; } /** * Returns the mean position (center longitude) of the track, in signed degrees. */ public double getMeanLongitude() { return (getLeftDegrees() + getRightDegrees()) / 2.0; } /** * Gets the minimum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be more than the current elevation. * * @return The smallest elevation reading for this trip in meters */ public double getMinElevation() { return elevationExtremities.getMin(); } /** * Gets the maximum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be less than the current elevation. * * @return The largest elevation reading for this trip in meters */ public double getMaxElevation() { return elevationExtremities.getMax(); } /** * Gets the maximum grade for this trip. * * @return The maximum grade for this trip as a fraction */ public double getMaxGrade() { return gradeExtremities.getMax(); } /** * Gets the minimum grade for this trip. * * @return The minimum grade for this trip as a fraction */ public double getMinGrade() { return gradeExtremities.getMin(); } // Setters - to be used when restoring state or loading from the DB /** * Sets the start time for this trip. * * @param startTime the start time, in milliseconds since the epoch */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * Sets the stop time for this trip. * * @param stopTime the stop time, in milliseconds since the epoch */ public void setStopTime(long stopTime) { this.stopTime = stopTime; } /** * Sets the total moving time. * * @param movingTime the moving time in milliseconds */ public void setMovingTime(long movingTime) { this.movingTime = movingTime; } /** * Sets the total trip time. * * @param totalTime the total trip time in milliseconds */ public void setTotalTime(long totalTime) { this.totalTime = totalTime; } /** * Sets the total trip distance. * * @param totalDistance the trip distance in meters */ public void setTotalDistance(double totalDistance) { this.totalDistance = totalDistance; } /** * Sets the total elevation variation during the trip. * * @param totalElevationGain the elevation variation in meters */ public void setTotalElevationGain(double totalElevationGain) { this.totalElevationGain = totalElevationGain; } /** * Sets the maximum speed reached during the trip. * * @param maxSpeed the maximum speed in meters per second */ public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } /** * Sets the minimum elevation reached during the trip. * * @param elevation the minimum elevation in meters */ public void setMinElevation(double elevation) { elevationExtremities.setMin(elevation); } /** * Sets the maximum elevation reached during the trip. * * @param elevation the maximum elevation in meters */ public void setMaxElevation(double elevation) { elevationExtremities.setMax(elevation); } /** * Sets the minimum grade obtained during the trip. * * @param grade the grade as a fraction (-1.0 would mean vertical downwards) */ public void setMinGrade(double grade) { gradeExtremities.setMin(grade); } /** * Sets the maximum grade obtained during the trip). * * @param grade the grade as a fraction (1.0 would mean vertical upwards) */ public void setMaxGrade(double grade) { gradeExtremities.setMax(grade); } /** * Sets the bounding box for this trip. * The unit for all parameters is signed decimal degrees (degrees * 1E6). * * @param leftE6 the westmost longitude reached * @param topE6 the northmost latitude reached * @param rightE6 the eastmost longitude reached * @param bottomE6 the southmost latitude reached */ public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) { latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6); longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6); } // Data manipulation methods /** * Adds to the current total distance. * * @param distance the distance to add in meters */ void addTotalDistance(double distance) { totalDistance += distance; } /** * Adds to the total elevation variation. * * @param gain the elevation variation in meters */ void addTotalElevationGain(double gain) { totalElevationGain += gain; } /** * Adds to the total moving time of the trip. * * @param time the time in milliseconds */ void addMovingTime(long time) { movingTime += time; } /** * Accounts for a new latitude value for the bounding box. * * @param latitude the latitude value in signed decimal degrees */ void updateLatitudeExtremities(double latitude) { latitudeExtremities.update(latitude); } /** * Accounts for a new longitude value for the bounding box. * * @param longitude the longitude value in signed decimal degrees */ void updateLongitudeExtremities(double longitude) { longitudeExtremities.update(longitude); } /** * Accounts for a new elevation value for the bounding box. * * @param elevation the elevation value in meters */ void updateElevationExtremities(double elevation) { elevationExtremities.update(elevation); } /** * Accounts for a new grade value. * * @param grade the grade value as a fraction */ void updateGradeExtremities(double grade) { gradeExtremities.update(grade); } // String conversion @Override public String toString() { return "TripStatistics { Start Time: " + getStartTime() + "; Total Time: " + getTotalTime() + "; Moving Time: " + getMovingTime() + "; Total Distance: " + getTotalDistance() + "; Elevation Gain: " + getTotalElevationGain() + "; Min Elevation: " + getMinElevation() + "; Max Elevation: " + getMaxElevation() + "; Average Speed: " + getAverageMovingSpeed() + "; Min Grade: " + getMinGrade() + "; Max Grade: " + getMaxGrade() + "}"; } // Parcelable interface and creator /** * Creator of statistics data from parcels. */ public static class Creator implements Parcelable.Creator<TripStatistics> { @Override public TripStatistics createFromParcel(Parcel source) { TripStatistics data = new TripStatistics(); data.startTime = source.readLong(); data.movingTime = source.readLong(); data.totalTime = source.readLong(); data.totalDistance = source.readDouble(); data.totalElevationGain = source.readDouble(); data.maxSpeed = source.readDouble(); double minLat = source.readDouble(); double maxLat = source.readDouble(); data.latitudeExtremities.set(minLat, maxLat); double minLong = source.readDouble(); double maxLong = source.readDouble(); data.longitudeExtremities.set(minLong, maxLong); double minElev = source.readDouble(); double maxElev = source.readDouble(); data.elevationExtremities.set(minElev, maxElev); double minGrade = source.readDouble(); double maxGrade = source.readDouble(); data.gradeExtremities.set(minGrade, maxGrade); return data; } @Override public TripStatistics[] newArray(int size) { return new TripStatistics[size]; } } /** * Creator of {@link TripStatistics} from parcels. */ public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startTime); dest.writeLong(movingTime); dest.writeLong(totalTime); dest.writeDouble(totalDistance); dest.writeDouble(totalElevationGain); dest.writeDouble(maxSpeed); dest.writeDouble(latitudeExtremities.getMin()); dest.writeDouble(latitudeExtremities.getMax()); dest.writeDouble(longitudeExtremities.getMin()); dest.writeDouble(longitudeExtremities.getMax()); dest.writeDouble(elevationExtremities.getMin()); dest.writeDouble(elevationExtremities.getMax()); dest.writeDouble(gradeExtremities.getMin()); dest.writeDouble(gradeExtremities.getMax()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.lib; /** * Constants for the My Tracks common library. * These constants should ideally not be used by third-party applications. * * @author Rodrigo Damazio */ public class MyTracksLibConstants { public static final String TAG = "MyTracksLib"; private MyTracksLibConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.samples.api; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * A receiver to receive MyTracks notifications. * * @author Jimmy Shih */ public class MyTracksReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); long trackId = intent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L); Toast.makeText(context, action + " " + trackId, Toast.LENGTH_LONG).show(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.samples.api; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.ITrackRecordingService; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Calendar; import java.util.List; /** * An activity to access MyTracks content provider and service. * * Note you must first install MyTracks before installing this app. * * You also need to enable third party application access inside MyTracks * MyTracks -> menu -> Settings -> Sharing -> Allow access * * @author Jimmy Shih */ public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); // utils to access the MyTracks content provider private MyTracksProviderUtils myTracksProviderUtils; // display output from the MyTracks content provider private TextView outputTextView; // MyTracks service private ITrackRecordingService myTracksService; // intent to access the MyTracks service private Intent intent; // connection to the MyTracks service private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { myTracksService = ITrackRecordingService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName className) { myTracksService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // for the MyTracks content provider myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); outputTextView = (TextView) findViewById(R.id.output); Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button); addWaypointsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Track> tracks = myTracksProviderUtils.getAllTracks(); Calendar now = Calendar.getInstance(); for (Track track : tracks) { Waypoint waypoint = new Waypoint(); waypoint.setTrackId(track.getId()); waypoint.setName(now.getTime().toLocaleString()); waypoint.setDescription(now.getTime().toLocaleString()); myTracksProviderUtils.insertWaypoint(waypoint); } } }); // for the MyTracks service intent = new Intent(); ComponentName componentName = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); intent.setComponent(componentName); Button startRecordingButton = (Button) findViewById(R.id.start_recording_button); startRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.startNewTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button); stopRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.endCurrentTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); } @Override protected void onStart() { super.onStart(); // use the MyTracks content provider to get all the tracks List<Track> tracks = myTracksProviderUtils.getAllTracks(); for (Track track : tracks) { outputTextView.append(track.getId() + " "); } // start and bind the MyTracks service startService(intent); bindService(intent, serviceConnection, 0); } @Override protected void onStop() { super.onStop(); // unbind and stop the MyTracks service if (myTracksService != null) { unbindService(serviceConnection); } stopService(intent); } }
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.bigtext; /** * 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
package ru.gelin.android.weather.notification.skin.bigtext; /** * This formatter displays "+" sign for positive temperature. */ public class TemperatureFormat extends ru.gelin.android.weather.notification.skin.impl.TemperatureFormat { protected String signedValue(int value) { if (value > 0) { return "+" + value; } else { return String.valueOf(value); } } }
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.skin.bigtext; import android.app.Notification; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; 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.notification.WeatherStorage; import ru.gelin.android.weather.notification.skin.Tag; import ru.gelin.android.weather.notification.skin.impl.*; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.STRING; /** * Extends the basic notification receiver. * Displays multiple notifications for each temperature character. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Initial notification ID */ static final int INITIAL_ID = 1; /** Max notification ID */ static final int MAX_ID = INITIAL_ID + 5; @Override protected void cancel(Context context) { Log.d(Tag.TAG, "cancelling weather"); cancelAll(context); } void cancelAll(Context context) { NotificationManager manager = getNotificationManager(context); for (int id = INITIAL_ID; id < MAX_ID; id++) { manager.cancel(id); } } @Override protected void notify(Context context, Weather weather) { Log.d(Tag.TAG, "displaying weather: " + weather); WeatherStorage storage = new WeatherStorage(context); storage.save(weather); cancelAll(context); if (weather.isEmpty() || weather.getConditions().size() <= 0) { unknownWeatherNotify(context, weather); } else { String temperature = getTemperatureText(context, weather); mainNotify(context, weather, temperature.charAt(0)); //TODO refactor passing of multiple parameters for (int i = temperature.length() - 1; i >= 0; i--) { notify(context, weather, INITIAL_ID + i, temperature.charAt(i)); } } notifyHandler(weather); } String getTemperatureText(Context context, Weather weather) { NotificationStyler styler = createStyler(context); TemperatureType type = styler.getTempType(); TemperatureFormat format = createTemperatureFormat(); WeatherCondition condition = weather.getConditions().get(0); switch (type) { case C: case CF: return format.format(condition.getTemperature(TemperatureUnit.C).getCurrent()); case F: case FC: return format.format(condition.getTemperature(TemperatureUnit.F).getCurrent()); default: return ""; //should never happen } } void unknownWeatherNotify(Context context, Weather weather) { ResourceIdFactory ids = ResourceIdFactory.getInstance(context); Notification notification = createFullNotification(context, weather); notification.tickerText = context.getString(ids.id(STRING, "unknown_weather")); getNotificationManager(context).notify(INITIAL_ID, notification); } void mainNotify(Context context, Weather weather, char c) { Notification notification = createFullNotification(context, weather); notification.iconLevel = getNotificationIconLevel(c); getNotificationManager(context).notify(INITIAL_ID, notification); } void notify(Context context, Weather weather, int id, char c) { Notification notification = createNotification(context, weather); notification.contentView = new RemoteViews(context.getPackageName(), R.layout.notification_empty); notification.iconLevel = getNotificationIconLevel(c); getNotificationManager(context).notify(id, notification); } Notification createNotification(Context context, Weather weather) { Notification notification = new Notification(); notification.icon = getNotificationIconId(weather); notification.when = weather.getTime().getTime(); notification.contentIntent = getContentIntent(context); notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_ONGOING_EVENT; return notification; } Notification createFullNotification(Context context, Weather weather) { Notification notification = createNotification(context, weather); NotificationStyler styler = createStyler(context); TemperatureType tempType = styler.getTempType(); notification.tickerText = formatTicker(context, weather, tempType); notification.contentView = new RemoteViews(context.getPackageName(), styler.getLayoutId()); RemoteWeatherLayout layout = getRemoteWeatherLayout(context, notification.contentView, styler); layout.bind(weather); //notification.contentIntent = getMainActivityPendingIntent(context); return notification; } @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.char_white; //TODO other colors } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return 0; //TODO refactor } protected int getNotificationIconLevel(char c) { return (int)c; } @Override protected TemperatureFormat createTemperatureFormat() { return new TemperatureFormat(); } }
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.bigtext; 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.skin.blacktext; /** * 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 */ package ru.gelin.android.weather.notification.skin.blacktext; import android.content.ComponentName; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Icon level shift relative to temp value */ static final int ICON_LEVEL_SHIFT = 100; @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.temp_icon_black; } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return weather.getConditions().get(0). getTemperature(unit).getCurrent() + ICON_LEVEL_SHIFT; } }
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.blacktext; 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.skin.blacktextplus; import android.content.Context; import android.view.View; import ru.gelin.android.weather.Weather; /** * Utility to layout weather values to view. */ public class WeatherLayout extends ru.gelin.android.weather.notification.skin.impl.WeatherLayout { public WeatherLayout(Context context, View view) { super(context, view); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.blacktextplus; import android.content.Context; import android.widget.RemoteViews; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.NotificationStyler; /** * Utility to layout weather values to remove view. */ public class RemoteWeatherLayout extends ru.gelin.android.weather.notification.skin.impl.RemoteWeatherLayout { /** * Creates the utility for specified context. */ public RemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { super(context, views, styler); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.blacktextplus; /** * 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
package ru.gelin.android.weather.notification.skin.blacktextplus; /** * This formatter displays "+" sign for positive temperature. */ public class TemperatureFormat extends ru.gelin.android.weather.notification.skin.impl.TemperatureFormat { @Override protected String signedValue(int value) { if (value > 0) { return "+" + value; } else { return String.valueOf(value); } } }
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.blacktextplus; import android.content.ComponentName; import android.content.Context; import android.widget.RemoteViews; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; import ru.gelin.android.weather.notification.skin.impl.NotificationStyler; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Icon level shift relative to temp value */ static final int ICON_LEVEL_SHIFT = 100; @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.temp_icon_black; } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return weather.getConditions().get(0). getTemperature(unit).getCurrent() + ICON_LEVEL_SHIFT; } @Override protected RemoteWeatherLayout getRemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { return new RemoteWeatherLayout(context, views, styler); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.blacktextplus; import android.content.Context; import android.view.View; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherInfoActivity; /** * Extends the basic weather info activity. * Overrides weather layout to render temp values with "+" sign. */ public class WeatherInfoActivity extends BaseWeatherInfoActivity { protected WeatherLayout createWeatherLayout(Context context, View view) { return new WeatherLayout(context, view); } }
Java
package ru.gelin.android.weather.notification.skin.blacktextplus; import android.content.Context; import ru.gelin.android.weather.Weather; /** * A special class to format weather. */ public class WeatherFormatter extends ru.gelin.android.weather.notification.skin.impl.WeatherFormatter { public WeatherFormatter(Context context, Weather weather) { super(context, weather); } @Override protected TemperatureFormat getTemperatureFormat() { return new TemperatureFormat(); } }
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.v11; import android.app.Notification; import android.content.ComponentName; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; import ru.gelin.android.weather.notification.skin.impl.WeatherNotificationReceiver; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends WeatherNotificationReceiver { /** Notification ID */ static final int ID = 1; @Override protected void notify(Context context, Weather weather) { Notification notification = new Notification.Builder(context). setContentTitle("Weather"). setSmallIcon(R.drawable.status_icon). setLargeIcon(getLargeIcon(context)). getNotification(); getNotificationManager(context).notify(ID, notification); } @Override protected void cancel(Context context) { getNotificationManager(context).cancel(ID); } Bitmap getLargeIcon(Context context) { Resources res = context.getResources(); Bitmap bitmap = Bitmap.createBitmap( res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setARGB(255, 255, 0, 0); canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 3, paint); return bitmap; } }
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.whitetextplus; import android.content.Context; import android.view.View; import ru.gelin.android.weather.Weather; /** * Utility to layout weather values to view. */ public class WeatherLayout extends ru.gelin.android.weather.notification.skin.impl.WeatherLayout { public WeatherLayout(Context context, View view) { super(context, view); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.whitetextplus; import android.content.Context; import android.widget.RemoteViews; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.NotificationStyler; /** * Utility to layout weather values to remove view. */ public class RemoteWeatherLayout extends ru.gelin.android.weather.notification.skin.impl.RemoteWeatherLayout { /** * Creates the utility for specified context. */ public RemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { super(context, views, styler); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.whitetextplus; /** * 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
package ru.gelin.android.weather.notification.skin.whitetextplus; /** * This formatter displays "+" sign for positive temperature. */ public class TemperatureFormat extends ru.gelin.android.weather.notification.skin.impl.TemperatureFormat { @Override protected String signedValue(int value) { if (value > 0) { return "+" + value; } else { return String.valueOf(value); } } }
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.whitetextplus; import android.content.ComponentName; import android.content.Context; import android.widget.RemoteViews; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; import ru.gelin.android.weather.notification.skin.impl.NotificationStyler; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Icon level shift relative to temp value */ static final int ICON_LEVEL_SHIFT = 100; @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.temp_icon_white; } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return weather.getConditions().get(0). getTemperature(unit).getCurrent() + ICON_LEVEL_SHIFT; } @Override protected RemoteWeatherLayout getRemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { return new RemoteWeatherLayout(context, views, styler); } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.whitetextplus; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherInfoActivity; import android.content.Context; import android.view.View; /** * Extends the basic weather info activity. * Overrides weather layout to render temp values with "+" sign. */ public class WeatherInfoActivity extends BaseWeatherInfoActivity { protected WeatherLayout createWeatherLayout(Context context, View view) { return new WeatherLayout(context, view); } }
Java
package ru.gelin.android.weather.notification.skin.whitetextplus; import android.content.Context; import ru.gelin.android.weather.Weather; /** * A special weather formatter. */ public class WeatherFormatter extends ru.gelin.android.weather.notification.skin.impl.WeatherFormatter { public WeatherFormatter(Context context, Weather weather) { super(context, weather); } @Override protected TemperatureFormat getTemperatureFormat() { return new TemperatureFormat(); } }
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.biggertext; /** * 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 */ package ru.gelin.android.weather.notification.skin.biggertext; import android.content.ComponentName; import android.content.Context; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Icon level shift relative to temp value */ static final int ICON_LEVEL_SHIFT = 100; @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.temp_icon_light; } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return weather.getConditions().get(0). getTemperature(unit).getCurrent() + ICON_LEVEL_SHIFT; } @Override protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.biggertext; 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
package ru.gelin.android.weather.notification.skin.biggertext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.WeatherCondition; import ru.gelin.android.weather.notification.skin.impl.Drawable2Bitmap; public class WeatherFormatter extends ru.gelin.android.weather.notification.skin.impl.WeatherFormatter { public WeatherFormatter(Context context, Weather weather) { super(context, weather); } @Override protected Bitmap formatLargeIcon() { WeatherCondition condition = getWeather().getConditions().get(0); Drawable drawable = getContext().getResources().getDrawable(R.drawable.temp_icon_light); drawable.setLevel(condition.getTemperature(getStyler().getTempType().getTemperatureUnit()).getCurrent() + SkinWeatherNotificationReceiver.ICON_LEVEL_SHIFT); return Drawable2Bitmap.convert(drawable); } }
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.whitetext; /** * 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 */ package ru.gelin.android.weather.notification.skin.whitetext; import android.content.ComponentName; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.notification.skin.impl.BaseWeatherNotificationReceiver; /** * Extends the basic notification receiver. * Overwrites the weather info activity intent and getting of the icon resource. */ public class SkinWeatherNotificationReceiver extends BaseWeatherNotificationReceiver { /** Icon level shift relative to temp value */ static final int ICON_LEVEL_SHIFT = 100; @Override protected ComponentName getWeatherInfoActivityComponentName() { return new ComponentName(SkinWeatherNotificationReceiver.class.getPackage().getName(), WeatherInfoActivity.class.getName()); } @Override protected int getNotificationIconId(Weather weather) { return R.drawable.temp_icon_white; } @Override protected int getNotificationIconLevel(Weather weather, TemperatureUnit unit) { return weather.getConditions().get(0). getTemperature(unit).getCurrent() + ICON_LEVEL_SHIFT; } }
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.whitetext; 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
/* * 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; /** * Holds cloudiness value. * Allows to set the value in different units. */ public class SimpleCloudiness implements Cloudiness { CloudinessUnit unit; int cloudiness = UNKNOWN; public SimpleCloudiness(CloudinessUnit unit) { this.unit = unit; } /** * Sets the cloudiness value in specified unit system. */ public void setValue(int cloudiness, CloudinessUnit unit) { if (cloudiness == UNKNOWN) { this.cloudiness = UNKNOWN; return; } this.cloudiness = convertValue(cloudiness, unit); } public int getValue() { return this.cloudiness; } public CloudinessUnit getCloudinessUnit() { return this.unit; } @Override public String getText() { StringBuilder result = new StringBuilder(); result.append("Cloudiness: "); if (getValue() == UNKNOWN) { result.append("unknown"); return result.toString(); } result.append(getValue()); result.append(getCloudinessUnit().getText()); return result.toString(); } public SimpleCloudiness convert(CloudinessUnit unit) { SimpleCloudiness result = new SimpleCloudiness(unit); result.setValue(this.getValue(), this.getCloudinessUnit()); return result; } /** * Converts the value from provided unit system into this unit system. */ protected int convertValue(int value, CloudinessUnit unit) { if (this.unit.equals(unit)) { return value; } if (CloudinessUnit.PERCENT.equals(unit) && CloudinessUnit.OKTA.equals(this.unit)) { return (int)Math.round(8.0 / 100 * value); } else if (CloudinessUnit.OKTA.equals(unit) && CloudinessUnit.PERCENT.equals(this.unit)) { return (int)(100 / 8.0 * value); } return value; } @Override public String toString() { return this.getClass().getName() + " unit: " + this.getCloudinessUnit() + " value: " + this.getValue(); } }
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; //import java.net.URL; import java.util.Set; /** * 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. * Default unit depends on the weather source. * Any unit conversions loses precision, so the default units are useful when cloning/copying the weather. */ Temperature getTemperature(); /** * Returns the temperature in specified units. */ @Deprecated Temperature getTemperature(UnitSystem units); /** * Returns the temperature in specified units. */ Temperature getTemperature(TemperatureUnit unit); /** * Returns humidity as a human readable text. * Can return null. */ @Deprecated String getHumidityText(); /** * Returns wind conditions as a human readable text. * Can return null. */ @Deprecated String getWindText(); /** * Returns humidity. */ Humidity getHumidity(); /** * Returns wind in default units. * Default unit depends on the weather source. * Any unit conversions loses precision, so the default units are useful when cloning/copying the weather. */ Wind getWind(); /** * Returns wind in specified units. */ Wind getWind(WindSpeedUnit unit); /** * Returns cloudiness in default units. * Default unit depends on the weather source. * Any unit conversions loses precision, so the default units are useful when cloning/copying the weather. */ Cloudiness getCloudiness(); /** * Returns cloudiness in specified units. */ Cloudiness getCloudiness(CloudinessUnit unit); /** * Returns precipitation value available for this weather condition. */ Precipitation getPrecipitation(); /** * Returns the set of weather condition types. * The returned set is unmodifiable. */ Set<WeatherConditionType> getConditionTypes(); }
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; /** * Holds temperature values. * Allows to set the values in different units. * 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 { TemperatureUnit tunit; int current = UNKNOWN; int low = UNKNOWN; int high = UNKNOWN; @Deprecated public SimpleTemperature(UnitSystem unit) { this.tunit = TemperatureUnit.valueOf(unit); } public SimpleTemperature(TemperatureUnit unit) { this.tunit = unit; } /** * Sets the current temperature in specified unit system. */ @Deprecated public void setCurrent(int temp, UnitSystem unit) { setCurrent(temp, TemperatureUnit.valueOf(unit)); } /** * Sets the low temperature in specified unit system. */ @Deprecated public void setLow(int temp, UnitSystem unit) { setLow(temp, TemperatureUnit.valueOf(unit)); } /** * Sets the high temperature in specified unit system. */ @Deprecated public void setHigh(int temp, UnitSystem unit) { setHigh(temp, TemperatureUnit.valueOf(unit)); } /** * Sets the current temperature in specified unit system. */ public void setCurrent(int temp, TemperatureUnit unit) { if (temp == UNKNOWN) { this.current = UNKNOWN; return; } this.current = convertValue(temp, unit); } /** * Sets the low temperature in specified unit system. */ public void setLow(int temp, TemperatureUnit unit) { if (temp == UNKNOWN) { this.low = UNKNOWN; return; } this.low = convertValue(temp, unit); } /** * Sets the high temperature in specified unit system. */ public void setHigh(int temp, TemperatureUnit unit) { if (temp == UNKNOWN) { this.high = UNKNOWN; return; } this.high = convertValue(temp, unit); } //@Override public int getCurrent() { if (this.current == UNKNOWN) { if (getLow() == UNKNOWN || getHigh() == UNKNOWN) { return 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 @Deprecated public UnitSystem getUnitSystem() { switch (this.tunit) { case C: return UnitSystem.SI; case F: return UnitSystem.US; } return UnitSystem.SI; } //@Override public TemperatureUnit getTemperatureUnit() { return this.tunit; } /** * Creates new temperature in another unit system. */ @Deprecated public SimpleTemperature convert(UnitSystem unit) { return convert(TemperatureUnit.valueOf(unit)); } public SimpleTemperature convert(TemperatureUnit unit) { SimpleTemperature result = new SimpleTemperature(unit); result.setCurrent(this.getCurrent(), this.getTemperatureUnit()); result.setLow(this.getLow(), this.getTemperatureUnit()); result.setHigh(this.getHigh(), this.getTemperatureUnit()); return result; } /** * Converts the value from provided unit system into this temperature set unit system. */ protected int convertValue(int value, TemperatureUnit unit) { if (this.tunit.equals(unit)) { return value; } switch (unit) { case C: switch (this.tunit) { case F: return Math.round(value * 9f / 5f + 32); //C -> F case K: return Math.round(value + 273.15f); //C -> K } case F: switch (this.tunit) { case C: return Math.round((value - 32) * 5f / 9f); //F -> C case K: return Math.round((value - 32) * 5f / 9f + 273.15f); //F -> K } case K: switch (this.tunit) { case C: return Math.round(value - 273.15f); //K -> C case F: return Math.round((value - 273.15f) * 9f / 5f + 32); //K -> F } } return value; } @Override public String toString() { return this.getClass().getName() + " unit: " + this.getTemperatureUnit() + " current: " + this.getCurrent() + " high: " + this.getHigh() + " low: " + this.getLow(); } }
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; public interface Humidity { /** Unknown humidity value */ static int UNKNOWN = Integer.MIN_VALUE; /** * Current humidity. */ int getValue(); /** * Returns humidity as a human readable text. * Can return null. */ String getText(); }
Java
package ru.gelin.android.weather; /** * Supported cloudiness units. */ public enum CloudinessUnit { PERCENT("%"), OKTA(" oktas"); String text = ""; CloudinessUnit(String text) { this.text = text; } public String getText() { return this.text; } }
Java
/* * Weather API. * Copyright (C) 2012 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; /** * Holds precipitation value. */ public interface Precipitation { /** Unknown precipitation value */ static float UNKNOWN = Float.MIN_VALUE; /** * Returns general precipitation value for the period. */ float getValue(PrecipitationPeriod period); /** * Precipitation unit for this instance. */ PrecipitationUnit getPrecipitationUnit(); /** * Returns precipitation value as a human readable text. * Can return null. */ String getText(); }
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; /** * 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. */ @Deprecated UnitSystem getUnitSystem(); /** * Units of this weather. */ TemperatureUnit getTemperatureUnit(); }
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; 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, Vladimir Kubyshed * * 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.net.URL; 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 the time when the weather was requested. * May differ from the weather timestamp. */ Date getQueryTime(); /** * Returns default unit system (SI or US). */ @Deprecated 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(); /** * Returns the URL to be opened in browser to display more detailed forecast. * @return the URL or null */ URL getForecastURL(); }
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; public enum WindSpeedUnit { MPH, KMPH, MPS; }
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; /** * Simple location which query and text are equal and are set in constructor. */ public class SimpleLocation implements Location { String text; boolean geo; /** * Creates the location. * Geo is false here. * @param locationText query and the text value. */ public SimpleLocation(String text) { this(text, false); } /** * Creates the location. * @param locationText query and the text value. * @param geo flag */ public SimpleLocation(String text, boolean geo) { this.text = text; this.geo = geo; } //@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; } @Override public boolean isGeo() { return this.geo; } }
Java
package ru.gelin.android.weather; /** * Weather condition type priorities. */ class WeatherConditionTypePriority { static final int EXTREME_PRIORITY = 6; static final int THUNDERSTORM_PRIORITY = 5; static final int RAIN_PRIORITY = 4; static final int SNOW_PRIORITY = 3; static final int DRIZZLE_PRIORITY = 2; static final int ATMOSPHERE_PRIORITY = 1; static final int CLOUDS_PRIORITY = 0; private WeatherConditionTypePriority() { //avoid instantiation } }
Java
package ru.gelin.android.weather; /** * Supported precipitation units. */ public enum PrecipitationUnit { MM; }
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; public interface Wind { /** Unknown wind speed value */ static int UNKNOWN = Integer.MIN_VALUE; /** * Returns wind direction. */ WindDirection getDirection(); /** * Returns wind speed. */ int getSpeed(); /** * Wind speed units for this instance. */ WindSpeedUnit getSpeedUnit(); /** * Returns wind conditions as a human readable text. * Can return null. */ String getText(); }
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; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; /** * Simple weather realization. Holds only one temperature value. Used for tests. */ public class TestWeather implements Weather { /** Location */ Location location = new SimpleLocation("Test location"); /** Time */ Date time = new Date(); /** List of conditions */ List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); public TestWeather(int temperature) { this.conditions.add(createCondition(temperature)); this.conditions.add(createCondition(temperature)); this.conditions.add(createCondition(temperature)); this.conditions.add(createCondition(temperature)); } SimpleWeatherCondition createCondition(int temp) { SimpleWeatherCondition condition = new SimpleWeatherCondition(); SimpleTemperature temperature = new SimpleTemperature(TemperatureUnit.C); temperature.setCurrent(temp, TemperatureUnit.C); condition.setTemperature(temperature); SimpleHumidity humidity = new SimpleHumidity(); humidity.setValue(0); condition.setHumidity(humidity); SimpleWind wind = new SimpleWind(WindSpeedUnit.MPS); condition.setWind(wind); condition.setConditionText("Test weather"); return condition; } //@Override public Location getLocation() { return this.location; } //@Override public Date getTime() { return this.time; } public Date getQueryTime() { return this.time; } //@Override @Deprecated public UnitSystem getUnitSystem() { return UnitSystem.SI; } //@Override public List<WeatherCondition> getConditions() { return Collections.unmodifiableList(new ArrayList<WeatherCondition>(this.conditions)); } //@Override public boolean isEmpty() { return false; } public URL getForecastURL() { return null; } }
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; public enum TemperatureUnit { C, F, K; //K /** * Converts deprecated UnitSystem to new TemperatureUnit. */ @SuppressWarnings("deprecation") public static TemperatureUnit valueOf(UnitSystem unitSystem) { switch (unitSystem) { case SI: return TemperatureUnit.C; case US: return TemperatureUnit.F; } return TemperatureUnit.C; } }
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; 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; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import ru.gelin.android.weather.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import static ru.gelin.android.weather.notification.WeatherStorageKeys.*; /** * Stores and retrieves the weather objects to SharedPreferences. * The exact classes of the retrieved Weather can differ from the classes * of the saved weather. */ @SuppressWarnings("deprecation") 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.putLong(QUERY_TIME, weather.getQueryTime().getTime()); if (weather.getForecastURL() == null) { editor.remove(FORECAST_URL); } else { editor.putString(FORECAST_URL, String.valueOf(weather.getForecastURL())); } if (weather.getUnitSystem() == null) { editor.remove(UNIT_SYSTEM); } else { editor.putString(UNIT_SYSTEM, weather.getUnitSystem().toString()); } int i = 0; for (WeatherCondition condition : weather.getConditions()) { ConditionPreferencesEditor conditionEditor = new ConditionPreferencesEditor(editor, i); conditionEditor.putOrRemove(CONDITION_TEXT, condition.getConditionText()); conditionEditor.putOrRemove(CONDITION_TYPES, condition.getConditionTypes()); Temperature temp = condition.getTemperature(); conditionEditor.putOrRemove(TEMPERATURE_UNIT, temp.getTemperatureUnit()); conditionEditor.putOrRemove(CURRENT_TEMP, temp.getCurrent()); conditionEditor.putOrRemove(LOW_TEMP, temp.getLow()); conditionEditor.putOrRemove(HIGH_TEMP, temp.getHigh()); Humidity hum = condition.getHumidity(); conditionEditor.putOrRemove(HUMIDITY_VALUE, hum.getValue()); conditionEditor.putOrRemove(HUMIDITY_TEXT, hum.getText()); Wind wind = condition.getWind(); conditionEditor.putOrRemove(WIND_SPEED_UNIT, wind.getSpeedUnit()); conditionEditor.putOrRemove(WIND_SPEED, wind.getSpeed()); conditionEditor.putOrRemove(WIND_DIR, wind.getDirection()); conditionEditor.putOrRemove(WIND_TEXT, wind.getText()); Cloudiness cloudiness = condition.getCloudiness(); if (cloudiness == null) { conditionEditor.remove(CLOUDINESS_UNIT); conditionEditor.remove(CLOUDINESS_VALUE); } else { conditionEditor.putOrRemove(CLOUDINESS_UNIT, cloudiness.getCloudinessUnit()); conditionEditor.putOrRemove(CLOUDINESS_VALUE, cloudiness.getValue()); } Precipitation precipitation = condition.getPrecipitation(); if (precipitation == null) { conditionEditor.remove(PRECIPITATION_UNIT); conditionEditor.remove(PRECIPITATION_PERIOD); conditionEditor.remove(PRECIPITATION_VALUE); } else { conditionEditor.putOrRemove(PRECIPITATION_UNIT, precipitation.getPrecipitationUnit()); conditionEditor.putOrRemove(PRECIPITATION_PERIOD, PrecipitationPeriod.PERIOD_1H.getHours()); conditionEditor.putOrRemove(PRECIPITATION_VALUE, precipitation.getValue(PrecipitationPeriod.PERIOD_1H)); } i++; } for (; i < 4; i++) { ConditionPreferencesEditor conditionEditor = new ConditionPreferencesEditor(editor, i); conditionEditor.remove(CONDITION_TEXT); conditionEditor.remove(CONDITION_TYPES, 0); conditionEditor.remove(TEMPERATURE_UNIT); conditionEditor.remove(CURRENT_TEMP); conditionEditor.remove(LOW_TEMP); conditionEditor.remove(HIGH_TEMP); conditionEditor.remove(HUMIDITY_VALUE); conditionEditor.remove(HUMIDITY_TEXT); conditionEditor.remove(WIND_SPEED_UNIT); conditionEditor.remove(WIND_SPEED); conditionEditor.remove(WIND_DIR); conditionEditor.remove(WIND_TEXT); conditionEditor.remove(CLOUDINESS_UNIT); conditionEditor.remove(CLOUDINESS_VALUE); conditionEditor.remove(PRECIPITATION_UNIT); conditionEditor.remove(PRECIPITATION_PERIOD); conditionEditor.remove(PRECIPITATION_VALUE); } editor.commit(); } /** * Loads the weather. * The values of the saved weather are restored, not exact classes. */ public Weather load() { SimpleWeather weather = new ParcelableWeather2(); Location location = new SimpleLocation( preferences.getString(LOCATION, "")); weather.setLocation(location); weather.setTime(new Date(preferences.getLong(TIME, 0))); weather.setQueryTime(new Date(preferences.getLong(QUERY_TIME, System.currentTimeMillis()))); try { weather.setForecastURL(new URL(preferences.getString(FORECAST_URL, ""))); } catch (MalformedURLException e) { weather.setForecastURL(null); } int i = 0; List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(); while (preferences.contains(String.format(CONDITION_TEXT, i))) { ConditionPreferencesReader conditionReader = new ConditionPreferencesReader(preferences, i); SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.setConditionText(conditionReader.get(CONDITION_TEXT, "")); Collection<WeatherConditionType> types = conditionReader.getEnums(CONDITION_TYPES, WeatherConditionType.class); for (WeatherConditionType type : types) { condition.addConditionType(type); } TemperatureUnit tunit = conditionReader.get(TEMPERATURE_UNIT, TemperatureUnit.F); SimpleTemperature temp = new SimpleTemperature(tunit); temp.setCurrent(conditionReader.get(CURRENT_TEMP, Temperature.UNKNOWN), tunit); temp.setLow(conditionReader.get(LOW_TEMP, Temperature.UNKNOWN), tunit); temp.setHigh(conditionReader.get(HIGH_TEMP, Temperature.UNKNOWN), tunit); condition.setTemperature(temp); SimpleHumidity hum = new SimpleHumidity(); hum.setValue(conditionReader.get(HUMIDITY_VALUE, Humidity.UNKNOWN)); hum.setText(conditionReader.get(HUMIDITY_TEXT, "")); condition.setHumidity(hum); WindSpeedUnit windSpeedUnit = conditionReader.get(WIND_SPEED_UNIT, WindSpeedUnit.MPH); SimpleWind wind = new SimpleWind(windSpeedUnit); wind.setSpeed(conditionReader.get(WIND_SPEED, Wind.UNKNOWN), windSpeedUnit); wind.setDirection(conditionReader.get(WIND_DIR, WindDirection.N)); wind.setText(conditionReader.get(WIND_TEXT, "")); condition.setWind(wind); CloudinessUnit cloudinessUnit = conditionReader.get(CLOUDINESS_UNIT, CloudinessUnit.OKTA); SimpleCloudiness cloudiness = new SimpleCloudiness(cloudinessUnit); cloudiness.setValue(conditionReader.get(CLOUDINESS_VALUE, Cloudiness.UNKNOWN), cloudinessUnit); condition.setCloudiness(cloudiness); PrecipitationUnit precipitationUnit = conditionReader.get(PRECIPITATION_UNIT, PrecipitationUnit.MM); SimplePrecipitation precipitation = new SimplePrecipitation(precipitationUnit); PrecipitationPeriod precipitationPeriod = PrecipitationPeriod.valueOf( conditionReader.get(PRECIPITATION_PERIOD, PrecipitationPeriod.PERIOD_1H.getHours())); precipitation.setValue(conditionReader.get(PRECIPITATION_VALUE, Precipitation.UNKNOWN), precipitationPeriod); condition.setPrecipitation(precipitation); 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(); } private abstract static class ConditionPreferences { int index; protected ConditionPreferences(int index) { this.index = index; } protected String formatKey(String keyTemplate) { return String.format(keyTemplate, this.index); } protected String formatKey(String keyTemplate, int subindex) { return String.format(keyTemplate, this.index, subindex); } } private static class ConditionPreferencesEditor extends ConditionPreferences { SharedPreferences.Editor editor; public ConditionPreferencesEditor(SharedPreferences.Editor editor, int index) { super(index); this.editor = editor; } public void remove(String key) { this.editor.remove(formatKey(key)); } public void remove(String key, int subindex) { this.editor.remove(formatKey(key, subindex)); } public void putOrRemove(String key, String value) { if (value == null || "".equals(value)) { this.editor.remove(formatKey(key)); } else { this.editor.putString(formatKey(key), value); } } public void putOrRemove(String key, Enum value) { if (value == null) { this.editor.remove(formatKey(key)); } else { this.editor.putString(formatKey(key), String.valueOf(value)); } } public void putOrRemove(String key, Collection values) { int i = 0; if (values != null) { for (Object value : values) { this.editor.putString(formatKey(key, i), String.valueOf(value)); i++; } } this.editor.remove(formatKey(key, i)); } public void putOrRemove(String key, int value) { if (value == Integer.MIN_VALUE) { this.editor.remove(formatKey(key)); } else { this.editor.putInt(formatKey(key), value); } } public void putOrRemove(String key, float value) { if (value == Float.MIN_VALUE) { this.editor.remove(formatKey(key)); } else { this.editor.putFloat(formatKey(key), value); } } } private static class ConditionPreferencesReader extends ConditionPreferences { SharedPreferences preferences; public ConditionPreferencesReader(SharedPreferences preferences, int index) { super(index); this.preferences = preferences; } public String get(String key, String defaultValue) { return this.preferences.getString(formatKey(key), defaultValue); } public <E extends Enum<E>> E get(String key, E defaultValue) { Class<? extends Enum> enumClass = defaultValue.getClass(); return (E)Enum.valueOf(enumClass, this.preferences.getString(formatKey(key), String.valueOf(defaultValue))); } public <E extends Enum<E>> Collection<E> getEnums(String key, Class<E> enumClass) { List<E> result = new ArrayList<E>(); int i = 0; while (this.preferences.contains(formatKey(key, i))) { result.add(Enum.valueOf(enumClass, this.preferences.getString(formatKey(key, i), null))); i++; } return result; } public int get(String key, int defaultValue) { return this.preferences.getInt(formatKey(key), defaultValue); } public float get(String key, float defaultValue) { return this.preferences.getFloat(formatKey(key), defaultValue); } } }
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 ru.gelin.android.weather.Weather; public class IntentParameters { /** * Intent action which should be accepted by the receiver. * Intent with this action is sent to the old skins and is deprecated. * Has "ru.gelin.android.weather.notification.ACTION_WEATHER_UPDATE" value. */ @Deprecated public static final String ACTION_WEATHER_UPDATE = Tag.class.getPackage().getName() + ".ACTION_WEATHER_UPDATE"; /** * Intent action which should be accepted by the receiver. * This is new intent action which should be used in the code of new skins. * This action was added in release 0.3. * Has "ru.gelin.android.weather.notification.ACTION_WEATHER_UPDATE_2" value. */ public static final String ACTION_WEATHER_UPDATE_2 = Tag.class.getPackage().getName() + ".ACTION_WEATHER_UPDATE_2"; /** * Intent extra which contains {@link Weather}. * Has "ru.gelin.android.weather.notification.EXTRA_WEATHER" value. * Note that this extra may contain objects of different types, depend on the Action of the Intent. */ public static final String EXTRA_WEATHER = Tag.class.getPackage().getName() + ".EXTRA_WEATHER"; /** Intent extra which contains boolean flag */ public static final String EXTRA_ENABLE_NOTIFICATION = Tag.class.getPackage().getName() + ".EXTRA_ENABLE_NOTIFICATION"; /** Intent action for the skin configuration activity */ public static final String ACTION_WEATHER_SKIN_PREFERENCES = Tag.class.getPackage().getName() + ".ACTION_WEATHER_SKIN_PREFERENCES"; private IntentParameters() { //avoid instantiation } }
Java
package ru.gelin.android.weather.notification; import android.content.Context; import android.content.Intent; /** * Static methods to start main app services and activites. */ public class AppUtils { /** Main app package name */ private static final String APP_PACKAGE_NAME = Tag.class.getPackage().getName(); /** Intent action to start the service */ public static String ACTION_START_UPDATE_SERVICE = APP_PACKAGE_NAME + ".ACTION_START_UPDATE_SERVICE"; /** Intent action to start the main activity */ public static String ACTION_START_MAIN_ACTIVITY = APP_PACKAGE_NAME + ".ACTION_START_MAIN_ACTIVITY"; /** Verbose extra name for the service start intent. */ public static String EXTRA_VERBOSE = "verbose"; /** Force extra name for the service start intent. */ public static String EXTRA_FORCE = "force"; /** * Returns intent to start the main activity. */ public static Intent getMainActivityIntent() { Intent startIntent = new Intent(ACTION_START_MAIN_ACTIVITY); startIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return startIntent; } /** * Starts the main activity. */ public static void startMainActivity(Context context) { context.startActivity(getMainActivityIntent()); } /** * Starts the update service. */ public static void startUpdateService(Context context) { startUpdateService(context, false, false); } /** * Starts the update service. * If the verbose is true, the update errors will be displayed as toasts. */ public static void startUpdateService(Context context, boolean verbose) { startUpdateService(context, verbose, false); } /** * Starts the service. * If the verbose is true, the update errors will be displayed as toasts. * If the force is true, the update will start even when the weather is * not expired. */ public static void startUpdateService(Context context, boolean verbose, boolean force) { Intent startIntent = new Intent(ACTION_START_UPDATE_SERVICE); //startIntent.setClassName(UpdateService.class.getPackage().getName(), UpdateService.class.getName()); startIntent.putExtra(EXTRA_VERBOSE, verbose); startIntent.putExtra(EXTRA_FORCE, force); context.startService(startIntent); } private AppUtils() { //avoid instantiation } }
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; /** * Constants for preference keys. */ public class PreferenceKeys { private PreferenceKeys() { //avoid instantiation } /** Enable notification preference key */ public static final String ENABLE_NOTIFICATION = "enable_notification"; /** Enable notification default value */ public static final boolean ENABLE_NOTIFICATION_DEFAULT = true; }
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.Bundle; import android.os.Parcel; import android.os.Parcelable; import ru.gelin.android.weather.*; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import static ru.gelin.android.weather.notification.ParcelableWeatherKeys.*; public class ParcelableWeather2 extends SimpleWeather implements Parcelable { /** Parcelable representation version */ static final int VERSION = 2; public ParcelableWeather2() { } /** * Copy constructor. */ public ParcelableWeather2(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); } Date queryTime = weather.getQueryTime(); if (time == null) { setQueryTime(new Date()); } else { setQueryTime(queryTime); } URL forecastURL = weather.getForecastURL(); setForecastURL(forecastURL); 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()); for (WeatherConditionType type : condition.getConditionTypes()) { copyCondition.addConditionType(type); } Temperature temp = condition.getTemperature(); SimpleTemperature copyTemp = new SimpleTemperature(TemperatureUnit.C); if (temp != null) { TemperatureUnit tempUnit = temp.getTemperatureUnit(); copyTemp = new SimpleTemperature(tempUnit); copyTemp.setCurrent(temp.getCurrent(), tempUnit); copyTemp.setLow(temp.getLow(), tempUnit); copyTemp.setHigh(temp.getHigh(), tempUnit); } copyCondition.setTemperature(copyTemp); Humidity hum = condition.getHumidity(); SimpleHumidity copyHum = new SimpleHumidity(); if (hum != null) { copyHum.setValue(hum.getValue()); copyHum.setText(hum.getText()); } copyCondition.setHumidity(copyHum); Wind wind = condition.getWind(); SimpleWind copyWind = new SimpleWind(WindSpeedUnit.MPS); if (wind != null) { WindSpeedUnit windUnit = wind.getSpeedUnit(); copyWind = new SimpleWind(windUnit); copyWind.setSpeed(wind.getSpeed(), windUnit); copyWind.setDirection(wind.getDirection()); copyWind.setText(wind.getText()); } copyCondition.setWind(copyWind); Cloudiness cloudiness = condition.getCloudiness(); SimpleCloudiness copyCloudiness = new SimpleCloudiness(CloudinessUnit.OKTA); if (cloudiness != null) { CloudinessUnit cloudinessUnit = cloudiness.getCloudinessUnit(); copyCloudiness = new SimpleCloudiness(cloudinessUnit); copyCloudiness.setValue(cloudiness.getValue(), cloudinessUnit); } copyCondition.setCloudiness(copyCloudiness); Precipitation precipitation = condition.getPrecipitation(); SimplePrecipitation copyPrecipitation = new SimplePrecipitation(PrecipitationUnit.MM); if (precipitation != null) { PrecipitationUnit precipitationUnit = precipitation.getPrecipitationUnit(); copyPrecipitation = new SimplePrecipitation(precipitationUnit); copyPrecipitation.setValue(precipitation.getValue(PrecipitationPeriod.PERIOD_1H), PrecipitationPeriod.PERIOD_1H); } copyCondition.setPrecipitation(copyPrecipitation); copyConditions.add(copyCondition); } setConditions(copyConditions); } //@Override public int describeContents() { return 0; } //@Override public void writeToParcel(Parcel dest, int flags) { writeVersion(dest); writeCommonParams(dest); for (WeatherCondition condition : getConditions()) { writeCondition(condition, dest); } } void writeVersion(Parcel dest) { dest.writeInt(VERSION); } void writeCommonParams(Parcel dest) { Bundle bundle = new Bundle(); Location location = getLocation(); if (location != null) { bundle.putString(LOCATION, location.getText()); } Date time = getTime(); if (time != null) { bundle.putLong(TIME, time.getTime()); } Date queryTime = getQueryTime(); if (queryTime != null) { bundle.putLong(QUERY_TIME, queryTime.getTime()); } URL forecastURL = getForecastURL(); if (forecastURL != null) { bundle.putString(FORECAST_URL, String.valueOf(forecastURL)); } List<WeatherCondition> conditions = getConditions(); if (conditions == null) { bundle.putInt(CONDITIONS_NUMBER, 0); } else { bundle.putInt(CONDITIONS_NUMBER, conditions.size()); } dest.writeBundle(bundle); } void writeCondition(WeatherCondition condition, Parcel dest) { Bundle bundle = new Bundle(); bundle.putString(CONDITION_TEXT, condition.getConditionText()); writeConditionTypes(condition.getConditionTypes(), bundle); writeTemperature(condition.getTemperature(), bundle); writeHumidity(condition.getHumidity(), bundle); writeWind(condition.getWind(), bundle); writeCloudiness(condition.getCloudiness(), bundle); writePrecipitation(condition.getPrecipitation(), bundle); dest.writeBundle(bundle); } void writeConditionTypes(Collection<WeatherConditionType> types, Bundle bundle) { String[] typesToStore = new String[types.size()]; int i = 0; for (WeatherConditionType type : types) { typesToStore[i] = String.valueOf(type); i++; } bundle.putStringArray(CONDITION_TYPES, typesToStore); } void writeTemperature(Temperature temp, Bundle bundle) { if (temp == null) { return; } bundle.putString(TEMPERATURE_UNIT, temp.getTemperatureUnit().toString()); bundle.putInt(CURRENT_TEMP, temp.getCurrent()); bundle.putInt(LOW_TEMP, temp.getLow()); bundle.putInt(HIGH_TEMP, temp.getHigh()); } void writeHumidity(Humidity humidity, Bundle bundle) { if (humidity == null) { return; } bundle.putString(HUMIDITY_TEXT, humidity.getText()); bundle.putInt(HUMIDITY_VALUE, humidity.getValue()); } void writeWind(Wind wind, Bundle bundle) { if (wind == null) { return; } bundle.putString(WIND_TEXT, wind.getText()); bundle.putString(WIND_SPEED_UNIT, wind.getSpeedUnit().toString()); bundle.putInt(WIND_SPEED, wind.getSpeed()); bundle.putString(WIND_DIR, wind.getDirection().toString()); } void writeCloudiness(Cloudiness cloudiness, Bundle bundle) { if (cloudiness == null) { return; } bundle.putString(CLOUDINESS_UNIT, cloudiness.getCloudinessUnit().toString()); bundle.putInt(CLOUDINESS_VALUE, cloudiness.getValue()); } void writePrecipitation(Precipitation precipitation, Bundle bundle) { if (precipitation == null) { return; } bundle.putString(PRECIPITATION_UNIT, precipitation.getPrecipitationUnit().toString()); bundle.putInt(PRECIPITATION_PERIOD, PrecipitationPeriod.PERIOD_1H.getHours()); bundle.putFloat(PRECIPITATION_VALUE, precipitation.getValue(PrecipitationPeriod.PERIOD_1H)); } private ParcelableWeather2(Parcel in) { int version = in.readInt(); if (version != VERSION) { return; } int conditionsSize = readCommonParams(in); List<WeatherCondition> conditions = new ArrayList<WeatherCondition>(conditionsSize); for (int i = 0; i < conditionsSize; i++) { WeatherCondition condition = readCondition(in); if (condition != null) { conditions.add(condition); } } setConditions(conditions); } /** * Reads and sets common weather params. * @return number of conditions */ int readCommonParams(Parcel in) { Bundle bundle = in.readBundle(this.getClass().getClassLoader()); setLocation(new SimpleLocation(bundle.getString(LOCATION))); setTime(new Date(bundle.getLong(TIME))); setQueryTime(new Date(bundle.getLong(QUERY_TIME))); try { setForecastURL(new URL(bundle.getString(FORECAST_URL))); } catch (MalformedURLException e) { setForecastURL(null); } return bundle.getInt(CONDITIONS_NUMBER); } WeatherCondition readCondition(Parcel in) { if (in.dataAvail() == 0) { return null; } Bundle bundle = in.readBundle(this.getClass().getClassLoader()); SimpleWeatherCondition condition = new SimpleWeatherCondition(); condition.setConditionText(bundle.getString(CONDITION_TEXT)); readConditionTypes(bundle, condition); condition.setTemperature(readTemperature(bundle)); condition.setHumidity(readHumidity(bundle)); condition.setWind(readWind(bundle)); condition.setCloudiness(readCloudiness(bundle)); condition.setPrecipitation(readPrecipitation(bundle)); return condition; } void readConditionTypes(Bundle bundle, SimpleWeatherCondition condition) { String[] types = bundle.getStringArray(CONDITION_TYPES); if (types == null) { return; } for (String type : types) { condition.addConditionType(WeatherConditionType.valueOf(type)); } } SimpleTemperature readTemperature(Bundle bundle) { TemperatureUnit unit; try { unit = TemperatureUnit.valueOf(bundle.getString(TEMPERATURE_UNIT)); } catch (Exception e) { return null; } SimpleTemperature temp = new SimpleTemperature(unit); temp.setCurrent(bundle.getInt(CURRENT_TEMP), unit); temp.setLow(bundle.getInt(LOW_TEMP), unit); temp.setHigh(bundle.getInt(HIGH_TEMP), unit); return temp; } SimpleHumidity readHumidity(Bundle bundle) { if (!bundle.containsKey(HUMIDITY_VALUE)) { return null; } SimpleHumidity hum = new SimpleHumidity(); hum.setValue(bundle.getInt(HUMIDITY_VALUE)); hum.setText(bundle.getString(HUMIDITY_TEXT)); return hum; } SimpleWind readWind(Bundle bundle) { WindSpeedUnit unit; try { unit = WindSpeedUnit.valueOf(bundle.getString(WIND_SPEED_UNIT)); } catch (Exception e) { return null; } SimpleWind wind = new SimpleWind(unit); wind.setSpeed(bundle.getInt(WIND_SPEED), unit); WindDirection dir; try { dir = WindDirection.valueOf(bundle.getString(WIND_DIR)); } catch (Exception e) { return null; } wind.setDirection(dir); wind.setText(bundle.getString(WIND_TEXT)); return wind; } SimpleCloudiness readCloudiness(Bundle bundle) { if (!bundle.containsKey(CLOUDINESS_VALUE)) { return null; } CloudinessUnit unit; try { unit = CloudinessUnit.valueOf(bundle.getString(CLOUDINESS_UNIT)); } catch (Exception e) { return null; } SimpleCloudiness cloudiness = new SimpleCloudiness(unit); cloudiness.setValue(bundle.getInt(CLOUDINESS_VALUE), unit); return cloudiness; } SimplePrecipitation readPrecipitation(Bundle bundle) { if (!bundle.containsKey(PRECIPITATION_VALUE)) { return null; } PrecipitationUnit unit; try { unit = PrecipitationUnit.valueOf(bundle.getString(PRECIPITATION_UNIT)); } catch (Exception e) { return null; } SimplePrecipitation precipitation = new SimplePrecipitation(unit); PrecipitationPeriod period; try { period = PrecipitationPeriod.valueOf(bundle.getInt(PRECIPITATION_PERIOD)); } catch (Exception e) { return null; } precipitation.setValue(bundle.getFloat(PRECIPITATION_VALUE), period); return precipitation; } public static final Parcelable.Creator<ParcelableWeather2> CREATOR = new Parcelable.Creator<ParcelableWeather2>() { public ParcelableWeather2 createFromParcel(Parcel in) { return new ParcelableWeather2(in); } public ParcelableWeather2[] newArray(int size) { return new ParcelableWeather2[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; class ParcelableWeatherKeys { private ParcelableWeatherKeys() { //avoid instantiation } /** Key for location. */ static final String LOCATION = "weather_location"; /** Key for time. */ static final String TIME = "weather_time"; /** Key for query time. */ static final String QUERY_TIME = "weather_query_time"; /** Key for number of conditions */ static final String CONDITIONS_NUMBER = "weather_conditions"; /** Key for condition text. */ static final String CONDITION_TEXT = "weather_condition_text"; /** Key for condition type. */ static final String CONDITION_TYPES = "weather_condition_types"; /** Key for temperature unit. */ static final String TEMPERATURE_UNIT = "weather_temperature_unit"; /** Key for current temp. */ static final String CURRENT_TEMP = "weather_current_temp"; /** Key for low temp. */ static final String LOW_TEMP = "weather_low_temp"; /** Key for high temp. */ static final String HIGH_TEMP = "weather_high_temp"; /** Key for humidity text. */ static final String HUMIDITY_TEXT = "weather_humidity_text"; /** Key for humidity value. */ static final String HUMIDITY_VALUE = "weather_humidity_value"; /** Key for wind text. */ static final String WIND_TEXT = "weather_wind_text"; /** Key for wind speed unit. */ static final String WIND_SPEED_UNIT = "weather_wind_speed_unit"; /** Key for wind speed. */ static final String WIND_SPEED = "weather_wind_speed"; /** Key for wind direction. */ static final String WIND_DIR = "weather_wind_direction"; /** Key for cloudiness unit. */ static final String CLOUDINESS_UNIT = "weather_cloudiness_unit"; /** Key for cloudiness value. */ static final String CLOUDINESS_VALUE = "weather_cloudiness_value"; /** Key for precipitation unit. */ static final String PRECIPITATION_UNIT = "weather_precipitation_unit"; /** Key for precipitation period. */ static final String PRECIPITATION_PERIOD = "weather_precipitation_period"; /** Key for precipitation value. */ static final String PRECIPITATION_VALUE = "weather_precipitation_value"; /** Key for forecast URL. */ static final String FORECAST_URL = "weather_forecast_url"; }
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 java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.weather.Humidity; import ru.gelin.android.weather.Location; import ru.gelin.android.weather.SimpleHumidity; import ru.gelin.android.weather.SimpleLocation; import ru.gelin.android.weather.SimpleTemperature; import ru.gelin.android.weather.SimpleWeather; import ru.gelin.android.weather.SimpleWeatherCondition; import ru.gelin.android.weather.SimpleWind; import ru.gelin.android.weather.Temperature; import ru.gelin.android.weather.TemperatureUnit; import ru.gelin.android.weather.UnitSystem; import ru.gelin.android.weather.Weather; import ru.gelin.android.weather.WeatherCondition; import ru.gelin.android.weather.Wind; import ru.gelin.android.weather.WindSpeedUnit; import android.os.Parcel; import android.os.Parcelable; /** * This parcelable weather allows to save only weather params which were used in version 0.2 of the application. * Now it's deprecated. * But, unfortunately, the class name cannot be changed for backward compatibility. * Use {@link ParcelableWeather2} whether possible. */ @SuppressWarnings("deprecation") @Deprecated 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); } 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(); TemperatureUnit tempUnit = temp.getTemperatureUnit(); SimpleTemperature copyTemp = new SimpleTemperature(tempUnit); if (temp != null) { copyTemp.setCurrent(temp.getCurrent(), tempUnit); copyTemp.setLow(temp.getLow(), tempUnit); copyTemp.setHigh(temp.getHigh(), tempUnit); } copyCondition.setTemperature(copyTemp); Humidity hum = condition.getHumidity(); SimpleHumidity copyHum = new SimpleHumidity(); if (hum != null) { copyHum.setValue(hum.getValue()); copyHum.setText(hum.getText()); } copyCondition.setHumidity(copyHum); Wind wind = condition.getWind(); WindSpeedUnit windUnit = wind.getSpeedUnit(); SimpleWind copyWind = new SimpleWind(windUnit); if (wind != null) { copyWind.setSpeed(wind.getSpeed(), windUnit); copyWind.setDirection(wind.getDirection()); copyWind.setText(wind.getText()); } copyCondition.setWind(copyWind); 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()); } if (getConditions() == null) { return; } try { WeatherCondition condition0 = getConditions().get(0); dest.writeString(condition0.getTemperature().getUnitSystem().toString()); } catch (Exception e) { dest.writeString(UnitSystem.SI.toString()); } for (WeatherCondition condition : getConditions()) { writeCondition(condition, dest); } } void writeCondition(WeatherCondition condition, Parcel dest) { dest.writeString(condition.getConditionText()); writeTemperature(condition.getTemperature(), dest); writeHumidity(condition.getHumidity(), dest); writeWind(condition.getWind(), dest); } void writeTemperature(Temperature temp, Parcel dest) { if (temp != null) { dest.writeInt(temp.getCurrent()); dest.writeInt(temp.getLow()); dest.writeInt(temp.getHigh()); } else { dest.writeInt(Temperature.UNKNOWN); dest.writeInt(Temperature.UNKNOWN); dest.writeInt(Temperature.UNKNOWN); } } void writeHumidity(Humidity humidity, Parcel dest) { if (humidity != null) { dest.writeString(humidity.getText()); } else { dest.writeString(null); } } void writeWind(Wind wind, Parcel dest) { if (wind != null) { dest.writeString(wind.getText()); } else { dest.writeString(null); } } 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); SimpleHumidity hum = new SimpleHumidity(); hum.setText(in.readString()); condition.setHumidity(hum); SimpleWind wind = new SimpleWind(WindSpeedUnit.MPH); wind.setText(in.readString()); condition.setWind(wind); 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.notification; class WeatherStorageKeys { private WeatherStorageKeys() { //avoid instantiation } /** Preference name for location. */ static final String LOCATION = "weather_location"; /** Preference name for weather time. */ static final String TIME = "weather_time"; /** Preference name for query time. */ static final String QUERY_TIME = "weather_query_time"; /** Preference name for unit system. */ @Deprecated 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 condition type. */ static final String CONDITION_TYPES = "weather_%d_condition_type_%d"; /** Preference name pattern for temperature unit. */ static final String TEMPERATURE_UNIT = "weather_%d_temperature_unit"; /** 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 humidity value. */ static final String HUMIDITY_VALUE = "weather_%d_humidity_value"; /** Preference name pattern for wind text. */ static final String WIND_TEXT = "weather_%d_wind_text"; /** Preference name pattern for wind speed unit. */ static final String WIND_SPEED_UNIT = "weather_%d_wind_speed_unit"; /** Preference name pattern for wind speed. */ static final String WIND_SPEED = "weather_%d_wind_speed"; /** Preference name pattern for wind direction. */ static final String WIND_DIR = "weather_%d_wind_direction"; /** Preference name pattern for cloudiness unit. */ static final String CLOUDINESS_UNIT = "weather_%d_cloudiness_unit"; /** Preference name pattern for cloudiness value. */ static final String CLOUDINESS_VALUE = "weather_%d_cloudiness_value"; /** Preference name pattern for precipitation unit. */ static final String PRECIPITATION_UNIT = "weather_%d_precipitation_unit"; /** Preference name pattern for precipitation period. */ static final String PRECIPITATION_PERIOD = "weather_%d_precipitation_period"; /** Preference name pattern for precipitation value. */ static final String PRECIPITATION_VALUE = "weather_%d_precipitation_value"; /** Preference name for forecast URL. */ static final String FORECAST_URL = "weather_forecast_url"; }
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; /** * Simple Humidity value. * Just holds the specified values. */ public class SimpleHumidity implements Humidity { protected int value = UNKNOWN; protected String text; /** * Sets the current humidity. */ public void setValue(int value) { this.value = value; } /** * Sets the current humidity. */ public void setText(String text) { this.text = text; } //@Override public int getValue() { return this.value; } //@Override public String getText() { return this.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; /** * 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(); /** * Returns true if this location represents geographical coordinates, * i.e. not query by a city name, for example. */ boolean isGeo(); }
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; /** * Common exception for weather getting errors. */ public class WeatherException extends Exception { private static final long serialVersionUID = -7139823134945463091L; 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; @Deprecated public enum UnitSystem { SI, US; public static UnitSystem valueOf(TemperatureUnit unit) { switch (unit) { case C: return SI; case F: return US; } return SI; } }
Java
/* * Weather API. * Copyright (C) 2012 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; /** * Holds cloudiness value. */ public interface Cloudiness { /** Unknown cloudiness value */ static int UNKNOWN = Integer.MIN_VALUE; /** * Returns general cloudiness value. */ int getValue(); /** * Cloudiness unit for this instance. */ CloudinessUnit getCloudinessUnit(); /** * Returns cloudiness as a human readable text. * Can return null. */ String getText(); }
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; import java.net.URL; 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; /** Query Time */ Date queryTime; /** Unit system */ @SuppressWarnings("deprecation") UnitSystem unit; /** List of conditions */ List<WeatherCondition> conditions; /** Forecast URL */ URL forecastURL; /** * Sets the location. */ public void setLocation(Location location) { this.location = location; } /** * Sets the weather time. */ public void setTime(Date time) { this.time = time; } /** * Sets the query time. */ public void setQueryTime(Date time) { this.queryTime = time; } /** * Sets the unit system. */ @Deprecated 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; } public Date getQueryTime() { return this.queryTime; } //@Override @Deprecated 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; } /** * Sets the forecast URL. */ public void setForecastURL(URL url) { this.forecastURL = url; } /** * Returns forecast URL. */ public URL getForecastURL() { return this.forecastURL; } }
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; import java.util.EnumSet; import java.util.Iterator; import java.util.Set; /** * Simple weather condition implementation which just holds * the values. */ public class SimpleWeatherCondition implements WeatherCondition { String conditionText; SimpleTemperature temperature; SimpleWind wind; Humidity humidity; SimpleCloudiness cloudiness; SimplePrecipitation precipitation; Set<WeatherConditionType> conditionTypes = EnumSet.noneOf(WeatherConditionType.class); /** * 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 setWind(SimpleWind wind) { this.wind = wind; } /** * Sets the humidity text. */ public void setHumidity(Humidity hum) { this.humidity = hum; } //@Override public String getConditionText() { return this.conditionText; } //@Override public Temperature getTemperature() { return this.temperature; } //@Override @Deprecated 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); } public Temperature getTemperature(TemperatureUnit unit) { if (this.temperature == null) { return null; } if (this.temperature.getTemperatureUnit().equals(unit)) { return this.temperature; } return this.temperature.convert(unit); } //@Deprecated //@Override public String getWindText() { return this.wind.getText(); } //@Deprecated //@Override public String getHumidityText() { return this.humidity.getText(); } //@override public Wind getWind() { return this.wind; } //@Override public Wind getWind(WindSpeedUnit unit) { if (this.wind == null) { return null; } if (this.wind.getSpeedUnit().equals(unit)) { return this.wind; } return this.wind.convert(unit); } //@Override public Humidity getHumidity() { return this.humidity; } public void setCloudiness(SimpleCloudiness cloudiness) { this.cloudiness = cloudiness; } public Cloudiness getCloudiness() { return this.cloudiness; } public Cloudiness getCloudiness(CloudinessUnit unit) { if (this.cloudiness == null) { return null; } return this.cloudiness.convert(unit); } public void setPrecipitation(SimplePrecipitation precipitation) { this.precipitation = precipitation; } public Precipitation getPrecipitation() { return this.precipitation; } public Set<WeatherConditionType> getConditionTypes() { return EnumSet.copyOf(this.conditionTypes); } public void addConditionType(WeatherConditionType newType) { if (newType == null) { return; } Iterator<WeatherConditionType> i = this.conditionTypes.iterator(); boolean insert = true; while (i.hasNext()) { WeatherConditionType type = i.next(); if (newType.getPriority() == type.getPriority()) { if (newType.getStrength() > type.getStrength()) { i.remove(); insert = true; } else if (newType.getStrength() < type.getStrength()) { insert = false; } } } if (insert) { this.conditionTypes.add(newType); } } }
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; public enum WindDirection { N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW; /** * Creates the direction from the azimuth degrees. */ public static WindDirection valueOf(int deg) { int degPositive = deg; if (deg < 0) { degPositive += (-deg / 360 + 1) * 360; } int degNormalized = degPositive % 360; int degRotated = degNormalized + (360 / 16 / 2); int sector = degRotated / (360 / 16); switch (sector) { case 0: return WindDirection.N; case 1: return WindDirection.NNE; case 2: return WindDirection.NE; case 3: return WindDirection.ENE; case 4: return WindDirection.E; case 5: return WindDirection.ESE; case 6: return WindDirection.SE; case 7: return WindDirection.SSE; case 8: return WindDirection.S; case 9: return WindDirection.SSW; case 10: return WindDirection.SW; case 11: return WindDirection.WSW; case 12: return WindDirection.W; case 13: return WindDirection.WNW; case 14: return WindDirection.NW; case 15: return WindDirection.NNW; case 16: return WindDirection.N; } return WindDirection.N; } }
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; /** * Holds wind speed and direction. * Allows to set the wind speed in different units. */ public class SimpleWind implements Wind { protected WindSpeedUnit wsunit; protected int speed = UNKNOWN; protected WindDirection direction = WindDirection.N; protected String text = null; /** * Constructs the wind. * The stored values will be returned in the specified unit system. */ public SimpleWind(WindSpeedUnit wsunit) { this.wsunit = wsunit; } /** * Creates new wind in another unit system. */ public SimpleWind convert(WindSpeedUnit unit) { SimpleWind result = new SimpleWind(unit); result.setText(this.text); result.setSpeed(this.speed, this.wsunit); result.setDirection(this.direction); return result; } /** * Sets the text representation of the wind speed and direction. */ public void setText(String text) { this.text = text; } /** * Sets the wind direction. */ public void setDirection(WindDirection direction) { this.direction = direction; } /** * Sets the wind speed in specified units. */ public void setSpeed(int speed, WindSpeedUnit unit) { if (this.wsunit.equals(unit)) { this.speed = speed; } else { this.speed = convert(speed, unit); } } //@Override public WindDirection getDirection() { return this.direction; } //@Override public int getSpeed() { return this.speed; } //@Override public WindSpeedUnit getSpeedUnit() { return this.wsunit; } //@Override public String getText() { return this.text; } int convert(int speed, WindSpeedUnit unit) { switch (wsunit) { case MPH: switch (unit) { case KMPH: return (int)Math.round(speed * 0.6214); case MPH: return this.speed; case MPS: return (int)Math.round(speed * 2.2370); } case MPS: switch (unit) { case KMPH: return (int)Math.round(speed * 0.2778); case MPH: return (int)Math.round(speed * 0.4470); case MPS: return this.speed; } case KMPH: switch (unit) { case KMPH: return this.speed; case MPH: return (int)Math.round(speed * 1.6093); case MPS: return (int)Math.round(speed * 3.6000); } } return 0; } }
Java
package ru.gelin.android.weather; /** * Simple implementation to hold precipitation value. */ public class SimplePrecipitation implements Precipitation { /** Unit for precipitations */ PrecipitationUnit unit = PrecipitationUnit.MM; /** Hours of precipitations */ int hours = 0; /** Value of precipitations */ float value = UNKNOWN; public SimplePrecipitation(PrecipitationUnit unit) { this.unit = unit; } public void setValue(float value, PrecipitationPeriod period) { this.value = value; this.hours = period.hours; } public void setValue(float value, int hours) { this.value = value; this.hours = hours; } public float getValue() { return this.value; } public int getHours() { return this.hours; } @Override public float getValue(PrecipitationPeriod period) { if (this.value == UNKNOWN) { return UNKNOWN; } return this.value / this.hours * period.getHours(); } @Override public PrecipitationUnit getPrecipitationUnit() { return this.unit; } @Override public String getText() { return "Precipitation: " + getValue(PrecipitationPeriod.PERIOD_1H) + " mm/h"; } }
Java
package ru.gelin.android.weather; /** * Supported precipitation period values. */ public enum PrecipitationPeriod { PERIOD_1H(1), PERIOD_3H(3); /** Period length in hours */ int hours; PrecipitationPeriod(int hours) { this.hours = hours; } public int getHours() { return this.hours; } public static PrecipitationPeriod valueOf(int hours) { switch (hours) { case 1: return PERIOD_1H; case 3: return PERIOD_3H; default: throw new IllegalArgumentException(hours + " is not valid value for PrecipitationPeriod"); } } }
Java
package ru.gelin.android.weather; import static ru.gelin.android.weather.WeatherConditionTypePriority.*; /** * Enumeration of declared condition conditionTypes. */ public enum WeatherConditionType { THUNDERSTORM_RAIN_LIGHT(THUNDERSTORM_PRIORITY, 7), THUNDERSTORM_RAIN(THUNDERSTORM_PRIORITY, 8), THUNDERSTORM_RAIN_HEAVY(THUNDERSTORM_PRIORITY, 9), THUNDERSTORM_LIGHT(THUNDERSTORM_PRIORITY, 0), THUNDERSTORM(THUNDERSTORM_PRIORITY, 1), THUNDERSTORM_HEAVY(THUNDERSTORM_PRIORITY, 2), THUNDERSTORM_RAGGED(THUNDERSTORM_PRIORITY, 3), THUNDERSTORM_DRIZZLE_LIGHT(THUNDERSTORM_PRIORITY, 4), THUNDERSTORM_DRIZZLE(THUNDERSTORM_PRIORITY, 5), THUNDERSTORM_DRIZZLE_HEAVY(THUNDERSTORM_PRIORITY, 6), DRIZZLE_LIGHT(DRIZZLE_PRIORITY, 0), DRIZZLE(DRIZZLE_PRIORITY, 1), DRIZZLE_HEAVY(DRIZZLE_PRIORITY, 2), DRIZZLE_RAIN_LIGHT(DRIZZLE_PRIORITY, 3), DRIZZLE_RAIN(DRIZZLE_PRIORITY, 4), DRIZZLE_RAIN_HEAVY(DRIZZLE_PRIORITY, 5), DRIZZLE_SHOWER(DRIZZLE_PRIORITY, 6), RAIN_LIGHT(RAIN_PRIORITY, 0), RAIN(RAIN_PRIORITY, 1), RAIN_HEAVY(RAIN_PRIORITY, 2), RAIN_VERY_HEAVY(RAIN_PRIORITY, 3), RAIN_EXTREME(RAIN_PRIORITY, 4), RAIN_FREEZING(RAIN_PRIORITY, 8), RAIN_SHOWER_LIGHT(RAIN_PRIORITY, 5), RAIN_SHOWER(RAIN_PRIORITY, 6), RAIN_SHOWER_HEAVY(RAIN_PRIORITY, 7), SNOW_LIGHT(SNOW_PRIORITY, 0), SNOW(SNOW_PRIORITY, 1), SNOW_HEAVY(SNOW_PRIORITY, 2), SLEET(SNOW_PRIORITY, 4), SNOW_SHOWER(SNOW_PRIORITY, 3), MIST(ATMOSPHERE_PRIORITY, -1), SMOKE(ATMOSPHERE_PRIORITY, 0), HAZE(ATMOSPHERE_PRIORITY, 0), SAND_WHIRLS(ATMOSPHERE_PRIORITY, 0), FOG(ATMOSPHERE_PRIORITY, 0), CLOUDS_CLEAR(CLOUDS_PRIORITY, 0), CLOUDS_FEW(CLOUDS_PRIORITY, 1), CLOUDS_SCATTERED(CLOUDS_PRIORITY, 2), CLOUDS_BROKEN(CLOUDS_PRIORITY, 3), CLOUDS_OVERCAST(CLOUDS_PRIORITY, 4), TORNADO(EXTREME_PRIORITY, 0), TROPICAL_STORM(EXTREME_PRIORITY, 0), HURRICANE(EXTREME_PRIORITY, 0), COLD(EXTREME_PRIORITY, 0), HOT(EXTREME_PRIORITY, 0), WINDY(EXTREME_PRIORITY, 0), HAIL(EXTREME_PRIORITY, 0); private int priority = -1; private int strength = 0; private WeatherConditionType(int priority, int strength) { this.priority = priority; this.strength = strength; } public int getPriority() { return this.priority; } public int getStrength() { return this.strength; } }
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; 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.skin; import android.os.Handler; import android.preference.PreferenceActivity; /** * Basic class which can update all weather notifications. */ public class UpdateNotificationActivity extends PreferenceActivity { /** Handler to take notification update actions */ Handler handler = new Handler(); /** * Performs the deferred update of the notification, * which allows to return from onPreferenceChange handler to update * preference value and update the notification later. */ protected void updateNotification() { handler.post(new Runnable() { //@Override public void run() { WeatherNotificationManager.update(UpdateNotificationActivity.this); } }); } }
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 */ /** * Classes to manage skins. */ package ru.gelin.android.weather.notification.skin;
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; /** * Constants for preference keys. */ class PreferenceKeys { private PreferenceKeys() { //avoid instantiation } /** Pattern of the preference key for enabled skin flags */ static final String SKIN_ENABLED_PATTERN = "skin_enabled_%s"; /** Pattern of the preference key for preference to start skin config activity */ static final String SKIN_CONFIG_PATTERN = "skin_config_%s"; }
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.content.Context; import android.graphics.drawable.Drawable; import android.text.method.MovementMethod; import android.view.View; import android.widget.ImageView; import android.widget.TextView; /** * Utility to layout weather values to view. */ public class WeatherLayout extends AbstractWeatherLayout { /** View to bind. */ View view; /** * Creates the utility for specified context. */ public WeatherLayout(Context context, View view) { super(context); this.view = view; } @Override protected int getTextColor() { return NO_CHANGE_COLOR; } @Override protected void setText(int viewId, CharSequence text, int color) { TextView textView = (TextView)this.view.findViewById(viewId); if (textView == null) { return; } if (text == null) { textView.setText(""); return; } textView.setText(text); } @Override protected void setIcon(int viewId, Drawable drawable, int level) { ImageView imageView = (ImageView)this.view.findViewById(viewId); if (imageView == null) { return; } imageView.setImageDrawable(drawable); imageView.setImageLevel(level); } @Override protected void setVisibility(int viewId, int visibility) { View view = this.view.findViewById(viewId); if (view == null) { return; } view.setVisibility(visibility); } @Override protected void setMovementMethod(int viewId, MovementMethod method) { View view = this.view.findViewById(viewId); if (!(view instanceof TextView)) { return; } ((TextView)view).setMovementMethod(method); } }
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.content.Context; import android.graphics.drawable.Drawable; import android.text.method.MovementMethod; import android.widget.RemoteViews; import java.util.Date; /** * Utility to layout weather values to remove view. */ public class RemoteWeatherLayout extends AbstractWeatherLayout { static final int MAIN_ICON = 64; static final int FORECAST_ICON = 16; /** View to bind. */ RemoteViews views; /** Text style */ NotificationStyler styler; /** * Creates the utility for specified context. */ public RemoteWeatherLayout(Context context, RemoteViews views, NotificationStyler styler) { super(context); this.views = views; this.styler = styler; } @Override protected int getTextColor() { return this.styler.getTextStyle().getTextColor(); } @Override protected void setText(int viewId, CharSequence text, int color) { if (skipView(viewId)) { return; } if (text == null) { views.setTextViewText(viewId, ""); return; } if (color != 0) { views.setTextColor(viewId, color); } views.setTextViewText(viewId, text); } @Override protected int getMainIconSize() { return MAIN_ICON; } @Override protected int getForecastIconSize() { return FORECAST_ICON; } @Override protected void setIcon(int viewId, Drawable drawable, int level) { if (skipView(viewId)) { return; } drawable.setLevel(level); views.setImageViewBitmap(viewId, Drawable2Bitmap.convert(drawable)); } @Override protected void setVisibility(int viewId, int visibility) { if (skipView(viewId)) { //TODO: how to determine if the view is absent? return; } views.setViewVisibility(viewId, visibility); } @Override protected void setMovementMethod(int viewId, MovementMethod method) { return; } boolean skipView(int viewId) { return !this.styler.isViewInLayout(viewId); } protected void bindUpdateTime(Date update) { if (update.getTime() == 0) { setText(id("update_time_short"), "", NO_CHANGE_COLOR); return; } String text = getContext().getString(string("update_time_short"), update); setText(id("update_time_short"), text, NO_CHANGE_COLOR); } }
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.Humidity; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.STRING; public class HumidityFormat { Context context; ResourceIdFactory ids; public HumidityFormat(Context context) { this.context = context; this.ids = ResourceIdFactory.getInstance(context); } public String format(Humidity humidity) { if (humidity == null) { return ""; } if (humidity.getValue() == Humidity.UNKNOWN) { return ""; } return String.format(this.context.getString( this.ids.id(STRING, "humidity_caption")), humidity.getValue()); } }
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.content.Context; import android.content.res.Resources; import android.util.Log; import ru.gelin.android.weather.notification.skin.Tag; import java.util.HashMap; import java.util.Map; /** * Retrieves the integers IDs of resources by the name. * Caches the results. * Use it in the base classes which will be used in multiple applications when you * retrieves a resource by ID. */ public class ResourceIdFactory { /** "id" resource type */ public static final String ID = "id"; /** "string" resource type */ public static final String STRING = "string"; /** "layout" resource type */ public static final String LAYOUT = "layout"; /** "xml" resource type */ public static final String XML = "xml"; /** "drawable" resource type */ public static final String DRAWABLE = "drawable"; /** Map of instances */ static final Map<String, ResourceIdFactory> instances = new HashMap<String, ResourceIdFactory>(); /** Map of IDs */ final Map<String, Integer> ids = new HashMap<String, Integer>(); /** Package name for the factory */ String packageName; /** Resources */ Resources resources; /** * Returns the instance of the factory for the context. */ public static ResourceIdFactory getInstance(Context context) { String packageName = context.getPackageName(); ResourceIdFactory factory = instances.get(packageName); if (factory == null) { factory = new ResourceIdFactory(context); instances.put(packageName, factory); } return factory; } /** * Private constructor to avoid accidental creation. */ private ResourceIdFactory(Context context) { this.packageName = context.getPackageName(); this.resources = context.getResources(); } /** * Returns the ID of the resource with specified type; */ public int id(String type, String name) { String key = type + "/" + name; Integer id = this.ids.get(key); if (id == null) { id = this.resources.getIdentifier(name, type, this.packageName); this.ids.put(key, id); } if (id == 0) { Log.w(Tag.TAG, this.packageName + ":" + type + "/" + name + " not found"); } return id; } /** * Returns the "id/<name>" resource ID. */ public int id(String name) { return id(ID, name); } }
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.content.Context; import android.graphics.drawable.Drawable; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.view.View; import ru.gelin.android.weather.*; import ru.gelin.android.weather.TemperatureUnit; import java.net.URL; import java.util.Calendar; import java.util.Date; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.STRING; /** * Utility to layout weather values. */ public abstract class AbstractWeatherLayout { static final String URL_TEMPLATE = "<a href=\"%s\">%s</a>"; static final int MAIN_ICON = 48; static final int FORECAST_ICON = 16; static final int NO_CHANGE_COLOR = 0; /** Current context */ private final Context context; private final ResourceIdFactory ids; /** * Creates the utility for specified context. */ protected AbstractWeatherLayout(Context context) { this.context = context; this.ids = ResourceIdFactory.getInstance(context); } protected Context getContext() { return this.context; } protected ResourceIdFactory getIds() { return this.ids; } /** * Retreives "id/<name>" resource ID. */ protected int id(String name) { return getIds().id(name); } /** * Retreives "string/<name>" resource ID. */ protected int string(String name) { return getIds().id(STRING, name); } /** * Lays out the weather values on a view. */ public void bind(Weather weather) { if (weather.isEmpty()) { emptyViews(); } else { bindViews(weather); } } void bindViews(Weather weather) { WeatherFormatter formatter = getWeatherFormatter(getContext(), weather); bindUpdateTime(weather.getQueryTime()); setText(id("location"), weather.getLocation().getText(), getTextColor()); if (weather.getConditions().size() <= 0) { return; } WeatherCondition currentCondition = weather.getConditions().get(0); setIcon(id("condition_icon"), formatter.getWeatherConditionFormat().getDrawable(currentCondition), getMainIconSize()); setText(id("condition"), formatter.getWeatherConditionFormat().getText(currentCondition), getTextColor()); bindWindHumidity(currentCondition, formatter); TemperatureType tempType = formatter.getStyler().getTempType(); Temperature tempC = currentCondition.getTemperature(TemperatureUnit.C); Temperature tempF = currentCondition.getTemperature(TemperatureUnit.F); TemperatureUnit mainUnit = tempType.getTemperatureUnit(); Temperature mainTemp = currentCondition.getTemperature(mainUnit); setVisibility(id("temp"), View.VISIBLE); setText(id("current_temp"), formatter.getTemperatureFormat().format(mainTemp.getCurrent(), tempType), getTextColor()); switch(tempType) { //TODO: remove multiple appearance of this switch case C: case F: setVisibility(id("current_temp_alt"), View.GONE); break; case CF: setText(id("current_temp_alt"), formatter.getTemperatureFormat().format(tempF.getCurrent(), TemperatureType.F), getTextColor()); setVisibility(id("current_temp_alt"), View.VISIBLE); break; case FC: setText(id("current_temp_alt"), formatter.getTemperatureFormat().format(tempC.getCurrent(), TemperatureType.C), getTextColor()); setVisibility(id("current_temp_alt"), View.VISIBLE); break; } setText(id("high_temp"), formatter.getTemperatureFormat().format(mainTemp.getHigh()), getTextColor()); setText(id("low_temp"), formatter.getTemperatureFormat().format(mainTemp.getLow()), getTextColor()); bindForecasts(weather, formatter); bindForecastUrl(weather); } protected void bindUpdateTime(Date update) { if (update.getTime() == 0) { setText(id("update_time"), "", NO_CHANGE_COLOR); } else if (isDate(update)) { setText(id("update_time"), getContext().getString(string("update_date_format"), update), getTextColor()); } else { setText(id("update_time"), getContext().getString(string("update_time_format"), update), getTextColor()); } } protected void bindWindHumidity(WeatherCondition currentCondition, WeatherFormatter formatter) { WindUnit windUnit = formatter.getStyler().getWindUnit(); Wind wind = currentCondition.getWind(windUnit.getWindSpeedUnit()); setText(id("wind"), formatter.getWindFormat().format(wind), getTextColor()); Humidity humidity = currentCondition.getHumidity(); setText(id("humidity"), formatter.getHumidityFormat().format(humidity), getTextColor()); } protected void bindForecasts(Weather weather, WeatherFormatter formatter) { setVisibility(id("forecasts"), View.VISIBLE); bindForecast(weather, formatter, 1, id("forecast_1"), id("forecast_condition_icon_1"), id("forecast_day_1"), id("forecast_condition_1"), id("forecast_high_temp_1"), id("forecast_low_temp_1")); bindForecast(weather, formatter, 2, id("forecast_2"), id("forecast_condition_icon_2"), id("forecast_day_2"), id("forecast_condition_2"), id("forecast_high_temp_2"), id("forecast_low_temp_2")); bindForecast(weather, formatter, 3, id("forecast_3"), id("forecast_condition_icon_3"), id("forecast_day_3"), id("forecast_condition_3"), id("forecast_high_temp_3"), id("forecast_low_temp_3")); } void bindForecast(Weather weather, WeatherFormatter formatter, int i, int groupId, int iconId, int dayId, int conditionId, int highTempId, int lowTempId) { if (weather.getConditions().size() > i) { setVisibility(groupId, View.VISIBLE); WeatherCondition forecastCondition = weather.getConditions().get(i); Date tomorrow = addDays(weather.getTime(), i); setIcon(iconId, formatter.getWeatherConditionFormat().getDrawable(forecastCondition), getForecastIconSize()); setText(dayId, getContext().getString(string("forecast_day_format"), tomorrow), getTextColor()); setText(conditionId, formatter.getWeatherConditionFormat().getText(forecastCondition), getTextColor()); Temperature forecastTemp = forecastCondition.getTemperature( formatter.getStyler().getTempType().getTemperatureUnit()); setText(highTempId, formatter.getTemperatureFormat().format(forecastTemp.getHigh()), getTextColor()); setText(lowTempId, formatter.getTemperatureFormat().format(forecastTemp.getLow()), getTextColor()); } else { setVisibility(groupId, View.GONE); } } void bindForecastUrl(Weather weather) { if (weather.getForecastURL() == null) { setVisibility(id("forecast_url"), View.INVISIBLE); return; } setVisibility(id("forecast_url"), View.VISIBLE); URL url = weather.getForecastURL(); String link = String.format(URL_TEMPLATE, url.toString(), url.getHost()); setMovementMethod(id("forecast_url"), LinkMovementMethod.getInstance()); setText(id("forecast_url"), Html.fromHtml(link), NO_CHANGE_COLOR); } void emptyViews() { setText(id("update_time"), "", NO_CHANGE_COLOR); setText(id("location"), "", NO_CHANGE_COLOR); setText(id("condition"), getContext().getString(string("unknown_weather")), getTextColor()); setText(id("humidity"), "", NO_CHANGE_COLOR); setText(id("wind"), "", NO_CHANGE_COLOR); setText(id("wind_humidity_text"), "", NO_CHANGE_COLOR); setVisibility(id("temp"), View.INVISIBLE); setVisibility(id("forecasts"), View.GONE); setVisibility(id("forecasts_text"), View.GONE); setVisibility(id("forecast_url"), View.INVISIBLE); } protected abstract void setText(int viewId, CharSequence text, int color); protected abstract void setIcon(int viewId, Drawable drawable, int level); protected abstract void setVisibility(int viewId, int visibility); protected abstract void setMovementMethod(int viewId, MovementMethod method); Date addDays(Date date, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, days); return calendar.getTime(); } /** * Returns true if the provided date has zero (0:00:00) time. */ boolean isDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.HOUR) == 0 && calendar.get(Calendar.MINUTE) == 0 && calendar.get(Calendar.SECOND) == 0 && calendar.get(Calendar.MILLISECOND) == 0; } /** * Returns the text color to be set on all text views. * This color is passed to #setText() calls. */ protected abstract int getTextColor(); /** * Returns size of the main condition icon. In dp. */ protected int getMainIconSize() { return MAIN_ICON; } /** * Returns size of the forecast condition icon. In dp. */ protected int getForecastIconSize() { return FORECAST_ICON; } protected WeatherFormatter getWeatherFormatter(Context context, Weather weather) { return new WeatherFormatter(context, 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.skin.impl; import android.os.Build; /** * Constants for preference keys. */ public class PreferenceKeys { /** Temperature unit preference name */ static final String TEMP_UNIT = "temp_unit"; /** Temperature unit default value */ static final String TEMP_UNIT_DEFAULT = TemperatureType.C.toString(); /** Wind speed unit preference name */ static final String WS_UNIT = "ws_unit"; static final String WS_UNIT_DEFAULT = WindUnit.MPH.toString(); /** Notification style preference key */ public static final String NOTIFICATION_STYLE = "notification_style"; /** Notification style defatul value */ public static final String NOTIFICATION_STYLE_DEFAULT = NotificationStyle.CUSTOM_STYLE.toString(); /** Notification text style preference key */ public static final String NOTIFICATION_TEXT_STYLE = "notification_text_style"; /** Notification text style default value */ public static final String NOTIFICATION_TEXT_STYLE_DEFAULT = Integer.valueOf(Build.VERSION.SDK) < 11 ? NotificationTextStyle.BLACK_TEXT.toString() : NotificationTextStyle.WHITE_TEXT.toString(); /** Notification icon style preference key */ public static final String NOTIFICATION_ICON_STYLE = "notification_icon_style"; /** Notification icon style default value */ public static final boolean NOTIFICATION_ICON_STYLE_DEFAULT = true; /** Notification forecast style preference key */ public static final String NOTIFICATION_FORECASTS_STYLE = "notification_forecasts_style"; /** Notification forecast style default value */ public static final boolean NOTIFICATION_FORECASTS_STYLE_DEFAULT = true; private PreferenceKeys() { //avoid instantiation } }
Java
package ru.gelin.android.weather.notification.skin.impl; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.DrawableContainer; /** * Utility class to convert Drawable from resources into Bitmap. */ public class Drawable2Bitmap { /** * Extracts Bitmap from BitmapDrawable. * Goes into DrawableContainer hierarchy using {@link android.graphics.drawable.Drawable#getCurrent()}. * If the final Drawable is not BitmapDrawable, returns null. * @param drawable BitmapDrawable or DrawableContainer * @return Bitmap or null */ public static Bitmap convert(Drawable drawable) { Drawable bitmapDrawable = drawable.getCurrent(); while (bitmapDrawable instanceof DrawableContainer) { bitmapDrawable = drawable.getCurrent(); } if (!(bitmapDrawable instanceof BitmapDrawable)) { return null; } return ((BitmapDrawable)bitmapDrawable).getBitmap(); } private Drawable2Bitmap() { //avoid instantiation } }
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.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import ru.gelin.android.weather.notification.skin.UpdateNotificationActivity; import static ru.gelin.android.weather.notification.skin.impl.ResourceIdFactory.XML; /** * Base class for skin configuration activity. */ public class BaseConfigActivity extends UpdateNotificationActivity implements OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ResourceIdFactory ids = ResourceIdFactory.getInstance(this); addPreferencesFromResource(ids.id(XML, "skin_preferences")); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); enablePreferences(prefs.getString(PreferenceKeys.NOTIFICATION_STYLE, PreferenceKeys.NOTIFICATION_STYLE_DEFAULT)); addPreferenceListener(getPreferenceScreen()); } private void addPreferenceListener(PreferenceGroup prefs) { for (int i = 0; i < prefs.getPreferenceCount(); i++) { Preference pref = prefs.getPreference(i); if (pref instanceof PreferenceGroup) { addPreferenceListener((PreferenceGroup) pref); } else { pref.setOnPreferenceChangeListener(this); } } } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (PreferenceKeys.NOTIFICATION_STYLE.equals(preference.getKey())) { enablePreferences(newValue); } updateNotification(); return true; } private void enablePreferences(Object notificationStyleValue) { boolean enabled = NotificationStyle.CUSTOM_STYLE.equals( NotificationStyle.valueOf(String.valueOf(notificationStyleValue))); findPreference(PreferenceKeys.NOTIFICATION_TEXT_STYLE).setEnabled(enabled); findPreference(PreferenceKeys.NOTIFICATION_ICON_STYLE).setEnabled(enabled); findPreference(PreferenceKeys.NOTIFICATION_FORECASTS_STYLE).setEnabled(enabled); } }
Java