code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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.services; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.os.RemoteException; import android.util.Log; import java.util.List; /** * Helper for reading service state. * * @author Rodrigo Damazio */ public class ServiceUtils { /** * Checks whether we're currently recording. * The checking is done by calling the service, if provided, or alternatively by reading * recording state saved to preferences. * * @param ctx the current context * @param service the service, or null if not bound to it * @param preferences the preferences, or null if not available * @return true if the service is recording (or supposed to be recording), false otherwise */ public static boolean isRecording(Context ctx, ITrackRecordingService service, SharedPreferences preferences) { if (service != null) { try { return service.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to check if service is recording", e); } catch (IllegalStateException e) { Log.e(TAG, "Failed to check if service is recording", e); } } if (preferences == null) { preferences = ctx.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); } return preferences.getLong(ctx.getString(R.string.recording_track_key), -1) > 0; } /** * Checks whether the recording service is currently running. * * @param ctx the current context * @return true if the service is running, false otherwise */ public static boolean isServiceRunning(Context ctx) { ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { ComponentName componentName = serviceInfo.service; String serviceName = componentName.getClassName(); if (serviceName.equals(TrackRecordingService.class.getName())) { return true; } } return false; } private ServiceUtils() {} }
Java
package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.Handler; import android.util.Log; import java.util.EnumSet; import java.util.Set; /** * External data source manager, which converts system-level events into My Tracks data events. * * @author Rodrigo Damazio */ class DataSourceManager { /** Single interface for receiving system events that were registered for. */ interface DataSourceListener { void notifyTrackUpdated(); void notifyWaypointUpdated(); void notifyPointsUpdated(); void notifyPreferenceChanged(String key); void notifyLocationProviderEnabled(boolean enabled); void notifyLocationProviderAvailable(boolean available); void notifyLocationChanged(Location loc); void notifyHeadingChanged(float heading); } private final DataSourceListener listener; /** Observer for when the tracks table is updated. */ private class TrackObserver extends ContentObserver { public TrackObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyTrackUpdated(); } } /** Observer for when the waypoints table is updated. */ private class WaypointObserver extends ContentObserver { public WaypointObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyWaypointUpdated(); } } /** Observer for when the points table is updated. */ private class PointObserver extends ContentObserver { public PointObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyPointsUpdated(); } } /** Listener for when preferences change. */ private class HubSharedPreferenceListener implements OnSharedPreferenceChangeListener { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { listener.notifyPreferenceChanged(key); } } /** Listener for the current location (independent from track data). */ private class CurrentLocationListener implements LocationListener { @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderAvailable(status == LocationProvider.AVAILABLE); } @Override public void onProviderEnabled(String provider) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderEnabled(true); } @Override public void onProviderDisabled(String provider) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderEnabled(false); } @Override public void onLocationChanged(Location location) { listener.notifyLocationChanged(location); } } /** Listener for compass readings. */ private class CompassListener implements SensorEventListener { @Override public void onSensorChanged(SensorEvent event) { listener.notifyHeadingChanged(event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } } /** Wrapper for registering internal listeners. */ private final DataSourcesWrapper dataSources; // Internal listeners (to receive data from the system) private final Set<ListenerDataType> registeredListeners = EnumSet.noneOf(ListenerDataType.class); private final Handler contentHandler; private final ContentObserver pointObserver; private final ContentObserver waypointObserver; private final ContentObserver trackObserver; private final LocationListener locationListener; private final OnSharedPreferenceChangeListener preferenceListener; private final SensorEventListener compassListener; DataSourceManager(DataSourceListener listener, DataSourcesWrapper dataSources) { this.listener = listener; this.dataSources = dataSources; contentHandler = new Handler(); pointObserver = new PointObserver(); waypointObserver = new WaypointObserver(); trackObserver = new TrackObserver(); compassListener = new CompassListener(); locationListener = new CurrentLocationListener(); preferenceListener = new HubSharedPreferenceListener(); } /** Updates the internal (sensor, position, etc) listeners. */ void updateAllListeners(EnumSet<ListenerDataType> externallyNeededListeners) { EnumSet<ListenerDataType> neededListeners = EnumSet.copyOf(externallyNeededListeners); // Special case - map sampled-out points type to points type since they // correspond to the same internal listener. if (neededListeners.contains(ListenerDataType.SAMPLED_OUT_POINT_UPDATES)) { neededListeners.remove(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); neededListeners.add(ListenerDataType.POINT_UPDATES); } Log.d(TAG, "Updating internal listeners to types " + neededListeners); // Unnecessary = registered - needed Set<ListenerDataType> unnecessaryListeners = EnumSet.copyOf(registeredListeners); unnecessaryListeners.removeAll(neededListeners); // Missing = needed - registered Set<ListenerDataType> missingListeners = EnumSet.copyOf(neededListeners); missingListeners.removeAll(registeredListeners); // Remove all unnecessary listeners. for (ListenerDataType type : unnecessaryListeners) { unregisterListener(type); } // Add all missing listeners. for (ListenerDataType type : missingListeners) { registerListener(type); } // Now all needed types are registered. registeredListeners.clear(); registeredListeners.addAll(neededListeners); } private void registerListener(ListenerDataType type) { switch (type) { case COMPASS_UPDATES: { // Listen to compass Sensor compass = dataSources.getSensor(Sensor.TYPE_ORIENTATION); if (compass != null) { Log.d(TAG, "TrackDataHub: Now registering sensor listener."); dataSources.registerSensorListener(compassListener, compass, SensorManager.SENSOR_DELAY_UI); } break; } case LOCATION_UPDATES: dataSources.requestLocationUpdates(locationListener); break; case POINT_UPDATES: dataSources.registerContentObserver( TrackPointsColumns.CONTENT_URI, false, pointObserver); break; case TRACK_UPDATES: dataSources.registerContentObserver(TracksColumns.CONTENT_URI, false, trackObserver); break; case WAYPOINT_UPDATES: dataSources.registerContentObserver( WaypointsColumns.CONTENT_URI, false, waypointObserver); break; case DISPLAY_PREFERENCES: dataSources.registerOnSharedPreferenceChangeListener(preferenceListener); break; case SAMPLED_OUT_POINT_UPDATES: throw new IllegalArgumentException("Should have been mapped to point updates"); } } private void unregisterListener(ListenerDataType type) { switch (type) { case COMPASS_UPDATES: dataSources.unregisterSensorListener(compassListener); break; case LOCATION_UPDATES: dataSources.removeLocationUpdates(locationListener); break; case POINT_UPDATES: dataSources.unregisterContentObserver(pointObserver); break; case TRACK_UPDATES: dataSources.unregisterContentObserver(trackObserver); break; case WAYPOINT_UPDATES: dataSources.unregisterContentObserver(waypointObserver); break; case DISPLAY_PREFERENCES: dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListener); break; case SAMPLED_OUT_POINT_UPDATES: throw new IllegalArgumentException("Should have been mapped to point updates"); } } /** Unregisters all internal (sensor, position, etc.) listeners. */ void unregisterAllListeners() { dataSources.removeLocationUpdates(locationListener); dataSources.unregisterSensorListener(compassListener); dataSources.unregisterContentObserver(trackObserver); dataSources.unregisterContentObserver(waypointObserver); dataSources.unregisterContentObserver(pointObserver); dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListener); } }
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.content; import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS; import static com.google.android.apps.mytracks.Constants.MAX_NETWORK_AGE_MS; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.hardware.Sensor; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.net.Uri; import android.util.Log; import android.widget.Toast; /** * Real implementation of the data sources, which talks to system services. * * @author Rodrigo Damazio */ class DataSourcesWrapperImpl implements DataSourcesWrapper { // System services private final SensorManager sensorManager; private final LocationManager locationManager; private final ContentResolver contentResolver; private final SharedPreferences sharedPreferences; private final Context context; DataSourcesWrapperImpl(Context context, SharedPreferences sharedPreferences) { this.context = context; this.sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); this.contentResolver = context.getContentResolver(); this.sharedPreferences = sharedPreferences; } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } @Override public void registerContentObserver(Uri contentUri, boolean descendents, ContentObserver observer) { contentResolver.registerContentObserver(contentUri, descendents, observer); } @Override public void unregisterContentObserver(ContentObserver observer) { contentResolver.unregisterContentObserver(observer); } @Override public Sensor getSensor(int type) { return sensorManager.getDefaultSensor(type); } @Override public void registerSensorListener(SensorEventListener listener, Sensor sensor, int sensorDelay) { sensorManager.registerListener(listener, sensor, sensorDelay); } @Override public void unregisterSensorListener(SensorEventListener listener) { sensorManager.unregisterListener(listener); } @Override public boolean isLocationProviderEnabled(String provider) { return locationManager.isProviderEnabled(provider); } @Override public void requestLocationUpdates(LocationListener listener) { // Check if the provider exists. LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER); if (gpsProvider == null) { listener.onProviderDisabled(LocationManager.GPS_PROVIDER); locationManager.removeUpdates(listener); return; } // Listen to GPS location. String providerName = gpsProvider.getName(); Log.d(Constants.TAG, "TrackDataHub: Using location provider " + providerName); locationManager.requestLocationUpdates(providerName, 0 /*minTime*/, 0 /*minDist*/, listener); // Give an initial update on provider state. if (locationManager.isProviderEnabled(providerName)) { listener.onProviderEnabled(providerName); } else { listener.onProviderDisabled(providerName); } // Listen to network location try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60 * 5 /*minTime*/, 0 /*minDist*/, listener); } catch (RuntimeException e) { // If anything at all goes wrong with getting a cell location do not // abort. Cell location is not essential to this app. Log.w(Constants.TAG, "Could not register network location listener.", e); } } @Override public Location getLastKnownLocation() { // TODO: Let's look at more advanced algorithms to determine the best // current location. Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); final long now = System.currentTimeMillis(); if (loc == null || loc.getTime() < now - MAX_LOCATION_AGE_MS) { // We don't have a recent GPS fix, just use cell towers if available loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); int toastResId = R.string.my_location_approximate_location; if (loc == null || loc.getTime() < now - MAX_NETWORK_AGE_MS) { // We don't have a recent cell tower location, let the user know: toastResId = R.string.my_location_no_location; } // Let the user know we have only an approximate location: Toast.makeText(context, context.getString(toastResId), Toast.LENGTH_LONG).show(); } return loc; } @Override public void removeLocationUpdates(LocationListener listener) { locationManager.removeUpdates(listener); } }
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.content; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import android.util.Log; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** * Manager for the external data listeners and their listening types. * * @author Rodrigo Damazio */ class TrackDataListeners { /** Internal representation of a listener's registration. */ static class ListenerRegistration { final TrackDataListener listener; final EnumSet<ListenerDataType> types; // State that was last notified to the listener, for resuming after a pause. long lastTrackId; long lastPointId; int lastSamplingFrequency; int numLoadedPoints; public ListenerRegistration(TrackDataListener listener, EnumSet<ListenerDataType> types) { this.listener = listener; this.types = types; } public boolean isInterestedIn(ListenerDataType type) { return types.contains(type); } public void resetState() { lastTrackId = 0L; lastPointId = 0L; lastSamplingFrequency = 0; numLoadedPoints = 0; } @Override public String toString() { return "ListenerRegistration [listener=" + listener + ", types=" + types + ", lastTrackId=" + lastTrackId + ", lastPointId=" + lastPointId + ", lastSamplingFrequency=" + lastSamplingFrequency + ", numLoadedPoints=" + numLoadedPoints + "]"; } } /** Map of external listener to its registration details. */ private final Map<TrackDataListener, ListenerRegistration> registeredListeners = new HashMap<TrackDataListener, ListenerRegistration>(); /** * Map of external paused listener to its registration details. * This will automatically discard listeners which are GCed. */ private final WeakHashMap<TrackDataListener, ListenerRegistration> oldListeners = new WeakHashMap<TrackDataListener, ListenerRegistration>(); /** Map of data type to external listeners interested in it. */ private final Map<ListenerDataType, Set<TrackDataListener>> listenerSetsPerType = new EnumMap<ListenerDataType, Set<TrackDataListener>>(ListenerDataType.class); public TrackDataListeners() { // Create sets for all data types at startup. for (ListenerDataType type : ListenerDataType.values()) { listenerSetsPerType.put(type, new LinkedHashSet<TrackDataListener>()); } } /** * Registers a listener to send data to. * It is ok to call this method before {@link TrackDataHub#start}, and in that case * the data will only be passed to listeners when {@link TrackDataHub#start} is called. * * @param listener the listener to register * @param dataTypes the type of data that the listener is interested in */ public ListenerRegistration registerTrackDataListener(final TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) { Log.d(TAG, "Registered track data listener: " + listener); if (registeredListeners.containsKey(listener)) { throw new IllegalStateException("Listener already registered"); } ListenerRegistration registration = oldListeners.remove(listener); if (registration == null) { registration = new ListenerRegistration(listener, dataTypes); } registeredListeners.put(listener, registration); for (ListenerDataType type : dataTypes) { // This is guaranteed not to be null. Set<TrackDataListener> typeSet = listenerSetsPerType.get(type); typeSet.add(listener); } return registration; } /** * Unregisters a listener to send data to. * * @param listener the listener to unregister */ public void unregisterTrackDataListener(TrackDataListener listener) { Log.d(TAG, "Unregistered track data listener: " + listener); // Remove and keep the corresponding registration. ListenerRegistration match = registeredListeners.remove(listener); if (match == null) { Log.w(TAG, "Tried to unregister listener which is not registered."); return; } // Remove it from the per-type sets for (ListenerDataType type : match.types) { listenerSetsPerType.get(type).remove(listener); } // Keep it around in case it's re-registered soon oldListeners.put(listener, match); } public ListenerRegistration getRegistration(TrackDataListener listener) { ListenerRegistration registration = registeredListeners.get(listener); if (registration == null) { registration = oldListeners.get(listener); } return registration; } public Set<TrackDataListener> getListenersFor(ListenerDataType type) { return listenerSetsPerType.get(type); } public EnumSet<ListenerDataType> getAllRegisteredTypes() { EnumSet<ListenerDataType> listeners = EnumSet.noneOf(ListenerDataType.class); for (ListenerRegistration registration : this.registeredListeners.values()) { listeners.addAll(registration.types); } return listeners; } public boolean hasListeners() { return !registeredListeners.isEmpty(); } public int getNumListeners() { return registeredListeners.size(); } }
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 com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.os.Binder; import android.os.Process; import android.text.TextUtils; import android.util.Log; /** * A provider that handles recorded (GPS) tracks and their track points. * * @author Leif Hendrik Wilden */ public class MyTracksProvider extends ContentProvider { private static final String DATABASE_NAME = "mytracks.db"; private static final int DATABASE_VERSION = 19; private static final int TRACKPOINTS = 1; private static final int TRACKPOINTS_ID = 2; private static final int TRACKS = 3; private static final int TRACKS_ID = 4; private static final int WAYPOINTS = 5; private static final int WAYPOINTS_ID = 6; private static final String TRACKPOINTS_TABLE = "trackpoints"; private static final String TRACKS_TABLE = "tracks"; private static final String WAYPOINTS_TABLE = "waypoints"; public static final String TAG = "MyTracksProvider"; /** * Helper which creates or upgrades the database if necessary. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TRACKPOINTS_TABLE + " (" + TrackPointsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TrackPointsColumns.TRACKID + " INTEGER, " + TrackPointsColumns.LONGITUDE + " INTEGER, " + TrackPointsColumns.LATITUDE + " INTEGER, " + TrackPointsColumns.TIME + " INTEGER, " + TrackPointsColumns.ALTITUDE + " FLOAT, " + TrackPointsColumns.ACCURACY + " FLOAT, " + TrackPointsColumns.SPEED + " FLOAT, " + TrackPointsColumns.BEARING + " FLOAT, " + TrackPointsColumns.SENSOR + " BLOB);"); db.execSQL("CREATE TABLE " + TRACKS_TABLE + " (" + TracksColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TracksColumns.NAME + " STRING, " + TracksColumns.DESCRIPTION + " STRING, " + TracksColumns.CATEGORY + " STRING, " + TracksColumns.STARTID + " INTEGER, " + TracksColumns.STOPID + " INTEGER, " + TracksColumns.STARTTIME + " INTEGER, " + TracksColumns.STOPTIME + " INTEGER, " + TracksColumns.NUMPOINTS + " INTEGER, " + TracksColumns.TOTALDISTANCE + " FLOAT, " + TracksColumns.TOTALTIME + " INTEGER, " + TracksColumns.MOVINGTIME + " INTEGER, " + TracksColumns.MINLAT + " INTEGER, " + TracksColumns.MAXLAT + " INTEGER, " + TracksColumns.MINLON + " INTEGER, " + TracksColumns.MAXLON + " INTEGER, " + TracksColumns.AVGSPEED + " FLOAT, " + TracksColumns.AVGMOVINGSPEED + " FLOAT, " + TracksColumns.MAXSPEED + " FLOAT, " + TracksColumns.MINELEVATION + " FLOAT, " + TracksColumns.MAXELEVATION + " FLOAT, " + TracksColumns.ELEVATIONGAIN + " FLOAT, " + TracksColumns.MINGRADE + " FLOAT, " + TracksColumns.MAXGRADE + " FLOAT, " + TracksColumns.MAPID + " STRING, " + TracksColumns.TABLEID + " STRING);"); db.execSQL("CREATE TABLE " + WAYPOINTS_TABLE + " (" + WaypointsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + WaypointsColumns.NAME + " STRING, " + WaypointsColumns.DESCRIPTION + " STRING, " + WaypointsColumns.CATEGORY + " STRING, " + WaypointsColumns.ICON + " STRING, " + WaypointsColumns.TRACKID + " INTEGER, " + WaypointsColumns.TYPE + " INTEGER, " + WaypointsColumns.LENGTH + " FLOAT, " + WaypointsColumns.DURATION + " INTEGER, " + WaypointsColumns.STARTTIME + " INTEGER, " + WaypointsColumns.STARTID + " INTEGER, " + WaypointsColumns.STOPID + " INTEGER, " + WaypointsColumns.LONGITUDE + " INTEGER, " + WaypointsColumns.LATITUDE + " INTEGER, " + WaypointsColumns.TIME + " INTEGER, " + WaypointsColumns.ALTITUDE + " FLOAT, " + WaypointsColumns.ACCURACY + " FLOAT, " + WaypointsColumns.SPEED + " FLOAT, " + WaypointsColumns.BEARING + " FLOAT, " + WaypointsColumns.TOTALDISTANCE + " FLOAT, " + WaypointsColumns.TOTALTIME + " INTEGER, " + WaypointsColumns.MOVINGTIME + " INTEGER, " + WaypointsColumns.AVGSPEED + " FLOAT, " + WaypointsColumns.AVGMOVINGSPEED + " FLOAT, " + WaypointsColumns.MAXSPEED + " FLOAT, " + WaypointsColumns.MINELEVATION + " FLOAT, " + WaypointsColumns.MAXELEVATION + " FLOAT, " + WaypointsColumns.ELEVATIONGAIN + " FLOAT, " + WaypointsColumns.MINGRADE + " FLOAT, " + WaypointsColumns.MAXGRADE + " FLOAT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 17) { // Wipe the old data. Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TRACKPOINTS_TABLE); db.execSQL("DROP TABLE IF EXISTS " + TRACKS_TABLE); db.execSQL("DROP TABLE IF EXISTS " + WAYPOINTS_TABLE); onCreate(db); } else { // Incremental updates go here. // Each time you increase the DB version, add a corresponding if clause. Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion); // Sensor data. if (oldVersion <= 17) { Log.w(TAG, "Upgrade DB: Adding sensor column."); db.execSQL("ALTER TABLE " + TRACKPOINTS_TABLE + " ADD " + TrackPointsColumns.SENSOR + " BLOB"); } if (oldVersion <= 18) { Log.w(TAG, "Upgrade DB: Adding tableid column."); db.execSQL("ALTER TABLE " + TRACKS_TABLE + " ADD " + TracksColumns.TABLEID + " STRING"); } } } } private final UriMatcher urlMatcher; private SQLiteDatabase db; public MyTracksProvider() { urlMatcher = new UriMatcher(UriMatcher.NO_MATCH); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "trackpoints", TRACKPOINTS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "trackpoints/#", TRACKPOINTS_ID); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "tracks", TRACKS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "tracks/#", TRACKS_ID); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "waypoints", WAYPOINTS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "waypoints/#", WAYPOINTS_ID); } private boolean canAccess() { if (Binder.getCallingPid() == Process.myPid()) { return true; } else { Context context = getContext(); SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(context.getString(R.string.allow_access_key), false); } } @Override public boolean onCreate() { if (!canAccess()) { return false; } DatabaseHelper dbHelper = new DatabaseHelper(getContext()); try { db = dbHelper.getWritableDatabase(); } catch (SQLiteException e) { Log.e(TAG, "Unable to open database for writing", e); } return db != null; } @Override public int delete(Uri url, String where, String[] selectionArgs) { if (!canAccess()) { return 0; } String table; boolean shouldVacuum = false; switch (urlMatcher.match(url)) { case TRACKPOINTS: table = TRACKPOINTS_TABLE; break; case TRACKS: table = TRACKS_TABLE; shouldVacuum = true; break; case WAYPOINTS: table = WAYPOINTS_TABLE; break; default: throw new IllegalArgumentException("Unknown URL " + url); } Log.w(MyTracksProvider.TAG, "provider delete in " + table + "!"); int count = db.delete(table, where, selectionArgs); getContext().getContentResolver().notifyChange(url, null, true); if (shouldVacuum) { // If a potentially large amount of data was deleted, we want to reclaim its space. Log.i(TAG, "Vacuuming the database"); db.execSQL("VACUUM"); } return count; } @Override public String getType(Uri url) { if (!canAccess()) { return null; } switch (urlMatcher.match(url)) { case TRACKPOINTS: return TrackPointsColumns.CONTENT_TYPE; case TRACKPOINTS_ID: return TrackPointsColumns.CONTENT_ITEMTYPE; case TRACKS: return TracksColumns.CONTENT_TYPE; case TRACKS_ID: return TracksColumns.CONTENT_ITEMTYPE; case WAYPOINTS: return WaypointsColumns.CONTENT_TYPE; case WAYPOINTS_ID: return WaypointsColumns.CONTENT_ITEMTYPE; default: throw new IllegalArgumentException("Unknown URL " + url); } } @Override public Uri insert(Uri url, ContentValues initialValues) { if (!canAccess()) { return null; } Log.d(MyTracksProvider.TAG, "MyTracksProvider.insert"); ContentValues values; if (initialValues != null) { values = initialValues; } else { values = new ContentValues(); } int urlMatchType = urlMatcher.match(url); return insertType(url, urlMatchType, values); } private Uri insertType(Uri url, int urlMatchType, ContentValues values) { switch (urlMatchType) { case TRACKPOINTS: return insertTrackPoint(url, values); case TRACKS: return insertTrack(url, values); case WAYPOINTS: return insertWaypoint(url, values); default: throw new IllegalArgumentException("Unknown URL " + url); } } @Override public int bulkInsert(Uri url, ContentValues[] valuesBulk) { if (!canAccess()) { return 0; } Log.d(MyTracksProvider.TAG, "MyTracksProvider.bulkInsert"); int numInserted = 0; try { // Use a transaction in order to make the insertions run as a single batch db.beginTransaction(); int urlMatch = urlMatcher.match(url); for (numInserted = 0; numInserted < valuesBulk.length; numInserted++) { ContentValues values = valuesBulk[numInserted]; if (values == null) { values = new ContentValues(); } insertType(url, urlMatch, values); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return numInserted; } private Uri insertTrackPoint(Uri url, ContentValues values) { boolean hasLat = values.containsKey(TrackPointsColumns.LATITUDE); boolean hasLong = values.containsKey(TrackPointsColumns.LONGITUDE); boolean hasTime = values.containsKey(TrackPointsColumns.TIME); if (!hasLat || !hasLong || !hasTime) { throw new IllegalArgumentException( "Latitude, longitude, and time values are required."); } long rowId = db.insert(TRACKPOINTS_TABLE, TrackPointsColumns._ID, values); if (rowId >= 0) { Uri uri = ContentUris.appendId( TrackPointsColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLiteException("Failed to insert row into " + url); } private Uri insertTrack(Uri url, ContentValues values) { boolean hasStartTime = values.containsKey(TracksColumns.STARTTIME); boolean hasStartId = values.containsKey(TracksColumns.STARTID); if (!hasStartTime || !hasStartId) { throw new IllegalArgumentException( "Both start time and start id values are required."); } long rowId = db.insert(TRACKS_TABLE, TracksColumns._ID, values); if (rowId > 0) { Uri uri = ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLException("Failed to insert row into " + url); } private Uri insertWaypoint(Uri url, ContentValues values) { long rowId = db.insert(WAYPOINTS_TABLE, WaypointsColumns._ID, values); if (rowId > 0) { Uri uri = ContentUris.appendId( WaypointsColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLException("Failed to insert row into " + url); } @Override public Cursor query( Uri url, String[] projection, String selection, String[] selectionArgs, String sort) { if (!canAccess()) { return null; } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); int match = urlMatcher.match(url); String sortOrder = null; if (match == TRACKPOINTS) { qb.setTables(TRACKPOINTS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = TrackPointsColumns.DEFAULT_SORT_ORDER; } } else if (match == TRACKPOINTS_ID) { qb.setTables(TRACKPOINTS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else if (match == TRACKS) { qb.setTables(TRACKS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = TracksColumns.DEFAULT_SORT_ORDER; } } else if (match == TRACKS_ID) { qb.setTables(TRACKS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else if (match == WAYPOINTS) { qb.setTables(WAYPOINTS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = WaypointsColumns.DEFAULT_SORT_ORDER; } } else if (match == WAYPOINTS_ID) { qb.setTables(WAYPOINTS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else { throw new IllegalArgumentException("Unknown URL " + url); } if (ApiFeatures.getInstance().canReuseSQLiteQueryBuilder()) { Log.i(Constants.TAG, "Build query: " + qb.buildQuery(projection, selection, selectionArgs, null, null, sortOrder, null)); } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), url); return c; } @Override public int update(Uri url, ContentValues values, String where, String[] selectionArgs) { if (!canAccess()) { return 0; } int count; int match = urlMatcher.match(url); if (match == TRACKPOINTS) { count = db.update(TRACKPOINTS_TABLE, values, where, selectionArgs); } else if (match == TRACKPOINTS_ID) { String segment = url.getPathSegments().get(1); count = db.update(TRACKPOINTS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else if (match == TRACKS) { count = db.update(TRACKS_TABLE, values, where, selectionArgs); } else if (match == TRACKS_ID) { String segment = url.getPathSegments().get(1); count = db.update(TRACKS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else if (match == WAYPOINTS) { count = db.update(WAYPOINTS_TABLE, values, where, selectionArgs); } else if (match == WAYPOINTS_ID) { String segment = url.getPathSegments().get(1); count = db.update(WAYPOINTS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else { throw new IllegalArgumentException("Unknown URL " + url); } getContext().getContentResolver().notifyChange(url, null, true); return count; } }
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; /** * Utilities for serializing primitive types. * * @author Rodrigo Damazio */ public class ContentTypeIds { public static final byte BOOLEAN_TYPE_ID = 0; public static final byte LONG_TYPE_ID = 1; public static final byte INT_TYPE_ID = 2; public static final byte FLOAT_TYPE_ID = 3; public static final byte DOUBLE_TYPE_ID = 4; public static final byte STRING_TYPE_ID = 5; public static final byte BLOB_TYPE_ID = 6; private ContentTypeIds() { /* Not instantiable */ } }
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.content; import static com.google.android.apps.mytracks.Constants.DEFAULT_MIN_REQUIRED_ACCURACY; import static com.google.android.apps.mytracks.Constants.MAX_DISPLAYED_WAYPOINTS_POINTS; import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS; import static com.google.android.apps.mytracks.Constants.MAX_NETWORK_AGE_MS; import static com.google.android.apps.mytracks.Constants.TAG; import static com.google.android.apps.mytracks.Constants.TARGET_DISPLAYED_TRACK_POINTS; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DataSourceManager.DataSourceListener; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.DoubleBufferedLocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState; import com.google.android.apps.mytracks.content.TrackDataListeners.ListenerRegistration; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.hardware.GeomagneticField; import android.location.Location; import android.location.LocationManager; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.util.Collections; import java.util.EnumSet; import java.util.Set; /** * Track data hub, which receives data (both live and recorded) from many * different sources and distributes it to those interested after some standard * processing. * * TODO: Simplify the threading model here, it's overly complex and it's not obvious why * certain race conditions won't happen. * * @author Rodrigo Damazio */ public class TrackDataHub { // Preference keys private final String SELECTED_TRACK_KEY; private final String RECORDING_TRACK_KEY; private final String MIN_REQUIRED_ACCURACY_KEY; private final String METRIC_UNITS_KEY; private final String SPEED_REPORTING_KEY; // Overridable constants private final int targetNumPoints; /** Types of data that we can expose. */ public static enum ListenerDataType { /** Listen to when the selected track changes. */ SELECTED_TRACK_CHANGED, /** Listen to when the tracks change. */ TRACK_UPDATES, /** Listen to when the waypoints change. */ WAYPOINT_UPDATES, /** Listen to when the current track points change. */ POINT_UPDATES, /** * Listen to sampled-out points. * Listening to this without listening to {@link #POINT_UPDATES} * makes no sense and may yield unexpected results. */ SAMPLED_OUT_POINT_UPDATES, /** Listen to updates to the current location. */ LOCATION_UPDATES, /** Listen to updates to the current heading. */ COMPASS_UPDATES, /** Listens to changes in display preferences. */ DISPLAY_PREFERENCES; } /** Listener which receives events from the system. */ private class HubDataSourceListener implements DataSourceListener { @Override public void notifyTrackUpdated() { TrackDataHub.this.notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES)); } @Override public void notifyWaypointUpdated() { TrackDataHub.this.notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES)); } @Override public void notifyPointsUpdated() { TrackDataHub.this.notifyPointsUpdated(true, 0, 0, getListenersFor(ListenerDataType.POINT_UPDATES), getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES)); } @Override public void notifyPreferenceChanged(String key) { TrackDataHub.this.notifyPreferenceChanged(key); } @Override public void notifyLocationProviderEnabled(boolean enabled) { hasProviderEnabled = enabled; TrackDataHub.this.notifyFixType(); } @Override public void notifyLocationProviderAvailable(boolean available) { hasFix = available; TrackDataHub.this.notifyFixType(); } @Override public void notifyLocationChanged(Location loc) { TrackDataHub.this.notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } @Override public void notifyHeadingChanged(float heading) { lastSeenMagneticHeading = heading; maybeUpdateDeclination(); TrackDataHub.this.notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES)); } } // Application services private final Context context; private final MyTracksProviderUtils providerUtils; private final SharedPreferences preferences; // Get content notifications on the main thread, send listener callbacks in another. // This ensures listener calls are serialized. private HandlerThread listenerHandlerThread; private Handler listenerHandler; /** Manager for external listeners (those from activities). */ private final TrackDataListeners dataListeners; /** Wrapper for interacting with system data managers. */ private DataSourcesWrapper dataSources; /** Manager for system data listener registrations. */ private DataSourceManager dataSourceManager; /** Condensed listener for system data listener events. */ private final DataSourceListener dataSourceListener = new HubDataSourceListener(); // Cached preference values private int minRequiredAccuracy; private boolean useMetricUnits; private boolean reportSpeed; // Cached sensor readings private float declination; private long lastDeclinationUpdate; private float lastSeenMagneticHeading; // Cached GPS readings private Location lastSeenLocation; private boolean hasProviderEnabled = true; private boolean hasFix; private boolean hasGoodFix; // Transient state about the selected track private long selectedTrackId; private long firstSeenLocationId; private long lastSeenLocationId; private int numLoadedPoints; private int lastSamplingFrequency; private DoubleBufferedLocationFactory locationFactory; private boolean started = false; /** * Builds a new {@link TrackDataHub} instance. */ public synchronized static TrackDataHub newInstance(Context context) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(context); return new TrackDataHub(context, new TrackDataListeners(), preferences, providerUtils, TARGET_DISPLAYED_TRACK_POINTS); } /** * Injection constructor. */ // @VisibleForTesting TrackDataHub(Context ctx, TrackDataListeners listeners, SharedPreferences preferences, MyTracksProviderUtils providerUtils, int targetNumPoints) { this.context = ctx; this.dataListeners = listeners; this.preferences = preferences; this.providerUtils = providerUtils; this.targetNumPoints = targetNumPoints; this.locationFactory = new DoubleBufferedLocationFactory(); SELECTED_TRACK_KEY = context.getString(R.string.selected_track_key); RECORDING_TRACK_KEY = context.getString(R.string.recording_track_key); MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key); METRIC_UNITS_KEY = context.getString(R.string.metric_units_key); SPEED_REPORTING_KEY = context.getString(R.string.report_speed_key); resetState(); } /** * Starts listening to data sources and reporting the data to external * listeners. */ public void start() { Log.i(TAG, "TrackDataHub.start"); if (isStarted()) { Log.w(TAG, "Already started, ignoring"); return; } started = true; listenerHandlerThread = new HandlerThread("trackDataContentThread"); listenerHandlerThread.start(); listenerHandler = new Handler(listenerHandlerThread.getLooper()); dataSources = newDataSources(); dataSourceManager = new DataSourceManager(dataSourceListener, dataSources); // This may or may not register internal listeners, depending on whether // we already had external listeners. dataSourceManager.updateAllListeners(getNeededListenerTypes()); loadSharedPreferences(); // If there were listeners already registered, make sure they become up-to-date. loadDataForAllListeners(); } // @VisibleForTesting protected DataSourcesWrapper newDataSources() { return new DataSourcesWrapperImpl(context, preferences); } /** * Stops listening to data sources and reporting the data to external * listeners. */ public void stop() { Log.i(TAG, "TrackDataHub.stop"); if (!isStarted()) { Log.w(TAG, "Not started, ignoring"); return; } // Unregister internal listeners even if there are external listeners registered. dataSourceManager.unregisterAllListeners(); listenerHandlerThread.getLooper().quit(); started = false; dataSources = null; dataSourceManager = null; listenerHandlerThread = null; listenerHandler = null; } private boolean isStarted() { return started; } @Override protected void finalize() throws Throwable { if (isStarted() || (listenerHandlerThread != null && listenerHandlerThread.isAlive())) { Log.e(TAG, "Forgot to stop() TrackDataHub"); } super.finalize(); } private void loadSharedPreferences() { selectedTrackId = preferences.getLong(SELECTED_TRACK_KEY, -1); useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true); reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true); minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY, DEFAULT_MIN_REQUIRED_ACCURACY); } /** Updates known magnetic declination if needed. */ private void maybeUpdateDeclination() { if (lastSeenLocation == null) { // We still don't know where we are. return; } // Update the declination every hour long now = System.currentTimeMillis(); if (now - lastDeclinationUpdate < 60 * 60 * 1000) { return; } lastDeclinationUpdate = now; long timestamp = lastSeenLocation.getTime(); if (timestamp == 0) { // Hack for Samsung phones which don't populate the time field timestamp = now; } declination = getDeclinationFor(lastSeenLocation, timestamp); Log.i(TAG, "Updated magnetic declination to " + declination); } // @VisibleForTesting protected float getDeclinationFor(Location location, long timestamp) { GeomagneticField field = new GeomagneticField( (float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), timestamp); return field.getDeclination(); } /** * Forces the current location to be updated and reported to all listeners. * The reported location may be from the network provider if the GPS provider * is not available or doesn't have a fix. */ public void forceUpdateLocation() { if (!isStarted()) { Log.w(TAG, "Not started, not forcing location update"); return; } Log.i(TAG, "Forcing location update"); Location loc = dataSources.getLastKnownLocation(); if (loc != null) { notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } } /** Returns the ID of the currently-selected track. */ public long getSelectedTrackId() { if (!isStarted()) { loadSharedPreferences(); } return selectedTrackId; } /** Returns whether there's a track currently selected. */ public boolean isATrackSelected() { return getSelectedTrackId() > 0; } /** Returns whether the selected track is still being recorded. */ public boolean isRecordingSelected() { if (!isStarted()) { loadSharedPreferences(); } long recordingTrackId = preferences.getLong(RECORDING_TRACK_KEY, -1); return recordingTrackId > 0 && recordingTrackId == selectedTrackId; } /** * Loads the given track and makes it the currently-selected one. * It is ok to call this method before {@link #start}, and in that case * the data will only be passed to listeners when {@link #start} is called. * * @param trackId the ID of the track to load */ public void loadTrack(long trackId) { if (trackId == selectedTrackId) { Log.w(TAG, "Not reloading track, id=" + trackId); return; } // Save the selection to memory and flush. selectedTrackId = trackId; ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges( preferences.edit().putLong(SELECTED_TRACK_KEY, trackId)); // Force it to reload data from the beginning. Log.d(TAG, "Loading track"); resetState(); loadDataForAllListeners(); } /** * Resets the internal state of what data has already been loaded into listeners. */ private void resetState() { firstSeenLocationId = -1; lastSeenLocationId = -1; numLoadedPoints = 0; lastSamplingFrequency = -1; } /** * Unloads the currently-selected track. */ public void unloadCurrentTrack() { loadTrack(-1); } public void registerTrackDataListener( TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) { synchronized (dataListeners) { ListenerRegistration registration = dataListeners.registerTrackDataListener(listener, dataTypes); // Don't load any data or start internal listeners if start() hasn't been // called. When it is called, we'll do both things. if (!isStarted()) return; loadNewDataForListener(registration); dataSourceManager.updateAllListeners(getNeededListenerTypes()); } } public void unregisterTrackDataListener(TrackDataListener listener) { synchronized (dataListeners) { dataListeners.unregisterTrackDataListener(listener); // Don't load any data or start internal listeners if start() hasn't been // called. When it is called, we'll do both things. if (!isStarted()) return; dataSourceManager.updateAllListeners(getNeededListenerTypes()); } } /** * Reloads all track data received so far into the specified listeners. */ public void reloadDataForListener(TrackDataListener listener) { ListenerRegistration registration; synchronized (dataListeners) { registration = dataListeners.getRegistration(listener); registration.resetState(); loadNewDataForListener(registration); } } /** * Reloads all track data received so far into the specified listeners. * * Assumes it's called from a block that synchronizes on {@link #dataListeners}. */ private void loadNewDataForListener(final ListenerRegistration registration) { if (!isStarted()) { Log.w(TAG, "Not started, not reloading"); return; } if (registration == null) { Log.w(TAG, "Not reloading for null registration"); return; } // If a listener happens to be added after this method but before the Runnable below is // executed, it will have triggered a separate call to load data only up to the point this // listener got to. This is ensured by being synchronized on listeners. final boolean isOnlyListener = (dataListeners.getNumListeners() == 1); runInListenerThread(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { // Reload everything if either it's a different track, or the track has been resampled // (this also covers the case of a new registration). boolean reloadAll = registration.lastTrackId != selectedTrackId || registration.lastSamplingFrequency != lastSamplingFrequency; Log.d(TAG, "Doing a " + (reloadAll ? "full" : "partial") + " reload for " + registration); TrackDataListener listener = registration.listener; Set<TrackDataListener> listenerSet = Collections.singleton(listener); if (registration.isInterestedIn(ListenerDataType.DISPLAY_PREFERENCES)) { reloadAll |= listener.onUnitsChanged(useMetricUnits); reloadAll |= listener.onReportSpeedChanged(reportSpeed); } if (reloadAll && registration.isInterestedIn(ListenerDataType.SELECTED_TRACK_CHANGED)) { notifySelectedTrackChanged(selectedTrackId, listenerSet); } if (registration.isInterestedIn(ListenerDataType.TRACK_UPDATES)) { notifyTrackUpdated(listenerSet); } boolean interestedInPoints = registration.isInterestedIn(ListenerDataType.POINT_UPDATES); boolean interestedInSampledOutPoints = registration.isInterestedIn(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); if (interestedInPoints || interestedInSampledOutPoints) { long minPointId = 0; int previousNumPoints = 0; if (reloadAll) { // Clear existing points and send them all again notifyPointsCleared(listenerSet); } else { // Send only new points minPointId = registration.lastPointId + 1; previousNumPoints = registration.numLoadedPoints; } // If this is the only listener we have registered, keep the state that we serve to it as // a reference for other future listeners. if (isOnlyListener && reloadAll) { resetState(); } notifyPointsUpdated(isOnlyListener, minPointId, previousNumPoints, listenerSet, interestedInSampledOutPoints ? listenerSet : Collections.EMPTY_SET); } if (registration.isInterestedIn(ListenerDataType.WAYPOINT_UPDATES)) { notifyWaypointUpdated(listenerSet); } if (registration.isInterestedIn(ListenerDataType.LOCATION_UPDATES)) { if (lastSeenLocation != null) { notifyLocationChanged(lastSeenLocation, true, listenerSet); } else { notifyFixType(); } } if (registration.isInterestedIn(ListenerDataType.COMPASS_UPDATES)) { notifyHeadingChanged(listenerSet); } } }); } /** * Reloads all track data received so far into the specified listeners. */ private void loadDataForAllListeners() { if (!isStarted()) { Log.w(TAG, "Not started, not reloading"); return; } synchronized (dataListeners) { if (!dataListeners.hasListeners()) { Log.d(TAG, "No listeners, not reloading"); return; } } runInListenerThread(new Runnable() { @Override public void run() { // Ignore the return values here, we're already sending the full data set anyway for (TrackDataListener listener : getListenersFor(ListenerDataType.DISPLAY_PREFERENCES)) { listener.onUnitsChanged(useMetricUnits); listener.onReportSpeedChanged(reportSpeed); } notifySelectedTrackChanged(selectedTrackId, getListenersFor(ListenerDataType.SELECTED_TRACK_CHANGED)); notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES)); Set<TrackDataListener> pointListeners = getListenersFor(ListenerDataType.POINT_UPDATES); Set<TrackDataListener> sampledOutPointListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); notifyPointsCleared(pointListeners); notifyPointsUpdated(true, 0, 0, pointListeners, sampledOutPointListeners); notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES)); if (lastSeenLocation != null) { notifyLocationChanged(lastSeenLocation, true, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } else { notifyFixType(); } notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES)); } }); } /** * Called when a preference changes. * * @param key the key to the preference that changed */ private void notifyPreferenceChanged(String key) { if (MIN_REQUIRED_ACCURACY_KEY.equals(key)) { minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY, DEFAULT_MIN_REQUIRED_ACCURACY); } else if (METRIC_UNITS_KEY.equals(key)) { useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true); notifyUnitsChanged(); } else if (SPEED_REPORTING_KEY.equals(key)) { reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true); notifySpeedReportingChanged(); } else if (SELECTED_TRACK_KEY.equals(key)) { long trackId = preferences.getLong(SELECTED_TRACK_KEY, -1); loadTrack(trackId); } } /** Called when the speed/pace reporting preference changes. */ private void notifySpeedReportingChanged() { if (!isStarted()) return; runInListenerThread(new Runnable() { @Override public void run() { Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES); for (TrackDataListener listener : displayListeners) { // TODO: Do the reloading just once for all interested listeners if (listener.onReportSpeedChanged(reportSpeed)) { synchronized (dataListeners) { reloadDataForListener(listener); } } } } }); } /** Called when the metric units setting changes. */ private void notifyUnitsChanged() { if (!isStarted()) return; runInListenerThread(new Runnable() { @Override public void run() { Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES); for (TrackDataListener listener : displayListeners) { if (listener.onUnitsChanged(useMetricUnits)) { synchronized (dataListeners) { reloadDataForListener(listener); } } } } }); } /** Notifies about the current GPS fix state. */ private void notifyFixType() { final TrackDataListener.ProviderState state; if (!hasProviderEnabled) { state = ProviderState.DISABLED; } else if (!hasFix) { state = ProviderState.NO_FIX; } else if (!hasGoodFix) { state = ProviderState.BAD_FIX; } else { state = ProviderState.GOOD_FIX; } runInListenerThread(new Runnable() { @Override public void run() { // Notify to everyone. Log.d(TAG, "Notifying fix type: " + state); for (TrackDataListener listener : getListenersFor(ListenerDataType.LOCATION_UPDATES)) { listener.onProviderStateChange(state); } } }); } /** * Notifies the the current location has changed, without any filtering. * If the state of GPS fix has changed, that will also be reported. * * @param location the current location * @param listeners the listeners to notify */ private void notifyLocationChanged(Location location, Set<TrackDataListener> listeners) { notifyLocationChanged(location, false, listeners); } /** * Notifies that the current location has changed, without any filtering. * If the state of GPS fix has changed, that will also be reported. * * @param location the current location * @param forceUpdate whether to force the notifications to happen * @param listeners the listeners to notify */ private void notifyLocationChanged(Location location, boolean forceUpdate, final Set<TrackDataListener> listeners) { if (location == null) return; if (listeners.isEmpty()) return; boolean isGpsLocation = location.getProvider().equals(LocationManager.GPS_PROVIDER); boolean oldHasFix = hasFix; boolean oldHasGoodFix = hasGoodFix; long now = System.currentTimeMillis(); if (isGpsLocation) { // We consider a good fix to be a recent one with reasonable accuracy. hasFix = !isLocationOld(location, now, MAX_LOCATION_AGE_MS); hasGoodFix = (location.getAccuracy() <= minRequiredAccuracy); } else { if (!isLocationOld(lastSeenLocation, now, MAX_LOCATION_AGE_MS)) { // This is a network location, but we have a recent/valid GPS location, just ignore this. return; } // We haven't gotten a GPS location in a while (or at all), assume we have no fix anymore. hasFix = false; hasGoodFix = false; // If the network location is recent, we'll use that. if (isLocationOld(location, now, MAX_NETWORK_AGE_MS)) { // Alas, we have no clue where we are. location = null; } } if (hasFix != oldHasFix || hasGoodFix != oldHasGoodFix || forceUpdate) { notifyFixType(); } lastSeenLocation = location; final Location finalLoc = location; runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onCurrentLocationChanged(finalLoc); } } }); } /** * Returns true if the given location is either invalid or too old. * * @param location the location to test * @param now the current timestamp in milliseconds * @param maxAge the maximum age in milliseconds * @return true if it's invalid or too old, false otherwise */ private static boolean isLocationOld(Location location, long now, long maxAge) { return !LocationUtils.isValidLocation(location) || now - location.getTime() > maxAge; } /** * Notifies that the current heading has changed. * * @param listeners the listeners to notify */ private void notifyHeadingChanged(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { float heading = lastSeenMagneticHeading + declination; for (TrackDataListener listener : listeners) { listener.onCurrentHeadingChanged(heading); } } }); } /** * Notifies that a new track has been selected.. * * @param trackId the new selected track * @param listeners the listeners to notify */ private void notifySelectedTrackChanged(long trackId, final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; Log.i(TAG, "New track selected, id=" + trackId); final Track track = providerUtils.getTrack(trackId); runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onSelectedTrackChanged(track, isRecordingSelected()); } } }); } /** * Notifies that the currently-selected track's data has been updated. * * @param listeners the listeners to notify */ private void notifyTrackUpdated(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; final Track track = providerUtils.getTrack(selectedTrackId); runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onTrackUpdated(track); } } }); } /** * Notifies that waypoints have been updated. * We assume few waypoints, so we reload them all every time. * * @param listeners the listeners to notify */ private void notifyWaypointUpdated(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; // Always reload all the waypoints. final Cursor cursor = providerUtils.getWaypointsCursor( selectedTrackId, 0L, MAX_DISPLAYED_WAYPOINTS_POINTS); runInListenerThread(new Runnable() { @Override public void run() { Log.d(TAG, "Reloading waypoints"); for (TrackDataListener listener : listeners) { listener.clearWaypoints(); } try { if (cursor != null && cursor.moveToFirst()) { do { Waypoint waypoint = providerUtils.createWaypoint(cursor); if (!LocationUtils.isValidLocation(waypoint.getLocation())) { continue; } for (TrackDataListener listener : listeners) { listener.onNewWaypoint(waypoint); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } for (TrackDataListener listener : listeners) { listener.onNewWaypointsDone(); } } }); } /** * Tells listeners to clear the current list of points. * * @param listeners the listeners to notify */ private void notifyPointsCleared(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.clearTrackPoints(); } } }); } /** * Notifies the given listeners about track points in the given ID range. * * @param keepState whether to load and save state about the already-notified points. * If true, only new points are reported. * If false, then the whole track will be loaded, without affecting the state. * @param minPointId the first point ID to notify, inclusive, or 0 to determine from * internal state * @param previousNumPoints the number of points to assume were previously loaded for * these listeners, or 0 to assume it's the kept state */ private void notifyPointsUpdated(final boolean keepState, final long minPointId, final int previousNumPoints, final Set<TrackDataListener> sampledListeners, final Set<TrackDataListener> sampledOutListeners) { if (sampledListeners.isEmpty() && sampledOutListeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { notifyPointsUpdatedSync(keepState, minPointId, previousNumPoints, sampledListeners, sampledOutListeners); } }); } /** * Synchronous version of the above method. */ private void notifyPointsUpdatedSync(boolean keepState, long minPointId, int previousNumPoints, Set<TrackDataListener> sampledListeners, Set<TrackDataListener> sampledOutListeners) { // If we're loading state, start from after the last seen point up to the last recorded one // (all new points) // If we're not loading state, then notify about all the previously-seen points. if (minPointId <= 0) { minPointId = keepState ? lastSeenLocationId + 1 : 0; } long maxPointId = keepState ? -1 : lastSeenLocationId; // TODO: Move (re)sampling to a separate class. if (numLoadedPoints >= targetNumPoints) { // We're about to exceed the maximum desired number of points, so reload // the whole track with fewer points (the sampling frequency will be // lower). We do this for every listener even if we were loading just for // a few of them (why miss the oportunity?). Log.i(TAG, "Resampling point set after " + numLoadedPoints + " points."); resetState(); synchronized (dataListeners) { sampledListeners = getListenersFor(ListenerDataType.POINT_UPDATES); sampledOutListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); } maxPointId = -1; minPointId = 0; previousNumPoints = 0; keepState = true; for (TrackDataListener listener : sampledListeners) { listener.clearTrackPoints(); } } // Keep the originally selected track ID so we can stop if it changes. long currentSelectedTrackId = selectedTrackId; // If we're ignoring state, start from the beginning of the track int localNumLoadedPoints = previousNumPoints; if (previousNumPoints <= 0) { localNumLoadedPoints = keepState ? numLoadedPoints : 0; } long localFirstSeenLocationId = keepState ? firstSeenLocationId : -1; long localLastSeenLocationId = minPointId; long lastStoredLocationId = providerUtils.getLastLocationId(currentSelectedTrackId); int pointSamplingFrequency = -1; LocationIterator it = providerUtils.getLocationIterator( currentSelectedTrackId, minPointId, false, locationFactory); while (it.hasNext()) { if (currentSelectedTrackId != selectedTrackId) { // The selected track changed beneath us, stop. break; } Location location = it.next(); long locationId = it.getLocationId(); // If past the last wanted point, stop. // This happens when adding a new listener after data has already been loaded, // in which case we only want to bring that listener up to the point where the others // were. In case it does happen, we should be wasting few points (only the ones not // yet notified to other listeners). if (maxPointId > 0 && locationId > maxPointId) { break; } if (localFirstSeenLocationId == -1) { // This was our first point, keep its ID localFirstSeenLocationId = locationId; } if (pointSamplingFrequency == -1) { // Now we already have at least one point, calculate the sampling // frequency. // It should be noted that a non-obvious consequence of this sampling is that // no matter how many points we get in the newest batch, we'll never exceed // MAX_DISPLAYED_TRACK_POINTS = 2 * TARGET_DISPLAYED_TRACK_POINTS before resampling. long numTotalPoints = lastStoredLocationId - localFirstSeenLocationId; numTotalPoints = Math.max(0L, numTotalPoints); pointSamplingFrequency = (int) (1 + numTotalPoints / targetNumPoints); } notifyNewPoint(location, locationId, lastStoredLocationId, localNumLoadedPoints, pointSamplingFrequency, sampledListeners, sampledOutListeners); localNumLoadedPoints++; localLastSeenLocationId = locationId; } it.close(); if (keepState) { numLoadedPoints = localNumLoadedPoints; firstSeenLocationId = localFirstSeenLocationId; lastSeenLocationId = localLastSeenLocationId; } // Always keep the sampling frequency - if it changes we'll do a full reload above anyway. lastSamplingFrequency = pointSamplingFrequency; for (TrackDataListener listener : sampledListeners) { listener.onNewTrackPointsDone(); // Update the listener state ListenerRegistration registration = dataListeners.getRegistration(listener); if (registration != null) { registration.lastTrackId = currentSelectedTrackId; registration.lastPointId = localLastSeenLocationId; registration.lastSamplingFrequency = pointSamplingFrequency; registration.numLoadedPoints = localNumLoadedPoints; } } } private void notifyNewPoint(Location location, long locationId, long lastStoredLocationId, int loadedPoints, int pointSamplingFrequency, Set<TrackDataListener> sampledListeners, Set<TrackDataListener> sampledOutListeners) { boolean isValid = LocationUtils.isValidLocation(location); if (!isValid) { // Invalid points are segment splits - report those separately. // TODO: Always send last valid point before and first valid point after a split for (TrackDataListener listener : sampledListeners) { listener.onSegmentSplit(); } return; } // Include a point if it fits one of the following criteria: // - Has the mod for the sampling frequency (includes first point). // - Is the last point and we are not recording this track. boolean recordingSelected = isRecordingSelected(); boolean includeInSample = (loadedPoints % pointSamplingFrequency == 0 || (!recordingSelected && locationId == lastStoredLocationId)); if (!includeInSample) { for (TrackDataListener listener : sampledOutListeners) { listener.onSampledOutTrackPoint(location); } } else { // Point is valid and included in sample. for (TrackDataListener listener : sampledListeners) { // No need to allocate a new location (we can safely reuse the existing). listener.onNewTrackPoint(location); } } } // @VisibleForTesting protected void runInListenerThread(Runnable runnable) { if (listenerHandler == null) { // Use a Throwable to ensure the stack trace is logged. Log.e(TAG, "Tried to use listener thread before start()", new Throwable()); return; } listenerHandler.post(runnable); } private Set<TrackDataListener> getListenersFor(ListenerDataType type) { synchronized (dataListeners) { return dataListeners.getListenersFor(type); } } private EnumSet<ListenerDataType> getNeededListenerTypes() { EnumSet<ListenerDataType> neededTypes = dataListeners.getAllRegisteredTypes(); // We always want preference updates. neededTypes.add(ListenerDataType.DISPLAY_PREFERENCES); return neededTypes; } }
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.content; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.location.Location; /** * Listener for track data, for both initial and incremental loading. * * @author Rodrigo Damazio */ public interface TrackDataListener { /** States for the GPS location provider. */ public enum ProviderState { DISABLED, NO_FIX, BAD_FIX, GOOD_FIX; } /** * Called when the location provider changes state. */ void onProviderStateChange(ProviderState state); /** * Called when the current location changes. * This is meant for immediate location display only - track point data is * delivered by other methods below, such as {@link #onNewTrackPoint}. * * @param loc the last known location */ void onCurrentLocationChanged(Location loc); /** * Called when the current heading changes. * * @param heading the current heading, already accounting magnetic declination */ void onCurrentHeadingChanged(double heading); /** * Called when the currently-selected track changes. * This will be followed by calls to data methods such as * {@link #onTrackUpdated}, {@link #clearTrackPoints}, * {@link #onNewTrackPoint(Location)}, etc., even if no track is currently * selected (in which case you'll only get calls to clear the current data). * * @param track the selected track, or null if no track is selected * @param isRecording whether we're currently recording the selected track */ void onSelectedTrackChanged(Track track, boolean isRecording); /** * Called when the track and/or its statistics have been updated. * * @param track the updated version of the track */ void onTrackUpdated(Track track); /** * Called to clear any previously-sent track points. * This can be called at any time that we decide the data needs to be * reloaded, such as when it needs to be resampled. */ void clearTrackPoints(); /** * Called when a new interesting track point is read. * In this case, interesting means that the point has already undergone * sampling and invalid point filtering. * * @param loc the new track point */ void onNewTrackPoint(Location loc); /** * Called when a uninteresting track point is read. * Uninteresting points are all points that get sampled out of the track. * * @param loc the new track point */ void onSampledOutTrackPoint(Location loc); /** * Called when an invalid point (representing a segment split) is read. */ void onSegmentSplit(); /** * Called when we're done (for the time being) sending new points. * This gets called after every batch of calls to {@link #onNewTrackPoint}, * {@link #onSampledOutTrackPoint} and {@link #onSegmentSplit}. */ void onNewTrackPointsDone(); /** * Called to clear any previously-sent waypoints. * This can be called at any time that we decide the data needs to be * reloaded. */ void clearWaypoints(); /** * Called when a new waypoint is read. * * @param wpt the new waypoint */ void onNewWaypoint(Waypoint wpt); /** * Called when we're done (for the time being) sending new waypoints. * This gets called after every batch of calls to {@link #clearWaypoints} and * {@link #onNewWaypoint}. */ void onNewWaypointsDone(); /** * Called when the display units are changed by the user. * * @param metric true if the units are metric, false if imperial * @return true to reload all the data, false otherwise */ boolean onUnitsChanged(boolean metric); /** * Called when the speed/pace display unit is changed by the user. * * @param reportSpeed true to report speed, false for pace * @return true to reload all the data, false otherwise */ boolean onReportSpeedChanged(boolean reportSpeed); }
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.content; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.hardware.Sensor; import android.hardware.SensorEventListener; import android.location.Location; import android.location.LocationListener; import android.net.Uri; /** * Interface for abstracting registration of external data source listeners. * * @author Rodrigo Damazio */ interface DataSourcesWrapper { // Preferences void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener); void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener); // Content provider void registerContentObserver(Uri contentUri, boolean descendents, ContentObserver observer); void unregisterContentObserver(ContentObserver observer); // Sensors Sensor getSensor(int type); void registerSensorListener(SensorEventListener listener, Sensor sensor, int sensorDelay); void unregisterSensorListener(SensorEventListener listener); // Location boolean isLocationProviderEnabled(String provider); void requestLocationUpdates(LocationListener listener); void removeLocationUpdates(LocationListener listener); Location getLastKnownLocation(); }
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; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.util.Log; import android.widget.TextView; import java.text.NumberFormat; /** * Various utility functions for views that display statistics information. * * @author Sandor Dornbush */ public class StatsUtilities { private final Activity activity; private static final NumberFormat LAT_LONG_FORMAT = NumberFormat.getNumberInstance(); private static final NumberFormat ALTITUDE_FORMAT = NumberFormat.getIntegerInstance(); private static final NumberFormat SPEED_FORMAT = NumberFormat.getNumberInstance(); private static final NumberFormat GRADE_FORMAT = NumberFormat.getPercentInstance(); static { LAT_LONG_FORMAT.setMaximumFractionDigits(5); LAT_LONG_FORMAT.setMinimumFractionDigits(5); SPEED_FORMAT.setMaximumFractionDigits(2); SPEED_FORMAT.setMinimumFractionDigits(2); GRADE_FORMAT.setMaximumFractionDigits(1); GRADE_FORMAT.setMinimumFractionDigits(1); } /** * True if distances should be displayed in metric units (from shared * preferences). */ private boolean metricUnits = true; /** * True - report speed * False - report pace */ private boolean reportSpeed = true; public StatsUtilities(Activity a) { this.activity = a; } public boolean isMetricUnits() { return metricUnits; } public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; } public boolean isReportSpeed() { return reportSpeed; } public void setReportSpeed(boolean reportSpeed) { this.reportSpeed = reportSpeed; } public void setUnknown(int id) { ((TextView) activity.findViewById(id)).setText(R.string.value_unknown); } public void setText(int id, double d, NumberFormat format) { if (!Double.isNaN(d) && !Double.isInfinite(d)) { setText(id, format.format(d)); } else { setUnknown(id); } } public void setText(int id, String s) { int lengthLimit = 8; String displayString = s.length() > lengthLimit ? s.substring(0, lengthLimit - 3) + "..." : s; ((TextView) activity.findViewById(id)).setText(displayString); } public void setLatLong(int id, double d) { TextView msgTextView = (TextView) activity.findViewById(id); msgTextView.setText(LAT_LONG_FORMAT.format(d)); } public void setAltitude(int id, double d) { setText(id, (metricUnits ? d : (d * UnitConversions.M_TO_FT)), ALTITUDE_FORMAT); } public void setDistance(int id, double d) { setText(id, (metricUnits ? d : (d * UnitConversions.KM_TO_MI)), SPEED_FORMAT); } public void setSpeed(int id, double d) { if (d == 0) { setUnknown(id); return; } double speed = metricUnits ? d : d * UnitConversions.KM_TO_MI; if (reportSpeed) { setText(id, speed, SPEED_FORMAT); } else { // Format as milliseconds per unit long pace = (long) (3600000.0 / speed); setTime(id, pace); } } public void setAltitudeUnits(int unitLabelId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(metricUnits ? R.string.unit_meter : R.string.unit_feet); } public void setDistanceUnits(int unitLabelId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(metricUnits ? R.string.unit_kilometer : R.string.unit_mile); } public void setSpeedUnits(int unitLabelId, int unitLabelBottomId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(reportSpeed ? (metricUnits ? R.string.unit_kilometer : R.string.unit_mile) : R.string.unit_minute); unitTextView = (TextView) activity.findViewById(unitLabelBottomId); unitTextView.setText(reportSpeed ? R.string.unit_hour : (metricUnits ? R.string.unit_kilometer : R.string.unit_mile)); } public void setTime(int id, long l) { setText(id, StringUtils.formatTime(l)); } public void setGrade(int id, double d) { setText(id, d, GRADE_FORMAT); } /** * Updates the unit fields. */ public void updateUnits() { setSpeedUnits(R.id.speed_unit_label_top, R.id.speed_unit_label_bottom); updateWaypointUnits(); } /** * Updates the units fields used by waypoints. */ public void updateWaypointUnits() { setSpeedUnits(R.id.average_moving_speed_unit_label_top, R.id.average_moving_speed_unit_label_bottom); setSpeedUnits(R.id.average_speed_unit_label_top, R.id.average_speed_unit_label_bottom); setDistanceUnits(R.id.total_distance_unit_label); setSpeedUnits(R.id.max_speed_unit_label_top, R.id.max_speed_unit_label_bottom); setAltitudeUnits(R.id.elevation_unit_label); setAltitudeUnits(R.id.elevation_gain_unit_label); setAltitudeUnits(R.id.min_elevation_unit_label); setAltitudeUnits(R.id.max_elevation_unit_label); } /** * Sets all fields to "-" (unknown). */ public void setAllToUnknown() { // "Instant" values: setUnknown(R.id.elevation_register); setUnknown(R.id.latitude_register); setUnknown(R.id.longitude_register); setUnknown(R.id.speed_register); // Values from provider: setUnknown(R.id.total_time_register); setUnknown(R.id.moving_time_register); setUnknown(R.id.total_distance_register); setUnknown(R.id.average_speed_register); setUnknown(R.id.average_moving_speed_register); setUnknown(R.id.max_speed_register); setUnknown(R.id.min_elevation_register); setUnknown(R.id.max_elevation_register); setUnknown(R.id.elevation_gain_register); setUnknown(R.id.min_grade_register); setUnknown(R.id.max_grade_register); } public void setAllStats(long movingTime, double totalDistance, double averageSpeed, double averageMovingSpeed, double maxSpeed, double minElevation, double maxElevation, double elevationGain, double minGrade, double maxGrade) { setTime(R.id.moving_time_register, movingTime); setDistance(R.id.total_distance_register, totalDistance / 1000); setSpeed(R.id.average_speed_register, averageSpeed * 3.6); setSpeed(R.id.average_moving_speed_register, averageMovingSpeed * 3.6); setSpeed(R.id.max_speed_register, maxSpeed * 3.6); setAltitude(R.id.min_elevation_register, minElevation); setAltitude(R.id.max_elevation_register, maxElevation); setAltitude(R.id.elevation_gain_register, elevationGain); setGrade(R.id.min_grade_register, minGrade); setGrade(R.id.max_grade_register, maxGrade); } public void setAllStats(TripStatistics stats) { setTime(R.id.moving_time_register, stats.getMovingTime()); setDistance(R.id.total_distance_register, stats.getTotalDistance() / 1000); setSpeed(R.id.average_speed_register, stats.getAverageSpeed() * 3.6); setSpeed(R.id.average_moving_speed_register, stats.getAverageMovingSpeed() * 3.6); setSpeed(R.id.max_speed_register, stats.getMaxSpeed() * 3.6); setAltitude(R.id.min_elevation_register, stats.getMinElevation()); setAltitude(R.id.max_elevation_register, stats.getMaxElevation()); setAltitude(R.id.elevation_gain_register, stats.getTotalElevationGain()); setGrade(R.id.min_grade_register, stats.getMinGrade()); setGrade(R.id.max_grade_register, stats.getMaxGrade()); setTime(R.id.total_time_register, stats.getTotalTime()); } public void setSpeedLabel(int id, int speedString, int paceString) { Log.w(Constants.TAG, "Setting view " + id + " to " + reportSpeed + " speed: " + speedString + " pace: " + paceString); TextView tv = ((TextView) activity.findViewById(id)); if (tv != null) { tv.setText(reportSpeed ? speedString : paceString); } else { Log.w(Constants.TAG, "Could not find id: " + id); } } public void setSpeedLabels() { setSpeedLabel(R.id.average_speed_label, R.string.stat_average_speed, R.string.stat_average_pace); setSpeedLabel(R.id.average_moving_speed_label, R.string.stat_average_moving_speed, R.string.stat_average_moving_pace); setSpeedLabel(R.id.max_speed_label, R.string.stat_max_speed, R.string.stat_min_pace); } }
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; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.RadioGroup; /** * An activity that allows the user to set the chart settings. * * @author Sandor Dornbush */ public class ChartSettingsDialog extends Dialog { private RadioButton distance; private CheckBox[] series; private OnClickListener clickListener; public ChartSettingsDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chart_settings); Button cancel = (Button) findViewById(R.id.chart_settings_cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (clickListener != null) { clickListener.onClick(ChartSettingsDialog.this, BUTTON_NEGATIVE); } dismiss(); } }); Button okButton = (Button) findViewById(R.id.chart_settings_ok); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (clickListener != null) { clickListener.onClick(ChartSettingsDialog.this, BUTTON_POSITIVE); } dismiss(); } }); distance = (RadioButton) findViewById(R.id.chart_settings_by_distance); series = new CheckBox[ChartView.NUM_SERIES]; series[ChartView.ELEVATION_SERIES] = (CheckBox) findViewById(R.id.chart_settings_elevation); series[ChartView.SPEED_SERIES] = (CheckBox) findViewById(R.id.chart_settings_speed); series[ChartView.POWER_SERIES] = (CheckBox) findViewById(R.id.chart_settings_power); series[ChartView.CADENCE_SERIES] = (CheckBox) findViewById(R.id.chart_settings_cadence); series[ChartView.HEART_RATE_SERIES] = (CheckBox) findViewById(R.id.chart_settings_heart_rate); } public void setMode(Mode mode) { RadioGroup rd = (RadioGroup) findViewById(R.id.chart_settings_x); rd.check(mode == Mode.BY_DISTANCE ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); } public void setSeriesEnabled(int seriesIdx, boolean enabled) { series[seriesIdx].setChecked(enabled); } public Mode getMode() { if (distance == null) return Mode.BY_DISTANCE; return distance.isChecked() ? Mode.BY_DISTANCE : Mode.BY_TIME; } public boolean isSeriesEnabled(int seriesIdx) { if (series == null) return true; return series[seriesIdx].isChecked(); } public void setOnClickListener(OnClickListener clickListener) { this.clickListener = clickListener; } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.io.backup.BackupActivityHelper; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.sensors.ant.AntUtils; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.BluetoothDeviceUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * An activity that let's the user see and edit the settings. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class SettingsActivity extends PreferenceActivity { // Value when the task frequency is off. private static final String TASK_FREQUENCY_OFF = "0"; // Value when the recording interval is 'Adapt battery life'. private static final String RECORDING_INTERVAL_ADAPT_BATTERY_LIFE = "-2"; // Value when the recording interval is 'Adapt accuracy'. private static final String RECORDING_INTERVAL_ADAPT_ACCURACY = "-1"; // Value for the recommended recording interval. private static final String RECORDING_INTERVAL_RECOMMENDED = "0"; // Value when the auto resume timeout is never. private static final String AUTO_RESUME_TIMEOUT_NEVER = "0"; // Value when the auto resume timeout is always. private static final String AUTO_RESUME_TIMEOUT_ALWAYS = "-1"; // Value for the recommended recording distance. private static final String RECORDING_DISTANCE_RECOMMENDED = "5"; // Value for the recommended track distance. private static final String TRACK_DISTANCE_RECOMMENDED = "200"; // Value for the recommended GPS accuracy. private static final String GPS_ACCURACY_RECOMMENDED = "200"; // Value when the GPS accuracy is for excellent GPS signal. private static final String GPS_ACCURACY_EXCELLENT = "10"; // Value when the GPS accuracy is for poor GPS signal. private static final String GPS_ACCURACY_POOR = "5000"; private BackupPreferencesListener backupListener; private SharedPreferences preferences; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // The volume we want to control is the Text-To-Speech volume ApiFeatures apiFeatures = ApiFeatures.getInstance(); int volumeStream = new StatusAnnouncerFactory(apiFeatures).getVolumeStream(); setVolumeControlStream(volumeStream); // Tell it where to read/write preferences PreferenceManager preferenceManager = getPreferenceManager(); preferenceManager.setSharedPreferencesName(Constants.SETTINGS_NAME); preferenceManager.setSharedPreferencesMode(0); // Set up automatic preferences backup backupListener = apiFeatures.getApiAdapter().getBackupPreferencesListener(this); preferences = preferenceManager.getSharedPreferences(); preferences.registerOnSharedPreferenceChangeListener(backupListener); // Load the preferences to be displayed addPreferencesFromResource(R.xml.preferences); // Disable voice announcement if not available if (!apiFeatures.hasTextToSpeech()) { IntegerListPreference announcementFrequency = (IntegerListPreference) findPreference( getString(R.string.announcement_frequency_key)); announcementFrequency.setEnabled(false); announcementFrequency.setValue(TASK_FREQUENCY_OFF); announcementFrequency.setSummary(R.string.settings_recording_voice_not_available); } setRecordingIntervalOptions(); setAutoResumeTimeoutOptions(); // Hook up switching of displayed list entries between metric and imperial // units CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); metricUnitsPreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean isMetric = (Boolean) newValue; updateDisplayOptions(isMetric); return true; } }); updateDisplayOptions(metricUnitsPreference.isChecked()); customizeSensorOptionsPreferences(); customizeTrackColorModePreferences(); // Hook up action for resetting all settings Preference resetPreference = findPreference(getString(R.string.reset_key)); resetPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { onResetPreferencesClick(); return true; } }); // Add a confirmation dialog for the 'Allow access' preference. final CheckBoxPreference allowAccessPreference = (CheckBoxPreference) findPreference( getString(R.string.allow_access_key)); allowAccessPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if ((Boolean) newValue) { AlertDialog dialog = new AlertDialog.Builder(SettingsActivity.this) .setCancelable(true) .setTitle(getString(R.string.settings_sharing_allow_access)) .setMessage(getString(R.string.settings_sharing_allow_access_confirm_message)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int button) { allowAccessPreference.setChecked(true); } }) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); return false; } else { return true; } } }); } /** * Sets the display options for the 'Time between points' option. */ private void setRecordingIntervalOptions() { String[] values = getResources().getStringArray(R.array.recording_interval_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(RECORDING_INTERVAL_ADAPT_BATTERY_LIFE)) { options[i] = getString(R.string.value_adapt_battery_life); } else if (values[i].equals(RECORDING_INTERVAL_ADAPT_ACCURACY)) { options[i] = getString(R.string.value_adapt_accuracy); } else if (values[i].equals(RECORDING_INTERVAL_RECOMMENDED)) { options[i] = getString(R.string.value_smallest_recommended); } else { int value = Integer.parseInt(values[i]); String format; if (value < 60) { format = getString(R.string.value_integer_second); } else { value = value / 60; format = getString(R.string.value_integer_minute); } options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference( getString(R.string.min_recording_interval_key)); list.setEntries(options); } /** * Sets the display options for the 'Auto-resume timeout' option. */ private void setAutoResumeTimeoutOptions() { String[] values = getResources().getStringArray(R.array.recording_auto_resume_timeout_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(AUTO_RESUME_TIMEOUT_NEVER)) { options[i] = getString(R.string.value_never); } else if (values[i].equals(AUTO_RESUME_TIMEOUT_ALWAYS)) { options[i] = getString(R.string.value_always); } else { int value = Integer.parseInt(values[i]); String format = getString(R.string.value_integer_minute); options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference( getString(R.string.auto_resume_track_timeout_key)); list.setEntries(options); } private void customizeSensorOptionsPreferences() { ListPreference sensorTypePreference = (ListPreference) findPreference(getString(R.string.sensor_type_key)); sensorTypePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { updateSensorSettings((String) newValue); return true; } }); updateSensorSettings(sensorTypePreference.getValue()); if (!AntUtils.hasAntSupport(this)) { // The sensor options screen has a few ANT-specific options which we // need to remove. First, we need to remove the ANT sensor types. // Second, we need to remove the ANT unpairing options. Set<Integer> toRemove = new HashSet<Integer>(); String[] antValues = getResources().getStringArray(R.array.sensor_type_ant_values); for (String antValue : antValues) { toRemove.add(sensorTypePreference.findIndexOfValue(antValue)); } CharSequence[] entries = sensorTypePreference.getEntries(); CharSequence[] entryValues = sensorTypePreference.getEntryValues(); CharSequence[] filteredEntries = new CharSequence[entries.length - toRemove.size()]; CharSequence[] filteredEntryValues = new CharSequence[filteredEntries.length]; for (int i = 0, last = 0; i < entries.length; i++) { if (!toRemove.contains(i)) { filteredEntries[last] = entries[i]; filteredEntryValues[last++] = entryValues[i]; } } sensorTypePreference.setEntries(filteredEntries); sensorTypePreference.setEntryValues(filteredEntryValues); PreferenceScreen sensorOptionsScreen = (PreferenceScreen) findPreference(getString(R.string.sensor_options_key)); sensorOptionsScreen.removePreference(findPreference(getString(R.string.ant_options_key))); } } private void customizeTrackColorModePreferences() { ListPreference trackColorModePreference = (ListPreference) findPreference(getString(R.string.track_color_mode_key)); trackColorModePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { updateTrackColorModeSettings((String) newValue); return true; } }); updateTrackColorModeSettings(trackColorModePreference.getValue()); setTrackColorModePreferenceListeners(); PreferenceCategory speedOptionsCategory = (PreferenceCategory) findPreference( getString(R.string.track_color_mode_fixed_speed_options_key)); speedOptionsCategory.removePreference( findPreference(getString(R.string.track_color_mode_fixed_speed_slow_key))); speedOptionsCategory.removePreference( findPreference(getString(R.string.track_color_mode_fixed_speed_medium_key))); } @Override protected void onResume() { super.onResume(); configureBluetoothPreferences(); Preference backupNowPreference = findPreference(getString(R.string.backup_to_sd_key)); Preference restoreNowPreference = findPreference(getString(R.string.restore_from_sd_key)); Preference resetPreference = findPreference(getString(R.string.reset_key)); // If recording, disable backup/restore/reset // (we don't want to get to inconsistent states) boolean recording = preferences.getLong(getString(R.string.recording_track_key), -1) != -1; backupNowPreference.setEnabled(!recording); restoreNowPreference.setEnabled(!recording); resetPreference.setEnabled(!recording); backupNowPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_backup_now_summary); restoreNowPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_backup_restore_summary); resetPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_reset_summary); // Add actions to the backup preferences backupNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(SettingsActivity.this); backupHelper.writeBackup(); return true; } }); restoreNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(SettingsActivity.this); backupHelper.restoreBackup(); return true; } }); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(backupListener); super.onPause(); } private void updateSensorSettings(String sensorType) { boolean usesBluetooth = getString(R.string.sensor_type_value_zephyr).equals(sensorType) || getString(R.string.sensor_type_value_polar).equals(sensorType); findPreference( getString(R.string.bluetooth_sensor_key)).setEnabled(usesBluetooth); findPreference( getString(R.string.bluetooth_pairing_key)).setEnabled(usesBluetooth); // Update the ANT+ sensors. // TODO: Only enable on phones that have ANT+. Preference antHrm = findPreference(getString(R.string.ant_heart_rate_sensor_id_key)); Preference antSrm = findPreference(getString(R.string.ant_srm_bridge_sensor_id_key)); if (antHrm != null && antSrm != null) { antHrm .setEnabled(getString(R.string.sensor_type_value_ant).equals(sensorType)); antSrm .setEnabled(getString(R.string.sensor_type_value_srm_ant_bridge).equals(sensorType)); } } private void updateTrackColorModeSettings(String trackColorMode) { boolean usesFixedSpeed = trackColorMode.equals(getString(R.string.display_track_color_value_fixed)); boolean usesDynamicSpeed = trackColorMode.equals(getString(R.string.display_track_color_value_dynamic)); findPreference(getString(R.string.track_color_mode_fixed_speed_slow_display_key)) .setEnabled(usesFixedSpeed); findPreference(getString(R.string.track_color_mode_fixed_speed_medium_display_key)) .setEnabled(usesFixedSpeed); findPreference(getString(R.string.track_color_mode_dynamic_speed_variation_key)) .setEnabled(usesDynamicSpeed); } /** * Updates display options that depends on the preferred distance units, metric or imperial. * * @param isMetric true to use metric units, false to use imperial */ private void updateDisplayOptions(boolean isMetric) { setTaskOptions(isMetric, R.string.announcement_frequency_key); setTaskOptions(isMetric, R.string.split_frequency_key); setRecordingDistanceOptions(isMetric, R.string.min_recording_distance_key); setTrackDistanceOptions(isMetric, R.string.max_recording_distance_key); setGpsAccuracyOptions(isMetric, R.string.min_required_accuracy_key); } /** * Sets the display options for a periodic task. */ private void setTaskOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_task_frequency_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(TASK_FREQUENCY_OFF)) { options[i] = getString(R.string.value_off); } else if (values[i].startsWith("-")) { int value = Integer.parseInt(values[i].substring(1)); int stringId = isMetric ? R.string.value_integer_kilometer : R.string.value_integer_mile; String format = getString(stringId); options[i] = String.format(format, value); } else { int value = Integer.parseInt(values[i]); String format = getString(R.string.value_integer_minute); options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'Distance between points' option. */ private void setRecordingDistanceOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_distance_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); if (!isMetric) { value = (int) (value * UnitConversions.M_TO_FT); } String format; if (values[i].equals(RECORDING_DISTANCE_RECOMMENDED)) { int stringId = isMetric ? R.string.value_integer_meter_recommended : R.string.value_integer_feet_recommended; format = getString(stringId); } else { int stringId = isMetric ? R.string.value_integer_meter : R.string.value_integer_feet; format = getString(stringId); } options[i] = String.format(format, value); } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'Distance between Tracks'. */ private void setTrackDistanceOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_track_distance_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); String format; if (isMetric) { int stringId = values[i].equals(TRACK_DISTANCE_RECOMMENDED) ? R.string.value_integer_meter_recommended : R.string.value_integer_meter; format = getString(stringId); options[i] = String.format(format, value); } else { value = (int) (value * UnitConversions.M_TO_FT); if (value < 2000) { int stringId = values[i].equals(TRACK_DISTANCE_RECOMMENDED) ? R.string.value_integer_feet_recommended : R.string.value_integer_feet; format = getString(stringId); options[i] = String.format(format, value); } else { double mile = value / UnitConversions.MI_TO_FEET; format = getString(R.string.value_float_mile); options[i] = String.format(format, mile); } } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'GPS accuracy'. */ private void setGpsAccuracyOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_gps_accuracy_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); String format; if (isMetric) { if (values[i].equals(GPS_ACCURACY_RECOMMENDED)) { format = getString(R.string.value_integer_meter_recommended); } else if (values[i].equals(GPS_ACCURACY_EXCELLENT)) { format = getString(R.string.value_integer_meter_excellent_gps); } else if (values[i].equals(GPS_ACCURACY_POOR)) { format = getString(R.string.value_integer_meter_poor_gps); } else { format = getString(R.string.value_integer_meter); } options[i] = String.format(format, value); } else { value = (int) (value * UnitConversions.M_TO_FT); if (value < 2000) { if (values[i].equals(GPS_ACCURACY_RECOMMENDED)) { format = getString(R.string.value_integer_feet_recommended); } else if (values[i].equals(GPS_ACCURACY_EXCELLENT)) { format = getString(R.string.value_integer_feet_excellent_gps); } else { format = getString(R.string.value_integer_feet); } options[i] = String.format(format, value); } else { double mile = value / UnitConversions.MI_TO_FEET; if (values[i].equals(GPS_ACCURACY_POOR)) { format = getString(R.string.value_float_mile_poor_gps); } else { format = getString(R.string.value_float_mile); } options[i] = String.format(format, mile); } } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Configures preference actions related to bluetooth. */ private void configureBluetoothPreferences() { if (BluetoothDeviceUtils.isBluetoothMethodSupported()) { // Populate the list of bluetooth devices populateBluetoothDeviceList(); // Make the pair devices preference go to the system preferences findPreference(getString(R.string.bluetooth_pairing_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Intent settingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); startActivity(settingsIntent); return false; } }); } } /** * Populates the list preference with all available bluetooth devices. */ private void populateBluetoothDeviceList() { // Build the list of entries and their values List<String> entries = new ArrayList<String>(); List<String> entryValues = new ArrayList<String>(); // The actual devices BluetoothDeviceUtils.getInstance().populateDeviceLists(entries, entryValues); CharSequence[] entriesArray = entries.toArray(new CharSequence[entries.size()]); CharSequence[] entryValuesArray = entryValues.toArray(new CharSequence[entryValues.size()]); ListPreference devicesPreference = (ListPreference) findPreference(getString(R.string.bluetooth_sensor_key)); devicesPreference.setEntryValues(entryValuesArray); devicesPreference.setEntries(entriesArray); } /** Callback for when user asks to reset all settings. */ private void onResetPreferencesClick() { AlertDialog dialog = new AlertDialog.Builder(this) .setCancelable(true) .setTitle(R.string.settings_reset) .setMessage(R.string.settings_reset_dialog_message) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int button) { onResetPreferencesConfirmed(); } }) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); } /** Callback for when user confirms resetting all settings. */ private void onResetPreferencesConfirmed() { // Change preferences in a separate thread. new Thread() { @Override public void run() { Log.i(TAG, "Resetting all settings"); // Actually wipe preferences (and save synchronously). preferences.edit().clear().commit(); // Give UI feedback in the UI thread. runOnUiThread(new Runnable() { @Override public void run() { // Give feedback to the user. Toast.makeText( SettingsActivity.this, R.string.settings_reset_done, Toast.LENGTH_SHORT).show(); // Restart the settings activity so all changes are loaded. Intent intent = getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); } }.start(); } /** * Set the given edit text preference text. * If the units are not metric convert the value before displaying. */ private void viewTrackColorModeSettings(EditTextPreference preference, int id) { CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); if(metricUnitsPreference.isChecked()) { return; } // Convert miles/h to km/h SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); String metricspeed = prefs.getString(getString(id), null); int englishspeed; try { englishspeed = (int) (Double.parseDouble(metricspeed) * UnitConversions.KMH_TO_MPH); } catch (NumberFormatException e) { englishspeed = 0; } preference.getEditText().setText(String.valueOf(englishspeed)); } /** * Saves the given edit text preference value. * If the units are not metric convert the value before saving. */ private void validateTrackColorModeSettings(String newValue, int id) { CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); String metricspeed; if(!metricUnitsPreference.isChecked()) { // Convert miles/h to km/h try { metricspeed = String.valueOf( (int) (Double.parseDouble(newValue) * UnitConversions.MPH_TO_KMH) + 1); } catch (NumberFormatException e) { metricspeed = "0"; } } else { metricspeed = newValue; } SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); Editor editor = prefs.edit(); editor.putString(getString(id), metricspeed); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } /** * Sets the TrackColorMode preference listeners. */ private void setTrackColorModePreferenceListeners() { setTrackColorModePreferenceListener(R.string.track_color_mode_fixed_speed_slow_display_key, R.string.track_color_mode_fixed_speed_slow_key); setTrackColorModePreferenceListener(R.string.track_color_mode_fixed_speed_medium_display_key, R.string.track_color_mode_fixed_speed_medium_key); } /** * Sets a TrackColorMode preference listener. */ private void setTrackColorModePreferenceListener(int displayKey, final int metricKey) { EditTextPreference trackColorModePreference = (EditTextPreference) findPreference(getString(displayKey)); trackColorModePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { validateTrackColorModeSettings((String) newValue, metricKey); return true; } }); trackColorModePreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { viewTrackColorModeSettings((EditTextPreference) preference, metricKey); return true; } }); } }
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.maps; import com.google.android.apps.mytracks.ColoredPath; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import java.util.ArrayList; import java.util.List; /** * A path painter that varies the path colors based on fixed speeds or average speed margin * depending of the TrackPathDescriptor passed to its constructor. * * @author Vangelis S. */ public class DynamicSpeedTrackPathPainter implements TrackPathPainter { private final Paint selectedTrackPaintSlow; private final Paint selectedTrackPaintMedium; private final Paint selectedTrackPaintFast; private final List<ColoredPath> coloredPaths; private final TrackPathDescriptor trackPathDescriptor; private int slowSpeed; private int normalSpeed; public DynamicSpeedTrackPathPainter (Context context, TrackPathDescriptor trackPathDescriptor) { this.trackPathDescriptor = trackPathDescriptor; selectedTrackPaintSlow = TrackPathUtilities.getPaint(R.color.slow_path, context); selectedTrackPaintMedium = TrackPathUtilities.getPaint(R.color.normal_path, context); selectedTrackPaintFast = TrackPathUtilities.getPaint(R.color.fast_path, context); this.coloredPaths = new ArrayList<ColoredPath>(); } @Override public void drawTrack(Canvas canvas) { for(int i = 0; i < coloredPaths.size(); ++i) { ColoredPath coloredPath = coloredPaths.get(i); canvas.drawPath(coloredPath.getPath(), coloredPath.getPathPaint()); } } @Override public void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points) { // Whether to start a new segment on new valid and visible point. boolean newSegment = startLocationIdx <= 0 || !points.get(startLocationIdx - 1).valid; boolean lastVisible = !newSegment; final Point pt = new Point(); clear(); slowSpeed = trackPathDescriptor.getSlowSpeed(); normalSpeed = trackPathDescriptor.getNormalSpeed(); // Loop over track points. for (int i = startLocationIdx; i < points.size(); ++i) { CachedLocation loc = points.get(i); // Check if valid, if not then indicate a new segment. if (!loc.valid) { newSegment = true; continue; } final GeoPoint geoPoint = loc.geoPoint; // Check if this breaks the existing segment. boolean visible = alwaysVisible || viewRect.contains( geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6()); if (!visible && !lastVisible) { // This is a point outside view not connected to a visible one. newSegment = true; } lastVisible = visible; // Either move to beginning of a new segment or continue the old one. if (newSegment) { projection.toPixels(geoPoint, pt); newSegment = false; } else { ColoredPath coloredPath; if(loc.speed <= slowSpeed) { coloredPath = new ColoredPath(selectedTrackPaintSlow); } else if(loc.speed <= normalSpeed) { coloredPath = new ColoredPath(selectedTrackPaintMedium); } else { coloredPath = new ColoredPath(selectedTrackPaintFast); } coloredPath.getPath().moveTo(pt.x, pt.y); projection.toPixels(geoPoint, pt); coloredPath.getPath().lineTo(pt.x, pt.y); coloredPaths.add(coloredPath); } } } @Override public void clear() { coloredPaths.clear(); } @Override public boolean needsRedraw() { return trackPathDescriptor.needsRedraw(); } @Override public Path getLastPath() { Path path = new Path(); for(int i = 0; i < coloredPaths.size(); ++i) { path.addPath(coloredPaths.get(i).getPath()); } return path; } }
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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A dynamic speed path descriptor. * * @author Vangelis S. */ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor, OnSharedPreferenceChangeListener { private int slowSpeed; private int normalSpeed; private int speedMargin; private double averageMovingSpeed; private final Context context; public DynamicSpeedTrackPathDescriptor(Context context){ this.context = context; SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { speedMargin = 25; return; } prefs.registerOnSharedPreferenceChangeListener(this); speedMargin = Integer.parseInt(prefs.getString( context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25")); } /** * Get the slow speed calculated based on the % below the average speed. * @return The speed limit considered as slow. */ public int getSlowSpeed() { slowSpeed = (int) (averageMovingSpeed - (averageMovingSpeed * speedMargin / 100)); return slowSpeed; } /** * Get the medium speed calculated based on the % above the average speed. * @return The speed limit considered as normal. */ public int getNormalSpeed() { normalSpeed = (int) (averageMovingSpeed + (averageMovingSpeed * speedMargin / 100)); return normalSpeed; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "DynamicSpeedTrackPathDescriptor: onSharedPreferences changed " + key); if (key == null || !key.equals(context.getString(R.string.track_color_mode_dynamic_speed_variation_key))) { return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { speedMargin = 25; return; } speedMargin = Integer.parseInt( prefs.getString( context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25")); } @Override public boolean needsRedraw() { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long currentTrackId = prefs.getLong(context.getString(R.string.selected_track_key), -1); if(currentTrackId == -1) { // Could not find track. return false; } Track track = MyTracksProviderUtils.Factory.get(context).getTrack(currentTrackId); TripStatistics stats = track.getStatistics(); double newaverageSpeed = (int) Math.floor(stats.getAverageMovingSpeed() * 3.6); if(averageMovingSpeed == 0) { averageMovingSpeed = newaverageSpeed; return true; } double difference = Math.max(averageMovingSpeed, newaverageSpeed); if (difference == 0.0) { difference = 0.0; } else { difference = Math.abs(averageMovingSpeed - newaverageSpeed) / difference * 100; } if(difference >= 20) { averageMovingSpeed = newaverageSpeed; return true; } return false; } }
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.maps; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import java.util.List; /** * A path painter that not variates the path colors. * * @author Vangelis S. */ public class SingleColorTrackPathPainter implements TrackPathPainter { private final Paint selectedTrackPaint; private Path path; public SingleColorTrackPathPainter(Context context) { selectedTrackPaint = TrackPathUtilities.getPaint(R.color.red, context); } @Override public void drawTrack(Canvas canvas) { canvas.drawPath(path, selectedTrackPaint); } @Override public void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points) { // Whether to start a new segment on new valid and visible point. boolean newSegment = startLocationIdx <= 0 || !points.get(startLocationIdx - 1).valid; boolean lastVisible = !newSegment; final Point pt = new Point(); // Loop over track points. int numPoints = points.size(); path = newPath(); path.incReserve(numPoints); for (int i = startLocationIdx; i < numPoints ; ++i) { CachedLocation loc = points.get(i); // Check if valid, if not then indicate a new segment. if (!loc.valid) { newSegment = true; continue; } final GeoPoint geoPoint = loc.geoPoint; // Check if this breaks the existing segment. boolean visible = alwaysVisible || viewRect.contains(geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6()); if (!visible && !lastVisible) { // This is a point outside view not connected to a visible one. newSegment = true; } lastVisible = visible; // Either move to beginning of a new segment or continue the old one. projection.toPixels(geoPoint, pt); if (newSegment) { path.moveTo(pt.x, pt.y); newSegment = false; } else { path.lineTo(pt.x, pt.y); } } } @Override public void clear() { path = null; } @Override public boolean needsRedraw() { return false; } @Override public Path getLastPath() { return path; } // Visible for testing public Path newPath() { return new Path(); } }
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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A fixed speed path descriptor. * * @author Vangelis S. */ public class FixedSpeedTrackPathDescriptor implements TrackPathDescriptor, OnSharedPreferenceChangeListener { private int slowSpeed; private int normalSpeed; private final Context context; public FixedSpeedTrackPathDescriptor(Context context) { this.context = context; SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { slowSpeed = 9; normalSpeed = 17; return; } prefs.registerOnSharedPreferenceChangeListener(this); try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), "9")); } catch (NumberFormatException e) { slowSpeed = 9; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), "17")); } catch (NumberFormatException e) { normalSpeed = 17; } } /** * Gets the slow speed for reference. * @return The speed limit considered as slow. */ public int getSlowSpeed() { return slowSpeed; } /** * Gets the normal speed for reference. * @return The speed limit considered as normal. */ public int getNormalSpeed() { return normalSpeed; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "FixedSpeedTrackPathDescriptor: onSharedPreferences changed " + key); if (key == null || (!key.equals(context.getString(R.string.track_color_mode_fixed_speed_slow_key)) && !key.equals(context.getString(R.string.track_color_mode_fixed_speed_medium_key)))) { return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { slowSpeed = 9; normalSpeed = 17; return; } try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), "9")); } catch (NumberFormatException e) { slowSpeed = 9; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), "17")); } catch (NumberFormatException e) { normalSpeed = 17; } } @Override public boolean needsRedraw() { return false; } }
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.maps; /** * An interface for classes which describe how to draw a track path. * * @author Vangelis S. */ public interface TrackPathDescriptor { /** * @return The maximum speed which is considered slow. */ int getSlowSpeed(); /** * @return The maximum speed which is considered normal. */ int getNormalSpeed(); /** * @return True if the path needs to be updated. */ boolean needsRedraw(); }
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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A factory for TrackPathPainters. * * @author Vangelis S. */ public class TrackPathPainterFactory { private TrackPathPainterFactory() { } /** * Get a new TrackPathPainter. * @param context Context to fetch system preferences. * @return The TrackPathPainter that corresponds to the track color mode setting. */ public static TrackPathPainter getTrackPathPainter(Context context) { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { return new SingleColorTrackPathPainter(context); } String colorMode = prefs.getString(context.getString(R.string.track_color_mode_key), null); Log.i(TAG, "Creating track path painter of type: " + colorMode); if (colorMode == null || colorMode.equals(context.getString(R.string.display_track_color_value_none))) { return new SingleColorTrackPathPainter(context); } else if (colorMode.equals(context.getString(R.string.display_track_color_value_fixed))) { return new DynamicSpeedTrackPathPainter(context, new FixedSpeedTrackPathDescriptor(context)); } else if (colorMode.equals(context.getString(R.string.display_track_color_value_dynamic))) { return new DynamicSpeedTrackPathPainter(context, new DynamicSpeedTrackPathDescriptor(context)); } else { Log.w(TAG, "Using default track path painter. Unrecognized painter: " + colorMode); return new SingleColorTrackPathPainter(context); } } }
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.maps; import android.content.Context; import android.graphics.Paint; /** * Various utility functions for TrackPath painting. * * @author Vangelis S. */ public class TrackPathUtilities { public static Paint getPaint(int id, Context context) { Paint paint = new Paint(); paint.setColor(context.getResources().getColor(id)); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); return paint; } }
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.maps; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.Projection; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Rect; import java.util.List; /** * An interface for classes which paint the track path. * * @author Vangelis S. */ public interface TrackPathPainter { /** * Clears the related data. */ void clear(); /** * Draws the path to the canvas. * @param canvas The Canvas to draw upon */ void drawTrack(Canvas canvas); /** * Updates the path. * @param projection The Canvas to draw upon. * @param viewRect The Path to be drawn. * @param startLocationIdx The start point from where update the path. * @param alwaysVisible Flag for alwaysvisible. * @param points The list of points used to update the path. */ void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points); /** * @return True if the path needs to be updated. */ boolean needsRedraw(); /** * @return The path being used currently. */ Path getLastPath(); }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.apps.mytracks.io.sendtogoogle.SendActivity; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.GeoRect; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.mytracks.R; import android.content.ContentUris; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.EnumSet; /** * The map view activity of the MyTracks application. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class MapActivity extends com.google.android.maps.MapActivity implements View.OnTouchListener, View.OnClickListener, TrackDataListener { // Saved instance state keys: // --------------------------- private static final String KEY_CURRENT_LOCATION = "currentLocation"; private static final String KEY_KEEP_MY_LOCATION_VISIBLE = "keepMyLocationVisible"; private TrackDataHub dataHub; /** * True if the map should be scrolled so that the pointer is always in the * visible area. */ private boolean keepMyLocationVisible; /** * The current pointer location. * This is kept to quickly center on it when the user requests. */ private Location currentLocation; // UI elements: // ------------- private RelativeLayout screen; private MapView mapView; private MapOverlay mapOverlay; private LinearLayout messagePane; private TextView messageText; private LinearLayout busyPane; private ImageButton optionsBtn; private MenuItem myLocation; private MenuItem toggleLayers; /** * We are not displaying driving directions. Just an arbitrary track that is * not associated to any licensed mapping data. Therefore it should be okay to * return false here and still comply with the terms of service. */ @Override protected boolean isRouteDisplayed() { return false; } /** * We are displaying a location. This needs to return true in order to comply * with the terms of service. */ @Override protected boolean isLocationDisplayed() { return true; } // Application life cycle: // ------------------------ @Override protected void onCreate(Bundle bundle) { Log.d(TAG, "MapActivity.onCreate"); super.onCreate(bundle); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); // Inflate the layout: setContentView(R.layout.mytracks_layout); // Remove the window's background because the MapView will obscure it getWindow().setBackgroundDrawable(null); // Set up a map overlay: screen = (RelativeLayout) findViewById(R.id.screen); mapView = (MapView) findViewById(R.id.map); mapView.requestFocus(); mapOverlay = new MapOverlay(this); mapView.getOverlays().add(mapOverlay); mapView.setOnTouchListener(this); mapView.setBuiltInZoomControls(true); messagePane = (LinearLayout) findViewById(R.id.messagepane); messageText = (TextView) findViewById(R.id.messagetext); busyPane = (LinearLayout) findViewById(R.id.busypane); optionsBtn = (ImageButton) findViewById(R.id.showOptions); optionsBtn.setOnCreateContextMenuListener(contextMenuListener); optionsBtn.setOnClickListener(this); } @Override protected void onRestoreInstanceState(Bundle bundle) { Log.d(TAG, "MapActivity.onRestoreInstanceState"); if (bundle != null) { super.onRestoreInstanceState(bundle); keepMyLocationVisible = bundle.getBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, false); if (bundle.containsKey(KEY_CURRENT_LOCATION)) { currentLocation = (Location) bundle.getParcelable(KEY_CURRENT_LOCATION); if (currentLocation != null) { showCurrentLocation(); } } else { currentLocation = null; } } } @Override protected void onResume() { Log.d(TAG, "MapActivity.onResume"); super.onResume(); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); dataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.POINT_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.COMPASS_UPDATES)); } @Override protected void onSaveInstanceState(Bundle outState) { Log.d(TAG, "MapActivity.onSaveInstanceState"); outState.putBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, keepMyLocationVisible); if (currentLocation != null) { outState.putParcelable(KEY_CURRENT_LOCATION, currentLocation); } super.onSaveInstanceState(outState); } @Override protected void onPause() { Log.d(TAG, "MapActivity.onPause"); dataHub.unregisterTrackDataListener(this); dataHub = null; super.onPause(); } // Utility functions: // ------------------- /** * Shows the options button if a track is selected, or hide it if not. */ private void updateOptionsButton(boolean trackSelected) { optionsBtn.setVisibility( trackSelected ? View.VISIBLE : View.INVISIBLE); } /** * Tests if a location is visible. * * @param location a given location * @return true if the given location is within the visible map area */ private boolean locationIsVisible(Location location) { if (location == null || mapView == null) { return false; } GeoPoint center = mapView.getMapCenter(); int latSpan = mapView.getLatitudeSpan(); int lonSpan = mapView.getLongitudeSpan(); // Bottom of map view is obscured by zoom controls/buttons. // Subtract a margin from the visible area: GeoPoint marginBottom = mapView.getProjection().fromPixels( 0, mapView.getHeight()); GeoPoint marginTop = mapView.getProjection().fromPixels(0, mapView.getHeight() - mapView.getZoomButtonsController().getZoomControls().getHeight()); int margin = Math.abs(marginTop.getLatitudeE6() - marginBottom.getLatitudeE6()); GeoRect r = new GeoRect(center, latSpan, lonSpan); r.top += margin; GeoPoint geoPoint = LocationUtils.getGeoPoint(location); return r.contains(geoPoint); } /** * Moves the location pointer to the current location and center the map if * the current location is outside the visible area. */ private void showCurrentLocation() { if (mapOverlay == null || mapView == null) { return; } mapOverlay.setMyLocation(currentLocation); mapView.postInvalidate(); if (currentLocation != null && keepMyLocationVisible && !locationIsVisible(currentLocation)) { GeoPoint geoPoint = LocationUtils.getGeoPoint(currentLocation); MapController controller = mapView.getController(); controller.animateTo(geoPoint); } } @Override public void onTrackUpdated(Track track) { // We don't care. } /** * Zooms and pans the map so that the given track is visible. * * @param track the track */ private void zoomMapToBoundaries(Track track) { if (mapView == null) { return; } if (track == null || track.getNumberOfPoints() < 2) { return; } TripStatistics stats = track.getStatistics(); int bottom = stats.getBottom(); int left = stats.getLeft(); int latSpanE6 = stats.getTop() - bottom; int lonSpanE6 = stats.getRight() - left; if (latSpanE6 > 0 && latSpanE6 < 180E6 && lonSpanE6 > 0 && lonSpanE6 < 360E6) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint( bottom + latSpanE6 / 2, left + lonSpanE6 / 2); if (LocationUtils.isValidGeoPoint(center)) { mapView.getController().setCenter(center); mapView.getController().zoomToSpan(latSpanE6, lonSpanE6); } } } /** * Zooms and pans the map so that the given waypoint is visible. */ public void showWaypoint(long waypointId) { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(this); Waypoint wpt = providerUtils.getWaypoint(waypointId); if (wpt != null && wpt.getLocation() != null) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint( (int) (wpt.getLocation().getLatitude() * 1E6), (int) (wpt.getLocation().getLongitude() * 1E6)); mapView.getController().setCenter(center); mapView.getController().setZoom(20); mapView.invalidate(); } } @Override public void onSelectedTrackChanged(final Track track, final boolean isRecording) { runOnUiThread(new Runnable() { @Override public void run() { boolean trackSelected = track != null; updateOptionsButton(trackSelected); mapOverlay.setTrackDrawingEnabled(trackSelected); if (trackSelected) { busyPane.setVisibility(View.VISIBLE); zoomMapToBoundaries(track); mapOverlay.setShowEndMarker(!isRecording); busyPane.setVisibility(View.GONE); } mapView.invalidate(); } }); } private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.track_list_context_menu_title); menu.add(0, Constants.MENU_EDIT, 0, R.string.track_list_edit_track); if (!dataHub.isRecordingSelected()) { String saveFileFormat = getString(R.string.track_list_save_file); String shareFileFormat = getString(R.string.track_list_share_file); String fileTypes[] = getResources().getStringArray(R.array.file_types); menu.add(0, Constants.MENU_SEND_TO_GOOGLE, 0, R.string.track_list_send_google); SubMenu share = menu.addSubMenu(0, Constants.MENU_SHARE, 0, R.string.track_list_share_track); share.add(0, Constants.MENU_SHARE_LINK, 0, R.string.track_list_share_url); share.add( 0, Constants.MENU_SHARE_GPX_FILE, 0, String.format(shareFileFormat, fileTypes[0])); share.add( 0, Constants.MENU_SHARE_KML_FILE, 0, String.format(shareFileFormat, fileTypes[1])); share.add( 0, Constants.MENU_SHARE_CSV_FILE, 0, String.format(shareFileFormat, fileTypes[2])); share.add( 0, Constants.MENU_SHARE_TCX_FILE, 0, String.format(shareFileFormat, fileTypes[3])); SubMenu save = menu.addSubMenu(0, Constants.MENU_WRITE_TO_SD_CARD, 0, R.string.track_list_save_sd); save.add( 0, Constants.MENU_SAVE_GPX_FILE, 0, String.format(saveFileFormat, fileTypes[0])); save.add( 0, Constants.MENU_SAVE_KML_FILE, 0, String.format(saveFileFormat, fileTypes[1])); save.add( 0, Constants.MENU_SAVE_CSV_FILE, 0, String.format(saveFileFormat, fileTypes[2])); save.add( 0, Constants.MENU_SAVE_TCX_FILE, 0, String.format(saveFileFormat, fileTypes[3])); menu.add(0, Constants.MENU_CLEAR_MAP, 0, R.string.track_list_clear_map); menu.add(0, Constants.MENU_DELETE, 0, R.string.track_list_delete_track); } } }; @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case Constants.MENU_SEND_TO_GOOGLE: SendActivity.sendToGoogle(this, dataHub.getSelectedTrackId(), false); return true; case Constants.MENU_SHARE_LINK: SendActivity.sendToGoogle(this, dataHub.getSelectedTrackId(), true); return true; case Constants.MENU_SAVE_GPX_FILE: case Constants.MENU_SAVE_KML_FILE: case Constants.MENU_SAVE_CSV_FILE: case Constants.MENU_SAVE_TCX_FILE: case Constants.MENU_SHARE_GPX_FILE: case Constants.MENU_SHARE_KML_FILE: case Constants.MENU_SHARE_CSV_FILE: case Constants.MENU_SHARE_TCX_FILE: SaveActivity.handleExportTrackAction(this, dataHub.getSelectedTrackId(), Constants.getActionFromMenuId(item.getItemId())); return true; case Constants.MENU_EDIT: { Intent intent = new Intent(this, TrackDetails.class); // TODO: Pass in a content URI intent.putExtra("trackid", dataHub.getSelectedTrackId()); startActivity(intent); return true; } case Constants.MENU_DELETE: { Uri uri = ContentUris.withAppendedId( TracksColumns.CONTENT_URI, dataHub.getSelectedTrackId()); Intent intent = new Intent(Intent.ACTION_DELETE, uri); startActivity(intent); return true; } case Constants.MENU_CLEAR_MAP: dataHub.unloadCurrentTrack(); return true; default: return super.onMenuItemSelected(featureId, item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); myLocation = menu.add(0, Constants.MENU_MY_LOCATION, 0, R.string.menu_map_view_my_location); myLocation.setIcon(android.R.drawable.ic_menu_mylocation); toggleLayers = menu.add(0, Constants.MENU_TOGGLE_LAYERS, 0, R.string.menu_map_view_satellite_mode); toggleLayers.setIcon(android.R.drawable.ic_menu_mapmode); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { toggleLayers.setTitle(mapView.isSatellite() ? R.string.menu_map_view_map_mode : R.string.menu_map_view_satellite_mode); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case Constants.MENU_MY_LOCATION: { dataHub.forceUpdateLocation(); keepMyLocationVisible = true; if (mapView.getZoomLevel() < 18) { mapView.getController().setZoom(18); } if (currentLocation != null) { showCurrentLocation(); } return true; } case Constants.MENU_TOGGLE_LAYERS: { mapView.setSatellite(!mapView.isSatellite()); return true; } } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { if (v == messagePane) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } else if (v == optionsBtn) { optionsBtn.performLongClick(); } } /** * We want the pointer to become visible again in case of the next location * update: */ @Override public boolean onTouch(View view, MotionEvent event) { if (keepMyLocationVisible && event.getAction() == MotionEvent.ACTION_MOVE) { if (!locationIsVisible(currentLocation)) { keepMyLocationVisible = false; } } return false; } @Override public void onProviderStateChange(ProviderState state) { final int messageId; final boolean isGpsDisabled; switch (state) { case DISABLED: messageId = R.string.gps_need_to_enable; isGpsDisabled = true; break; case NO_FIX: case BAD_FIX: messageId = R.string.gps_wait_for_fix; isGpsDisabled = false; break; case GOOD_FIX: // Nothing to show. messageId = -1; isGpsDisabled = false; break; default: throw new IllegalArgumentException("Unexpected state: " + state); } runOnUiThread(new Runnable() { @Override public void run() { if (messageId != -1) { messageText.setText(messageId); messagePane.setVisibility(View.VISIBLE); if (isGpsDisabled) { // Give a warning about this state. Toast.makeText(MapActivity.this, R.string.gps_not_found, Toast.LENGTH_LONG).show(); // Make clicking take the user to the location settings. messagePane.setOnClickListener(MapActivity.this); } else { messagePane.setOnClickListener(null); } } else { messagePane.setVisibility(View.GONE); } screen.requestLayout(); } }); } @Override public void onCurrentLocationChanged(Location location) { currentLocation = location; showCurrentLocation(); } @Override public void onCurrentHeadingChanged(double heading) { synchronized (this) { if (mapOverlay.setHeading((float) heading)) { mapView.postInvalidate(); } } } @Override public void clearWaypoints() { mapOverlay.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (LocationUtils.isValidLocation(waypoint.getLocation())) { // TODO: Optimize locking inside addWaypoint mapOverlay.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { mapView.postInvalidate(); } @Override public void clearTrackPoints() { mapOverlay.clearPoints(); } @Override public void onNewTrackPoint(Location loc) { mapOverlay.addLocation(loc); } @Override public void onSegmentSplit() { mapOverlay.addSegmentSplit(); } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onNewTrackPointsDone() { mapView.postInvalidate(); } @Override public boolean onUnitsChanged(boolean metric) { // We don't care. return false; } @Override public boolean onReportSpeedChanged(boolean reportSpeed) { // We don't care. return false; } }
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; import android.graphics.Paint; import android.graphics.Path; /** * Represents a colored {@code Path} to save its relative color for drawing. * @author Vangelis S. */ public class ColoredPath { private final Path path; private final Paint pathPaint; /** * Constructor for a ColoredPath by color. */ public ColoredPath(int color) { path = new Path(); pathPaint = new Paint(); pathPaint.setColor(color); pathPaint.setStrokeWidth(3); pathPaint.setStyle(Paint.Style.STROKE); pathPaint.setAntiAlias(true); } /** * Constructor for a ColoredPath by Paint. */ public ColoredPath(Paint paint) { path = new Path(); pathPaint = paint; } /** * @return the path */ public Path getPath() { return path; } /** * @return the pathPaint */ public Paint getPathPaint() { return pathPaint; } }
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; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; /** * A list preference which persists its values as integers instead of strings. * Code reading the values should use * {@link android.content.SharedPreferences#getInt}. * When using XML-declared arrays for entry values, the arrays should be regular * string arrays containing valid integer values. * * @author Rodrigo Damazio */ public class IntegerListPreference extends ListPreference { public IntegerListPreference(Context context) { super(context); verifyEntryValues(null); } public IntegerListPreference(Context context, AttributeSet attrs) { super(context, attrs); verifyEntryValues(null); } @Override public void setEntryValues(CharSequence[] entryValues) { CharSequence[] oldValues = getEntryValues(); super.setEntryValues(entryValues); verifyEntryValues(oldValues); } @Override public void setEntryValues(int entryValuesResId) { CharSequence[] oldValues = getEntryValues(); super.setEntryValues(entryValuesResId); verifyEntryValues(oldValues); } @Override protected String getPersistedString(String defaultReturnValue) { // During initial load, there's no known default value int defaultIntegerValue = Integer.MIN_VALUE; if (defaultReturnValue != null) { defaultIntegerValue = Integer.parseInt(defaultReturnValue); } // When the list preference asks us to read a string, instead read an // integer. int value = getPersistedInt(defaultIntegerValue); return Integer.toString(value); } @Override protected boolean persistString(String value) { // When asked to save a string, instead save an integer return persistInt(Integer.parseInt(value)); } private void verifyEntryValues(CharSequence[] oldValues) { CharSequence[] entryValues = getEntryValues(); if (entryValues == null) { return; } for (CharSequence entryValue : entryValues) { try { Integer.parseInt(entryValue.toString()); } catch (NumberFormatException nfe) { super.setEntryValues(oldValues); throw nfe; } } } }
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; import com.google.android.maps.mytracks.R; import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; /** * A preference for an ANT device pairing. * Currently this shows the ID and lets the user clear that ID for future pairing. * TODO: Support pairing from this preference. * * @author Sandor Dornbush */ public class AntPreference extends Preference { public AntPreference(Context context) { super(context); init(); } public AntPreference(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { int sensorId = getPersistedInt(0); if (sensorId == 0) { setSummary(R.string.settings_sensor_ant_not_paired); } else { setSummary( String.format(getContext().getString(R.string.settings_sensor_ant_paired), sensorId)); } // Add actions to allow repairing. setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AntPreference.this.persistInt(0); setSummary(R.string.settings_sensor_ant_not_paired); return true; } }); } }
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; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; /** * Screen in which the user enters details about a waypoint. * * @author Leif Hendrik Wilden */ public class WaypointDetails extends Activity implements OnClickListener { public static final String WAYPOINT_ID_EXTRA = "com.google.android.apps.mytracks.WAYPOINT_ID"; /** * The id of the way point being edited (taken from bundle, "waypointid") */ private Long waypointId; private EditText name; private EditText description; private AutoCompleteTextView category; private View detailsView; private View statsView; private StatsUtilities utils; private Waypoint waypoint; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.mytracks_waypoint_details); utils = new StatsUtilities(this); SharedPreferences preferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences != null) { boolean useMetric = preferences.getBoolean(getString(R.string.metric_units_key), true); utils.setMetricUnits(useMetric); boolean displaySpeed = preferences.getBoolean(getString(R.string.report_speed_key), true); utils.setReportSpeed(displaySpeed); utils.updateWaypointUnits(); utils.setSpeedLabels(); } // Required extra when launching this intent: waypointId = getIntent().getLongExtra(WAYPOINT_ID_EXTRA, -1); if (waypointId < 0) { Log.d(Constants.TAG, "MyTracksWaypointsDetails intent was launched w/o waypoint id."); finish(); return; } // Optional extra that can be used to suppress the cancel button: boolean hasCancelButton = getIntent().getBooleanExtra("hasCancelButton", true); name = (EditText) findViewById(R.id.waypointdetails_name); description = (EditText) findViewById(R.id.waypointdetails_description); category = (AutoCompleteTextView) findViewById(R.id.waypointdetails_category); statsView = findViewById(R.id.waypoint_stats); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.waypoint_types, android.R.layout.simple_dropdown_item_1line); category.setAdapter(adapter); detailsView = findViewById(R.id.waypointdetails_description_layout); Button cancel = (Button) findViewById(R.id.waypointdetails_cancel); if (hasCancelButton) { cancel.setOnClickListener(this); cancel.setVisibility(View.VISIBLE); } else { cancel.setVisibility(View.INVISIBLE); } Button save = (Button) findViewById(R.id.waypointdetails_save); save.setOnClickListener(this); fillDialog(); } private void fillDialog() { waypoint = MyTracksProviderUtils.Factory.get(this).getWaypoint(waypointId); if (waypoint != null) { name.setText(waypoint.getName()); ImageView icon = (ImageView) findViewById(R.id.waypointdetails_icon); int iconId = -1; switch(waypoint.getType()) { case Waypoint.TYPE_WAYPOINT: description.setText(waypoint.getDescription()); detailsView.setVisibility(View.VISIBLE); category.setText(waypoint.getCategory()); statsView.setVisibility(View.GONE); iconId = R.drawable.blue_pushpin; break; case Waypoint.TYPE_STATISTICS: detailsView.setVisibility(View.GONE); statsView.setVisibility(View.VISIBLE); iconId = R.drawable.ylw_pushpin; TripStatistics waypointStats = waypoint.getStatistics(); utils.setAllStats(waypointStats); utils.setAltitude( R.id.elevation_register, waypoint.getLocation().getAltitude()); name.setImeOptions(EditorInfo.IME_ACTION_DONE); break; } icon.setImageDrawable(getResources().getDrawable(iconId)); } } private void saveDialog() { ContentValues values = new ContentValues(); values.put(WaypointsColumns.NAME, name.getText().toString()); if (waypoint != null && waypoint.getType() == Waypoint.TYPE_WAYPOINT) { values.put(WaypointsColumns.DESCRIPTION, description.getText().toString()); values.put(WaypointsColumns.CATEGORY, category.getText().toString()); } getContentResolver().update( WaypointsColumns.CONTENT_URI, values, "_id = " + waypointId, null /*selectionArgs*/); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.waypointdetails_cancel: finish(); break; case R.id.waypointdetails_save: saveDialog(); finish(); break; } } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import android.location.Location; import android.util.Log; /** * Statistics keeper for a trip. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class TripStatisticsBuilder { /** * Statistical data about the trip, which can be displayed to the user. */ private final TripStatistics data; /** * The last location that the gps reported. */ private Location lastLocation; /** * The last location that contributed to the stats. It is also the last * location the user was found to be moving. */ private Location lastMovingLocation; /** * The current speed in meters/second as reported by the gps. */ private double currentSpeed; /** * The current grade. This value is very noisy and not reported to the user. */ private double currentGrade; /** * Is the trip currently paused? * All trips start paused. */ private boolean paused = true; /** * A buffer of the last speed readings in meters/second. */ private final DoubleBuffer speedBuffer = new DoubleBuffer(Constants.SPEED_SMOOTHING_FACTOR); /** * A buffer of the recent elevation readings in meters. */ private final DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); /** * A buffer of the distance between recent gps readings in meters. */ private final DoubleBuffer distanceBuffer = new DoubleBuffer(Constants.DISTANCE_SMOOTHING_FACTOR); /** * A buffer of the recent grade calculations. */ private final DoubleBuffer gradeBuffer = new DoubleBuffer(Constants.GRADE_SMOOTHING_FACTOR); /** * The total number of locations in this trip. */ private long totalLocations = 0; private int minRecordingDistance = Constants.DEFAULT_MIN_RECORDING_DISTANCE; /** * Creates a new trip starting at the given time. * * @param startTime the start time. */ public TripStatisticsBuilder(long startTime) { data = new TripStatistics(); resumeAt(startTime); } /** * Creates a new trip, starting with existing statistics data. * * @param statsData the statistics data to copy and start from */ public TripStatisticsBuilder(TripStatistics statsData) { data = new TripStatistics(statsData); if (data.getStartTime() > 0) { resumeAt(data.getStartTime()); } } /** * Adds a location to the current trip. This will update all of the internal * variables with this new location. * * @param currentLocation the current gps location * @param systemTime the time used for calculation of totalTime. This should * be the phone's time (not GPS time) * @return true if the person is moving */ public boolean addLocation(Location currentLocation, long systemTime) { if (paused) { Log.w(TAG, "Tried to account for location while track is paused"); return false; } totalLocations++; double elevationDifference = updateElevation(currentLocation.getAltitude()); // Update the "instant" values: data.setTotalTime(systemTime - data.getStartTime()); currentSpeed = currentLocation.getSpeed(); // This was the 1st location added, remember it and do nothing else: if (lastLocation == null) { lastLocation = currentLocation; lastMovingLocation = currentLocation; return false; } updateBounds(currentLocation); // Don't do anything if we didn't move since last fix: double distance = lastLocation.distanceTo(currentLocation); if (distance < minRecordingDistance && currentSpeed < Constants.MAX_NO_MOVEMENT_SPEED) { lastLocation = currentLocation; return false; } data.addTotalDistance(lastMovingLocation.distanceTo(currentLocation)); updateSpeed(currentLocation.getTime(), currentSpeed, lastLocation.getTime(), lastLocation.getSpeed()); updateGrade(distance, elevationDifference); lastLocation = currentLocation; lastMovingLocation = currentLocation; return true; } /** * Updates the track's bounding box to include the given location. */ private void updateBounds(Location location) { data.updateLatitudeExtremities(location.getLatitude()); data.updateLongitudeExtremities(location.getLongitude()); } /** * Updates the elevation measurements. * * @param elevation the current elevation */ // @VisibleForTesting double updateElevation(double elevation) { double oldSmoothedElevation = getSmoothedElevation(); elevationBuffer.setNext(elevation); double smoothedElevation = getSmoothedElevation(); data.updateElevationExtremities(smoothedElevation); double elevationDifference = elevationBuffer.isFull() ? smoothedElevation - oldSmoothedElevation : 0.0; if (elevationDifference > 0) { data.addTotalElevationGain(elevationDifference); } return elevationDifference; } /** * Updates the speed measurements. * * @param updateTime the time of the speed update * @param speed the current speed * @param lastLocationTime the time of the last speed update * @param lastLocationSpeed the speed of the last update */ // @VisibleForTesting void updateSpeed(long updateTime, double speed, long lastLocationTime, double lastLocationSpeed) { // We are now sure the user is moving. long timeDifference = updateTime - lastLocationTime; if (timeDifference < 0) { Log.e(TAG, "Found negative time change: " + timeDifference); } data.addMovingTime(timeDifference); if (isValidSpeed(updateTime, speed, lastLocationTime, lastLocationSpeed, speedBuffer)) { speedBuffer.setNext(speed); if (speed > data.getMaxSpeed()) { data.setMaxSpeed(speed); } double movingSpeed = data.getAverageMovingSpeed(); if (speedBuffer.isFull() && (movingSpeed > data.getMaxSpeed())) { data.setMaxSpeed(movingSpeed); } } else { Log.d(TAG, "TripStatistics ignoring big change: Raw Speed: " + speed + " old: " + lastLocationSpeed + " [" + toString() + "]"); } } /** * Checks to see if this is a valid speed. * * @param updateTime The time at the current reading * @param speed The current speed * @param lastLocationTime The time at the last location * @param lastLocationSpeed Speed at the last location * @param speedBuffer A buffer of recent readings * @return True if this is likely a valid speed */ public static boolean isValidSpeed(long updateTime, double speed, long lastLocationTime, double lastLocationSpeed, DoubleBuffer speedBuffer) { // We don't want to count 0 towards the speed. if (speed == 0) { return false; } // We are now sure the user is moving. long timeDifference = updateTime - lastLocationTime; // There are a lot of noisy speed readings. // Do the cheapest checks first, most expensive last. // The following code will ignore unlikely to be real readings. // - 128 m/s seems to be an internal android error code. if (Math.abs(speed - 128) < 1) { return false; } // Another check for a spurious reading. See if the path seems physically // likely. Ignore any speeds that imply accelaration greater than 2g's // Really who can accelerate faster? double speedDifference = Math.abs(lastLocationSpeed - speed); if (speedDifference > Constants.MAX_ACCELERATION * timeDifference) { return false; } // There are three additional checks if the reading gets this far: // - Only use the speed if the buffer is full // - Check that the current speed is less than 10x the recent smoothed speed // - Double check that the current speed does not imply crazy acceleration double smoothedSpeed = speedBuffer.getAverage(); double smoothedDiff = Math.abs(smoothedSpeed - speed); return !speedBuffer.isFull() || (speed < smoothedSpeed * 10 && smoothedDiff < Constants.MAX_ACCELERATION * timeDifference); } /** * Updates the grade measurements. * * @param distance the distance the user just traveled * @param elevationDifference the elevation difference between the current * reading and the previous reading */ // @VisibleForTesting void updateGrade(double distance, double elevationDifference) { distanceBuffer.setNext(distance); double smoothedDistance = distanceBuffer.getAverage(); // With the error in the altitude measurement it is dangerous to divide // by anything less than 5. if (!elevationBuffer.isFull() || !distanceBuffer.isFull() || smoothedDistance < 5.0) { return; } currentGrade = elevationDifference / smoothedDistance; gradeBuffer.setNext(currentGrade); data.updateGradeExtremities(gradeBuffer.getAverage()); } /** * Pauses the track at the given time. * * @param time the time to pause at */ public void pauseAt(long time) { if (paused) { return; } data.setStopTime(time); data.setTotalTime(time - data.getStartTime()); lastLocation = null; // Make sure the counter restarts. paused = true; } /** * Resumes the current track at the given time. * * @param time the time to resume at */ public void resumeAt(long time) { if (!paused) { return; } // TODO: The times are bogus if the track is paused then resumed again data.setStartTime(time); data.setStopTime(-1); paused = false; } @Override public String toString() { return "TripStatistics { Data: " + data.toString() + "; Total Locations: " + totalLocations + "; Paused: " + paused + "; Current speed: " + currentSpeed + "; Current grade: " + currentGrade + "}"; } /** * Returns the amount of time the user has been idle or 0 if they are moving. */ public long getIdleTime() { if (lastLocation == null || lastMovingLocation == null) return 0; return lastLocation.getTime() - lastMovingLocation.getTime(); } /** * Gets the current elevation smoothed over several readings. The elevation * data is very noisy so it is better to use the smoothed elevation than the * raw elevation for many tasks. * * @return The elevation smoothed over several readings */ public double getSmoothedElevation() { return elevationBuffer.getAverage(); } public TripStatistics getStatistics() { // Take a snapshot - we don't want anyone messing with our internals return new TripStatistics(data); } public void setMinRecordingDistance(int minRecordingDistance) { this.minRecordingDistance = minRecordingDistance; } }
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; /** * This class maintains a buffer of doubles. This buffer is a convenient class * for storing a series of doubles and calculating information about them. This * is a FIFO buffer. * * @author Sandor Dornbush */ public class DoubleBuffer { /** * The location that the next write will occur at. */ private int index; /** * The sliding buffer of doubles. */ private final double[] buffer; /** * Have all of the slots in the buffer been filled? */ private boolean isFull; /** * Creates a buffer with size elements. * * @param size the number of elements in the buffer * @throws IllegalArgumentException if the size is not a positive value */ public DoubleBuffer(int size) { if (size < 1) { throw new IllegalArgumentException("The buffer size must be positive."); } buffer = new double[size]; reset(); } /** * Adds a double to the buffer. If the buffer is full the oldest element is * overwritten. * * @param d the double to add */ public void setNext(double d) { if (index == buffer.length) { index = 0; } buffer[index] = d; index++; if (index == buffer.length) { isFull = true; } } /** * Are all of the entries in the buffer used? */ public boolean isFull() { return isFull; } /** * Resets the buffer to the initial state. */ public void reset() { index = 0; isFull = false; } /** * Gets the average of values from the buffer. * * @return The average of the buffer */ public double getAverage() { int numberOfEntries = isFull ? buffer.length : index; if (numberOfEntries == 0) { return 0; } double sum = 0; for (int i = 0; i < numberOfEntries; i++) { sum += buffer[i]; } return sum / numberOfEntries; } /** * Gets the average and standard deviation of the buffer. * * @return An array of two elements - the first is the average, and the second * is the variance */ public double[] getAverageAndVariance() { int numberOfEntries = isFull ? buffer.length : index; if (numberOfEntries == 0) { return new double[]{0, 0}; } double sum = 0; double sumSquares = 0; for (int i = 0; i < numberOfEntries; i++) { sum += buffer[i]; sumSquares += Math.pow(buffer[i], 2); } double average = sum / numberOfEntries; return new double[]{average, sumSquares / numberOfEntries - Math.pow(average, 2)}; } @Override public String toString() { StringBuffer stringBuffer = new StringBuffer("Full: "); stringBuffer.append(isFull); stringBuffer.append("\n"); for (int i = 0; i < buffer.length; i++) { stringBuffer.append((i == index) ? "<<" : "["); stringBuffer.append(buffer[i]); stringBuffer.append((i == index) ? ">> " : "] "); } return stringBuffer.toString(); } }
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.widgets; import static com.google.android.apps.mytracks.Constants.SETTINGS_NAME; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.MyTracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.services.ControlRecordingService; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.os.Handler; import android.util.Log; import android.widget.RemoteViews; /** * An AppWidgetProvider for displaying key track statistics (distance, time, * speed) from the current or most recent track. * * @author Sandor Dornbush * @author Paul R. Saxman */ public class TrackWidgetProvider extends AppWidgetProvider implements OnSharedPreferenceChangeListener { class TrackObserver extends ContentObserver { public TrackObserver() { super(contentHandler); } public void onChange(boolean selfChange) { updateTrack(null); } } private final Handler contentHandler; private MyTracksProviderUtils providerUtils; private Context context; private String unknown; private String distanceLabel; private String speedLabel; private String paceLabel; private TrackObserver trackObserver; private boolean isMetric; private boolean reportSpeed; private long selectedTrackId; private SharedPreferences sharedPreferences; private String TRACK_STARTED_ACTION; private String TRACK_STOPPED_ACTION; public TrackWidgetProvider() { super(); contentHandler = new Handler(); selectedTrackId = -1; } private void initialize(Context aContext) { if (this.context != null) { return; } this.context = aContext; trackObserver = new TrackObserver(); providerUtils = MyTracksProviderUtils.Factory.get(context); unknown = context.getString(R.string.value_unknown); sharedPreferences = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE); sharedPreferences.registerOnSharedPreferenceChangeListener(this); onSharedPreferenceChanged(sharedPreferences, null); context.getContentResolver().registerContentObserver( TracksColumns.CONTENT_URI, true, trackObserver); TRACK_STARTED_ACTION = context.getString(R.string.track_started_broadcast_action); TRACK_STOPPED_ACTION = context.getString(R.string.track_stopped_broadcast_action); } @Override public void onReceive(Context aContext, Intent intent) { super.onReceive(aContext, intent); initialize(aContext); selectedTrackId = intent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), selectedTrackId); String action = intent.getAction(); Log.d(TAG, "TrackWidgetProvider.onReceive: trackId=" + selectedTrackId + ", action=" + action); if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action) || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) || TRACK_STARTED_ACTION.equals(action) || TRACK_STOPPED_ACTION.equals(action)) { updateTrack(action); } } @Override public void onDisabled(Context aContext) { if (trackObserver != null) { aContext.getContentResolver().unregisterContentObserver(trackObserver); } if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } } private void updateTrack(String action) { Track track = null; if (selectedTrackId != -1) { Log.d(TAG, "TrackWidgetProvider.updateTrack: Retrieving specified track."); track = providerUtils.getTrack(selectedTrackId); } else { Log.d(TAG, "TrackWidgetProvider.updateTrack: Attempting to retrieve previous track."); // TODO we should really read the pref. track = providerUtils.getLastTrack(); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName widget = new ComponentName(context, TrackWidgetProvider.class); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.track_widget); // Make all of the stats open the mytracks activity. Intent intent = new Intent(context, MyTracks.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.appwidget_track_statistics, pendingIntent); if (action != null) { updateViewButton(views, action); } updateViewTrackStatistics(views, track); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget); for (int appWidgetId : appWidgetIds) { appWidgetManager.updateAppWidget(appWidgetId, views); } } /** * Update the widget's button with the appropriate intent and icon. * * @param views The RemoteViews containing the button * @param action The action broadcast from the track service */ private void updateViewButton(RemoteViews views, String action) { if (TRACK_STARTED_ACTION.equals(action)) { // If a new track is started by this appwidget or elsewhere, // toggle the button to active and have it disable the track if pressed. setButtonIntent(views, R.string.track_action_end, R.drawable.appwidget_button_enabled); } else { // If a track is stopped by this appwidget or elsewhere, // toggle the button to inactive and have it start a new track if pressed. setButtonIntent(views, R.string.track_action_start, R.drawable.appwidget_button_disabled); } } /** * Set up the main widget button. * * @param views The widget views * @param action The resource id of the action to fire when the button is pressed * @param icon The resource id of the icon to show for the button */ private void setButtonIntent(RemoteViews views, int action, int icon) { Intent intent = new Intent(context, ControlRecordingService.class); intent.setAction(context.getString(action)); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.appwidget_button, pendingIntent); views.setImageViewResource(R.id.appwidget_button, icon); } /** * Update the specified widget's view with the distance, time, and speed of * the specified track. * * @param views The RemoteViews to update with statistics * @param track The track to extract statistics from. */ protected void updateViewTrackStatistics(RemoteViews views, Track track) { if (track == null) { views.setTextViewText(R.id.appwidget_distance_text, unknown); views.setTextViewText(R.id.appwidget_time_text, unknown); views.setTextViewText(R.id.appwidget_speed_text, unknown); return; } TripStatistics stats = track.getStatistics(); // TODO replace this with format strings and miles. // convert meters to kilometers double displayDistance = stats.getTotalDistance() / 1000; if (!isMetric) { displayDistance *= UnitConversions.KM_TO_MI; } String distance = StringUtils.formatSingleDecimalPlace(displayDistance) + " " + this.distanceLabel; // convert ms to minutes String time = StringUtils.formatTime(stats.getMovingTime()); String speed = unknown; if (!Double.isNaN(stats.getAverageMovingSpeed())) { // Convert m/s to km/h double displaySpeed = stats.getAverageMovingSpeed() * 3.6; if (!isMetric) { displaySpeed *= UnitConversions.KMH_TO_MPH; } if (reportSpeed) { speed = StringUtils.formatSingleDecimalPlace(displaySpeed) + " " + this.speedLabel; } else { long displayPace = (long) (3600000.0 / displaySpeed); speed = StringUtils.formatTime(displayPace) + " " + paceLabel; } } views.setTextViewText(R.id.appwidget_distance_text, distance); views.setTextViewText(R.id.appwidget_time_text, time); views.setTextViewText(R.id.appwidget_speed_text, speed); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { String metricUnitsKey = context.getString(R.string.metric_units_key); if (key == null || key.equals(metricUnitsKey)) { isMetric = prefs.getBoolean(metricUnitsKey, true); distanceLabel = context.getString(isMetric ? R.string.unit_kilometer : R.string.unit_mile); speedLabel = context.getString( isMetric ? R.string.unit_kilometer_per_hour : R.string.unit_mile_per_hour); paceLabel = context.getString( isMetric ? R.string.unit_minute_per_kilometer : R.string.unit_minute_per_mile); } String reportSpeedKey = context.getString(R.string.report_speed_key); if (key == null || key.equals(reportSpeedKey)) { reportSpeed = prefs.getBoolean(reportSpeedKey, true); } String selectedTrackKey = context.getString(R.string.selected_track_key); if (key == null || key.equals(selectedTrackKey)) { selectedTrackId = prefs.getLong(selectedTrackKey, -1); Log.d(TAG, "TrackWidgetProvider setting selecting track from preference: " + selectedTrackId); } } }
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; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.file.GpxImporter; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.PowerManager.WakeLock; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * A class that will import all GPX tracks in /sdcard/MyTracks/gpx/ * * @author David Piggott */ public class ImportAllTracks { private final Activity activity; private FileUtils fileUtils; private boolean singleTrackSelected; private String gpxPath; private WakeLock wakeLock; private ProgressDialog progress; private int gpxFileCount; private int importSuccessCount; private long importedTrackIds[]; public ImportAllTracks(Activity activity) { this(activity, null); } /** * Constructor to import tracks. * * @param activity the activity * @param path path of the gpx file to import and display. If null, then just * import all the gpx files under MyTracks/gpx and do not display any * track. */ public ImportAllTracks(Activity activity, String path) { Log.i(Constants.TAG, "ImportAllTracks: Starting"); this.activity = activity; fileUtils = new FileUtils(); singleTrackSelected = path != null; gpxPath = path == null ? fileUtils.buildExternalDirectoryPath("gpx") : path; new Thread(runner).start(); } private final Runnable runner = new Runnable() { public void run() { aquireLocksAndImport(); } }; /** * Makes sure that we keep the phone from sleeping. See if there is a current * track. Acquire a wake lock if there is no current track. */ private void aquireLocksAndImport() { SharedPreferences prefs = activity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId == -1) { wakeLock = SystemUtils.acquireWakeLock(activity, wakeLock); } // Now we can safely import everything. importAll(); // Release the wake lock if we acquired one. // TODO check what happens if we started recording after getting this lock. if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.i(Constants.TAG, "ImportAllTracks: Releasing wake lock."); } activity.runOnUiThread(new Thread() { @Override public void run() { showDoneDialog(); } }); } private void showDoneDialog() { Log.i(Constants.TAG, "ImportAllTracks: Done"); AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (gpxFileCount == 0) { builder.setMessage(activity.getString(R.string.import_no_file, gpxPath)); } else { String totalFiles = activity.getResources().getQuantityString( R.plurals.importGpxFiles, gpxFileCount, gpxFileCount); builder.setMessage( activity.getString(R.string.import_success, importSuccessCount, totalFiles, gpxPath)); } builder.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (singleTrackSelected) { long lastTrackId = importedTrackIds[importedTrackIds.length - 1]; Uri trackUri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, lastTrackId); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(trackUri, TracksColumns.CONTENT_ITEMTYPE); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); activity.finish(); } } }); builder.show(); } private void makeProgressDialog(final int trackCount) { String importMsg = activity.getString(R.string.track_list_import_all); progress = new ProgressDialog(activity); progress.setIcon(android.R.drawable.ic_dialog_info); progress.setTitle(importMsg); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setMax(trackCount); progress.setProgress(0); progress.show(); } /** * Actually import the tracks. This should be called after the wake locks have * been acquired. */ private void importAll() { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(activity); if (!fileUtils.isSdCardAvailable()) { return; } List<File> gpxFiles = getGpxFiles(); gpxFileCount = gpxFiles.size(); if (gpxFileCount == 0) { return; } Log.i(Constants.TAG, "ImportAllTracks: Importing: " + gpxFileCount + " tracks."); activity.runOnUiThread(new Runnable() { public void run() { makeProgressDialog(gpxFileCount); } }); Iterator<File> gpxFilesIterator = gpxFiles.iterator(); for (int currentFileNumber = 0; gpxFilesIterator.hasNext(); currentFileNumber++) { File currentFile = gpxFilesIterator.next(); final int status = currentFileNumber; activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progress == null) { return; } progress.setProgress(status); } } }); if (importFile(currentFile, providerUtils)) { importSuccessCount++; } } if (progress != null) { synchronized (this) { progress.dismiss(); progress = null; } } } /** * Attempts to import a GPX file. Returns true on success, issues error * notifications and returns false on failure. */ private boolean importFile(File gpxFile, MyTracksProviderUtils providerUtils) { Log.i(Constants.TAG, "ImportAllTracks: importing: " + gpxFile.getName()); try { importedTrackIds = GpxImporter.importGPXFile(new FileInputStream(gpxFile), providerUtils); return true; } catch (FileNotFoundException e) { Log.w(Constants.TAG, "GPX file wasn't found/went missing: " + gpxFile.getAbsolutePath(), e); } catch (ParserConfigurationException e) { Log.w(Constants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (SAXException e) { Log.w(Constants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (IOException e) { Log.w(Constants.TAG, "Error reading file: " + gpxFile.getAbsolutePath(), e); } Toast.makeText(activity, activity.getString(R.string.import_error, gpxFile.getName()), Toast.LENGTH_LONG).show(); return false; } /** * Gets a list of the GPX files. If singleTrackSelected is true, returns a * list containing just the gpxPath file. If singleTrackSelected is false, * returns a list of GPX files under the gpxPath directory. */ private List<File> getGpxFiles() { List<File> gpxFiles = new LinkedList<File>(); File file = new File(gpxPath); if (singleTrackSelected) { gpxFiles.add(file); } else { File[] gpxFileCandidates = file.listFiles(); if (gpxFileCandidates != null) { for (File candidate : gpxFileCandidates) { if (!candidate.isDirectory() && candidate.getName().endsWith(".gpx")) { gpxFiles.add(candidate); } } } } return gpxFiles; } }
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; import com.google.android.apps.mytracks.stats.ExtremityMonitor; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import java.text.NumberFormat; /** * This class encapsulates meta data about one series of values for a chart. * * @author Sandor Dornbush */ public class ChartValueSeries { private final ExtremityMonitor monitor = new ExtremityMonitor(); private final NumberFormat format; private final Path path = new Path(); private final Paint fillPaint; private final Paint strokePaint; private final Paint labelPaint; private final ZoomSettings zoomSettings; private String title; private double min; private double max = 1.0; private int effectiveMax; private int effectiveMin; private double spread; private int interval; private boolean enabled = true; /** * This class controls how effective min/max values of a {@link ChartValueSeries} are calculated. */ public static class ZoomSettings { private int intervals; private final int absoluteMin; private final int absoluteMax; private final int[] zoomLevels; public ZoomSettings(int intervals, int[] zoomLevels) { this.intervals = intervals; this.absoluteMin = Integer.MAX_VALUE; this.absoluteMax = Integer.MIN_VALUE; this.zoomLevels = zoomLevels; checkArgs(); } public ZoomSettings(int intervals, int absoluteMin, int absoluteMax, int[] zoomLevels) { this.intervals = intervals; this.absoluteMin = absoluteMin; this.absoluteMax = absoluteMax; this.zoomLevels = zoomLevels; checkArgs(); } private void checkArgs() { if (intervals <= 0 || zoomLevels == null || zoomLevels.length == 0) { throw new IllegalArgumentException("Expecing positive intervals and non-empty zoom levels"); } for (int i = 1; i < zoomLevels.length; ++i) { if (zoomLevels[i] <= zoomLevels[i - 1]) { throw new IllegalArgumentException("Expecting zoom levels in ascending order"); } } } public int getIntervals() { return intervals; } public int getAbsoluteMin() { return absoluteMin; } public int getAbsoluteMax() { return absoluteMax; } public int[] getZoomLevels() { return zoomLevels; } /** * Calculates the interval between markings given the min and max values. * This function attempts to find the smallest zoom level that fits [min,max] after rounding * it to the current zoom level. * * @param min the minimum value in the series * @param max the maximum value in the series * @return the calculated interval for the given range */ public int calculateInterval(double min, double max) { min = Math.min(min, absoluteMin); max = Math.max(max, absoluteMax); for (int i = 0; i < zoomLevels.length; ++i) { int zoomLevel = zoomLevels[i]; int roundedMin = (int)(min / zoomLevel) * zoomLevel; if (roundedMin > min) { roundedMin -= zoomLevel; } double interval = (max - roundedMin) / intervals; if (zoomLevel >= interval) { return zoomLevel; } } return zoomLevels[zoomLevels.length - 1]; } } /** * Constructs a new chart value series. * * @param context The context for the chart * @param fillColor The paint for filling the chart * @param strokeColor The paint for stroking the outside the chart, optional * @param zoomSettings The settings related to zooming * @param titleId The title ID * * TODO: Get rid of Context and inject appropriate values instead. */ public ChartValueSeries( Context context, int fillColor, int strokeColor, ZoomSettings zoomSettings, int titleId) { this.format = NumberFormat.getIntegerInstance(); fillPaint = new Paint(); fillPaint.setStyle(Style.FILL); fillPaint.setColor(context.getResources().getColor(fillColor)); fillPaint.setAntiAlias(true); if (strokeColor != -1) { strokePaint = new Paint(); strokePaint.setStyle(Style.STROKE); strokePaint.setColor(context.getResources().getColor(strokeColor)); strokePaint.setAntiAlias(true); // Make a copy of the stroke paint with the default thickness. labelPaint = new Paint(strokePaint); strokePaint.setStrokeWidth(2f); } else { strokePaint = null; labelPaint = fillPaint; } this.zoomSettings = zoomSettings; this.title = context.getString(titleId); } /** * Draws the path of the chart */ public void drawPath(Canvas c) { c.drawPath(path, fillPaint); if (strokePaint != null) { c.drawPath(path, strokePaint); } } /** * Resets this series */ public void reset() { monitor.reset(); } /** * Updates this series with a new value */ public void update(double d) { monitor.update(d); } /** * @return The interval between markers */ public int getInterval() { return interval; } /** * Determines what the min and max of the chart will be. * This will round down and up the min and max respectively. */ public void updateDimension() { if (monitor.getMax() == Double.NEGATIVE_INFINITY) { min = 0; max = 1; } else { min = monitor.getMin(); max = monitor.getMax(); } min = Math.min(min, zoomSettings.getAbsoluteMin()); max = Math.max(max, zoomSettings.getAbsoluteMax()); this.interval = zoomSettings.calculateInterval(min, max); // Round it up. effectiveMax = ((int) (max / interval)) * interval + interval; // Round it down. effectiveMin = ((int) (min / interval)) * interval; if (min < 0) { effectiveMin -= interval; } spread = effectiveMax - effectiveMin; } /** * @return The length of the longest string from the series */ public int getMaxLabelLength() { String minS = format.format(effectiveMin); String maxS = format.format(getMax()); return Math.max(minS.length(), maxS.length()); } /** * @return The rounded down minimum value */ public int getMin() { return effectiveMin; } /** * @return The rounded up maximum value */ public int getMax() { return effectiveMax; } /** * @return The difference between the min and max values in the series */ public double getSpread() { return spread; } /** * @return The number format for this series */ NumberFormat getFormat() { return format; } /** * @return The path for this series */ Path getPath() { return path; } /** * @return The paint for this series */ Paint getPaint() { return strokePaint == null ? fillPaint : strokePaint; } public Paint getLabelPaint() { return labelPaint; } /** * @return The title of the series */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * @return is this series enabled */ public boolean isEnabled() { return enabled; } /** * Sets the series enabled flag. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean hasData() { return monitor.hasData(); } }
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; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.file.TrackWriter; import com.google.android.apps.mytracks.io.file.TrackWriterFactory; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.Cursor; import android.os.PowerManager.WakeLock; import android.util.Log; import android.widget.Toast; /** * A class that will export all tracks to the sd card. * * @author Sandor Dornbush */ public class ExportAllTracks { // These must line up with the index in the array. public static final int GPX_OPTION_INDEX = 0; public static final int KML_OPTION_INDEX = 1; public static final int CSV_OPTION_INDEX = 2; public static final int TCX_OPTION_INDEX = 3; private final Activity activity; private WakeLock wakeLock; private ProgressDialog progress; private TrackFileFormat format = TrackFileFormat.GPX; private final DialogInterface.OnClickListener itemClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case GPX_OPTION_INDEX: format = TrackFileFormat.GPX; break; case KML_OPTION_INDEX: format = TrackFileFormat.KML; break; case CSV_OPTION_INDEX: format = TrackFileFormat.CSV; break; case TCX_OPTION_INDEX: format = TrackFileFormat.TCX; break; default: Log.w(Constants.TAG, "Unknown export format: " + which); } } }; public ExportAllTracks(Activity activity) { this.activity = activity; Log.i(Constants.TAG, "ExportAllTracks: Starting"); String exportFileFormat = activity.getString(R.string.track_list_export_file); String fileTypes[] = activity.getResources().getStringArray(R.array.file_types); String[] choices = new String[fileTypes.length]; for (int i = 0; i < fileTypes.length; i++) { choices[i] = String.format(exportFileFormat, fileTypes[i]); } AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.track_list_export_all); builder.setSingleChoiceItems(choices, 0, itemClick); builder.setPositiveButton(R.string.generic_ok, positiveClick); builder.setNegativeButton(R.string.generic_cancel, null); builder.show(); } private final DialogInterface.OnClickListener positiveClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new Thread(runner, "SendToMyMaps").start(); } }; private final Runnable runner = new Runnable() { public void run() { aquireLocksAndExport(); } }; /** * Makes sure that we keep the phone from sleeping. * See if there is a current track. Aquire a wake lock if there is no * current track. */ private void aquireLocksAndExport() { SharedPreferences prefs = activity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId != -1) { wakeLock = SystemUtils.acquireWakeLock(activity, wakeLock); } // Now we can safely export everything. exportAll(); // Release the wake lock if we recorded one. // TODO check what happens if we started recording after getting this lock. if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.i(Constants.TAG, "ExportAllTracks: Releasing wake lock."); } Log.i(Constants.TAG, "ExportAllTracks: Done"); showToast(R.string.export_success, Toast.LENGTH_SHORT); } private void makeProgressDialog(final int trackCount) { String exportMsg = activity.getString(R.string.track_list_export_all); progress = new ProgressDialog(activity); progress.setIcon(android.R.drawable.ic_dialog_info); progress.setTitle(exportMsg); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setMax(trackCount); progress.setProgress(0); progress.show(); } /** * Actually export the tracks. * This should be called after the wake locks have been aquired. */ private void exportAll() { // Get a cursor over all tracks. Cursor cursor = null; try { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(activity); cursor = providerUtils.getTracksCursor(""); if (cursor == null) { return; } final int trackCount = cursor.getCount(); Log.i(Constants.TAG, "ExportAllTracks: Exporting: " + cursor.getCount() + " tracks."); int idxTrackId = cursor.getColumnIndexOrThrow(TracksColumns._ID); activity.runOnUiThread(new Runnable() { public void run() { makeProgressDialog(trackCount); } }); for (int i = 0; cursor.moveToNext(); i++) { final int status = i; activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progress == null) { return; } progress.setProgress(status); } } }); long id = cursor.getLong(idxTrackId); Log.i(Constants.TAG, "ExportAllTracks: exporting: " + id); TrackWriter writer = TrackWriterFactory.newWriter(activity, providerUtils, id, format); if (writer == null) { showToast(R.string.export_error, Toast.LENGTH_LONG); return; } writer.writeTrack(); if (!writer.wasSuccess()) { // Abort the whole export on the first error. showToast(writer.getErrorMessage(), Toast.LENGTH_LONG); return; } } } finally { if (cursor != null) { cursor.close(); } if (progress != null) { synchronized (this) { progress.dismiss(); progress = null; } } } } private void showToast(final int messageId, final int length) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, messageId, length).show(); } }); } }
Java
package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Window; import android.widget.ScrollView; import android.widget.TextView; import java.util.List; /** * Activity for viewing the combined statistics for all the recorded tracks. * * Other features to add - menu items to change setings. * * @author Fergus Nelson */ public class AggregatedStatsActivity extends Activity implements OnSharedPreferenceChangeListener { private final StatsUtilities utils; private MyTracksProviderUtils tracksProvider; private boolean metricUnits = true; public AggregatedStatsActivity() { this.utils = new StatsUtilities(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(Constants.TAG, "StatsActivity: onSharedPreferences changed " + key); if (key != null) { if (key.equals(getString(R.string.metric_units_key))) { metricUnits = sharedPreferences.getBoolean( getString(R.string.metric_units_key), true); utils.setMetricUnits(metricUnits); utils.updateUnits(); loadAggregatedStats(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.tracksProvider = MyTracksProviderUtils.Factory.get(this); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.stats); ScrollView sv = ((ScrollView) findViewById(R.id.scrolly)); sv.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); SharedPreferences preferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences != null) { metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true); preferences.registerOnSharedPreferenceChangeListener(this); } utils.setMetricUnits(metricUnits); utils.updateUnits(); utils.setSpeedLabel(R.id.speed_label, R.string.stat_speed, R.string.stat_pace); utils.setSpeedLabels(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (metrics.heightPixels > 600) { ((TextView) findViewById(R.id.speed_register)).setTextSize(80.0f); } loadAggregatedStats(); } /** * 1. Reads tracks from the db * 2. Merges the trip stats from the tracks * 3. Updates the view */ private void loadAggregatedStats() { List<Track> tracks = retrieveTracks(); TripStatistics rollingStats = null; if (!tracks.isEmpty()) { rollingStats = new TripStatistics(tracks.iterator().next() .getStatistics()); for (int i = 1; i < tracks.size(); i++) { rollingStats.merge(tracks.get(i).getStatistics()); } } updateView(rollingStats); } private List<Track> retrieveTracks() { return tracksProvider.getAllTracks(); } private void updateView(TripStatistics aggStats) { if (aggStats != null) { utils.setAllStats(aggStats); } } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.util.Log; /** * Activity used to delete a track. * * @author Rodrigo Damazio */ public class DeleteTrack extends Activity implements DialogInterface.OnClickListener, OnCancelListener { private static final int CONFIRM_DIALOG = 1; private MyTracksProviderUtils providerUtils; private long deleteTrackId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); if (!Intent.ACTION_DELETE.equals(action) || !UriUtils.matchesContentUri(data, TracksColumns.CONTENT_URI)) { Log.e(TAG, "Got bad delete intent: " + intent); finish(); } deleteTrackId = ContentUris.parseId(data); showDialog(CONFIRM_DIALOG); } @Override protected Dialog onCreateDialog(int id) { if (id != CONFIRM_DIALOG) { Log.e(TAG, "Unknown dialog " + id); return null; } AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.track_list_delete_track_confirm_message)); builder.setTitle(getString(R.string.generic_confirm_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(getString(R.string.generic_yes), this); builder.setNegativeButton(getString(R.string.generic_no), this); builder.setOnCancelListener(this); return builder.create(); } @Override public void onClick(DialogInterface dialogInterface, int which) { dialogInterface.dismiss(); if (which == DialogInterface.BUTTON_POSITIVE) { deleteTrack(); } finish(); } @Override public void onCancel(DialogInterface dialog) { onClick(dialog, DialogInterface.BUTTON_NEGATIVE); } private void deleteTrack() { providerUtils.deleteTrack(deleteTrackId); // If the track we just deleted was selected, unselect it. String selectedKey = getString(R.string.selected_track_key); SharedPreferences preferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences.getLong(selectedKey, -1) == deleteTrackId) { Editor editor = preferences.edit().putLong(selectedKey, -1); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.io.file.TempFileCleaner; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.ServiceUtils; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.EulaUtil; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.TabActivity; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.Toast; /** * The super activity that embeds our sub activities. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ @SuppressWarnings("deprecation") public class MyTracks extends TabActivity implements OnTouchListener { private static final int DIALOG_EULA_ID = 0; private TrackDataHub dataHub; /** * Menu manager. */ private MenuManager menuManager; /** * Preferences. */ private SharedPreferences preferences; /** * True if a new track should be created after the track recording service * binds. */ private boolean startNewTrackRequested = false; /** * Utilities to deal with the database. */ private MyTracksProviderUtils providerUtils; /** * Google Analytics tracker */ private GoogleAnalyticsTracker tracker; /* * Tabs/View navigation: */ private NavControls navControls; private final Runnable changeTab = new Runnable() { public void run() { getTabHost().setCurrentTab(navControls.getCurrentIcons()); } }; /* * Recording service interaction: */ private final Runnable serviceBindCallback = new Runnable() { @Override public void run() { synchronized (serviceConnection) { ITrackRecordingService service = serviceConnection.getServiceIfBound(); if (startNewTrackRequested && service != null) { Log.i(TAG, "Starting recording"); startNewTrackRequested = false; startRecordingNewTrack(service); } else if (startNewTrackRequested) { Log.w(TAG, "Not yet starting recording"); } } } }; private TrackRecordingServiceConnection serviceConnection; /* * Application lifetime events: * ============================ */ @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "MyTracks.onCreate"); super.onCreate(savedInstanceState); ApiFeatures apiFeatures = ApiFeatures.getInstance(); if (!SystemUtils.isRelease(this)) { apiFeatures.getApiAdapter().enableStrictMode(); } tracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in manual dispatch mode... tracker.start(getString(R.string.my_tracks_analytics_id), getApplicationContext()); tracker.setProductVersion("android-mytracks", SystemUtils.getMyTracksVersion(this)); tracker.trackPageView("/appstart"); tracker.dispatch(); providerUtils = MyTracksProviderUtils.Factory.get(this); preferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); menuManager = new MenuManager(this); serviceConnection = new TrackRecordingServiceConnection(this, serviceBindCallback); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(apiFeatures).getVolumeStream(); setVolumeControlStream(volumeStream); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); final Resources res = getResources(); final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("Map", res.getDrawable( android.R.drawable.ic_menu_mapmode)) .setContent(new Intent(this, MapActivity.class))); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("Stats", res.getDrawable(R.drawable.menu_stats)) .setContent(new Intent(this, StatsActivity.class))); tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("Chart", res.getDrawable(R.drawable.menu_elevation)) .setContent(new Intent(this, ChartActivity.class))); // Hide the tab widget itself. We'll use overlayed prev/next buttons to // switch between the tabs: tabHost.getTabWidget().setVisibility(View.GONE); RelativeLayout layout = new RelativeLayout(this); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.setLayoutParams(params); navControls = new NavControls(this, layout, getResources().obtainTypedArray(R.array.left_icons), getResources().obtainTypedArray(R.array.right_icons), changeTab); navControls.show(); tabHost.addView(layout); layout.setOnTouchListener(this); if (!EulaUtil.getEulaValue(this)) { showDialog(DIALOG_EULA_ID); } } @Override protected void onStart() { Log.d(TAG, "MyTracks.onStart"); super.onStart(); dataHub.start(); // Ensure that service is running and bound if we're supposed to be recording if (ServiceUtils.isRecording(this, null, preferences)) { serviceConnection.startAndBind(); } Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); if ((Intent.ACTION_VIEW.equals(action) || Intent.ACTION_EDIT.equals(action)) && TracksColumns.CONTENT_ITEMTYPE.equals(intent.getType()) && UriUtils.matchesContentUri(data, TracksColumns.CONTENT_URI)) { long trackId = ContentUris.parseId(data); dataHub.loadTrack(trackId); } } @Override protected void onResume() { // Called when the current activity is being displayed or re-displayed // to the user. Log.d(TAG, "MyTracks.onResume"); serviceConnection.bindIfRunning(); super.onResume(); } @Override protected void onPause() { // Called when activity is going into the background, but has not (yet) been // killed. Shouldn't block longer than approx. 2 seconds. Log.d(TAG, "MyTracks.onPause"); super.onPause(); } @Override protected void onStop() { Log.d(TAG, "MyTracks.onStop"); dataHub.stop(); tracker.dispatch(); tracker.stop(); // Clean up any temporary track files. TempFileCleaner.clean(); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "MyTracks.onDestroy"); serviceConnection.unbind(); super.onDestroy(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_EULA_ID: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.eula_title); builder.setMessage(R.string.eula_message); builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EulaUtil.setEulaValue(MyTracks.this); Intent startIntent = new Intent(MyTracks.this, WelcomeActivity.class); startActivityForResult(startIntent, Constants.WELCOME); } }); builder.setNegativeButton(R.string.eula_decline, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setCancelable(true); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); return builder.create(); default: return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return menuManager.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menuManager.onPrepareOptionsMenu(menu, providerUtils.getLastTrack() != null, ServiceUtils.isRecording(this, serviceConnection.getServiceIfBound(), preferences), dataHub.isATrackSelected()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return menuManager.onOptionsItemSelected(item) ? true : super.onOptionsItemSelected(item); } /* * Key events: * =========== */ @Override public boolean onTrackballEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (ServiceUtils.isRecording(this, serviceConnection.getServiceIfBound(), preferences)) { try { insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } catch (RemoteException e) { Log.e(TAG, "Cannot insert statistics marker.", e); } catch (IllegalStateException e) { Log.e(TAG, "Cannot insert statistics marker.", e); } return true; } } return super.onTrackballEvent(event); } @Override public void onActivityResult(int requestCode, int resultCode, final Intent results) { Log.d(TAG, "MyTracks.onActivityResult"); long trackId = dataHub.getSelectedTrackId(); if (results != null) { trackId = results.getLongExtra("trackid", trackId); } switch (requestCode) { case Constants.SHOW_TRACK: { if (results != null) { if (trackId >= 0) { dataHub.loadTrack(trackId); // The track list passed the requested action as result code. Hand // it off to the onActivityResult for further processing: if (resultCode != Constants.SHOW_TRACK) { onActivityResult(resultCode, Activity.RESULT_OK, results); } } } break; } case Constants.SHOW_WAYPOINT: { if (results != null) { final long waypointId = results.getLongExtra("waypointid", -1); if (waypointId >= 0) { MapActivity map = (MapActivity) getLocalActivityManager().getActivity("tab1"); if (map != null) { getTabHost().setCurrentTab(0); map.showWaypoint(waypointId); } } } break; } case Constants.WELCOME: { CheckUnits.check(this); break; } default: { Log.w(TAG, "Warning unhandled request code: " + requestCode); } } } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navControls.show(); } return false; } /** * Inserts a waypoint marker. * * TODO: Merge with WaypointsList#insertWaypoint. * * @return Id of the inserted statistics marker. * @throws RemoteException If the call on the service failed. */ private long insertWaypoint(WaypointCreationRequest request) throws RemoteException { ITrackRecordingService trackRecordingService = serviceConnection.getServiceIfBound(); if (trackRecordingService == null) { throw new IllegalStateException("The recording service is not bound."); } try { long waypointId = trackRecordingService.insertWaypoint(request); if (waypointId >= 0) { Toast.makeText(this, R.string.marker_insert_success, Toast.LENGTH_LONG).show(); } return waypointId; } catch (RemoteException e) { Toast.makeText(this, R.string.marker_insert_error, Toast.LENGTH_LONG).show(); throw e; } } private void startRecordingNewTrack( ITrackRecordingService trackRecordingService) { try { long recordingTrackId = trackRecordingService.startNewTrack(); // Select the recording track. dataHub.loadTrack(recordingTrackId); Toast.makeText(this, getString(R.string.track_record_success), Toast.LENGTH_SHORT).show(); // TODO: We catch Exception, because after eliminating the service process // all exceptions it may throw are no longer wrapped in a RemoteException. } catch (Exception e) { Toast.makeText(this, getString(R.string.track_record_error), Toast.LENGTH_SHORT).show(); Log.w(TAG, "Unable to start recording.", e); } } /** * Starts the track recording service (if not already running) and binds to * it. Starts recording a new track. */ void startRecording() { synchronized (serviceConnection) { startNewTrackRequested = true; serviceConnection.startAndBind(); // Binding was already requested before, it either already happened // (in which case running the callback manually triggers the actual recording start) // or it will happen in the future // (in which case running the callback now will have no effect). serviceBindCallback.run(); } } /** * Stops the track recording service and unbinds from it. Will display a toast * "Stopped recording" and pop up the Track Details activity. */ void stopRecording() { // Save the track id as the shared preference will overwrite the recording track id. SharedPreferences sharedPreferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long currentTrackId = sharedPreferences.getLong(getString(R.string.recording_track_key), -1); ITrackRecordingService trackRecordingService = serviceConnection.getServiceIfBound(); if (trackRecordingService != null) { try { trackRecordingService.endCurrentTrack(); } catch (Exception e) { Log.e(TAG, "Unable to stop recording.", e); } } serviceConnection.stop(); if (currentTrackId > 0) { Intent intent = new Intent(MyTracks.this, TrackDetails.class); intent.putExtra("trackid", currentTrackId); intent.putExtra("hasCancelButton", false); startActivity(intent); } } long getSelectedTrackId() { return dataHub.getSelectedTrackId(); } }
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; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; /** * Checks with the user if he prefers the metric units or the imperial units. * * @author Sandor Dornbush */ class CheckUnits { private static final String CHECK_UNITS_PREFERENCE_FILE = "checkunits"; private static final String CHECK_UNITS_PREFERENCE_KEY = "checkunits.checked"; private static boolean metric = true; public static void check(final Context context) { final SharedPreferences checkUnitsSharedPreferences = context.getSharedPreferences( CHECK_UNITS_PREFERENCE_FILE, Context.MODE_PRIVATE); if (checkUnitsSharedPreferences.getBoolean(CHECK_UNITS_PREFERENCE_KEY, false)) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(context.getString(R.string.preferred_units_title)); CharSequence[] items = { context.getString(R.string.preferred_units_metric), context.getString(R.string.preferred_units_imperial) }; builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { metric = true; } else { metric = false; } } }); builder.setCancelable(true); builder.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { recordCheckPerformed(checkUnitsSharedPreferences); SharedPreferences useMetricPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = useMetricPreferences.edit(); String key = context.getString(R.string.metric_units_key); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges( editor.putBoolean(key, metric)); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { recordCheckPerformed(checkUnitsSharedPreferences); } }); builder.show(); } private static void recordCheckPerformed(SharedPreferences preferences) { ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges( preferences.edit().putBoolean(CHECK_UNITS_PREFERENCE_KEY, true)); } private CheckUnits() {} }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.ServiceUtils; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Window; import android.widget.ScrollView; import android.widget.TextView; import java.util.EnumSet; /** * An activity that displays track statistics to the user. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class StatsActivity extends Activity implements TrackDataListener { /** * A runnable for posting to the UI thread. Will update the total time field. */ private final Runnable updateResults = new Runnable() { public void run() { if (dataHub != null && dataHub.isRecordingSelected()) { utils.setTime(R.id.total_time_register, System.currentTimeMillis() - startTime); } } }; private StatsUtilities utils; private UIUpdateThread thread; /** * The start time of the selected track. */ private long startTime = -1; private TrackDataHub dataHub; private SharedPreferences preferences; /** * A thread that updates the total time field every second. */ private class UIUpdateThread extends Thread { public UIUpdateThread() { super(); Log.i(TAG, "Created UI update thread"); } @Override public void run() { Log.i(TAG, "Started UI update thread"); while (ServiceUtils.isRecording(StatsActivity.this, null, preferences)) { runOnUiThread(updateResults); try { Thread.sleep(1000L); } catch (InterruptedException e) { Log.w(TAG, "StatsActivity: Caught exception on sleep.", e); break; } } Log.w(TAG, "UIUpdateThread finished."); } } /** Called when the activity is first created. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); preferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); utils = new StatsUtilities(this); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.stats); ScrollView sv = ((ScrollView) findViewById(R.id.scrolly)); sv.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); showUnknownLocation(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (metrics.heightPixels > 600) { ((TextView) findViewById(R.id.speed_register)).setTextSize(80.0f); } } @Override protected void onResume() { super.onResume(); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); dataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } @Override protected void onPause() { dataHub.unregisterTrackDataListener(this); dataHub = null; if (thread != null) { thread.interrupt(); thread = null; } super.onStop(); } @Override public boolean onUnitsChanged(boolean metric) { // Ignore if unchanged. if (metric == utils.isMetricUnits()) return false; utils.setMetricUnits(metric); updateLabels(); return true; // Reload data } @Override public boolean onReportSpeedChanged(boolean displaySpeed) { // Ignore if unchanged. if (displaySpeed == utils.isReportSpeed()) return false; utils.setReportSpeed(displaySpeed); updateLabels(); return true; // Reload data } private void updateLabels() { runOnUiThread(new Runnable() { @Override public void run() { utils.updateUnits(); utils.setSpeedLabel(R.id.speed_label, R.string.stat_speed, R.string.stat_pace); utils.setSpeedLabels(); } }); } /** * Updates the given location fields (latitude, longitude, altitude) and all * other fields. * * @param l may be null (will set location fields to unknown) */ private void showLocation(Location l) { utils.setAltitude(R.id.elevation_register, l.getAltitude()); utils.setLatLong(R.id.latitude_register, l.getLatitude()); utils.setLatLong(R.id.longitude_register, l.getLongitude()); utils.setSpeed(R.id.speed_register, l.getSpeed() * 3.6); } private void showUnknownLocation() { utils.setUnknown(R.id.elevation_register); utils.setUnknown(R.id.latitude_register); utils.setUnknown(R.id.longitude_register); utils.setUnknown(R.id.speed_register); } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { /* * Checks if this activity needs to update live track data or not. * If so, make sure that: * a) a thread keeps updating the total time * b) a location listener is registered * c) a content observer is registered * Otherwise unregister listeners, observers, and kill update thread. */ final boolean startThread = (thread == null) && isRecording; final boolean killThread = (thread != null) && (!isRecording); if (startThread) { thread = new UIUpdateThread(); thread.start(); } else if (killThread) { thread.interrupt(); thread = null; } } @Override public void onCurrentLocationChanged(final Location loc) { TrackDataHub localDataHub = dataHub; if (localDataHub != null && localDataHub.isRecordingSelected()) { runOnUiThread(new Runnable() { @Override public void run() { if (loc != null) { showLocation(loc); } else { showUnknownLocation(); } } }); } } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onProviderStateChange(ProviderState state) { switch (state) { case DISABLED: case NO_FIX: runOnUiThread(new Runnable() { @Override public void run() { showUnknownLocation(); } }); break; } } @Override public void onTrackUpdated(final Track track) { TrackDataHub localDataHub = dataHub; final boolean recordingSelected = localDataHub != null && localDataHub.isRecordingSelected(); runOnUiThread(new Runnable() { @Override public void run() { if (track == null || track.getStatistics() == null) { utils.setAllToUnknown(); return; } startTime = track.getStatistics().getStartTime(); if (!recordingSelected) { utils.setTime(R.id.total_time_register, track.getStatistics().getTotalTime()); showUnknownLocation(); } utils.setAllStats(track.getStatistics()); } }); } @Override public void clearWaypoints() { // We don't care. } @Override public void onNewWaypoint(Waypoint wpt) { // We don't care. } @Override public void onNewWaypointsDone() { // We don't care. } @Override public void clearTrackPoints() { // We don't care. } @Override public void onNewTrackPoint(Location loc) { // We don't care. } @Override public void onSegmentSplit() { // We don't care. } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onNewTrackPointsDone() { // We don't care. } }
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; /** * Constants used by the MyTracks application. * * @author Leif Hendrik Wilden */ public abstract class Constants { /** * Should be used by all log statements */ public static final String TAG = "MyTracks"; /** * Name of the top-level directory inside the SD card where our files will * be read from/written to. */ public static final String SDCARD_TOP_DIR = "MyTracks"; /* * onActivityResult request codes: */ public static final int GET_LOGIN = 0; public static final int GET_MAP = 1; public static final int SHOW_TRACK = 2; public static final int AUTHENTICATE_TO_MY_MAPS = 3; public static final int AUTHENTICATE_TO_FUSION_TABLES = 4; public static final int AUTHENTICATE_TO_DOCLIST = 5; public static final int AUTHENTICATE_TO_TRIX = 6; public static final int SHARE_GPX_FILE = 7; public static final int SHARE_KML_FILE = 8; public static final int SHARE_CSV_FILE = 9; public static final int SHARE_TCX_FILE = 10; public static final int SAVE_GPX_FILE = 11; public static final int SAVE_KML_FILE = 12; public static final int SAVE_CSV_FILE = 13; public static final int SAVE_TCX_FILE = 14; public static final int SHOW_WAYPOINT = 15; public static final int WELCOME = 16; /* * Menu ids: */ public static final int MENU_MY_LOCATION = 1; public static final int MENU_TOGGLE_LAYERS = 2; public static final int MENU_CHART_SETTINGS = 3; /* * Context menu ids: */ public static final int MENU_EDIT = 100; public static final int MENU_DELETE = 101; public static final int MENU_SEND_TO_GOOGLE = 102; public static final int MENU_SHARE = 103; public static final int MENU_SHOW = 104; public static final int MENU_SHARE_LINK = 200; public static final int MENU_SHARE_GPX_FILE = 201; public static final int MENU_SHARE_KML_FILE = 202; public static final int MENU_SHARE_CSV_FILE = 203; public static final int MENU_SHARE_TCX_FILE = 204; public static final int MENU_WRITE_TO_SD_CARD = 205; public static final int MENU_SAVE_GPX_FILE = 206; public static final int MENU_SAVE_KML_FILE = 207; public static final int MENU_SAVE_CSV_FILE = 208; public static final int MENU_SAVE_TCX_FILE = 209; public static final int MENU_CLEAR_MAP = 210; /** * The number of distance readings to smooth to get a stable signal. */ public static final int DISTANCE_SMOOTHING_FACTOR = 25; /** * The number of elevation readings to smooth to get a somewhat accurate * signal. */ public static final int ELEVATION_SMOOTHING_FACTOR = 25; /** * The number of grade readings to smooth to get a somewhat accurate signal. */ public static final int GRADE_SMOOTHING_FACTOR = 5; /** * The number of speed reading to smooth to get a somewhat accurate signal. */ public static final int SPEED_SMOOTHING_FACTOR = 25; /** * Maximum number of track points displayed by the map overlay. */ public static final int MAX_DISPLAYED_TRACK_POINTS = 10000; /** * Target number of track points displayed by the map overlay. * We may display more than this number of points. */ public static final int TARGET_DISPLAYED_TRACK_POINTS = 5000; /** * Maximum number of track points ever loaded at once from the provider into * memory. * With a recording frequency of 2 seconds, 15000 corresponds to 8.3 hours. */ public static final int MAX_LOADED_TRACK_POINTS = 20000; /** * Maximum number of track points ever loaded at once from the provider into * memory in a single call to read points. */ public static final int MAX_LOADED_TRACK_POINTS_PER_BATCH = 1000; /** * Maximum number of way points displayed by the map overlay. */ public static final int MAX_DISPLAYED_WAYPOINTS_POINTS = 128; /** * Maximum number of way points that will be loaded at one time. */ public static final int MAX_LOADED_WAYPOINTS_POINTS = 10000; /** * Any time segment where the distance traveled is less than this value will * not be considered moving. */ public static final double MAX_NO_MOVEMENT_DISTANCE = 2; /** * Anything faster than that (in meters per second) will be considered moving. */ public static final double MAX_NO_MOVEMENT_SPEED = 0.224; /** * Ignore any acceleration faster than this. * Will ignore any speeds that imply accelaration greater than 2g's * 2g = 19.6 m/s^2 = 0.0002 m/ms^2 = 0.02 m/(m*ms) */ public static final double MAX_ACCELERATION = 0.02; /** Maximum age of a GPS location to be considered current. */ public static final long MAX_LOCATION_AGE_MS = 60 * 1000; // 1 minute /** Maximum age of a network location to be considered current. */ public static final long MAX_NETWORK_AGE_MS = 1000 * 60 * 10; // 10 minutes /** * The type of account that we can use for gdata uploads. */ public static final String ACCOUNT_TYPE = "com.google"; /** * The name of extra intent property to indicate whether we want to resume * a previously recorded track. */ public static final String RESUME_TRACK_EXTRA_NAME = "com.google.android.apps.mytracks.RESUME_TRACK"; public static int getActionFromMenuId(int menuId) { switch (menuId) { case Constants.MENU_SHARE_KML_FILE: return Constants.SHARE_KML_FILE; case Constants.MENU_SHARE_GPX_FILE: return Constants.SHARE_GPX_FILE; case Constants.MENU_SHARE_CSV_FILE: return Constants.SHARE_CSV_FILE; case Constants.MENU_SHARE_TCX_FILE: return Constants.SHARE_TCX_FILE; case Constants.MENU_SAVE_GPX_FILE: return Constants.SAVE_GPX_FILE; case Constants.MENU_SAVE_KML_FILE: return Constants.SAVE_KML_FILE; case Constants.MENU_SAVE_CSV_FILE: return Constants.SAVE_CSV_FILE; case Constants.MENU_SAVE_TCX_FILE: return Constants.SAVE_TCX_FILE; default: return -1; } } public static final String MAPSHOP_BASE_URL = "https://maps.google.com/maps/ms"; /* * Default values - keep in sync with those in preferences.xml. */ public static final int DEFAULT_ANNOUNCEMENT_FREQUENCY = -1; public static final int DEFAULT_AUTO_RESUME_TRACK_TIMEOUT = 10; // In min. public static final int DEFAULT_MAX_RECORDING_DISTANCE = 200; public static final int DEFAULT_MIN_RECORDING_DISTANCE = 5; public static final int DEFAULT_MIN_RECORDING_INTERVAL = 0; public static final int DEFAULT_MIN_REQUIRED_ACCURACY = 200; public static final int DEFAULT_SPLIT_FREQUENCY = 0; public static final String SETTINGS_NAME = "SettingsActivity"; /** * This is an abstract utility class. */ protected Constants() { } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.maps.TrackPathPainter; import com.google.android.apps.mytracks.maps.TrackPathPainterFactory; import com.google.android.apps.mytracks.maps.TrackPathUtilities; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.location.Location; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * A map overlay that displays a "MyLocation" arrow, an error circle, the * currently recording track and optionally a selected track. * * @author Leif Hendrik Wilden */ public class MapOverlay extends Overlay implements OnSharedPreferenceChangeListener { private final Drawable[] arrows; private final int arrowWidth, arrowHeight; private final Drawable statsMarker; private final Drawable waypointMarker; private final Drawable startMarker; private final Drawable endMarker; private final int markerWidth, markerHeight; private final Paint errorCirclePaint; private final Context context; private final List<Waypoint> waypoints; private final List<CachedLocation> points; private final BlockingQueue<CachedLocation> pendingPoints; private boolean trackDrawingEnabled; private int lastHeading = 0; private Location myLocation; private boolean showEndMarker = true; // TODO: Remove it completely after completing performance tests. private boolean alwaysVisible = true; private GeoPoint lastReferencePoint; private Rect lastViewRect; private boolean lastPathExists; private TrackPathPainter trackPathPainter; /** * Represents a pre-processed {@code Location} to speed up drawing. * This class is more like a data object and doesn't provide accessors. */ public static class CachedLocation { public final boolean valid; public final GeoPoint geoPoint; public final int speed; /** * Constructor for an invalid cached location. */ public CachedLocation() { this.valid = false; this.geoPoint = null; this.speed = -1; } /** * Constructor for a potentially valid cached location. */ public CachedLocation(Location location) { this.valid = LocationUtils.isValidLocation(location); this.geoPoint = valid ? LocationUtils.getGeoPoint(location) : null; this.speed = (int) Math.floor(location.getSpeed() * 3.6); } }; public MapOverlay(Context context) { this.context = context; this.waypoints = new ArrayList<Waypoint>(); this.points = new ArrayList<CachedLocation>(1024); this.pendingPoints = new ArrayBlockingQueue<CachedLocation>( Constants.MAX_DISPLAYED_TRACK_POINTS, true); // TODO: Can we use a FrameAnimation or similar here rather // than individual resources for each arrow direction? final Resources resources = context.getResources(); arrows = new Drawable[] { resources.getDrawable(R.drawable.arrow_0), resources.getDrawable(R.drawable.arrow_20), resources.getDrawable(R.drawable.arrow_40), resources.getDrawable(R.drawable.arrow_60), resources.getDrawable(R.drawable.arrow_80), resources.getDrawable(R.drawable.arrow_100), resources.getDrawable(R.drawable.arrow_120), resources.getDrawable(R.drawable.arrow_140), resources.getDrawable(R.drawable.arrow_160), resources.getDrawable(R.drawable.arrow_180), resources.getDrawable(R.drawable.arrow_200), resources.getDrawable(R.drawable.arrow_220), resources.getDrawable(R.drawable.arrow_240), resources.getDrawable(R.drawable.arrow_260), resources.getDrawable(R.drawable.arrow_280), resources.getDrawable(R.drawable.arrow_300), resources.getDrawable(R.drawable.arrow_320), resources.getDrawable(R.drawable.arrow_340) }; arrowWidth = arrows[lastHeading].getIntrinsicWidth(); arrowHeight = arrows[lastHeading].getIntrinsicHeight(); for (Drawable arrow : arrows) { arrow.setBounds(0, 0, arrowWidth, arrowHeight); } statsMarker = resources.getDrawable(R.drawable.ylw_pushpin); markerWidth = statsMarker.getIntrinsicWidth(); markerHeight = statsMarker.getIntrinsicHeight(); statsMarker.setBounds(0, 0, markerWidth, markerHeight); startMarker = resources.getDrawable(R.drawable.green_dot); startMarker.setBounds(0, 0, markerWidth, markerHeight); endMarker = resources.getDrawable(R.drawable.red_dot); endMarker.setBounds(0, 0, markerWidth, markerHeight); waypointMarker = resources.getDrawable(R.drawable.blue_pushpin); waypointMarker.setBounds(0, 0, markerWidth, markerHeight); errorCirclePaint = TrackPathUtilities.getPaint(R.color.blue, context); errorCirclePaint.setAlpha(127); trackPathPainter = TrackPathPainterFactory.getTrackPathPainter(context); context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) .registerOnSharedPreferenceChangeListener(this); } /** * Add a location to the map overlay. * * NOTE: This method doesn't take ownership of the given location, so it is * safe to reuse the same location while calling this method. * * @param l the location to add. */ public void addLocation(Location l) { // Queue up in the pending queue until it's merged with {@code #points}. if (!pendingPoints.offer(new CachedLocation(l))) { Log.e(TAG, "Unable to add pending points"); } } /** * Adds a segment split to the map overlay. */ public void addSegmentSplit() { if (!pendingPoints.offer(new CachedLocation())) { Log.e(TAG, "Unable to add pending points"); } } public void addWaypoint(Waypoint wpt) { // Note: We don't cache waypoints, because it's not worth the effort. if (wpt != null && wpt.getLocation() != null) { synchronized (waypoints) { waypoints.add(wpt); } } } public int getNumLocations() { synchronized (points) { return points.size() + pendingPoints.size(); } } // Visible for testing. public int getNumWaypoints() { synchronized (waypoints) { return waypoints.size(); } } public void clearPoints() { synchronized (getPoints()) { getPoints().clear(); pendingPoints.clear(); lastPathExists = false; lastViewRect = null; trackPathPainter.clear(); } } public void clearWaypoints() { synchronized (waypoints) { waypoints.clear(); } } public void setTrackDrawingEnabled(boolean trackDrawingEnabled) { this.trackDrawingEnabled = trackDrawingEnabled; } public void setShowEndMarker(boolean showEndMarker) { this.showEndMarker = showEndMarker; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) { return; } // It's safe to keep projection within a single draw operation. final Projection projection = getMapProjection(mapView); if (projection == null) { Log.w(TAG, "No projection, unable to draw"); return; } // Get the current viewing window. if (trackDrawingEnabled) { Rect viewRect = getMapViewRect(mapView); // Draw the selected track: drawTrack(canvas, projection, viewRect); // Draw the "Start" and "End" markers: drawMarkers(canvas, projection); // Draw the waypoints: drawWaypoints(canvas, projection); } // Draw the current location drawMyLocation(canvas, projection); } private void drawMarkers(Canvas canvas, Projection projection) { // Draw the "End" marker. if (showEndMarker) { for (int i = getPoints().size() - 1; i >= 0; --i) { if (getPoints().get(i).valid) { drawElement(canvas, projection, getPoints().get(i).geoPoint, endMarker, -markerWidth / 2, -markerHeight); break; } } } // Draw the "Start" marker. for (int i = 0; i < getPoints().size(); ++i) { if (getPoints().get(i).valid) { drawElement(canvas, projection, getPoints().get(i).geoPoint, startMarker, -markerWidth / 2, -markerHeight); break; } } } // Visible for testing. Projection getMapProjection(MapView mapView) { return mapView.getProjection(); } // Visible for testing. Rect getMapViewRect(MapView mapView) { int w = mapView.getLongitudeSpan(); int h = mapView.getLatitudeSpan(); int cx = mapView.getMapCenter().getLongitudeE6(); int cy = mapView.getMapCenter().getLatitudeE6(); return new Rect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2); } // For use in testing only. public TrackPathPainter getTrackPathPainter() { return trackPathPainter; } // For use in testing only. public void setTrackPathPainter(TrackPathPainter trackPathPainter) { this.trackPathPainter = trackPathPainter; } private void drawWaypoints(Canvas canvas, Projection projection) { synchronized (waypoints) {; for (Waypoint wpt : waypoints) { Location loc = wpt.getLocation(); drawElement(canvas, projection, LocationUtils.getGeoPoint(loc), wpt.getType() == Waypoint.TYPE_STATISTICS ? statsMarker : waypointMarker, -(markerWidth / 2) + 3, -markerHeight); } } } private void drawMyLocation(Canvas canvas, Projection projection) { // Draw the arrow icon. if (myLocation == null) { return; } Point pt = drawElement(canvas, projection, LocationUtils.getGeoPoint(myLocation), arrows[lastHeading], -(arrowWidth / 2) + 3, -(arrowHeight / 2)); // Draw the error circle. float radius = projection.metersToEquatorPixels(myLocation.getAccuracy()); canvas.drawCircle(pt.x, pt.y, radius, errorCirclePaint); } private void drawTrack(Canvas canvas, Projection projection, Rect viewRect) { boolean draw; synchronized (points) { // Merge the pending points with the list of cached locations. final GeoPoint referencePoint = projection.fromPixels(0, 0); int newPoints = pendingPoints.drainTo(points); boolean newProjection = !viewRect.equals(lastViewRect) || !referencePoint.equals(lastReferencePoint); if (newPoints == 0 && lastPathExists && !newProjection) { // No need to recreate path (same points and viewing area). draw = true; } else { int numPoints = points.size(); if (numPoints < 2) { // Not enough points to draw a path. draw = false; } else if (!trackPathPainter.needsRedraw() && lastPathExists && !newProjection) { // Incremental update of the path, without repositioning the view. draw = true; trackPathPainter.updatePath(projection, viewRect, numPoints - newPoints, alwaysVisible, points); } else { // The view has changed so we have to start from scratch. draw = true; trackPathPainter.updatePath(projection, viewRect, 0, alwaysVisible, points); } } lastReferencePoint = referencePoint; lastViewRect = viewRect; } if (draw) { trackPathPainter.drawTrack(canvas); } } // Visible for testing. Point drawElement(Canvas canvas, Projection projection, GeoPoint geoPoint, Drawable element, int offsetX, int offsetY) { Point pt = new Point(); projection.toPixels(geoPoint, pt); canvas.save(); canvas.translate(pt.x + offsetX, pt.y + offsetY); element.draw(canvas); canvas.restore(); return pt; } /** * Sets the pointer location (will be drawn on next invalidate). */ public void setMyLocation(Location myLocation) { this.myLocation = myLocation; } /** * Sets the pointer heading in degrees (will be drawn on next invalidate). * * @return true if the visible heading changed (i.e. a redraw of pointer is * potentially necessary) */ public boolean setHeading(float heading) { int newhdg = Math.round(-heading / 360 * 18 + 180); while (newhdg < 0) newhdg += 18; while (newhdg > 17) newhdg -= 18; if (newhdg != lastHeading) { lastHeading = newhdg; return true; } else { return false; } } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (p.equals(mapView.getMapCenter())) { // There is (unfortunately) no good way to determine whether the tap was // caused by an actual tap on the screen or the track ball. If the // location is equal to the map center,then it was a track ball press with // very high likelihood. return false; } final Location tapLocation = LocationUtils.getLocation(p); double dmin = Double.MAX_VALUE; Waypoint waypoint = null; synchronized (waypoints) { for (int i = 0; i < waypoints.size(); i++) { final Location waypointLocation = waypoints.get(i).getLocation(); if (waypointLocation == null) { continue; } final double d = waypointLocation.distanceTo(tapLocation); if (d < dmin) { dmin = d; waypoint = waypoints.get(i); } } } if (waypoint != null && dmin < 15000000 / Math.pow(2, mapView.getZoomLevel())) { Intent intent = new Intent(context, WaypointDetails.class); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, waypoint.getId()); context.startActivity(intent); return true; } return super.onTap(p, mapView); } /** * @return the points */ public List<CachedLocation> getPoints() { return points; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "MapOverlay: onSharedPreferences changed " + key); if (key != null) { if (key.equals(context.getString(R.string.track_color_mode_key))) { trackPathPainter = TrackPathPainterFactory.getTrackPathPainter(context); } } } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.google.android.apps.mytracks.services.sensors.SensorManager; import com.google.android.apps.mytracks.services.sensors.SensorManagerFactory; import com.google.android.apps.mytracks.services.sensors.SensorUtils; import com.google.android.maps.mytracks.R; import com.google.protobuf.InvalidProtocolBufferException; import android.app.Activity; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.widget.TextView; import java.text.DateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * An activity that displays information about sensors. * * @author Sandor Dornbush */ public class SensorStateActivity extends Activity { private static final DateFormat TIMESTAMP_FORMAT = DateFormat.getTimeInstance(DateFormat.SHORT); private static final long REFRESH_PERIOD_MS = 250; private final StatsUtilities utils; /** * This timer periodically invokes the refresh timer task. */ private Timer timer; private final Runnable stateUpdater = new Runnable() { public void run() { if (isVisible) // only update when UI is visible updateState(); } }; /** * Connection to the recording service. */ private TrackRecordingServiceConnection serviceConnection; /** * A task which will update the U/I. */ private class RefreshTask extends TimerTask { @Override public void run() { runOnUiThread(stateUpdater); } }; /** * A temporary sensor manager, when none is available. */ SensorManager tempSensorManager = null; /** * A state flag set to true when the activity is active/visible, * i.e. after resume, and before pause * * Used to avoid updating after the pause event, because sometimes an update * event occurs even after the timer is cancelled. In this case, * it could cause the {@link #tempSensorManager} to be recreated, after it * is destroyed at the pause event. */ boolean isVisible = false; public SensorStateActivity() { utils = new StatsUtilities(this); Log.w(TAG, "SensorStateActivity()"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w(TAG, "SensorStateActivity.onCreate"); setContentView(R.layout.sensor_state); serviceConnection = new TrackRecordingServiceConnection(this, stateUpdater); serviceConnection.bindIfRunning(); updateState(); } @Override protected void onResume() { super.onResume(); isVisible = true; serviceConnection.bindIfRunning(); timer = new Timer(); timer.schedule(new RefreshTask(), REFRESH_PERIOD_MS, REFRESH_PERIOD_MS); } @Override protected void onPause() { isVisible = false; timer.cancel(); timer.purge(); timer = null; stopTempSensorManager(); super.onPause(); } @Override protected void onDestroy() { serviceConnection.unbind(); super.onDestroy(); } protected void updateState() { Log.d(TAG, "Updating SensorStateActivity"); ITrackRecordingService service = serviceConnection.getServiceIfBound(); // Check if service is available, and recording. boolean isRecording = false; if (service != null) { try { isRecording = service.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Unable to determine if service is recording.", e); } } // If either service isn't available, or not recording. if (!isRecording) { updateFromTempSensorManager(); } else { updateFromSysSensorManager(); } } private void updateFromTempSensorManager() { // Use variables to hold the sensor state and data set. Sensor.SensorState currentState = null; Sensor.SensorDataSet currentDataSet = null; // If no temp sensor manager is present, create one, and start it. if (tempSensorManager == null) { tempSensorManager = SensorManagerFactory.getSensorManager(this); if (tempSensorManager != null) tempSensorManager.onStartTrack(); } // If a temp sensor manager is available, use states from temp sensor // manager. if (tempSensorManager != null) { currentState = tempSensorManager.getSensorState(); currentDataSet = tempSensorManager.getSensorDataSet(); } // Update the sensor state, and sensor data, using the variables. updateSensorStateAndData(currentState, currentDataSet); } private void updateFromSysSensorManager() { // Use variables to hold the sensor state and data set. Sensor.SensorState currentState = null; Sensor.SensorDataSet currentDataSet = null; ITrackRecordingService service = serviceConnection.getServiceIfBound(); // If a temp sensor manager is present, shut it down, // probably recording just started. stopTempSensorManager(); // Get sensor details from the service. if (service == null) { Log.d(TAG, "Could not get track recording service."); } else { try { byte[] buff = service.getSensorData(); if (buff != null) { currentDataSet = Sensor.SensorDataSet.parseFrom(buff); } } catch (RemoteException e) { Log.e(TAG, "Could not read sensor data.", e); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "Could not read sensor data.", e); } try { currentState = Sensor.SensorState.valueOf(service.getSensorState()); } catch (RemoteException e) { Log.e(TAG, "Could not read sensor state.", e); currentState = Sensor.SensorState.NONE; } } // Update the sensor state, and sensor data, using the variables. updateSensorStateAndData(currentState, currentDataSet); } /** * Stops the temporary sensor manager, if one exists. */ private void stopTempSensorManager() { if (tempSensorManager != null) { tempSensorManager.shutdown(); tempSensorManager = null; } } private void updateSensorStateAndData(Sensor.SensorState state, Sensor.SensorDataSet dataSet) { updateSensorState(state == null ? Sensor.SensorState.NONE : state); updateSensorData(dataSet); } private void updateSensorState(Sensor.SensorState state) { TextView sensorTime = ((TextView) findViewById(R.id.sensor_state_register)); sensorTime.setText(SensorUtils.getStateAsString(state, this)); } protected void updateSensorData(Sensor.SensorDataSet sds) { if (sds == null) { utils.setUnknown(R.id.sensor_data_time_register); utils.setUnknown(R.id.cadence_state_register); utils.setUnknown(R.id.power_state_register); utils.setUnknown(R.id.heart_rate_register); utils.setUnknown(R.id.battery_level_register); return; } TextView sensorTime = ((TextView) findViewById(R.id.sensor_data_time_register)); sensorTime.setText( TIMESTAMP_FORMAT.format(new Date(sds.getCreationTime()))); if (sds.hasPower() && sds.getPower().hasValue() && sds.getPower().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.power_state_register, Integer.toString(sds.getPower().getValue())); } else { utils.setText(R.id.power_state_register, SensorUtils.getStateAsString( sds.hasPower() ? sds.getPower().getState() : Sensor.SensorState.NONE, this)); } if (sds.hasCadence() && sds.getCadence().hasValue() && sds.getCadence().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.cadence_state_register, Integer.toString(sds.getCadence().getValue())); } else { utils.setText(R.id.cadence_state_register, SensorUtils.getStateAsString( sds.hasCadence() ? sds.getCadence().getState() : Sensor.SensorState.NONE, this)); } if (sds.hasHeartRate() && sds.getHeartRate().hasValue() && sds.getHeartRate().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.heart_rate_register, Integer.toString(sds.getHeartRate().getValue())); } else { utils.setText(R.id.heart_rate_register, SensorUtils.getStateAsString( sds.hasHeartRate() ? sds.getHeartRate().getState() : Sensor.SensorState.NONE, this)); } if (sds.hasBatteryLevel() && sds.getBatteryLevel().hasValue() && sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.battery_level_register, Integer.toString(sds.getBatteryLevel().getValue())); } else { utils.setText(R.id.battery_level_register, SensorUtils.getStateAsString( sds.hasBatteryLevel() ? sds.getBatteryLevel().getState() : Sensor.SensorState.NONE, this)); } } }
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; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.ContentValues; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; /** * An activity that let's the user see and edit the user editable track meta * data such as name, activity type and description. * * @author Leif Hendrik Wilden */ public class TrackDetails extends Activity implements OnClickListener { /** * The id of the track being edited (taken from bundle, "trackid") */ private Long trackId; private EditText name; private EditText description; private AutoCompleteTextView category; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.mytracks_detail); // Required extra when launching this intent: trackId = getIntent().getLongExtra("trackid", -1); if (trackId < 0) { Log.d(Constants.TAG, "MyTracksDetails intent was launched w/o track id."); finish(); return; } // Optional extra that can be used to suppress the cancel button: boolean hasCancelButton = getIntent().getBooleanExtra("hasCancelButton", true); name = (EditText) findViewById(R.id.trackdetails_name); description = (EditText) findViewById(R.id.trackdetails_description); category = (AutoCompleteTextView) findViewById(R.id.trackdetails_category); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.activity_types, android.R.layout.simple_dropdown_item_1line); category.setAdapter(adapter); Button cancel = (Button) findViewById(R.id.trackdetails_cancel); if (hasCancelButton) { cancel.setOnClickListener(this); cancel.setVisibility(View.VISIBLE); } else { cancel.setVisibility(View.INVISIBLE); } Button save = (Button) findViewById(R.id.trackdetails_save); save.setOnClickListener(this); fillDialog(); } private void fillDialog() { Track track = MyTracksProviderUtils.Factory.get(this).getTrack(trackId); if (track != null) { name.setText(track.getName()); description.setText(track.getDescription()); category.setText(track.getCategory()); } } private void saveDialog() { ContentValues values = new ContentValues(); values.put(TracksColumns.NAME, name.getText().toString()); values.put(TracksColumns.DESCRIPTION, description.getText().toString()); values.put(TracksColumns.CATEGORY, category.getText().toString()); getContentResolver().update( TracksColumns.CONTENT_URI, values, "_id = " + trackId, null/*selectionArgs*/); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.trackdetails_cancel: finish(); break; case R.id.trackdetails_save: saveDialog(); finish(); break; } } }
Java
package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.content.Context; import android.preference.EditTextPreference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; /** * The {@link AutoCompleteTextPreference} class is a preference that allows for * string input using auto complete . It is a subclass of * {@link EditTextPreference} and shows the {@link AutoCompleteTextView} in a * dialog. * <p> * This preference will store a string into the SharedPreferences. * * @author Rimas Trumpa (with Matt Levan) */ public class AutoCompleteTextPreference extends EditTextPreference { private AutoCompleteTextView mEditText = null; public AutoCompleteTextPreference(Context context, AttributeSet attrs) { super(context, attrs); mEditText = new AutoCompleteTextView(context, attrs); mEditText.setThreshold(0); // Gets autocomplete values for 'Default Activity' preference if (getKey().equals(context.getString(R.string.default_activity_key))) { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.activity_types, android.R.layout.simple_dropdown_item_1line); mEditText.setAdapter(adapter); } } @Override protected void onBindDialogView(View view) { AutoCompleteTextView editText = mEditText; editText.setText(getText()); ViewParent oldParent = editText.getParent(); if (oldParent != view) { if (oldParent != null) { ((ViewGroup) oldParent).removeView(editText); } onAddEditTextToDialogView(view, editText); } } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { String value = mEditText.getText().toString(); if (callChangeListener(value)) { setText(value); } } } }
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; import com.google.android.maps.mytracks.R; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.util.Log; /** * Choose which account to upload track information to. * @author Sandor Dornbush */ public class AccountChooser { /** * The last selected account. */ private int selectedAccountIndex = -1; private Account selectedAccount = null; /** * An interface for receiving updates once the user has selected the account. */ public interface AccountHandler { /** * Handle the account being selected. * @param account The selected account or null if none could be found */ public void onAccountSelected(Account account); } /** * Chooses the best account to upload to. * If no account is found the user will be alerted. * If only one account is found that will be used. * If multiple accounts are found the user will be allowed to choose. * * @param activity The parent activity * @param handler The handler to be notified when an account has been selected */ public void chooseAccount(final Activity activity, final AccountHandler handler) { final Account[] accounts = AccountManager.get(activity) .getAccountsByType(Constants.ACCOUNT_TYPE); if (accounts.length < 1) { alertNoAccounts(activity, handler); return; } if (accounts.length == 1) { handler.onAccountSelected(accounts[0]); return; } // TODO This should be read out of a preference. if (selectedAccount != null) { handler.onAccountSelected(selectedAccount); return; } // Let the user choose. Log.e(Constants.TAG, "Multiple matching accounts found."); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.send_google_choose_account_title); builder.setCancelable(false); builder.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (selectedAccountIndex >= 0) { selectedAccount = accounts[selectedAccountIndex]; } handler.onAccountSelected(selectedAccount); } }); builder.setNegativeButton(R.string.generic_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); handler.onAccountSelected(null); } }); String[] choices = new String[accounts.length]; for (int i = 0; i < accounts.length; i++) { choices[i] = accounts[i].name; } builder.setSingleChoiceItems(choices, selectedAccountIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { selectedAccountIndex = which; } }); builder.show(); } public void setChosenAccount(String accountName, String accountType) { selectedAccount = new Account(accountName, accountType); } /** * Puts up a dialog alerting the user that no suitable account was found. */ private void alertNoAccounts(final Activity activity, final AccountHandler handler) { Log.e(Constants.TAG, "No matching accounts found."); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.send_google_no_account_title); builder.setMessage(R.string.send_google_no_account_message); builder.setCancelable(true); builder.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); handler.onAccountSelected(null); } }); builder.show(); } }
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; import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.ExtremityMonitor; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.widget.Scroller; import java.text.NumberFormat; import java.util.ArrayList; /** * Visualization of the chart. * * @author Sandor Dornbush * @author Leif Hendrik Wilden */ public class ChartView extends View { private static final int MIN_ZOOM_LEVEL = 1; /* * Scrolling logic: */ private final Scroller scroller; private VelocityTracker velocityTracker = null; /** Position of the last motion event */ private float lastMotionX; /* * Zoom logic: */ private int zoomLevel = 1; private int maxZoomLevel = 10; private static final int MAX_INTERVALS = 5; /* * Borders, margins, dimensions (in pixels): */ private int leftBorder = -1; /** * Unscaled top border of the chart. */ private static final int TOP_BORDER = 15; /** * Device scaled top border of the chart. */ private int topBorder; /** * Unscaled bottom border of the chart. */ private static final float BOTTOM_BORDER = 40; /** * Device scaled bottom border of the chart. */ private int bottomBorder; private static final int RIGHT_BORDER = 17; /** Space to leave for drawing the unit labels */ private static final int UNIT_BORDER = 15; private static final int FONT_HEIGHT = 10; private int w = 0; private int h = 0; private int effectiveWidth = 0; private int effectiveHeight = 0; /* * Ranges (in data units): */ private double maxX = 1; /** * The various series. */ public static final int ELEVATION_SERIES = 0; public static final int SPEED_SERIES = 1; public static final int POWER_SERIES = 2; public static final int CADENCE_SERIES = 3; public static final int HEART_RATE_SERIES = 4; public static final int NUM_SERIES = 5; private ChartValueSeries[] series; private final ExtremityMonitor xMonitor = new ExtremityMonitor(); private static final NumberFormat X_FORMAT = NumberFormat.getIntegerInstance(); private static final NumberFormat X_SHORT_FORMAT = NumberFormat.getNumberInstance(); static { X_SHORT_FORMAT.setMaximumFractionDigits(1); X_SHORT_FORMAT.setMinimumFractionDigits(1); } /* * Paints etc. used when drawing the chart: */ private final Paint borderPaint = new Paint(); private final Paint labelPaint = new Paint(); private final Paint gridPaint = new Paint(); private final Paint gridBarPaint = new Paint(); private final Paint clearPaint = new Paint(); private final Drawable pointer; private final Drawable statsMarker; private final Drawable waypointMarker; private final int markerWidth, markerHeight; /** * The chart data stored as an array of double arrays. Each one dimensional * array is composed of [x, y]. */ private final ArrayList<double[]> data = new ArrayList<double[]>(); /** * List of way points to be displayed. */ private final ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>(); private boolean metricUnits = true; private boolean showPointer = false; /** Display chart versus distance or time */ public enum Mode { BY_DISTANCE, BY_TIME } private Mode mode = Mode.BY_DISTANCE; public ChartView(Context context) { super(context); setUpChartValueSeries(context); labelPaint.setStyle(Style.STROKE); labelPaint.setColor(context.getResources().getColor(R.color.black)); labelPaint.setAntiAlias(true); borderPaint.setStyle(Style.STROKE); borderPaint.setColor(context.getResources().getColor(R.color.black)); borderPaint.setAntiAlias(true); gridPaint.setStyle(Style.STROKE); gridPaint.setColor(context.getResources().getColor(R.color.gray)); gridPaint.setAntiAlias(false); gridBarPaint.set(gridPaint); gridBarPaint.setPathEffect(new DashPathEffect(new float[] {3, 2}, 0)); clearPaint.setStyle(Style.FILL); clearPaint.setColor(context.getResources().getColor(R.color.white)); clearPaint.setAntiAlias(false); pointer = context.getResources().getDrawable(R.drawable.arrow_180); pointer.setBounds(0, 0, pointer.getIntrinsicWidth(), pointer.getIntrinsicHeight()); statsMarker = getResources().getDrawable(R.drawable.ylw_pushpin); markerWidth = statsMarker.getIntrinsicWidth(); markerHeight = statsMarker.getIntrinsicHeight(); statsMarker.setBounds(0, 0, markerWidth, markerHeight); waypointMarker = getResources().getDrawable(R.drawable.blue_pushpin); waypointMarker.setBounds(0, 0, markerWidth, markerHeight); scroller = new Scroller(context); setFocusable(true); setClickable(true); updateDimensions(); } private void setUpChartValueSeries(Context context) { series = new ChartValueSeries[NUM_SERIES]; // Create the value series. series[ELEVATION_SERIES] = new ChartValueSeries(context, R.color.elevation_fill, R.color.elevation_border, new ZoomSettings(MAX_INTERVALS, new int[] {5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000}), R.string.stat_elevation); series[SPEED_SERIES] = new ChartValueSeries(context, R.color.speed_fill, R.color.speed_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {1, 5, 10, 20, 50}), R.string.stat_speed); series[POWER_SERIES] = new ChartValueSeries(context, R.color.power_fill, R.color.power_border, new ZoomSettings(MAX_INTERVALS, 0, 1000, new int[] {5, 50, 100, 200}), R.string.sensor_state_power); series[CADENCE_SERIES] = new ChartValueSeries(context, R.color.cadence_fill, R.color.cadence_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {5, 10, 25, 50}), R.string.sensor_state_cadence); series[HEART_RATE_SERIES] = new ChartValueSeries(context, R.color.heartrate_fill, R.color.heartrate_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {25, 50}), R.string.sensor_state_heart_rate); } public void clearWaypoints() { waypoints.clear(); } public void addWaypoint(Waypoint waypoint) { waypoints.add(waypoint); } /** * Determines whether the pointer icon is shown on the last data point. */ public void setShowPointer(boolean showPointer) { this.showPointer = showPointer; } /** * Sets whether metric units are used or not. */ public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; } public void setReportSpeed(boolean reportSpeed, Context c) { series[SPEED_SERIES].setTitle(c.getString(reportSpeed ? R.string.stat_speed : R.string.stat_pace)); } private void addDataPointInternal(double[] theData) { xMonitor.update(theData[0]); int min = Math.min(series.length, theData.length - 1); for (int i = 1; i <= min; i++) { if (!Double.isNaN(theData[i])) { series[i - 1].update(theData[i]); } } // Fill in the extra's if needed. for (int i = theData.length; i < series.length; i++) { if (series[i].hasData()) { series[i].update(0); } } } /** * Adds multiple data points to the chart. * * @param theData an array list of data points to be added */ public void addDataPoints(ArrayList<double[]> theData) { synchronized (data) { data.addAll(theData); for (int i = 0; i < theData.size(); i++) { double d[] = theData.get(i); addDataPointInternal(d); } updateDimensions(); setUpPath(); } } /** * Clears all data. */ public void reset() { synchronized (data) { data.clear(); xMonitor.reset(); zoomLevel = 1; updateDimensions(); } } public void resetScroll() { scrollTo(0, 0); } /** * @return true if the chart can be zoomed into. */ public boolean canZoomIn() { return zoomLevel < maxZoomLevel; } /** * @return true if the chart can be zoomed out */ public boolean canZoomOut() { return zoomLevel > MIN_ZOOM_LEVEL; } /** * Zooms in one level (factor 2). */ public void zoomIn() { if (canZoomIn()) { zoomLevel++; setUpPath(); invalidate(); } } /** * Zooms out one level (factor 2). */ public void zoomOut() { if (canZoomOut()) { zoomLevel--; scroller.abortAnimation(); int scrollX = getScrollX(); if (scrollX > effectiveWidth * (zoomLevel - 1)) { scrollX = effectiveWidth * (zoomLevel - 1); scrollTo(scrollX, 0); } setUpPath(); invalidate(); } } /** * Initiates flinging. * * @param velocityX start velocity (pixels per second) */ public void fling(int velocityX) { scroller.fling(getScrollX(), 0, velocityX, 0, 0, effectiveWidth * (zoomLevel - 1), 0, 0); invalidate(); } /** * Scrolls the view horizontally by the given amount. * * @param deltaX number of pixels to scroll */ public void scrollBy(int deltaX) { int scrollX = getScrollX() + deltaX; if (scrollX < 0) { scrollX = 0; } int available = effectiveWidth * (zoomLevel - 1); if (scrollX > available) { scrollX = available; } scrollTo(scrollX, 0); } /** * @return the current display mode (by distance, by time) */ public Mode getMode() { return mode; } /** * Sets the display mode (by distance, by time). * It is expected that after the mode change, data will be reloaded. */ public void setMode(Mode mode) { this.mode = mode; } private int getWaypointX(Waypoint waypoint) { return (mode == Mode.BY_DISTANCE) ? getX(metricUnits ? waypoint.getLength() / 1000.0 : waypoint.getLength() * UnitConversions.KM_TO_MI / 1000.0) : getX(waypoint.getDuration()); } /** * Called by the parent to indicate that the mScrollX/Y values need to be * updated. Triggers a redraw during flinging. */ @Override public void computeScroll() { if (scroller.computeScrollOffset()) { int oldX = getScrollX(); int x = scroller.getCurrX(); scrollTo(x, 0); if (oldX != x) { onScrollChanged(x, 0, oldX, 0); postInvalidate(); } } } @Override public boolean onTouchEvent(MotionEvent event) { if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); final int action = event.getAction(); final float x = event.getX(); switch (action) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished will be * false if being flinged. */ if (!scroller.isFinished()) { scroller.abortAnimation(); } // Remember where the motion event started lastMotionX = x; break; case MotionEvent.ACTION_MOVE: // Scroll to follow the motion event final int deltaX = (int) (lastMotionX - x); lastMotionX = x; if (deltaX < 0) { if (getScrollX() > 0) { scrollBy(deltaX); } } else if (deltaX > 0) { final int availableToScroll = effectiveWidth * (zoomLevel - 1) - getScrollX(); if (availableToScroll > 0) { scrollBy(Math.min(availableToScroll, deltaX)); } } break; case MotionEvent.ACTION_UP: // Check if top area with waypoint markers was touched and find the // touched marker if any: if (event.getY() < 100) { int dmin = Integer.MAX_VALUE; Waypoint nearestWaypoint = null; for (int i = 0; i < waypoints.size(); i++) { final Waypoint waypoint = waypoints.get(i); final int d = Math.abs(getWaypointX(waypoint) - (int) event.getX() - getScrollX()); if (d < dmin) { dmin = d; nearestWaypoint = waypoint; } } if (nearestWaypoint != null && dmin < 100) { Intent intent = new Intent(getContext(), WaypointDetails.class); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, nearestWaypoint.getId()); getContext().startActivity(intent); return true; } } VelocityTracker myVelocityTracker = velocityTracker; myVelocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int) myVelocityTracker.getXVelocity(); if (Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) { fling(-initialVelocity); } if (velocityTracker != null) { velocityTracker.recycle(); velocityTracker = null; } break; } return true; } @Override protected void onDraw(Canvas c) { synchronized (data) { updateEffectiveDimensionsIfChanged(c); // Keep original state. c.save(); c.drawColor(Color.WHITE); if (data.isEmpty()) { // No data, draw only axes drawXAxis(c); drawYAxis(c); c.restore(); return; } // Clip to graph drawing space c.save(); clipToGraphSpace(c); // Draw the grid and the data on it. drawGrid(c); drawDataSeries(c); drawWaypoints(c); // Go back to full canvas drawing. c.restore(); // Draw the axes and their labels. drawAxesAndLabels(c); // Go back to original state. c.restore(); // Draw the pointer if (showPointer) { drawPointer(c); } } } /** Clips the given canvas to the area where the graph lines should be drawn. */ private void clipToGraphSpace(Canvas c) { c.clipRect(leftBorder + 1 + getScrollX(), topBorder + 1, w - RIGHT_BORDER + getScrollX() - 1, h - bottomBorder - 1); } /** Draws the axes and their labels into th e given canvas. */ private void drawAxesAndLabels(Canvas c) { drawXLabels(c); drawXAxis(c); drawSeriesTitles(c); c.translate(getScrollX(), 0); drawYAxis(c); float density = getContext().getResources().getDisplayMetrics().density; final int spacer = (int) (5 * density); int x = leftBorder - spacer; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { x -= drawYLabels(cvs, c, x) + spacer; } } } /** Draws the current pointer into the given canvas. */ private void drawPointer(Canvas c) { c.translate(getX(maxX) - pointer.getIntrinsicWidth() / 2, getY(series[0], data.get(data.size() - 1)[1]) - pointer.getIntrinsicHeight() / 2 - 12); pointer.draw(c); } /** Draws the waypoints into the given canvas. */ private void drawWaypoints(Canvas c) { for (int i = 1; i < waypoints.size(); i++) { final Waypoint waypoint = waypoints.get(i); if (waypoint.getLocation() == null) { continue; } c.save(); final float x = getWaypointX(waypoint); c.drawLine(x, h - bottomBorder, x, topBorder, gridPaint); c.translate(x - (float) markerWidth / 2.0f, (float) markerHeight); if (waypoints.get(i).getType() == Waypoint.TYPE_STATISTICS) { statsMarker.draw(c); } else { waypointMarker.draw(c); } c.restore(); } } /** Draws the data series into the given canvas. */ private void drawDataSeries(Canvas c) { for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { cvs.drawPath(c); } } } /** Draws the colored titles for the data series. */ private void drawSeriesTitles(Canvas c) { int sections = 1; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { sections++; } } int j = 0; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { int x = (int) (w * (double) ++j / sections) + getScrollX(); c.drawText(cvs.getTitle(), x, topBorder, cvs.getLabelPaint()); } } } /** * Sets up the path that is used to draw the chart in onDraw(). The path * needs to be updated any time after the data or histogram dimensions change. */ private void setUpPath() { synchronized (data) { for (ChartValueSeries cvs : series) { cvs.getPath().reset(); } if (!data.isEmpty()) { drawPaths(); closePaths(); } } } /** Actually draws the data points as a path. */ private void drawPaths() { // All of the data points to the respective series. // TODO: Come up with a better sampling than Math.max(1, (maxZoomLevel - zoomLevel + 1) / 2); int sampling = 1; for (int i = 0; i < data.size(); i += sampling) { double[] d = data.get(i); int min = Math.min(series.length, d.length - 1); for (int j = 0; j < min; ++j) { ChartValueSeries cvs = series[j]; Path path = cvs.getPath(); int x = getX(d[0]); int y = getY(cvs, d[j + 1]); if (i == 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } } } } /** Closes the drawn path so it looks like a solid graph. */ private void closePaths() { // Close the path. int yCorner = topBorder + effectiveHeight; int xCorner = getX(data.get(0)[0]); int min = series.length; for (int j = 0; j < min; j++) { ChartValueSeries cvs = series[j]; Path path = cvs.getPath(); int first = getFirstPointPopulatedIndex(j + 1); if (first != -1) { // Bottom right corner path.lineTo(getX(data.get(data.size() - 1)[0]), yCorner); // Bottom left corner path.lineTo(xCorner, yCorner); // Top right corner path.lineTo(xCorner, getY(cvs, data.get(first)[j + 1])); } } } /** * Finds the index of the first point which has a series populated. * * @param seriesIndex The index of the value series to search for * @return The index in the first data for the point in the series that has series * index value populated or -1 if none is found */ private int getFirstPointPopulatedIndex(int seriesIndex) { for (int i = 0; i < data.size(); i++) { if (data.get(i).length > seriesIndex) { return i; } } return -1; } /** * Updates the chart dimensions. */ private void updateDimensions() { maxX = xMonitor.getMax(); if (data.size() <= 1) { maxX = 1; } for (ChartValueSeries cvs : series) { cvs.updateDimension(); } // TODO: This is totally broken. Make sure that we calculate based on measureText for each // grid line, as the labels may vary across intervals. int maxLength = 0; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { maxLength += cvs.getMaxLabelLength(); } } float density = getContext().getResources().getDisplayMetrics().density; maxLength = Math.max(maxLength, 1); leftBorder = (int) (density * (4 + 8 * maxLength)); bottomBorder = (int) (density * BOTTOM_BORDER); topBorder = (int) (density * TOP_BORDER); updateEffectiveDimensions(); } /** Updates the effective dimensions where the graph will be drawn. */ private void updateEffectiveDimensions() { effectiveWidth = Math.max(0, w - leftBorder - RIGHT_BORDER); effectiveHeight = Math.max(0, h - topBorder - bottomBorder); } /** * Updates the effective dimensions where the graph will be drawn, only if the * dimensions of the given canvas have changed since the last call. */ private void updateEffectiveDimensionsIfChanged(Canvas c) { if (w != c.getWidth() || h != c.getHeight()) { // Dimensions have changed (for example due to orientation change). w = c.getWidth(); h = c.getHeight(); updateEffectiveDimensions(); setUpPath(); } } private int getX(double distance) { return leftBorder + (int) ((distance * effectiveWidth / maxX) * zoomLevel); } private int getY(ChartValueSeries cvs, double y) { int effectiveSpread = cvs.getInterval() * MAX_INTERVALS; return topBorder + effectiveHeight - (int) ((y - cvs.getMin()) * effectiveHeight / effectiveSpread); } /** Draws the labels on the X axis into the given canvas. */ private void drawXLabels(Canvas c) { double interval = (int) (maxX / zoomLevel / 4); boolean shortFormat = false; if (interval < 1) { interval = .5; shortFormat = true; } else if (interval < 5) { interval = 2; } else if (interval < 10) { interval = 5; } else { interval = (interval / 10) * 10; } drawXLabel(c, 0, shortFormat); int numLabels = 1; for (int i = 1; i * interval < maxX; i++) { drawXLabel(c, i * interval, shortFormat); numLabels++; } if (numLabels < 2) { drawXLabel(c, (int) maxX, shortFormat); } } /** Draws the labels on the Y axis into the given canvas. */ private float drawYLabels(ChartValueSeries cvs, Canvas c, int x) { int interval = cvs.getInterval(); float maxTextWidth = 0; for (int i = 0; i < MAX_INTERVALS; ++i) { maxTextWidth = Math.max(maxTextWidth, drawYLabel(cvs, c, x, i * interval + cvs.getMin())); } return maxTextWidth; } /** Draws a single label on the X axis. */ private void drawXLabel(Canvas c, double x, boolean shortFormat) { if (x < 0) { return; } String s = (mode == Mode.BY_DISTANCE) ? (shortFormat ? X_SHORT_FORMAT.format(x) : X_FORMAT.format(x)) : StringUtils.formatTime((long) x); c.drawText(s, getX(x), effectiveHeight + UNIT_BORDER + topBorder, labelPaint); } /** Draws a single label on the Y axis. */ private float drawYLabel(ChartValueSeries cvs, Canvas c, int x, int y) { int desiredY = (int) ((y - cvs.getMin()) * effectiveHeight / (cvs.getInterval() * MAX_INTERVALS)); desiredY = topBorder + effectiveHeight + FONT_HEIGHT / 2 - desiredY - 1; Paint p = new Paint(cvs.getLabelPaint()); p.setTextAlign(Align.RIGHT); String text = cvs.getFormat().format(y); c.drawText(text, x, desiredY, p); return p.measureText(text); } /** Draws the actual X axis line and its label. */ private void drawXAxis(Canvas canvas) { float rightEdge = getX(maxX); final int y = effectiveHeight + topBorder; canvas.drawLine(leftBorder, y, rightEdge, y, borderPaint); Context c = getContext(); String s = mode == Mode.BY_DISTANCE ? (metricUnits ? c.getString(R.string.unit_kilometer) : c.getString(R.string.unit_mile)) : c.getString(R.string.unit_minute); canvas.drawText(s, rightEdge, effectiveHeight + .2f * UNIT_BORDER + topBorder, labelPaint); } /** Draws the actual Y axis line and its label. */ private void drawYAxis(Canvas canvas) { canvas.drawRect(0, 0, leftBorder - 1, effectiveHeight + topBorder + UNIT_BORDER + 1, clearPaint); canvas.drawLine(leftBorder, UNIT_BORDER + topBorder, leftBorder, effectiveHeight + topBorder, borderPaint); for (int i = 1; i < MAX_INTERVALS; ++i) { int y = i * effectiveHeight / MAX_INTERVALS + topBorder; canvas.drawLine(leftBorder - 5, y, leftBorder, y, gridPaint); } Context c = getContext(); // TODO: This should really show units for all series. String s = metricUnits ? c.getString(R.string.unit_meter) : c.getString(R.string.unit_feet); canvas.drawText(s, leftBorder - UNIT_BORDER * .2f, UNIT_BORDER * .8f + topBorder, labelPaint); } /** Draws the grid for the graph. */ private void drawGrid(Canvas c) { float rightEdge = getX(maxX); for (int i = 1; i < MAX_INTERVALS; ++i) { int y = i * effectiveHeight / MAX_INTERVALS + topBorder; c.drawLine(leftBorder, y, rightEdge, y, gridBarPaint); } } /** * Returns whether a given time series is enabled for drawing. * * @param index the time series, one of {@link #ELEVATION_SERIES}, * {@link #SPEED_SERIES}, {@link #POWER_SERIES}, etc. * @return true if drawn, false otherwise */ public boolean isChartValueSeriesEnabled(int index) { return series[index].isEnabled(); } /** * Sets whether a given time series will be enabled for drawing. * * @param index the time series, one of {@link #ELEVATION_SERIES}, * {@link #SPEED_SERIES}, {@link #POWER_SERIES}, etc. */ public void setChartValueSeriesEnabled(int index, boolean enabled) { series[index].setEnabled(enabled); } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManager.AuthCallback; import com.google.android.apps.mytracks.io.AuthManagerFactory; import com.google.android.apps.mytracks.io.mymaps.MapsFacade; import com.google.android.apps.mytracks.io.mymaps.MyMapsConstants; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; /** * Activity which displays the list of current My Maps tracks for the user. * Returns RESULT_OK if the user picked a map, and returns "mapid" as an extra. * * @author Rodrigo Damazio */ public class MyMapsList extends Activity implements MapsFacade.MapsListCallback { private static final int GET_LOGIN = 1; public static final String EXTRA_ACCOUNT_NAME = "accountName"; public static final String EXTRA_ACCOUNT_TYPE = "accountType"; private MapsFacade mapsClient; private AuthManager auth; private MyMapsListAdapter listAdapter; private final OnItemClickListener clickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent result = new Intent(); result.putExtra("mapid", (String) listAdapter.getItem(position)); setResult(RESULT_OK, result); finish(); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); auth = AuthManagerFactory.getAuthManager(this, GET_LOGIN, null, true, MyMapsConstants.SERVICE_NAME); setContentView(R.layout.list); listAdapter = new MyMapsListAdapter(this); ListView list = (ListView) findViewById(R.id.maplist); list.setOnItemClickListener(clickListener); list.setAdapter(listAdapter); startLogin(); } private void startLogin() { // Starts in the UI thread. // TODO fix this for non-froyo devices. if (AuthManagerFactory.useModernAuthManager()) { Intent intent = getIntent(); String accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME); String accountType = intent.getStringExtra(EXTRA_ACCOUNT_TYPE); if (accountName == null || accountType == null) { Log.e(TAG, "Didn't receive account name or type"); setResult(RESULT_CANCELED); finish(); return; } doLogin(auth.getAccountObject(accountName, accountType)); } else { doLogin(null); } } private void doLogin(final Object account) { // Starts in the UI thread. auth.doLogin(new AuthCallback() { @Override public void onAuthResult(boolean success) { if (!success) { setResult(RESULT_CANCELED); finish(); return; } // Runs in UI thread. mapsClient = new MapsFacade(MyMapsList.this, auth); startLookup(); } }, account); } private void startLookup() { // Starts in the UI thread. new Thread() { @Override public void run() { // Communication with Maps happens in its own thread. // This will call onReceivedMapListing below. final boolean success = mapsClient.getMapsList(MyMapsList.this); runOnUiThread(new Runnable() { @Override public void run() { // Updating the UI when done happens in the UI thread. onLookupDone(success); } }); } }.start(); } @Override public void onReceivedMapListing(final String mapId, final String title, final String description, final boolean isPublic) { // Starts in the communication thread. runOnUiThread(new Runnable() { @Override public void run() { // Updating the list with new contents happens in the UI thread. listAdapter.addMapListing(mapId, title, description, isPublic); } }); } private void onLookupDone(boolean success) { // Starts in the UI thread. findViewById(R.id.loading).setVisibility(View.GONE); if (!success) { findViewById(R.id.failed).setVisibility(View.VISIBLE); } TextView emptyView = (TextView) findViewById(R.id.mapslist_empty); ListView list = (ListView) findViewById(R.id.maplist); list.setEmptyView(emptyView); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GET_LOGIN) { auth.authResult(resultCode, data); } super.onActivityResult(requestCode, resultCode, data); } }
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; import static com.google.android.apps.mytracks.Constants.TAG; import android.app.Activity; import android.app.Dialog; import android.util.Log; import android.view.WindowManager.BadTokenException; /** * A class to handle all dialog related events for My Tracks. * * @author Sandor Dornbush */ public class DialogManager { /** * The equivalent of {@link Dialog#show()}, but for a specific dialog * instance. */ public static void showDialogSafely(Activity activity, final Dialog dialog) { if (activity.isFinishing()) { Log.w(TAG, "Activity finishing - not showing dialog"); return; } activity.runOnUiThread(new Runnable() { public void run() { try { dialog.show(); } catch (BadTokenException e) { Log.w(TAG, "Could not display dialog", e); } catch (IllegalStateException e) { Log.w(TAG, "Could not display dialog", e); } } }); } /** * The equivalent of {@link Dialog#dismiss()}, but for a specific dialog * instance. */ public static void dismissDialogSafely(Activity activity, final Dialog dialog) { if (activity.isFinishing()) { Log.w(TAG, "Activity finishing - not dismissing dialog"); return; } activity.runOnUiThread(new Runnable() { public void run() { try { dialog.dismiss(); } catch (IllegalArgumentException e) { // This will be thrown if this dialog was not shown before. } } }); } private DialogManager() {} }
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; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.apps.mytracks.io.sendtogoogle.SendActivity; import com.google.android.apps.mytracks.services.ServiceUtils; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.ListActivity; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * A list activity displaying all the recorded tracks. There's a context * menu (via long press) displaying various options such as showing, editing, * deleting, sending to MyMaps, or writing to SD card. * * @author Leif Hendrik Wilden */ public class TrackList extends ListActivity implements SharedPreferences.OnSharedPreferenceChangeListener, View.OnClickListener { private int contextPosition = -1; private long trackId = -1; private ListView listView = null; private boolean metricUnits = true; private Cursor tracksCursor = null; /** * The id of the currently recording track. */ private long recordingTrackId = -1; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.track_list_context_menu_title); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; trackId = TrackList.this.listView.getAdapter().getItemId( contextPosition); menu.add(0, Constants.MENU_SHOW, 0, R.string.track_list_show_on_map); menu.add(0, Constants.MENU_EDIT, 0, R.string.track_list_edit_track); if (!isRecording() || trackId != recordingTrackId) { String saveFileFormat = getString(R.string.track_list_save_file); String shareFileFormat = getString(R.string.track_list_share_file); String fileTypes[] = getResources().getStringArray(R.array.file_types); menu.add(0, Constants.MENU_SEND_TO_GOOGLE, 0, R.string.track_list_send_google); SubMenu share = menu.addSubMenu(0, Constants.MENU_SHARE, 0, R.string.track_list_share_track); share.add(0, Constants.MENU_SHARE_LINK, 0, R.string.track_list_share_url); share.add( 0, Constants.MENU_SHARE_GPX_FILE, 0, String.format(shareFileFormat, fileTypes[0])); share.add( 0, Constants.MENU_SHARE_KML_FILE, 0, String.format(shareFileFormat, fileTypes[1])); share.add( 0, Constants.MENU_SHARE_CSV_FILE, 0, String.format(shareFileFormat, fileTypes[2])); share.add( 0, Constants.MENU_SHARE_TCX_FILE, 0, String.format(shareFileFormat, fileTypes[3])); SubMenu save = menu.addSubMenu(0, Constants.MENU_WRITE_TO_SD_CARD, 0, R.string.track_list_save_sd); save.add( 0, Constants.MENU_SAVE_GPX_FILE, 0, String.format(saveFileFormat, fileTypes[0])); save.add( 0, Constants.MENU_SAVE_KML_FILE, 0, String.format(saveFileFormat, fileTypes[1])); save.add( 0, Constants.MENU_SAVE_CSV_FILE, 0, String.format(saveFileFormat, fileTypes[2])); save.add( 0, Constants.MENU_SAVE_TCX_FILE, 0, String.format(saveFileFormat, fileTypes[3])); menu.add(0, Constants.MENU_DELETE, 0, R.string.track_list_delete_track); } } }; private final Runnable serviceBindingChanged = new Runnable() { @Override public void run() { updateButtonsEnabled(); } }; private TrackRecordingServiceConnection serviceConnection; private SharedPreferences preferences; @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (key == null) { return; } if (key.equals(getString(R.string.metric_units_key))) { metricUnits = sharedPreferences.getBoolean( getString(R.string.metric_units_key), true); if (tracksCursor != null && !tracksCursor.isClosed()) { tracksCursor.requery(); } } if (key.equals(getString(R.string.recording_track_key))) { recordingTrackId = sharedPreferences.getLong( getString(R.string.recording_track_key), -1); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent result = new Intent(); result.putExtra("trackid", id); setResult(Constants.SHOW_TRACK, result); finish(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case Constants.MENU_SHOW: { onListItemClick(null, null, 0, trackId); return true; } case Constants.MENU_EDIT: { Intent intent = new Intent(this, TrackDetails.class); intent.putExtra("trackid", trackId); startActivity(intent); return true; } case Constants.MENU_SHARE: case Constants.MENU_WRITE_TO_SD_CARD: return false; case Constants.MENU_SEND_TO_GOOGLE: SendActivity.sendToGoogle(this, trackId, false); return true; case Constants.MENU_SHARE_LINK: SendActivity.sendToGoogle(this, trackId, true); return true; case Constants.MENU_SAVE_GPX_FILE: case Constants.MENU_SAVE_KML_FILE: case Constants.MENU_SAVE_CSV_FILE: case Constants.MENU_SAVE_TCX_FILE: case Constants.MENU_SHARE_GPX_FILE: case Constants.MENU_SHARE_KML_FILE: case Constants.MENU_SHARE_CSV_FILE: case Constants.MENU_SHARE_TCX_FILE: SaveActivity.handleExportTrackAction(this, trackId, Constants.getActionFromMenuId(item.getItemId())); return true; case Constants.MENU_DELETE: { Intent intent = new Intent(Intent.ACTION_DELETE); Uri uri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, trackId); intent.setDataAndType(uri, TracksColumns.CONTENT_ITEMTYPE); startActivity(intent); return true; } default: Log.w(TAG, "Unknown menu item: " + item.getItemId() + "(" + item.getTitle() + ")"); return super.onMenuItemSelected(featureId, item); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tracklist_btn_delete_all: { Handler h = new DeleteAllTracks(this, null); h.handleMessage(null); break; } case R.id.tracklist_btn_export_all: { new ExportAllTracks(this); break; } case R.id.tracklist_btn_import_all: { new ImportAllTracks(this); break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_list); listView = getListView(); listView.setOnCreateContextMenuListener(contextMenuListener); preferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); serviceConnection = new TrackRecordingServiceConnection(this, serviceBindingChanged); View deleteAll = findViewById(R.id.tracklist_btn_delete_all); deleteAll.setOnClickListener(this); View exportAll = findViewById(R.id.tracklist_btn_export_all); exportAll.setOnClickListener(this); updateButtonsEnabled(); findViewById(R.id.tracklist_btn_import_all).setOnClickListener(this); preferences.registerOnSharedPreferenceChangeListener(this); metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true); recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); tracksCursor = getContentResolver().query( TracksColumns.CONTENT_URI, null, null, null, "_id DESC"); startManagingCursor(tracksCursor); setListAdapter(); } @Override protected void onStart() { super.onStart(); serviceConnection.bindIfRunning(); } @Override protected void onDestroy() { serviceConnection.unbind(); super.onDestroy(); } private void updateButtonsEnabled() { View deleteAll = findViewById(R.id.tracklist_btn_delete_all); View exportAll = findViewById(R.id.tracklist_btn_export_all); boolean notRecording = !isRecording(); deleteAll.setEnabled(notRecording); exportAll.setEnabled(notRecording); } private void setListAdapter() { // Get a cursor with all tracks SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.mytracks_list_item, tracksCursor, new String[] { TracksColumns.NAME, TracksColumns.STARTTIME, TracksColumns.TOTALDISTANCE, TracksColumns.DESCRIPTION, TracksColumns.CATEGORY }, new int[] { R.id.trackdetails_item_name, R.id.trackdetails_item_time, R.id.trackdetails_item_stats, R.id.trackdetails_item_description, R.id.trackdetails_item_category }); final int startTimeIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); final int totalTimeIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); final int totalDistanceIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { TextView textView = (TextView) view; if (columnIndex == startTimeIdx) { long time = cursor.getLong(startTimeIdx); textView.setText(String.format("%tc", time)); } else if (columnIndex == totalDistanceIdx) { double length = cursor.getDouble(totalDistanceIdx); String lengthUnit = null; if (metricUnits) { if (length > 1000) { length /= 1000; lengthUnit = getString(R.string.unit_kilometer); } else { lengthUnit = getString(R.string.unit_meter); } } else { if (length > UnitConversions.MI_TO_M) { length /= UnitConversions.MI_TO_M; lengthUnit = getString(R.string.unit_mile); } else { length *= UnitConversions.M_TO_FT; lengthUnit = getString(R.string.unit_feet); } } textView.setText(String.format("%s %.2f %s", StringUtils.formatTime(cursor.getLong(totalTimeIdx)), length, lengthUnit)); } else { textView.setText(cursor.getString(columnIndex)); if (textView.getText().length() < 1) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); } } return true; } }); setListAdapter(adapter); } private boolean isRecording() { return ServiceUtils.isRecording(TrackList.this, serviceConnection.getServiceIfBound(), preferences); } }
Java
package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.database.DataSetObserver; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.TextView; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; public class MyMapsListAdapter implements ListAdapter { private Vector<String[]> mapsList; private Vector<Boolean> publicList; private Set<DataSetObserver> observerSet; private final Activity activity; public MyMapsListAdapter(Activity activity) { this.activity = activity; mapsList = new Vector<String[]>(); publicList = new Vector<Boolean>(); observerSet = new HashSet<DataSetObserver>(); } public void addMapListing(String mapId, String title, String description, boolean isPublic) { synchronized (mapsList) { // Search through the maps list to see if it has the mapid and // remove it if so, so that we can replace it with updated info for (int i = 0; i < mapsList.size(); ++i) { if (mapId.equals(mapsList.get(i)[0])) { mapsList.remove(i); publicList.remove(i); --i; } } mapsList.add(new String[] { mapId, title, description }); publicList.add(isPublic); } Iterator<DataSetObserver> iter = observerSet.iterator(); while (iter.hasNext()) { iter.next().onChanged(); } } public String[] getMapListingArray(int position) { return mapsList.get(position); } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } @Override public int getCount() { return mapsList.size(); } @Override public Object getItem(int position) { return mapsList.get(position)[0]; } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = activity.getLayoutInflater().inflate(R.layout.listitem, parent, false); } String[] map = mapsList.get(position); ((TextView) convertView.findViewById(R.id.maplistitem)).setText(map[1]); ((TextView) convertView.findViewById(R.id.maplistdesc)).setText(map[2]); TextView publicUnlisted = (TextView) convertView.findViewById(R.id.maplistpublic); if (publicList.get(position)) { publicUnlisted.setTextColor(Color.RED); publicUnlisted.setText(R.string.my_maps_list_public_label); } else { publicUnlisted.setTextColor(Color.GREEN); publicUnlisted.setText(R.string.my_maps_list_unlisted_label); } return convertView; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return false; } @Override public boolean isEmpty() { return mapsList.isEmpty(); } @Override public void registerDataSetObserver(DataSetObserver observer) { observerSet.add(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { observerSet.remove(observer); } }
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; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; /** * Creates previous and next arrows for a given activity. * * @author Leif Hendrik Wilden */ public class NavControls { private static final int KEEP_VISIBLE_MILLIS = 4000; private static final boolean FADE_CONTROLS = true; private static final Animation SHOW_NEXT_ANIMATION = new AlphaAnimation(0F, 1F); private static final Animation HIDE_NEXT_ANIMATION = new AlphaAnimation(1F, 0F); private static final Animation SHOW_PREV_ANIMATION = new AlphaAnimation(0F, 1F); private static final Animation HIDE_PREV_ANIMATION = new AlphaAnimation(1F, 0F); /** * A touchable image view. * When touched it changes the navigation control icons accordingly. */ private class TouchLayout extends RelativeLayout implements Runnable { private final boolean isLeft; private final ImageView icon; public TouchLayout(Context context, boolean isLeft) { super(context); this.isLeft = isLeft; this.icon = new ImageView(context); icon.setVisibility(View.GONE); addView(icon); } public void setIcon(Drawable drawable) { icon.setImageDrawable(drawable); icon.setVisibility(View.VISIBLE); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: setPressed(true); shiftIcons(isLeft); // Call the user back handler.post(this); break; case MotionEvent.ACTION_UP: setPressed(false); break; } return super.onTouchEvent(event); } @Override public void run() { touchRunnable.run(); setPressed(false); } } private final Handler handler = new Handler(); private final Runnable dismissControls = new Runnable() { public void run() { hide(); } }; private final TouchLayout prevImage; private final TouchLayout nextImage; private final TypedArray leftIcons; private final TypedArray rightIcons; private final Runnable touchRunnable; private boolean isVisible = false; private int currentIcons; public NavControls(Context context, ViewGroup container, TypedArray leftIcons, TypedArray rightIcons, Runnable touchRunnable) { this.leftIcons = leftIcons; this.rightIcons = rightIcons; this.touchRunnable = touchRunnable; if (leftIcons.length() != rightIcons.length() || leftIcons.length() < 1) { throw new IllegalArgumentException("Invalid icons specified"); } if (touchRunnable == null) { throw new NullPointerException("Runnable cannot be null"); } LayoutParams prevParams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LayoutParams nextParams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); prevParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); prevParams.addRule(RelativeLayout.CENTER_VERTICAL); nextParams.addRule(RelativeLayout.CENTER_VERTICAL); nextImage = new TouchLayout(context, false); prevImage = new TouchLayout(context, true); nextImage.setLayoutParams(nextParams); prevImage.setLayoutParams(prevParams); nextImage.setVisibility(View.INVISIBLE); prevImage.setVisibility(View.INVISIBLE); container.addView(prevImage); container.addView(nextImage); prevImage.setIcon(leftIcons.getDrawable(0)); nextImage.setIcon(rightIcons.getDrawable(0)); this.currentIcons = 0; } private void keepVisible() { if (isVisible && FADE_CONTROLS) { handler.removeCallbacks(dismissControls); handler.postDelayed(dismissControls, KEEP_VISIBLE_MILLIS); } } public void show() { if (!isVisible) { SHOW_PREV_ANIMATION.setDuration(500); SHOW_PREV_ANIMATION.startNow(); prevImage.setPressed(false); prevImage.setAnimation(SHOW_PREV_ANIMATION); prevImage.setVisibility(View.VISIBLE); SHOW_NEXT_ANIMATION.setDuration(500); SHOW_NEXT_ANIMATION.startNow(); nextImage.setPressed(false); nextImage.setAnimation(SHOW_NEXT_ANIMATION); nextImage.setVisibility(View.VISIBLE); isVisible = true; keepVisible(); } else { keepVisible(); } } public void hideNow() { handler.removeCallbacks(dismissControls); isVisible = false; prevImage.clearAnimation(); prevImage.setVisibility(View.INVISIBLE); nextImage.clearAnimation(); nextImage.setVisibility(View.INVISIBLE); } public void hide() { isVisible = false; prevImage.setAnimation(HIDE_PREV_ANIMATION); HIDE_PREV_ANIMATION.setDuration(500); HIDE_PREV_ANIMATION.startNow(); prevImage.setVisibility(View.INVISIBLE); nextImage.setAnimation(HIDE_NEXT_ANIMATION); HIDE_NEXT_ANIMATION.setDuration(500); HIDE_NEXT_ANIMATION.startNow(); nextImage.setVisibility(View.INVISIBLE); } public int getCurrentIcons() { return currentIcons; } private void shiftIcons(boolean isLeft) { // Increment or decrement by one, with wrap around currentIcons = (currentIcons + leftIcons.length() + (isLeft ? -1 : 1)) % leftIcons.length(); prevImage.setIcon(leftIcons.getDrawable(currentIcons)); nextImage.setIcon(rightIcons.getDrawable(currentIcons)); } }
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.util; import com.google.android.apps.mytracks.Constants; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; /** * Utility class for acessing basic Android functionality. * * @author Rodrigo Damazio */ public class SystemUtils { private static final int RELEASE_SIGNATURE_HASHCODE = -1855564782; /** * Returns whether or not this is a release build. */ public static boolean isRelease(Context context) { try { Signature [] sigs = context.getPackageManager().getPackageInfo( context.getPackageName(), PackageManager.GET_SIGNATURES).signatures; for (Signature sig : sigs) { if (sig.hashCode() == RELEASE_SIGNATURE_HASHCODE) { return true; } } } catch (NameNotFoundException e) { Log.e(Constants.TAG, "Unable to get signatures", e); } return false; } /** * Get the My Tracks version from the manifest. * * @return the version, or an empty string in case of failure. */ public static String getMyTracksVersion(Context context) { try { PackageInfo pi = context.getPackageManager().getPackageInfo( "com.google.android.maps.mytracks", PackageManager.GET_META_DATA); return pi.versionName; } catch (NameNotFoundException e) { Log.w(Constants.TAG, "Failed to get version info.", e); return ""; } } /** * Tries to acquire a partial wake lock if not already acquired. Logs errors * and gives up trying in case the wake lock cannot be acquired. */ public static WakeLock acquireWakeLock(Activity activity, WakeLock wakeLock) { Log.i(Constants.TAG, "LocationUtils: Acquiring wake lock."); try { PowerManager pm = (PowerManager) activity .getSystemService(Context.POWER_SERVICE); if (pm == null) { Log.e(Constants.TAG, "LocationUtils: Power manager not found!"); return wakeLock; } if (wakeLock == null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); if (wakeLock == null) { Log.e(Constants.TAG, "LocationUtils: Could not create wake lock (null)."); } return wakeLock; } if (!wakeLock.isHeld()) { wakeLock.acquire(); if (!wakeLock.isHeld()) { Log.e(Constants.TAG, "LocationUtils: Could not acquire wake lock."); } } } catch (RuntimeException e) { Log.e(Constants.TAG, "LocationUtils: Caught unexpected exception: " + e.getMessage(), e); } return wakeLock; } private SystemUtils() {} }
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.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * Utilities for the EULA preference value. */ public class EulaUtil { private static final String EULA_PREFERENCE_FILE = "eula"; private static final String EULA_PREFERENCE_KEY = "eula.accepted"; private EulaUtil() {} public static boolean getEulaValue(Context context) { SharedPreferences preferences = context.getSharedPreferences( EULA_PREFERENCE_FILE, Context.MODE_PRIVATE); return preferences.getBoolean(EULA_PREFERENCE_KEY, false); } public static void setEulaValue(Context context) { SharedPreferences preferences = context.getSharedPreferences( EULA_PREFERENCE_FILE, Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putBoolean(EULA_PREFERENCE_KEY, true); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } }
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.util; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; /** * API level 5 specific implementation of the {@link ApiLevelAdapter}. * * @author Bartlomiej Niechwiej */ public class ApiLevel5Adapter extends ApiLevel3Adapter { @Override public void startForeground(Service service, NotificationManager notificationManager, int id, Notification notification) { service.startForeground(id, notification); } @Override public void stopForeground(Service service, NotificationManager notificationManager, int id) { service.stopForeground(id != -1); } }
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.util; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.GeoPoint; import android.location.Location; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Utility class for decimating tracks at a given level of precision. * * @author Leif Hendrik Wilden */ public class LocationUtils { /** * Computes the distance on the two sphere between the point c0 and the line * segment c1 to c2. * * @param c0 the first coordinate * @param c1 the beginning of the line segment * @param c2 the end of the lone segment * @return the distance in m (assuming spherical earth) */ public static double distance( final Location c0, final Location c1, final Location c2) { if (c1.equals(c2)) { return c2.distanceTo(c0); } final double s0lat = c0.getLatitude() * UnitConversions.TO_RADIANS; final double s0lng = c0.getLongitude() * UnitConversions.TO_RADIANS; final double s1lat = c1.getLatitude() * UnitConversions.TO_RADIANS; final double s1lng = c1.getLongitude() * UnitConversions.TO_RADIANS; final double s2lat = c2.getLatitude() * UnitConversions.TO_RADIANS; final double s2lng = c2.getLongitude() * UnitConversions.TO_RADIANS; double s2s1lat = s2lat - s1lat; double s2s1lng = s2lng - s1lng; final double u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng) / (s2s1lat * s2s1lat + s2s1lng * s2s1lng); if (u <= 0) { return c0.distanceTo(c1); } if (u >= 1) { return c0.distanceTo(c2); } Location sa = new Location(""); sa.setLatitude(c0.getLatitude() - c1.getLatitude()); sa.setLongitude(c0.getLongitude() - c1.getLongitude()); Location sb = new Location(""); sb.setLatitude(u * (c2.getLatitude() - c1.getLatitude())); sb.setLongitude(u * (c2.getLongitude() - c1.getLongitude())); return sa.distanceTo(sb); } /** * Decimates the given locations for a given zoom level. This uses a * Douglas-Peucker decimation algorithm. * * @param tolerance in meters * @param locations input * @param decimated output */ public static void decimate(double tolerance, ArrayList<Location> locations, ArrayList<Location> decimated) { final int n = locations.size(); if (n < 1) { return; } int idx; int maxIdx = 0; Stack<int[]> stack = new Stack<int[]>(); double[] dists = new double[n]; dists[0] = 1; dists[n - 1] = 1; double maxDist; double dist = 0.0; int[] current; if (n > 2) { int[] stackVal = new int[] {0, (n - 1)}; stack.push(stackVal); while (stack.size() > 0) { current = stack.pop(); maxDist = 0; for (idx = current[0] + 1; idx < current[1]; ++idx) { dist = LocationUtils.distance( locations.get(idx), locations.get(current[0]), locations.get(current[1])); if (dist > maxDist) { maxDist = dist; maxIdx = idx; } } if (maxDist > tolerance) { dists[maxIdx] = maxDist; int[] stackValCurMax = {current[0], maxIdx}; stack.push(stackValCurMax); int[] stackValMaxCur = {maxIdx, current[1]}; stack.push(stackValMaxCur); } } } int i = 0; idx = 0; decimated.clear(); for (Location l : locations) { if (dists[idx] != 0) { decimated.add(l); i++; } idx++; } Log.d(Constants.TAG, "Decimating " + n + " points to " + i + " w/ tolerance = " + tolerance); } /** * Decimates the given track for the given precision. * * @param track a track * @param precision desired precision in meters */ public static void decimate(Track track, double precision) { ArrayList<Location> decimated = new ArrayList<Location>(); decimate(precision, track.getLocations(), decimated); track.setLocations(decimated); } /** * Limits number of points by dropping any points beyond the given number of * points. Note: That'll actually discard points. * * @param track a track * @param numberOfPoints maximum number of points */ public static void cut(Track track, int numberOfPoints) { ArrayList<Location> locations = track.getLocations(); while (locations.size() > numberOfPoints) { locations.remove(locations.size() - 1); } } /** * Splits a track in multiple tracks where each piece has less or equal than * maxPoints. * * @param track the track to split * @param maxPoints maximum number of points for each piece * @return a list of one or more track pieces */ public static ArrayList<Track> split(Track track, int maxPoints) { ArrayList<Track> result = new ArrayList<Track>(); final int nTotal = track.getLocations().size(); int n = 0; Track piece = null; do { piece = new Track(); TripStatistics pieceStats = piece.getStatistics(); piece.setId(track.getId()); piece.setName(track.getName()); piece.setDescription(track.getDescription()); piece.setCategory(track.getCategory()); List<Location> pieceLocations = piece.getLocations(); for (int i = n; i < nTotal && pieceLocations.size() < maxPoints; i++) { piece.addLocation(track.getLocations().get(i)); } int nPointsPiece = pieceLocations.size(); if (nPointsPiece >= 2) { pieceStats.setStartTime(pieceLocations.get(0).getTime()); pieceStats.setStopTime(pieceLocations.get(nPointsPiece - 1).getTime()); result.add(piece); } n += (pieceLocations.size() - 1); } while (n < nTotal && piece.getLocations().size() > 1); return result; } /** * Test if a given GeoPoint is valid, i.e. within physical bounds. * * @param geoPoint the point to be tested * @return true, if it is a physical location on earth. */ public static boolean isValidGeoPoint(GeoPoint geoPoint) { return Math.abs(geoPoint.getLatitudeE6()) < 90E6 && Math.abs(geoPoint.getLongitudeE6()) <= 180E6; } /** * Checks if a given location is a valid (i.e. physically possible) location * on Earth. Note: The special separator locations (which have latitude = * 100) will not qualify as valid. Neither will locations with lat=0 and lng=0 * as these are most likely "bad" measurements which often cause trouble. * * @param location the location to test * @return true if the location is a valid location. */ public static boolean isValidLocation(Location location) { return location != null && Math.abs(location.getLatitude()) <= 90 && Math.abs(location.getLongitude()) <= 180; } /** * Gets a location from a GeoPoint. * * @param p a GeoPoint * @return the corresponding location */ public static Location getLocation(GeoPoint p) { Location result = new Location(""); result.setLatitude(p.getLatitudeE6() / 1.0E6); result.setLongitude(p.getLongitudeE6() / 1.0E6); return result; } public static GeoPoint getGeoPoint(Location location) { return new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)); } /** * This is a utility class w/ only static members. */ private LocationUtils() { } }
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.util; import android.net.Uri; import java.util.List; /** * Utilities for dealing with content and other types of URIs. * * @author Rodrigo Damazio */ public class UriUtils { public static boolean matchesContentUri(Uri uri, Uri baseContentUri) { if (uri == null) { return false; } // Check that scheme and authority are the same. if (!uri.getScheme().equals(baseContentUri.getScheme()) || !uri.getAuthority().equals(baseContentUri.getAuthority())) { return false; } // Checks that all the base path components are in the URI. List<String> uriPathSegments = uri.getPathSegments(); List<String> basePathSegments = baseContentUri.getPathSegments(); if (basePathSegments.size() > uriPathSegments.size()) { return false; } for (int i = 0; i < basePathSegments.size(); i++) { if (!uriPathSegments.get(i).equals(basePathSegments.get(i))) { return false; } } return true; } public static boolean isFileUri(Uri uri) { return "file".equals(uri.getScheme()); } private UriUtils() {} }
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.util; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import java.text.NumberFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.SimpleTimeZone; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Various string manipulation methods. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class StringUtils implements DescriptionGenerator { private final Context context; /** * Formats a number of milliseconds as a string. * * @param time - A period of time in milliseconds. * @return A string of the format M:SS, MM:SS or HH:MM:SS */ public static String formatTime(long time) { return formatTimeInternal(time, false); } /** * Formats a number of milliseconds as a string. To be used when we need the * hours to be shown even when it is zero, e.g. exporting data to a * spreadsheet. * * @param time - A period of time in milliseconds * @return A string of the format HH:MM:SS even if time is less than 1 hour */ public static String formatTimeAlwaysShowingHours(long time) { return formatTimeInternal(time, true); } private static final NumberFormat SINGLE_DECIMAL_PLACE_FORMAT = NumberFormat.getNumberInstance(); static { SINGLE_DECIMAL_PLACE_FORMAT.setMaximumFractionDigits(1); SINGLE_DECIMAL_PLACE_FORMAT.setMinimumFractionDigits(1); } /** * Formats a double precision number as decimal number with a single decimal * place. * * @param number A double precision number * @return A string representation of a decimal number, derived from the input * double, with a single decimal place */ public static final String formatSingleDecimalPlace(double number) { return SINGLE_DECIMAL_PLACE_FORMAT.format(number); } /** * Formats the given text as a CDATA element to be used in a XML file. This * includes adding the starting and ending CDATA tags. Please notice that this * may result in multiple consecutive CDATA tags. * * @param unescaped the unescaped text to be formatted * @return the formatted text, inside one or more CDATA tags */ public static String stringAsCData(String unescaped) { // "]]>" needs to be broken into multiple CDATA segments, like: // "Foo]]>Bar" becomes "<![CDATA[Foo]]]]><![CDATA[>Bar]]>" // (the end of the first CDATA has the "]]", the other has ">") String escaped = unescaped.replaceAll("]]>", "]]]]><![CDATA[>"); return "<![CDATA[" + escaped + "]]>"; } private static final SimpleDateFormat BASE_XML_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); static { BASE_XML_DATE_FORMAT.setTimeZone(new SimpleTimeZone(0, "UTC")); } private static final Pattern XML_DATE_EXTRAS_PATTERN = Pattern.compile("^(\\.\\d+)?(?:Z|([+-])(\\d{2}):(\\d{2}))?$"); /** * Parses an XML dateTime element as defined by the XML standard. * * @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">dateTime</a> */ public static long parseXmlDateTime(String xmlTime) { // Parse the base date (fixed format) ParsePosition position = new ParsePosition(0); Date date = BASE_XML_DATE_FORMAT.parse(xmlTime, position); if (date == null) { throw new IllegalArgumentException("Invalid XML dateTime value: '" + xmlTime + "' (at position " + position.getErrorIndex() + ")"); } // Parse the extras Matcher matcher = XML_DATE_EXTRAS_PATTERN.matcher(xmlTime.substring(position.getIndex())); if (!matcher.matches()) { // This will match even an empty string as all groups are optional, // so a non-match means some other garbage was there throw new IllegalArgumentException("Invalid XML dateTime value: " + xmlTime); } long time = date.getTime(); // Account for fractional seconds String fractional = matcher.group(1); if (fractional != null) { // Regex ensures fractional part is in (0,1( float fractionalSeconds = Float.parseFloat(fractional); long fractionalMillis = (long) (fractionalSeconds * 1000.0f); time += fractionalMillis; } // Account for timezones String sign = matcher.group(2); String offsetHoursStr = matcher.group(3); String offsetMinsStr = matcher.group(4); if (sign != null && offsetHoursStr != null && offsetMinsStr != null) { // Regex ensures sign is + or - boolean plusSign = sign.equals("+"); int offsetHours = Integer.parseInt(offsetHoursStr); int offsetMins = Integer.parseInt(offsetMinsStr); // Regex ensures values are >= 0 if (offsetHours > 14 || offsetMins > 59) { throw new IllegalArgumentException("Bad timezone in " + xmlTime); } long totalOffsetMillis = (offsetMins + offsetHours * 60L) * 60000L; // Make time go back to UTC if (plusSign) { time -= totalOffsetMillis; } else { time += totalOffsetMillis; } } return time; } /** * Formats a number of milliseconds as a string. * * @param time - A period of time in milliseconds * @param alwaysShowHours - Whether to display 00 hours if time is less than 1 * hour * @return A string of the format HH:MM:SS */ private static String formatTimeInternal(long time, boolean alwaysShowHours) { int[] parts = getTimeParts(time); StringBuilder builder = new StringBuilder(); if (parts[2] > 0 || alwaysShowHours) { builder.append(parts[2]); builder.append(':'); if (parts[1] <= 9) { builder.append("0"); } } builder.append(parts[1]); builder.append(':'); if (parts[0] <= 9) { builder.append("0"); } builder.append(parts[0]); return builder.toString(); } /** * Gets the time as an array of parts. */ public static int[] getTimeParts(long time) { if (time < 0) { int[] parts = getTimeParts(time * -1); parts[0] *= -1; parts[1] *= -1; parts[2] *= -1; return parts; } int[] parts = new int[3]; long seconds = time / 1000; parts[0] = (int) (seconds % 60); int tmp = (int) (seconds / 60); parts[1] = tmp % 60; parts[2] = tmp / 60; return parts; } public StringUtils(Context context) { this.context = context; } /** * 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) { boolean displaySpeed = true; SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences != null) { displaySpeed = preferences.getBoolean(context.getString(R.string.report_speed_key), true); } TripStatistics trackStats = track.getStatistics(); final double distanceInKm = trackStats.getTotalDistance() / 1000; final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI; final long minElevationInMeters = Math.round(trackStats.getMinElevation()); final long minElevationInFeet = Math.round(trackStats.getMinElevation() * UnitConversions.M_TO_FT); final long maxElevationInMeters = Math.round(trackStats.getMaxElevation()); final long maxElevationInFeet = Math.round(trackStats.getMaxElevation() * UnitConversions.M_TO_FT); final long elevationGainInMeters = Math.round(trackStats.getTotalElevationGain()); final long elevationGainInFeet = Math.round( trackStats.getTotalElevationGain() * UnitConversions.M_TO_FT); long minGrade = 0; long maxGrade = 0; double trackMaxGrade = trackStats.getMaxGrade(); double trackMinGrade = trackStats.getMinGrade(); if (!Double.isNaN(trackMaxGrade) && !Double.isInfinite(trackMaxGrade)) { maxGrade = Math.round(trackMaxGrade * 100); } if (!Double.isNaN(trackMinGrade) && !Double.isInfinite(trackMinGrade)) { minGrade = Math.round(trackMinGrade * 100); } String category = context.getString(R.string.value_unknown); String trackCategory = track.getCategory(); if (trackCategory != null && trackCategory.length() > 0) { category = trackCategory; } String averageSpeed = getSpeedString(trackStats.getAverageSpeed(), R.string.stat_average_speed, R.string.stat_average_pace, displaySpeed); String averageMovingSpeed = getSpeedString(trackStats.getAverageMovingSpeed(), R.string.stat_average_moving_speed, R.string.stat_average_moving_pace, displaySpeed); String maxSpeed = getSpeedString(trackStats.getMaxSpeed(), R.string.stat_max_speed, R.string.stat_min_pace, displaySpeed); return String.format("%s<p>" + "%s: %.2f %s (%.1f %s)<br>" + "%s: %s<br>" + "%s: %s<br>" + "%s %s %s" + "%s: %d %s (%d %s)<br>" + "%s: %d %s (%d %s)<br>" + "%s: %d %s (%d %s)<br>" + "%s: %d %%<br>" + "%s: %d %%<br>" + "%s: %tc<br>" + "%s: %s<br>" + "<img border=\"0\" src=\"%s\"/>", // Line 1 getCreatedByMyTracks(context, true), // Line 2 context.getString(R.string.stat_total_distance), distanceInKm, context.getString(R.string.unit_kilometer), distanceInMiles, context.getString(R.string.unit_mile), // Line 3 context.getString(R.string.stat_total_time), StringUtils.formatTime(trackStats.getTotalTime()), // Line 4 context.getString(R.string.stat_moving_time), StringUtils.formatTime(trackStats.getMovingTime()), // Line 5 averageSpeed, averageMovingSpeed, maxSpeed, // Line 6 context.getString(R.string.stat_min_elevation), minElevationInMeters, context.getString(R.string.unit_meter), minElevationInFeet, context.getString(R.string.unit_feet), // Line 7 context.getString(R.string.stat_max_elevation), maxElevationInMeters, context.getString(R.string.unit_meter), maxElevationInFeet, context.getString(R.string.unit_feet), // Line 8 context.getString(R.string.stat_elevation_gain), elevationGainInMeters, context.getString(R.string.unit_meter), elevationGainInFeet, context.getString(R.string.unit_feet), // Line 9 context.getString(R.string.stat_max_grade), maxGrade, // Line 10 context.getString(R.string.stat_min_grade), minGrade, // Line 11 context.getString(R.string.send_google_recorded), new Date(trackStats.getStartTime()), // Line 12 context.getString(R.string.track_detail_activity_type_hint), category, // Line 13 ChartURLGenerator.getChartUrl(distances, elevations, track, context)); } /** * Returns the 'Created by My Tracks on Android' string. * * @param context the context * @param addLink true to add a link to the My Tracks web site */ public static String getCreatedByMyTracks(Context context, boolean addLink) { String format = context.getString(R.string.send_google_by_my_tracks); if (addLink) { String url = context.getString(R.string.my_tracks_web_url); return String.format(format, "<a href='http://" + url + "'>", "</a>"); } else { return String.format(format, "", ""); } } private String getSpeedString(double speed, int speedLabel, int paceLabel, boolean displaySpeed) { double speedInKph = speed * 3.6; double speedInMph = speedInKph * UnitConversions.KMH_TO_MPH; if (displaySpeed) { return String.format("%s: %.2f %s (%.1f %s)<br>", context.getString(speedLabel), speedInKph, context.getString(R.string.unit_kilometer_per_hour), speedInMph, context.getString(R.string.unit_mile_per_hour)); } else { double paceInKm; double paceInMi; if (speed == 0) { paceInKm = 0.0; paceInMi = 0.0; } else { paceInKm = 60.0 / speedInKph; paceInMi = 60.0 / speedInMph; } return String.format("%s: %.2f %s (%.1f %s)<br>", context.getString(paceLabel), paceInKm, context.getString(R.string.unit_minute_per_kilometer), paceInMi, context.getString(R.string.unit_minute_per_mile)); } } /** * Generates a description for a waypoint (with information about the * statistics). * * @return a track description */ public String generateWaypointDescription(Waypoint waypoint) { TripStatistics stats = waypoint.getStatistics(); final double distanceInKm = stats.getTotalDistance() / 1000; final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI; final double averageSpeedInKmh = stats.getAverageSpeed() * 3.6; final double averageSpeedInMph = averageSpeedInKmh * UnitConversions.KMH_TO_MPH; final double movingSpeedInKmh = stats.getAverageMovingSpeed() * 3.6; final double movingSpeedInMph = movingSpeedInKmh * UnitConversions.KMH_TO_MPH; final double maxSpeedInKmh = stats.getMaxSpeed() * 3.6; final double maxSpeedInMph = maxSpeedInKmh * UnitConversions.KMH_TO_MPH; final long minElevationInMeters = Math.round(stats.getMinElevation()); final long minElevationInFeet = Math.round(stats.getMinElevation() * UnitConversions.M_TO_FT); final long maxElevationInMeters = Math.round(stats.getMaxElevation()); final long maxElevationInFeet = Math.round(stats.getMaxElevation() * UnitConversions.M_TO_FT); final long elevationGainInMeters = Math.round(stats.getTotalElevationGain()); final long elevationGainInFeet = Math.round( stats.getTotalElevationGain() * UnitConversions.M_TO_FT); long theMinGrade = 0; long theMaxGrade = 0; double maxGrade = stats.getMaxGrade(); double minGrade = stats.getMinGrade(); if (!Double.isNaN(maxGrade) && !Double.isInfinite(maxGrade)) { theMaxGrade = Math.round(maxGrade * 100); } if (!Double.isNaN(minGrade) && !Double.isInfinite(minGrade)) { theMinGrade = Math.round(minGrade * 100); } final String percent = "%"; return String.format( "%s: %.2f %s (%.1f %s)\n" + "%s: %s\n" + "%s: %s\n" + "%s: %.2f %s (%.1f %s)\n" + "%s: %.2f %s (%.1f %s)\n" + "%s: %.2f %s (%.1f %s)\n" + "%s: %d %s (%d %s)\n" + "%s: %d %s (%d %s)\n" + "%s: %d %s (%d %s)\n" + "%s: %d %s\n" + "%s: %d %s\n", context.getString(R.string.stat_total_distance), distanceInKm, context.getString(R.string.unit_kilometer), distanceInMiles, context.getString(R.string.unit_mile), context.getString(R.string.stat_total_time), StringUtils.formatTime(stats.getTotalTime()), context.getString(R.string.stat_moving_time), StringUtils.formatTime(stats.getMovingTime()), context.getString(R.string.stat_average_speed), averageSpeedInKmh, context.getString(R.string.unit_kilometer_per_hour), averageSpeedInMph, context.getString(R.string.unit_mile_per_hour), context.getString(R.string.stat_average_moving_speed), movingSpeedInKmh, context.getString(R.string.unit_kilometer_per_hour), movingSpeedInMph, context.getString(R.string.unit_mile_per_hour), context.getString(R.string.stat_max_speed), maxSpeedInKmh, context.getString(R.string.unit_kilometer_per_hour), maxSpeedInMph, context.getString(R.string.unit_mile_per_hour), context.getString(R.string.stat_min_elevation), minElevationInMeters, context.getString(R.string.unit_meter), minElevationInFeet, context.getString(R.string.unit_feet), context.getString(R.string.stat_max_elevation), maxElevationInMeters, context.getString(R.string.unit_meter), maxElevationInFeet, context.getString(R.string.unit_feet), context.getString(R.string.stat_elevation_gain), elevationGainInMeters, context.getString(R.string.unit_meter), elevationGainInFeet, context.getString(R.string.unit_feet), context.getString(R.string.stat_max_grade), theMaxGrade, percent, context.getString(R.string.stat_min_grade), theMinGrade, percent); } }
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.util; /** * Unit conversion constants. * * @author Sandor Dornbush */ public abstract class UnitConversions { public static final double KM_TO_MI = 0.621371192; public static final double M_TO_FT = 3.2808399; public static final double MI_TO_M = 1609.344; public static final double MI_TO_FEET = 5280.0; public static final double KMH_TO_MPH = 1000 * M_TO_FT / MI_TO_FEET; public static final double TO_RADIANS = Math.PI / 180.0; public static final double MPH_TO_KMH = 1.609344; protected UnitConversions() { } }
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.util; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.tasks.PeriodicTask; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerTask; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.apache.ApacheHttpTransport; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * API level 3 specific implementation of the {@link ApiLevelAdapter}. * * @author Bartlomiej Niechwiej */ public class ApiLevel3Adapter implements ApiLevelAdapter { @Override public void startForeground(Service service, NotificationManager notificationManager, int id, Notification notification) { setServiceForeground(service, true); notificationManager.notify(id, notification); } @Override public void stopForeground(Service service, NotificationManager notificationManager, int id) { setServiceForeground(service, false); if (id != -1) { notificationManager.cancel(id); } } @Override public PeriodicTask getStatusAnnouncerTask(Context context) { return new StatusAnnouncerTask(context); } @Override public BackupPreferencesListener getBackupPreferencesListener(Context context) { return new BackupPreferencesListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Do nothing } }; } private void setServiceForeground(Service service, boolean foreground) { // setForeground has been completely removed in API level 11, so we use reflection. try { Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class); setForegroundMethod.invoke(service, foreground); } catch (SecurityException e) { Log.e(TAG, "Unable to set service foreground state", e); } catch (NoSuchMethodException e) { Log.e(TAG, "Unable to set service foreground state", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to set service foreground state", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to set service foreground state", e); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to set service foreground state", e); } } @Override public void applyPreferenceChanges(Editor editor) { editor.commit(); } @Override public void enableStrictMode() { // Not supported } @Override public byte[] copyByteArray(byte[] input, int start, int end) { int length = end - start; byte[] output = new byte[length]; System.arraycopy(input, start, output, 0, length); return output; } @Override public HttpTransport getHttpTransport() { return new ApacheHttpTransport(); } }
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.util; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import java.util.Vector; /** * This class will generate google chart server url's. * * @author Sandor Dornbush */ public class ChartURLGenerator { private static final String CHARTS_BASE_URL = "http://chart.apis.google.com/chart?"; private ChartURLGenerator() { } /** * Gets a chart of a track. * * @param distances An array of distance measurements * @param elevations A matching array of elevation measurements * @param track The track for this chart * @param context The current appplication context */ public static String getChartUrl(Vector<Double> distances, Vector<Double> elevations, Track track, Context context) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = true; if (preferences != null) { metricUnits = preferences.getBoolean( context.getString(R.string.metric_units_key), true); } return getChartUrl(distances, elevations, track, context.getString(R.string.stat_elevation), metricUnits); } /** * Gets a chart of a track. * This form is for testing without contexts. * * @param distances An array of distance measurements * @param elevations A matching array of elevation measurements * @param track The track for this chart * @param title The title for the chart * @param metricUnits Should the data be displayed in metric units */ public static String getChartUrl( Vector<Double> distances, Vector<Double> elevations, Track track, String title, boolean metricUnits) { if (distances == null || elevations == null || track == null) { return null; } if (distances.size() != elevations.size()) { return null; } // Round it up. TripStatistics stats = track.getStatistics(); double effectiveMaxY = metricUnits ? stats.getMaxElevation() : stats.getMaxElevation() * UnitConversions.M_TO_FT; effectiveMaxY = ((int) (effectiveMaxY / 100)) * 100 + 100; // Round it down. double effectiveMinY = 0; double minElevation = metricUnits ? stats.getMinElevation() : stats.getMinElevation() * UnitConversions.M_TO_FT; effectiveMinY = ((int) (minElevation / 100)) * 100; if (stats.getMinElevation() < 0) { effectiveMinY -= 100; } double ySpread = effectiveMaxY - effectiveMinY; StringBuilder sb = new StringBuilder(CHARTS_BASE_URL); sb.append("&chs=600x350"); sb.append("&cht=lxy"); // Title sb.append("&chtt="); sb.append(title); // Labels sb.append("&chxt=x,y"); double distKM = stats.getTotalDistance() / 1000.0; double distDisplay = metricUnits ? distKM : (distKM * UnitConversions.KM_TO_MI); int xInterval = ((int) (distDisplay / 6)); int yInterval = ((int) (ySpread / 600)) * 100; if (yInterval < 100) { yInterval = 25; } // Range sb.append("&chxr=0,0,"); sb.append((int) distDisplay); sb.append(','); sb.append(xInterval); sb.append("|1,"); sb.append(effectiveMinY); sb.append(','); sb.append(effectiveMaxY); sb.append(','); sb.append(yInterval); // Line color sb.append("&chco=009A00"); // Fill sb.append("&chm=B,00AA00,0,0,0"); // Grid lines double desiredGrids = ySpread / yInterval; sb.append("&chg=100000,"); sb.append(100.0 / desiredGrids); sb.append(",1,0"); // Data sb.append("&chd=e:"); for (int i = 0; i < distances.size(); i++) { int normalized = (int) (getNormalizedDistance(distances.elementAt(i), track) * 4095); sb.append(ChartsExtendedEncoder.getEncodedValue(normalized)); } sb.append(ChartsExtendedEncoder.getSeparator()); for (int i = 0; i < elevations.size(); i++) { int normalized = (int) (getNormalizedElevation( elevations.elementAt(i), effectiveMinY, ySpread) * 4095); sb.append(ChartsExtendedEncoder.getEncodedValue(normalized)); } return sb.toString(); } private static double getNormalizedDistance(double d, Track track) { return d / track.getStatistics().getTotalDistance(); } private static double getNormalizedElevation( double d, double effectiveMinY, double ySpread) { return (d - effectiveMinY) / ySpread; } }
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.util; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.tasks.PeriodicTask; import com.google.api.client.http.HttpTransport; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.SharedPreferences; /** * A set of methods that may be implemented differently depending on the Android API level. * * @author Bartlomiej Niechwiej */ public interface ApiLevelAdapter { /** * Puts the specified service into foreground. * * Due to changes in API level 5. * * @param service the service to be put in foreground. * @param notificationManager the notification manager used to post the given * notification. * @param id the ID of the notification, unique within the application. * @param notification the notification to post. */ void startForeground(Service service, NotificationManager notificationManager, int id, Notification notification); /** * Puts the given service into background. * * Due to changes in API level 5. * * @param service the service to put into background. * @param notificationManager the notification manager to user when removing * notifications. * @param id the ID of the notification to be remove, or -1 if the * notification shouldn't be removed. */ void stopForeground(Service service, NotificationManager notificationManager, int id); /** * Gets a status announcer task. * * Due to changes in API level 8. */ PeriodicTask getStatusAnnouncerTask(Context context); /** * Gets a {@link BackupPreferencesListener}. * * Due to changes in API level 8. */ BackupPreferencesListener getBackupPreferencesListener(Context context); /** * Applies all changes done to the given preferences editor. * Changes may or may not be applied immediately. * * Due to changes in API level 9. */ void applyPreferenceChanges(SharedPreferences.Editor editor); /** * Enables strict mode where supported, only if this is a development build. * * Due to changes in API level 9. */ void enableStrictMode(); /** * Copies elements from the input byte array into a new byte array, from * indexes start (inclusive) to end (exclusive). The end index must be less * than or equal to input.length. * * Due to changes in API level 9. * * @param input the input byte array * @param start the start index * @param end the end index * @return a new array containing elements from the input byte array */ byte[] copyByteArray(byte[] input, int start, int end); /** * Gets a {@link HttpTransport}. * * Due to changes in API level 9. */ HttpTransport getHttpTransport(); }
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.util; import com.google.android.maps.GeoPoint; /** * A rectangle in geographical space. */ public class GeoRect { public int top; public int left; public int bottom; public int right; public GeoRect() { top = 0; left = 0; bottom = 0; right = 0; } public GeoRect(GeoPoint center, int latSpan, int longSpan) { top = center.getLatitudeE6() - latSpan / 2; left = center.getLongitudeE6() - longSpan / 2; bottom = center.getLatitudeE6() + latSpan / 2; right = center.getLongitudeE6() + longSpan / 2; } public GeoPoint getCenter() { return new GeoPoint(top / 2 + bottom / 2, left / 2 + right / 2); } public int getLatSpan() { return bottom - top; } public int getLongSpan() { return right - left; } public boolean contains(GeoPoint geoPoint) { if (geoPoint.getLatitudeE6() >= top && geoPoint.getLatitudeE6() <= bottom && geoPoint.getLongitudeE6() >= left && geoPoint.getLongitudeE6() <= right) { return true; } return false; } }
Java
package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListenerImpl; import com.google.android.apps.mytracks.services.tasks.FroyoStatusAnnouncerTask; import com.google.android.apps.mytracks.services.tasks.PeriodicTask; import android.content.Context; /** * API level 8 specific implementation of the {@link ApiLevelAdapter}. * * @author Jimmy Shih */ public class ApiLevel8Adapter extends ApiLevel5Adapter { @Override public PeriodicTask getStatusAnnouncerTask(Context context) { return new FroyoStatusAnnouncerTask(context); } @Override public BackupPreferencesListener getBackupPreferencesListener(Context context) { return new BackupPreferencesListenerImpl(context); } }
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.util; import com.google.android.apps.mytracks.Constants; import android.os.Environment; import java.io.File; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.util.regex.Pattern; /** * Utilities for dealing with files. * * @author Rodrigo Damazio */ public class FileUtils { /** * The maximum length of a filename, as per the FAT32 specification. */ private static final int MAX_FILENAME_LENGTH = 260; /** * A set of characters that are prohibited from being in file names. */ private static final Pattern PROHIBITED_CHAR_PATTERN = Pattern.compile("[^ A-Za-z0-9_.()-]+"); /** * Timestamp format in UTC time zone. */ public static final SimpleDateFormat FILE_TIMESTAMP_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); static { FILE_TIMESTAMP_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * Builds a path inside the My Tracks directory in the SD card. * * @param components the path components inside the mytracks directory * @return the full path to the destination */ public String buildExternalDirectoryPath(String... components) { StringBuilder dirNameBuilder = new StringBuilder(); dirNameBuilder.append(Environment.getExternalStorageDirectory()); dirNameBuilder.append(File.separatorChar); dirNameBuilder.append(Constants.SDCARD_TOP_DIR); for (String component : components) { dirNameBuilder.append(File.separatorChar); dirNameBuilder.append(component); } return dirNameBuilder.toString(); } /** * Returns whether the SD card is available. */ public boolean isSdCardAvailable() { return Environment.MEDIA_MOUNTED.equals( Environment.getExternalStorageState()); } /** * Normalizes the input string and make sure it is a valid fat32 file name. * * @param name the name to normalize * @return the sanitized name */ String sanitizeName(String name) { String cleaned = PROHIBITED_CHAR_PATTERN.matcher(name).replaceAll(""); return (cleaned.length() > MAX_FILENAME_LENGTH) ? cleaned.substring(0, MAX_FILENAME_LENGTH) : cleaned.toString(); } /** * Ensures the given directory exists by creating it and its parents if * necessary. * * @return whether the directory exists (either already existed or was * successfully created) */ public boolean ensureDirectoryExists(File dir) { if (dir.exists() && dir.isDirectory()) { return true; } if (dir.mkdirs()) { return true; } return false; } /** * Builds a filename with the given base name (prefix) and the given * extension, possibly adding a suffix to ensure the file doesn't exist. * * @param directory the directory the file will live in * @param fileBaseName the prefix for the file name * @param extension the file's extension * @return the complete file name, without the directory */ public synchronized String buildUniqueFileName(File directory, String fileBaseName, String extension) { return buildUniqueFileName(directory, fileBaseName, extension, 0); } /** * Builds a filename with the given base name (prefix) and the given * extension, possibly adding a suffix to ensure the file doesn't exist. * * @param directory the directory the file will live in * @param fileBaseName the prefix for the file name * @param extension the file's extension * @param suffix the first numeric suffix to try to use, or 0 for none * @return the complete file name, without the directory */ private String buildUniqueFileName(File directory, String fileBaseName, String extension, int suffix) { String suffixedBaseName = fileBaseName; if (suffix > 0) { suffixedBaseName += " (" + Integer.toString(suffix) + ")"; } String fullName = suffixedBaseName + "." + extension; String sanitizedName = sanitizeName(fullName); if (!fileExists(directory, sanitizedName)) { return sanitizedName; } return buildUniqueFileName(directory, fileBaseName, extension, suffix + 1); } /** * Checks whether a file with the given name exists in the given directory. * This is isolated so it can be overridden in tests. */ protected boolean fileExists(File directory, String fullName) { File file = new File(directory, fullName); return file.exists(); } }
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.util; import com.google.android.apps.mytracks.Constants; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.os.Build; import android.util.Log; import java.util.List; import java.util.Set; /** * Utilities for dealing with bluetooth devices. * This can be used safely even in systems that don't support bluetooth, * in which case a dummy implementation will be used. * * @author Rodrigo Damazio */ public abstract class BluetoothDeviceUtils { public static final String ANY_DEVICE = "any"; private static BluetoothDeviceUtils instance; /** * Dummy implementation, for systems that don't support bluetooth. */ private static class DummyImpl extends BluetoothDeviceUtils { @Override public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) { // Do nothing - no devices to add } @Override public BluetoothDevice findDeviceMatching(String targetDeviceAddress) { return null; } } /** * Real implementation, for systems that DO support bluetooth. */ private static class RealImpl extends BluetoothDeviceUtils { private final BluetoothAdapter bluetoothAdapter; public RealImpl() { bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { throw new IllegalStateException("Unable to get bluetooth adapter"); } } @Override public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) { ensureNotDiscovering(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices) { BluetoothClass bluetoothClass = device.getBluetoothClass(); if (bluetoothClass != null) { // Not really sure what we want, but I know what we don't want. switch(bluetoothClass.getMajorDeviceClass()) { case BluetoothClass.Device.Major.COMPUTER: case BluetoothClass.Device.Major.PHONE: break; default: deviceAddresses.add(device.getAddress()); deviceNames.add(device.getName()); } } } } @Override public BluetoothDevice findDeviceMatching(String targetDeviceAddress) { if (targetDeviceAddress.equals(ANY_DEVICE)) { return findAnyDevice(); } else { return findDeviceByAddress(targetDeviceAddress); } } /** * Finds and returns the first suitable bluetooth sensor. */ private BluetoothDevice findAnyDevice() { ensureNotDiscovering(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices) { // Look for the first paired computer device if (isSuitableDevice(device)) { return device; } } return null; } /** * Finds and returns a device with the given address, or null if it's not * a suitable sensor. */ private BluetoothDevice findDeviceByAddress(String targetDeviceAddress) { ensureNotDiscovering(); BluetoothDevice device = bluetoothAdapter.getRemoteDevice(targetDeviceAddress); if (isSuitableDevice(device)) { return device; } return null; } /** * Ensures the bluetooth adapter is not in discovery mode. */ private void ensureNotDiscovering() { // If it's in discovery mode, cancel that for now. bluetoothAdapter.cancelDiscovery(); } /** * Checks whether the given device is a suitable sensor. * * @param device the device to check * @return true if it's suitable, false otherwise */ private boolean isSuitableDevice(BluetoothDevice device) { // Check that the device is bonded if (device.getBondState() != BluetoothDevice.BOND_BONDED) { return false; } return true; } } /** * Returns the proper (singleton) instance of this class. */ public static BluetoothDeviceUtils getInstance() { if (instance == null) { if (!isBluetoothMethodSupported()) { Log.d(Constants.TAG, "Using dummy bluetooth utils"); instance = new DummyImpl(); } else { Log.d(Constants.TAG, "Using real bluetooth utils"); try { instance = new RealImpl(); } catch (IllegalStateException ise) { Log.w(Constants.TAG, "Oops, I mean, using dummy bluetooth utils", ise); instance = new DummyImpl(); } } } return instance; } /** * Populates the given lists with the names and addresses of all suitable * bluetooth devices. * * @param deviceNames the list to populate with user-visible names * @param deviceAddresses the list to populate with device addresses */ public abstract void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses); /** * Finds the bluetooth device with the given address. * * @param targetDeviceAddress the address of the device, or * {@link #ANY_DEVICE} for using the first suitable device * @return the device's descriptor, or null if not found */ public abstract BluetoothDevice findDeviceMatching(String targetDeviceAddress); /** * @return whether the bluetooth method is supported on this device */ public static boolean isBluetoothMethodSupported() { return Integer.parseInt(Build.VERSION.SDK) >= 5; } }
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.util; import com.google.android.apps.mytracks.Constants; import android.os.Build; import android.util.Log; /** * Utility class for determining if newer-API features are available on the * current device. * * @author Rodrigo Damazio */ public class ApiFeatures { /** * The API level of the Android version we are being run under. */ private static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); private static ApiFeatures instance; /** * The API level adapter for the Android version we are being run under. */ private ApiLevelAdapter apiLevelAdapter; /** * Returns the singleton instance of this class. */ public static ApiFeatures getInstance() { if (instance == null) { instance = new ApiFeatures(); } return instance; } /** * Injects a specific singleton instance, to be used for unit tests. */ @SuppressWarnings("hiding") public static void injectInstance(ApiFeatures instance) { ApiFeatures.instance = instance; } /** * Allow subclasses for mocking, but no direct instantiation. */ protected ApiFeatures() { // It is safe to import unsupported classes as long as we only actually // load the class when supported. if (getApiLevel() >= 9) { apiLevelAdapter = new ApiLevel9Adapter(); } else if (getApiLevel() >= 8) { apiLevelAdapter = new ApiLevel8Adapter(); } else if (getApiLevel() >= 5) { apiLevelAdapter = new ApiLevel5Adapter(); } else { apiLevelAdapter = new ApiLevel3Adapter(); } Log.i(Constants.TAG, "Using API level adapter " + apiLevelAdapter.getClass()); } public ApiLevelAdapter getApiAdapter() { return apiLevelAdapter; } // API Level 4 Changes /** * Returns whether text-to-speech is available. */ public boolean hasTextToSpeech() { return getApiLevel() >= 4; } // API Level 5 Changes /** * There's a bug (#1587) in Cupcake and Donut which prevents you from * using a SQLiteQueryBuilder twice. That is, if you call buildQuery * on a given instance (to log the statement for debugging), and then * call query on the same instance to make it actually do the query, * it'll regenerate the query for the second call, and will screw it * up. Specifically, it'll add extra parens which don't belong. */ public boolean canReuseSQLiteQueryBuilder() { return getApiLevel() >= 5; } // API Level 10 changes /** * Returns true if BluetoothDevice.createInsecureRfcommSocketToServiceRecord * is available. */ public boolean hasBluetoothDeviceCreateInsecureRfcommSocketToServiceRecord() { return getApiLevel() >= 10; } // Visible for testing. protected int getApiLevel() { return ANDROID_API_LEVEL; } }
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.util; import android.content.Context; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; /** * Utility functions for android resources. * * @author Sandor Dornbush */ public class ResourceUtils { public static CharSequence readFile(Context activity, int id) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( activity.getResources().openRawResource(id))); String line; StringBuilder buffer = new StringBuilder(); while ((line = in.readLine()) != null) { buffer.append(line).append('\n'); } return buffer; } catch (IOException e) { return ""; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } } } public static void readBinaryFileToOutputStream( Context activity, int id, OutputStream os) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( activity.getResources().openRawResource(id)); out = new BufferedOutputStream(os); int b; while ((b = in.read()) != -1) { out.write(b); } out.flush(); } catch (IOException e) { return; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } } private ResourceUtils() { } }
Java
package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import android.content.SharedPreferences.Editor; import android.os.StrictMode; import android.util.Log; import java.util.Arrays; /** * API level 9 specific implementation of the {@link ApiLevelAdapter}. * * @author Rodrigo Damazio */ public class ApiLevel9Adapter extends ApiLevel8Adapter { @Override public void applyPreferenceChanges(Editor editor) { // Apply asynchronously editor.apply(); } @Override public void enableStrictMode() { Log.d(Constants.TAG, "Enabling strict mode"); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); } @Override public byte[] copyByteArray(byte[] input, int start, int end) { return Arrays.copyOfRange(input, start, end); } @Override public HttpTransport getHttpTransport() { return new NetHttpTransport(); } }
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.util; /** * The singleton class representing the extended encoding of chart data. */ public class ChartsExtendedEncoder { // ChartServer data encoding in extended mode private static final String CHARTSERVER_EXTENDED_ENCODING_SEPARATOR = ","; private static final String CHARTSERVER_EXTENDED_ENCODING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-."; private static final int CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES = CHARTSERVER_EXTENDED_ENCODING.length(); private static final String MISSING_POINT_EXTENDED_ENCODING = "__"; private ChartsExtendedEncoder() { } public static String getEncodedValue(int scaled) { int index1 = scaled / CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES; if (index1 < 0 || index1 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) { return MISSING_POINT_EXTENDED_ENCODING; } int index2 = scaled % CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES; if (index2 < 0 || index2 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) { return MISSING_POINT_EXTENDED_ENCODING; } return String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index1)) + String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index2)); } public static String getSeparator() { return CHARTSERVER_EXTENDED_ENCODING_SEPARATOR; } }
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; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; /** * An activity that displays a welcome screen. * * @author Sandor Dornbush */ public class WelcomeActivity extends Activity { private static final int DIALOG_ABOUT_ID = 0; private static final int DIALOG_EULA_ID = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome); findViewById(R.id.welcome_ok).setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); findViewById(R.id.welcome_about).setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG_ABOUT_ID); } }); } @Override protected Dialog onCreateDialog(int id) { AlertDialog.Builder builder; switch (id) { case DIALOG_ABOUT_ID: LayoutInflater layoutInflator = LayoutInflater.from(this); View view = layoutInflator.inflate(R.layout.about, null); TextView aboutVersionTextView = (TextView) view.findViewById(R.id.about_version); aboutVersionTextView.setText(SystemUtils.getMyTracksVersion(this)); builder = new AlertDialog.Builder(this); builder.setView(view); builder.setPositiveButton(R.string.generic_ok, null); builder.setNegativeButton(R.string.about_license, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { showDialog(DIALOG_EULA_ID); } }); return builder.create(); case DIALOG_EULA_ID: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.eula_title); builder.setMessage(R.string.eula_message); builder.setPositiveButton(R.string.generic_ok, null); builder.setCancelable(true); return builder.create(); default: return null; } } }
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.io.sendtogoogle; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import com.google.android.apps.mytracks.AccountChooser; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyMapsList; import com.google.android.apps.mytracks.ProgressIndicator; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManager.AuthCallback; import com.google.android.apps.mytracks.io.AuthManagerFactory; import com.google.android.apps.mytracks.io.SendToDocs; import com.google.android.apps.mytracks.io.SendToFusionTables; import com.google.android.apps.mytracks.io.SendToFusionTables.OnSendCompletedListener; import com.google.android.apps.mytracks.io.SendToMyMaps; import com.google.android.apps.mytracks.io.mymaps.MapsFacade; import com.google.android.apps.mytracks.io.mymaps.MyMapsConstants; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.accounts.Account; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Helper activity for managing the sending of tracks to Google services. * * @author Rodrigo Damazio */ public class SendActivity extends Activity implements ProgressIndicator { // Keys for saved state variables. private static final String STATE_SEND_TO_MAPS = "mapsSend"; private static final String STATE_SEND_TO_FUSION_TABLES = "fusionSend"; private static final String STATE_SEND_TO_DOCS = "docsSend"; private static final String STATE_DOCS_SUCCESS = "docsSuccess"; private static final String STATE_FUSION_SUCCESS = "fusionSuccess"; private static final String STATE_MAPS_SUCCESS = "mapsSuccess"; private static final String STATE_STATE = "state"; private static final String EXTRA_SHARE_LINK = "shareLink"; private static final String STATE_ACCOUNT_TYPE = "accountType"; private static final String STATE_ACCOUNT_NAME = "accountName"; private static final String STATE_TABLE_ID = "tableId"; private static final String STATE_MAP_ID = "mapId"; /** States for the state machine that defines the upload process. */ private enum SendState { SEND_OPTIONS, START, AUTHENTICATE_MAPS, PICK_MAP, SEND_TO_MAPS, SEND_TO_MAPS_DONE, AUTHENTICATE_FUSION_TABLES, SEND_TO_FUSION_TABLES, SEND_TO_FUSION_TABLES_DONE, AUTHENTICATE_DOCS, AUTHENTICATE_TRIX, SEND_TO_DOCS, SEND_TO_DOCS_DONE, SHOW_RESULTS, SHARE_LINK, FINISH, DONE, NOT_READY } private static final int SEND_DIALOG = 1; private static final int PROGRESS_DIALOG = 2; /* @VisibleForTesting */ static final int DONE_DIALOG = 3; // UI private ProgressDialog progressDialog; // Services private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; private GoogleAnalyticsTracker tracker; // Authentication private AuthManager lastAuth; private final HashMap<String, AuthManager> authMap = new HashMap<String, AuthManager>(); private AccountChooser accountChooser; private String lastAccountName; private String lastAccountType; // Send request information. private boolean shareRequested = false; private long sendTrackId; private boolean sendToMyMaps; private boolean sendToMyMapsNewMap; private boolean sendToFusionTables; private boolean sendToDocs; // Send result information, used by results dialog. private boolean sendToMyMapsSuccess = false; private boolean sendToFusionTablesSuccess = false; private boolean sendToDocsSuccess = false; // Send result information, used to share a link. private String sendToMyMapsMapId; private String sendToFusionTablesTableId; // Current sending state. private SendState currentState; private final OnCancelListener finishOnCancelListener = new OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { onAllDone(); } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "SendActivity.onCreate"); super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); tracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in manual dispatch mode... tracker.start(getString(R.string.my_tracks_analytics_id), getApplicationContext()); tracker.setProductVersion("android-mytracks", SystemUtils.getMyTracksVersion(this)); resetState(); if (savedInstanceState != null) { restoreInstanceState(savedInstanceState); } // If we had the instance restored after it was done, reset it. if (currentState == SendState.DONE) { resetState(); } // Only consider the intent if we're not restoring from a previous state. if (currentState == SendState.SEND_OPTIONS) { if (!handleIntent()) { finish(); return; } } // Execute the state machine, at the start or restored state. Log.w(TAG, "Starting at state " + currentState); executeStateMachine(currentState); } private boolean handleIntent() { Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); Uri data = intent.getData(); if (!Intent.ACTION_SEND.equals(action) || !TracksColumns.CONTENT_ITEMTYPE.equals(type) || !UriUtils.matchesContentUri(data, TracksColumns.CONTENT_URI)) { Log.e(TAG, "Got bad send intent: " + intent); return false; } sendTrackId = ContentUris.parseId(data); shareRequested = intent.getBooleanExtra(EXTRA_SHARE_LINK, false); return true; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case SEND_DIALOG: return createSendDialog(); case PROGRESS_DIALOG: return createProgressDialog(); case DONE_DIALOG: return createDoneDialog(); } return null; } private Dialog createSendDialog() { final SendDialog sendDialog = new SendDialog(this); sendDialog.setOnClickListener(new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which != DialogInterface.BUTTON_POSITIVE) { finish(); return; } dialog.dismiss(); sendToMyMaps = sendDialog.getSendToMyMaps(); sendToMyMapsNewMap = sendDialog.getCreateNewMap(); sendToFusionTables = sendDialog.getSendToFusionTables(); sendToDocs = sendDialog.getSendToDocs(); executeStateMachine(SendState.START); } }); sendDialog.setOnCancelListener(finishOnCancelListener); return sendDialog; } private void restoreInstanceState(Bundle savedInstanceState) { currentState = SendState.values()[savedInstanceState.getInt(STATE_STATE)]; sendToMyMaps = savedInstanceState.getBoolean(STATE_SEND_TO_MAPS); sendToFusionTables = savedInstanceState.getBoolean(STATE_SEND_TO_FUSION_TABLES); sendToDocs = savedInstanceState.getBoolean(STATE_SEND_TO_DOCS); sendToMyMapsSuccess = savedInstanceState.getBoolean(STATE_MAPS_SUCCESS); sendToFusionTablesSuccess = savedInstanceState.getBoolean(STATE_FUSION_SUCCESS); sendToDocsSuccess = savedInstanceState.getBoolean(STATE_DOCS_SUCCESS); sendToMyMapsMapId = savedInstanceState.getString(STATE_MAP_ID); sendToFusionTablesTableId = savedInstanceState.getString(STATE_TABLE_ID); lastAccountName = savedInstanceState.getString(STATE_ACCOUNT_NAME); lastAccountType = savedInstanceState.getString(STATE_ACCOUNT_TYPE); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_STATE, currentState.ordinal()); outState.putBoolean(STATE_MAPS_SUCCESS, sendToMyMapsSuccess); outState.putBoolean(STATE_FUSION_SUCCESS, sendToFusionTablesSuccess); outState.putBoolean(STATE_DOCS_SUCCESS, sendToDocsSuccess); outState.putString(STATE_MAP_ID, sendToMyMapsMapId); outState.putString(STATE_TABLE_ID, sendToFusionTablesTableId); outState.putString(STATE_ACCOUNT_NAME, lastAccountName); outState.putString(STATE_ACCOUNT_TYPE, lastAccountType); // TODO: Ideally we should serialize/restore the authenticator map and lastAuth somehow, // but it's highly unlikely we'll get killed while an auth dialog is displayed. } @Override protected void onStop() { Log.d(TAG, "SendActivity.onStop, state=" + currentState); tracker.dispatch(); tracker.stop(); super.onStop(); } @Override protected void onDestroy() { Log.d(TAG, "SendActivity.onDestroy, state=" + currentState); super.onDestroy(); } private void executeStateMachine(SendState startState) { currentState = startState; // If a state handler returns NOT_READY, it means it's waiting for some // event, and will call this method again when it happens. while (currentState != SendState.DONE && currentState != SendState.NOT_READY) { Log.d(TAG, "Executing state " + currentState); currentState = executeState(currentState); Log.d(TAG, "New state is " + currentState); } } private SendState executeState(SendState state) { switch (state) { case SEND_OPTIONS: return showSendOptions(); case START: return startSend(); case AUTHENTICATE_MAPS: return authenticateToGoogleMaps(); case PICK_MAP: return pickMap(); case SEND_TO_MAPS: return sendToGoogleMaps(); case SEND_TO_MAPS_DONE: return onSendToGoogleMapsDone(); case AUTHENTICATE_FUSION_TABLES: return authenticateToFusionTables(); case SEND_TO_FUSION_TABLES: return sendToFusionTables(); case SEND_TO_FUSION_TABLES_DONE: return onSendToFusionTablesDone(); case AUTHENTICATE_DOCS: return authenticateToGoogleDocs(); case AUTHENTICATE_TRIX: return authenticateToGoogleTrix(); case SEND_TO_DOCS: return sendToGoogleDocs(); case SEND_TO_DOCS_DONE: return onSendToGoogleDocsDone(); case SHOW_RESULTS: return onSendToGoogleDone(); case SHARE_LINK: return shareLink(); case FINISH: return onAllDone(); default: Log.e(TAG, "Reached a non-executable state"); return null; } } private SendState showSendOptions() { showDialog(SEND_DIALOG); return SendState.NOT_READY; } /** * Initiates the process to send tracks to google. * This is called once the user has selected sending options via the * SendToGoogleDialog. */ private SendState startSend() { showDialog(PROGRESS_DIALOG); if (sendToMyMaps) { return SendState.AUTHENTICATE_MAPS; } else if (sendToFusionTables) { return SendState.AUTHENTICATE_FUSION_TABLES; } else if (sendToDocs) { return SendState.AUTHENTICATE_DOCS; } else { Log.w(TAG, "Nowhere to upload to"); return SendState.FINISH; } } private Dialog createProgressDialog() { progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setTitle(R.string.generic_progress_title); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMax(100); progressDialog.setProgress(0); return progressDialog; } private SendState authenticateToGoogleMaps() { Log.d(TAG, "SendActivity.authenticateToGoogleMaps"); progressDialog.setProgress(0); progressDialog.setMessage(getAuthenticatingProgressMessage(SendType.MYMAPS)); authenticate(Constants.AUTHENTICATE_TO_MY_MAPS, MyMapsConstants.SERVICE_NAME); // AUTHENTICATE_TO_MY_MAPS callback calls sendToGoogleMaps return SendState.NOT_READY; } private SendState pickMap() { if (!sendToMyMapsNewMap) { // Ask the user to choose a map to upload into Intent listIntent = new Intent(this, MyMapsList.class); listIntent.putExtra(MyMapsList.EXTRA_ACCOUNT_NAME, lastAccountName); listIntent.putExtra(MyMapsList.EXTRA_ACCOUNT_TYPE, lastAccountType); startActivityForResult(listIntent, Constants.GET_MAP); // The callback for GET_MAP calls authenticateToGoogleMaps return SendState.NOT_READY; } else { return SendState.SEND_TO_MAPS; } } private SendState sendToGoogleMaps() { tracker.trackPageView("/send/maps"); SendToMyMaps.OnSendCompletedListener onCompletion = new SendToMyMaps.OnSendCompletedListener() { @Override public void onSendCompleted(String mapId, boolean success) { sendToMyMapsSuccess = success; if (sendToMyMapsSuccess) { sendToMyMapsMapId = mapId; // Update the map id for this track: try { Track track = providerUtils.getTrack(sendTrackId); if (track != null) { track.setMapId(mapId); providerUtils.updateTrack(track); } else { Log.w(TAG, "Updating map id failed."); } } catch (RuntimeException e) { // If that fails whatever reasons we'll just log an error, but // continue. Log.w(TAG, "Updating map id failed.", e); } } executeStateMachine(SendState.SEND_TO_MAPS_DONE); } }; if (sendToMyMapsMapId == null) { sendToMyMapsMapId = SendToMyMaps.NEW_MAP_ID; } final SendToMyMaps sender = new SendToMyMaps(this, sendToMyMapsMapId, lastAuth, sendTrackId, this /*progressIndicator*/, onCompletion); new Thread(sender, "SendToMyMaps").start(); return SendState.NOT_READY; } private SendState onSendToGoogleMapsDone() { if (sendToFusionTables) { return SendState.AUTHENTICATE_FUSION_TABLES; } else if (sendToDocs) { return SendState.AUTHENTICATE_DOCS; } else { return SendState.SHOW_RESULTS; } } private SendState authenticateToFusionTables() { progressDialog.setProgress(0); progressDialog.setMessage(getAuthenticatingProgressMessage(SendType.FUSION_TABLES)); authenticate(Constants.AUTHENTICATE_TO_FUSION_TABLES, SendToFusionTables.SERVICE_ID); // AUTHENTICATE_TO_FUSION_TABLES callback calls sendToFusionTables return SendState.NOT_READY; } private SendState sendToFusionTables() { tracker.trackPageView("/send/fusion_tables"); OnSendCompletedListener onCompletion = new OnSendCompletedListener() { @Override public void onSendCompleted(String tableId, boolean success) { sendToFusionTablesSuccess = success; if (sendToFusionTablesSuccess) { sendToFusionTablesTableId = tableId; // Update the table id for this track: try { Track track = providerUtils.getTrack(sendTrackId); if (track != null) { track.setTableId(tableId); providerUtils.updateTrack(track); } else { Log.w(TAG, "Updating table id failed."); } } catch (RuntimeException e) { // If that fails whatever reasons we'll just log an error, but // continue. Log.w(TAG, "Updating table id failed.", e); } } executeStateMachine(SendState.SEND_TO_FUSION_TABLES_DONE); } }; final SendToFusionTables sender = new SendToFusionTables(this, lastAuth, sendTrackId, this /*progressIndicator*/, onCompletion); new Thread(sender, "SendToFusionTables").start(); return SendState.NOT_READY; } private SendState onSendToFusionTablesDone() { if (sendToDocs) { return SendState.AUTHENTICATE_DOCS; } else { return SendState.SHOW_RESULTS; } } private SendState authenticateToGoogleDocs() { setProgressValue(0); setProgressMessage(getAuthenticatingProgressMessage(SendType.DOCS)); authenticate(Constants.AUTHENTICATE_TO_DOCLIST, SendToDocs.GDATA_SERVICE_NAME_DOCLIST); // AUTHENTICATE_TO_DOCLIST callback calls authenticateToGoogleTrix return SendState.NOT_READY; } private SendState authenticateToGoogleTrix() { setProgressValue(30); setProgressMessage(getAuthenticatingProgressMessage(SendType.DOCS)); authenticate(Constants.AUTHENTICATE_TO_TRIX, SendToDocs.GDATA_SERVICE_NAME_TRIX); // AUTHENTICATE_TO_TRIX callback calls sendToGoogleDocs return SendState.NOT_READY; } private SendState sendToGoogleDocs() { Log.d(TAG, "Sending to Docs...."); tracker.trackPageView("/send/docs"); setProgressValue(50); String format = getString(R.string.send_google_progress_sending); String serviceName = getString(SendType.DOCS.getServiceName()); setProgressMessage(String.format(format, serviceName)); final SendToDocs sender = new SendToDocs(this, authMap.get(SendToDocs.GDATA_SERVICE_NAME_TRIX), authMap.get(SendToDocs.GDATA_SERVICE_NAME_DOCLIST), this); Runnable onCompletion = new Runnable() { public void run() { setProgressValue(100); sendToDocsSuccess = sender.wasSuccess(); executeStateMachine(SendState.SEND_TO_DOCS_DONE); } }; sender.setOnCompletion(onCompletion); sender.sendToDocs(sendTrackId); return SendState.NOT_READY; } private SendState onSendToGoogleDocsDone() { return SendState.SHOW_RESULTS; } private SendState onSendToGoogleDone() { tracker.dispatch(); runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "Sending to Google done."); dismissDialog(PROGRESS_DIALOG); dismissDialog(SEND_DIALOG); // Ensure a new done dialog is created each time. // This is required because the send results must be available at the // time the dialog is created. removeDialog(DONE_DIALOG); showDialog(DONE_DIALOG); } }); return SendState.NOT_READY; } private Dialog createDoneDialog() { Log.d(TAG, "Creating done dialog"); // We've finished sending the track to the user-selected services. Now // we tell them the results of the upload, and optionally share the track. // There are a few different paths through this code: // // 1. The user pre-requested a share (shareRequested == true). We're going // to display the result dialog *without* the share button (the share // listener will be null). The OK button listener will initiate the // share. // // 2. The user did not pre-request a share, and the set of services to // which we succeeded in uploading the track are compatible with // sharing. We'll display a share button (the share listener will be // non-null), and will share the link if the user clicks it. // // 3. The user did not pre-request a share, and the set of services to // which we succeeded in uploading the track are incompatible with // sharing. We won't display a share button. List<SendResult> results = makeSendToGoogleResults(); final boolean canShare = sendToFusionTablesTableId != null || sendToMyMapsMapId != null; final OnClickListener finishListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); executeStateMachine(SendState.FINISH); } }; DialogInterface.OnClickListener doShareListener = null; if (canShare) { doShareListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); executeStateMachine(SendState.SHARE_LINK); } }; } DialogInterface.OnClickListener onOkListener = (canShare && shareRequested) ? doShareListener : finishListener; DialogInterface.OnClickListener onShareListener = (canShare && !shareRequested) ? doShareListener : null; return ResultDialogFactory.makeDialog(this, results, onOkListener, onShareListener, finishOnCancelListener); } private SendState onAllDone() { Log.d(TAG, "All sending done."); removeDialog(PROGRESS_DIALOG); removeDialog(SEND_DIALOG); removeDialog(DONE_DIALOG); progressDialog = null; finish(); return SendState.DONE; } private SendState shareLink() { String url = null; if (sendToMyMaps && sendToMyMapsSuccess) { // Prefer a link to My Maps url = MapsFacade.buildMapUrl(sendToMyMapsMapId); } else if (sendToFusionTables && sendToFusionTablesSuccess) { // Otherwise try using the link to fusion tables url = getFusionTablesUrl(sendTrackId); } if (url != null) { shareLinkToMap(url); } else { Log.w(TAG, "Failed to share link"); } return SendState.FINISH; } /** * Shares a link to a My Map or Fusion Table via external app (email, gmail, ...) * A chooser with apps that support text/plain will be shown to the user. */ private void shareLinkToMap(String url) { boolean shareUrlOnly = sharedPreferences.getBoolean( getString(R.string.share_url_only_key), false); String msg = shareUrlOnly ? url : String.format( getResources().getText(R.string.share_track_url_body_format).toString(), url); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getText(R.string.share_track_subject).toString()); shareIntent.putExtra(Intent.EXTRA_TEXT, msg); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_track_picker_title).toString())); } protected String getFusionTablesUrl(long trackId) { Track track = providerUtils.getTrack(trackId); return SendToFusionTables.getMapVisualizationUrl(track); } /** * Creates a list of {@link SendResult} instances based on the set of * services selected in {@link SendDialog} and the results as known to * this class. */ private List<SendResult> makeSendToGoogleResults() { List<SendResult> results = new ArrayList<SendResult>(); if (sendToMyMaps) { results.add(new SendResult(SendType.MYMAPS, sendToMyMapsSuccess)); } if (sendToFusionTables) { results.add(new SendResult(SendType.FUSION_TABLES, sendToFusionTablesSuccess)); } if (sendToDocs) { results.add(new SendResult(SendType.DOCS, sendToDocsSuccess)); } return results; } /** * Initializes the authentication manager which obtains an authentication * token, prompting the user for a login and password if needed. */ private void authenticate(final int requestCode, final String service) { lastAuth = authMap.get(service); if (lastAuth == null) { Log.i(TAG, "Creating a new authentication for service: " + service); lastAuth = AuthManagerFactory.getAuthManager(this, Constants.GET_LOGIN, null, true, service); authMap.put(service, lastAuth); } Log.d(TAG, "Logging in to " + service + "..."); if (AuthManagerFactory.useModernAuthManager()) { runOnUiThread(new Runnable() { @Override public void run() { chooseAccount(requestCode, service); } }); } else { doLogin(requestCode, service, null); } } private void chooseAccount(final int requestCode, final String service) { if (accountChooser == null) { accountChooser = new AccountChooser(); // Restore state if necessary. if (lastAccountName != null && lastAccountType != null) { accountChooser.setChosenAccount(lastAccountName, lastAccountType); } } accountChooser.chooseAccount(SendActivity.this, new AccountChooser.AccountHandler() { @Override public void onAccountSelected(Account account) { if (account == null) { dismissDialog(PROGRESS_DIALOG); finish(); return; } lastAccountName = account.name; lastAccountType = account.type; doLogin(requestCode, service, account); } }); } private void doLogin(final int requestCode, final String service, final Object account) { lastAuth.doLogin(new AuthCallback() { @Override public void onAuthResult(boolean success) { Log.i(TAG, "Login success for " + service + ": " + success); if (!success) { executeStateMachine(SendState.SHOW_RESULTS); return; } onLoginSuccess(requestCode); } }, account); } @Override public void onActivityResult(int requestCode, int resultCode, final Intent results) { SendState nextState = null; switch (requestCode) { case Constants.GET_LOGIN: { if (resultCode == RESULT_CANCELED || lastAuth == null) { nextState = SendState.FINISH; break; } // This will invoke onAuthResult appropriately. lastAuth.authResult(resultCode, results); break; } case Constants.GET_MAP: { // User picked a map to upload to Log.d(TAG, "Get map result: " + resultCode); if (resultCode == RESULT_OK) { if (results.hasExtra("mapid")) { sendToMyMapsMapId = results.getStringExtra("mapid"); } nextState = SendState.SEND_TO_MAPS; } else { nextState = SendState.FINISH; } break; } default: { Log.e(TAG, "Unrequested result: " + requestCode); return; } } if (nextState != null) { executeStateMachine(nextState); } } private void onLoginSuccess(int requestCode) { SendState nextState; switch (requestCode) { case Constants.AUTHENTICATE_TO_MY_MAPS: // Authenticated with Google My Maps nextState = SendState.PICK_MAP; break; case Constants.AUTHENTICATE_TO_FUSION_TABLES: // Authenticated with Google Fusion Tables nextState = SendState.SEND_TO_FUSION_TABLES; break; case Constants.AUTHENTICATE_TO_DOCLIST: // Authenticated with Google Docs nextState = SendState.AUTHENTICATE_TRIX; break; case Constants.AUTHENTICATE_TO_TRIX: // Authenticated with Trix nextState = SendState.SEND_TO_DOCS; break; default: { Log.e(TAG, "Unrequested login code: " + requestCode); return; } } executeStateMachine(nextState); } /** * Resets status information for sending to MyMaps/Docs. */ private void resetState() { currentState = SendState.SEND_OPTIONS; sendToMyMapsMapId = null; sendToMyMapsSuccess = true; sendToFusionTablesSuccess = true; sendToDocsSuccess = true; sendToFusionTablesTableId = null; } /** * Gets a progress message indicating My Tracks is authenticating to a * service. * * @param type the type of service */ private String getAuthenticatingProgressMessage(SendType type) { String format = getString(R.string.send_google_progress_authenticating); String serviceName = getString(type.getServiceName()); return String.format(format, serviceName); } @Override public void setProgressMessage(final String message) { runOnUiThread(new Runnable() { public void run() { if (progressDialog != null) { progressDialog.setMessage(message); } } }); } @Override public void setProgressValue(final int percent) { runOnUiThread(new Runnable() { public void run() { if (progressDialog != null) { progressDialog.setProgress(percent); } } }); } @Override public void clearProgressMessage() { progressDialog.setMessage(""); } public static void sendToGoogle(Context ctx, long trackId, boolean shareLink) { Uri uri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, trackId); Intent intent = new Intent(ctx, SendActivity.class); intent.setAction(Intent.ACTION_SEND); intent.setDataAndType(uri, TracksColumns.CONTENT_ITEMTYPE); intent.putExtra(SendActivity.EXTRA_SHARE_LINK, shareLink); ctx.startActivity(intent); } }
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.io.sendtogoogle; import com.google.android.maps.mytracks.R; /** * Enumerates the services to which we can upload track data. * * @author Matthew Simmons */ public enum SendType { MYMAPS(R.string.send_google_my_maps, R.string.send_google_my_maps_url), FUSION_TABLES(R.string.send_google_fusion_tables, R.string.send_google_fusion_tables_url), DOCS(R.string.send_google_docs, R.string.send_google_docs_url); private int serviceName; private int serviceUrl; private SendType(int serviceName, int serviceUrl) { this.serviceName = serviceName; this.serviceUrl = serviceUrl; } /** Returns the resource ID for the printable (short) name of the service */ public int getServiceName() { return serviceName; } /** Returns the resource ID for the service's URL */ public int getServiceUrl() { return serviceUrl; } }
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.io.sendtogoogle; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.RadioButton; import android.widget.RadioGroup; /** * A dialog where the user can choose where to send the tracks to, i.e. * to Google My Maps, Google Docs, etc. * * @author Leif Hendrik Wilden */ public class SendDialog extends Dialog { private RadioButton newMapRadioButton; private RadioButton existingMapRadioButton; private CheckBox myMapsCheckBox; private CheckBox fusionTablesCheckBox; private CheckBox docsCheckBox; private OnClickListener clickListener; public SendDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_send_to_google); final Button sendButton = (Button) findViewById(R.id.send_google_send_now); final RadioGroup myMapsGroup = (RadioGroup) findViewById(R.id.send_google_my_maps_group); newMapRadioButton = (RadioButton) findViewById(R.id.send_google_new_map); existingMapRadioButton = (RadioButton) findViewById(R.id.send_google_existing_map); myMapsCheckBox = (CheckBox) findViewById(R.id.send_google_my_maps); fusionTablesCheckBox = (CheckBox) findViewById(R.id.send_google_fusion_tables); docsCheckBox = (CheckBox) findViewById(R.id.send_google_docs); Button cancel = (Button) findViewById(R.id.send_google_cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (clickListener != null) { clickListener.onClick(SendDialog.this, BUTTON_NEGATIVE); } dismiss(); } }); Button send = (Button) findViewById(R.id.send_google_send_now); send.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (clickListener != null) { clickListener.onClick(SendDialog.this, BUTTON_POSITIVE); } dismiss(); } }); OnCheckedChangeListener checkBoxListener = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton button, boolean checked) { sendButton.setEnabled(myMapsCheckBox.isChecked() || fusionTablesCheckBox.isChecked() || docsCheckBox.isChecked()); myMapsGroup.setVisibility(myMapsCheckBox.isChecked() ? View.VISIBLE : View.GONE); } }; myMapsCheckBox.setOnCheckedChangeListener(checkBoxListener); fusionTablesCheckBox.setOnCheckedChangeListener(checkBoxListener); docsCheckBox.setOnCheckedChangeListener(checkBoxListener); SharedPreferences prefs = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs != null) { boolean pickExistingMap = prefs.getBoolean( getContext().getString(R.string.pick_existing_map_key), false); newMapRadioButton.setChecked(!pickExistingMap); existingMapRadioButton.setChecked(pickExistingMap); myMapsCheckBox.setChecked( prefs.getBoolean(getContext().getString(R.string.send_to_my_maps_key), true)); fusionTablesCheckBox.setChecked( prefs.getBoolean(getContext().getString(R.string.send_to_fusion_tables_key), true)); docsCheckBox.setChecked( prefs.getBoolean(getContext().getString(R.string.send_to_docs_key), true)); } } @Override protected void onStop() { super.onStop(); SharedPreferences prefs = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs != null) { Editor editor = prefs.edit(); if (editor != null) { editor.putBoolean(getContext().getString(R.string.pick_existing_map_key), existingMapRadioButton.isChecked()); editor.putBoolean(getContext().getString(R.string.send_to_my_maps_key), myMapsCheckBox.isChecked()); editor.putBoolean(getContext().getString(R.string.send_to_fusion_tables_key), fusionTablesCheckBox.isChecked()); editor.putBoolean(getContext().getString(R.string.send_to_docs_key), docsCheckBox.isChecked()); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } } } public void setOnClickListener(OnClickListener clickListener) { this.clickListener = clickListener; } public boolean getCreateNewMap() { return newMapRadioButton.isChecked(); } public boolean getSendToMyMaps() { return myMapsCheckBox.isChecked(); } public boolean getSendToFusionTables() { return fusionTablesCheckBox.isChecked(); } public boolean getSendToDocs() { return docsCheckBox.isChecked(); } }
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.io.sendtogoogle; /** * This class represents the the result of the uploading of track data to a * single service. * * @author Matthew Simmons */ public class SendResult { private final SendType type; private final boolean success; /** * @param type the service to which track data was uploaded * @param success true if the uploading succeeded */ public SendResult(SendType type, boolean success) { this.type = type; this.success = success; } /** Returns the service to which the track data was uploaded */ public SendType getType() { return type; } /** Returns true if the uploading succeeded */ public boolean isSuccess() { return success; } }
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.io.sendtogoogle; import com.google.android.maps.mytracks.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.TextView; import java.util.List; /** * This class implements the {@link ListAdapter} used by the send-to-Google * result dialog created by {@link ResultDialogFactory}. It generates views * for each entry in an array of {@link SendResult} instances. * @author Matthew Simmons */ class ResultListAdapter extends ArrayAdapter<SendResult> { public ResultListAdapter(Context context, int textViewResourceId, List<SendResult> results) { super(context, textViewResourceId, results); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.send_to_google_result_list_item, null); } SendResult result = getItem(position); setImage(view, result.isSuccess() ? R.drawable.success : R.drawable.failure); setName(view, result.getType().getServiceName()); setUrl(view, result.getType().getServiceUrl()); return view; } @Override public boolean areAllItemsEnabled() { // We don't want the displayed items to be clickable return false; } // The following protected methods exist to be overridden for testing // purposes. Doing so insulates the test class from the details of the // layout. protected void setImage(View content, int drawableId) { ImageView imageView = (ImageView) content.findViewById(R.id.send_to_google_result_icon); imageView.setImageDrawable(getContext().getResources().getDrawable(drawableId)); } protected void setName(View content, int nameId) { setTextViewText(content, R.id.send_to_google_result_name, nameId); } protected void setUrl(View content, int urlId) { setTextViewText(content, R.id.send_to_google_result_url, urlId); } private void setTextViewText(View content, int viewId, int textId) { TextView textView = (TextView) content.findViewById(viewId); textView.setText(getContext().getString(textId)); } };
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.io.sendtogoogle; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.view.View; import android.widget.ListView; import java.util.List; /** * Creates the dialog used to display the results of sending track data to * Google. The dialog lists the services to which data was uploaded, along * with an indicator of success/failure. If possible, a button is displayed * offering to share the uploaded track. * * Implementation note: This class is a factory, rather than a {@link Dialog} * subclass, because alert dialogs have to be created with * {@link AlertDialog.Builder}. Attempts to subclass {@link AlertDialog} * directly have been unsuccessful, as {@link AlertDialog.Builder} uses a * private subclass to implement most of the interesting behavior. * * @author Matthew Simmons */ public class ResultDialogFactory { private ResultDialogFactory() {} /** * Create a send-to-Google result dialog. The caller is responsible for * showing it. * * @param activity the activity associated with the dialog * @param results the results to be displayed in the dialog * @param onOkClickListener the listener to invoke if the OK button is * clicked * @param onShareClickListener the listener to invoke if the Share button is * clicked. If no share listener is provided, the Share button will not * be displayed. * @return the created dialog */ public static AlertDialog makeDialog(Activity activity, List<SendResult> results, DialogInterface.OnClickListener onOkClickListener, DialogInterface.OnClickListener onShareClickListener, DialogInterface.OnCancelListener onCancelListener) { boolean success = true; for (SendResult result : results) { if (!result.isSuccess()) { success = false; break; } } AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setView(makeDialogContent(activity, results, success)); if (success) { builder.setTitle(R.string.generic_success_title); builder.setIcon(android.R.drawable.ic_dialog_info); } else { builder.setTitle(R.string.generic_error_title); builder.setIcon(android.R.drawable.ic_dialog_alert); } builder.setPositiveButton(activity.getString(R.string.generic_ok), onOkClickListener); if (onShareClickListener != null) { builder.setNegativeButton(activity.getString(R.string.send_google_result_share_url), onShareClickListener); } builder.setOnCancelListener(onCancelListener); return builder.create(); } private static View makeDialogContent(Activity activity, List<SendResult> results, boolean success) { ResultListAdapter resultListAdapter = new ResultListAdapter(activity, R.layout.send_to_google_result_list_item, results); View content = activity.getLayoutInflater().inflate(R.layout.send_to_google_result, null); ListView resultList = (ListView) content.findViewById(R.id.send_to_google_result_list); resultList.setAdapter(resultListAdapter); content.findViewById(R.id.send_to_google_result_comment) .setVisibility(success ? View.VISIBLE : View.GONE); content.findViewById(R.id.send_to_google_result_error) .setVisibility(success ? View.GONE : View.VISIBLE); return content; } }
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.io.docs; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import java.text.NumberFormat; import java.util.Locale; /** * <p>This class builds a string of XML tags used to talk to Docs using GData. * * <p>Sample Usage: * * <code> * String tags = new DocsTagBuilder(false) * .append("tagName", "tagValue") * .appendLargeUnits("bigTagName", 1.0) * .build(); * </code> * * <p>results in: * * <code> * <gsx:tagName><![CDATA[tagValue]]></gsx:tagName> * <gsx:bigTagName><![CDATA[1.00]]></gsx:bigTagName> * </code> * * @author Matthew Simmons */ class DocsTagBuilder { // Google Docs can only parse numbers in the English locale. private static final NumberFormat LARGE_UNIT_FORMAT = NumberFormat.getNumberInstance( Locale.ENGLISH); private static final NumberFormat SMALL_UNIT_FORMAT = NumberFormat.getIntegerInstance( Locale.ENGLISH); static { LARGE_UNIT_FORMAT.setMaximumFractionDigits(2); LARGE_UNIT_FORMAT.setMinimumFractionDigits(2); } protected final boolean metricUnits; protected final StringBuilder stringBuilder; /** * @param metricUnits True if metric units are to be used. If false, * imperial units will be used. */ DocsTagBuilder(boolean metricUnits) { this.metricUnits = metricUnits; this.stringBuilder = new StringBuilder(); } /** Appends a tag containing a string value */ DocsTagBuilder append(String name, String value) { appendTag(name, value); return this; } /** * Appends a tag containing a numeric value. The value will be formatted * according to the large distance of the specified measurement system (i.e. * kilometers or miles). * * @param name The tag name. * @param d The value to be formatted, in kilometers. */ DocsTagBuilder appendLargeUnits(String name, double d) { double value = metricUnits ? d : (d * UnitConversions.KM_TO_MI); appendTag(name, LARGE_UNIT_FORMAT.format(value)); return this; } /** * Appends a tag containing a numeric value. The value will be formatted * according to the small distance of the specified measurement system (i.e. * meters or feet). * * @param name The tag name. * @param d The value to be formatted, in meters. */ DocsTagBuilder appendSmallUnits(String name, double d) { double value = metricUnits ? d : (d * UnitConversions.M_TO_FT); appendTag(name, SMALL_UNIT_FORMAT.format(value)); return this; } /** Returns a string containing all tags which have been added. */ String build() { return stringBuilder.toString(); } private void appendTag(String name, String value) { stringBuilder.append("<gsx:") .append(name) .append(">") .append(StringUtils.stringAsCData(value)) .append("</gsx:") .append(name) .append(">"); } }
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.io.docs; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.gdata.GDataWrapper; import com.google.android.apps.mytracks.io.gdata.GDataWrapper.QueryFunction; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ResourceUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.docs.SpreadsheetsClient; import com.google.wireless.gdata.docs.SpreadsheetsClient.WorksheetEntry; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata2.client.AuthenticationException; import android.content.Context; import android.util.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicReference; /** * This class contains helper methods for interacting with Google Docs and * Google Spreadsheets. * * @author Sandor Dornbush * @author Matthew Simmons */ public class DocsHelper { private static final String DOCS_FEED_URL = "https://docs.google.com/feeds/documents/private/full"; private static final String DOCS_SPREADSHEET_URL = "https://docs.google.com/feeds/documents/private/full/spreadsheet%3A"; private static final String DOCS_WORKSHEETS_URL_FORMAT = "https://spreadsheets.google.com/feeds/worksheets/%s/private/full"; private static final String DOCS_MY_SPREADSHEETS_FEED_URL = "https://docs.google.com/feeds/documents/private/full?category=mine,spreadsheet"; private static final String DOCS_SPREADSHEET_URL_FORMAT = "https://spreadsheets.google.com/feeds/list/%s/%s/private/full"; private static final String CONTENT_TYPE_PARAM = "Content-Type"; private static final String OPENDOCUMENT_SPREADSHEET_MIME_TYPE = "application/x-vnd.oasis.opendocument.spreadsheet"; private static final String ATOM_FEED_MIME_TYPE = "application/atom+xml"; /** * Creates a new MyTracks spreadsheet with the given name. * * @param context The context associated with this request. * @param docListWrapper The GData handle for the Document List service. * @param name The name for the newly-created spreadsheet. * @return The spreadsheet ID, if one is created. {@code null} will be * returned if a GData error didn't occur, but no spreadsheet ID was * returned. */ public String createSpreadsheet(final Context context, final GDataWrapper<GDataServiceClient> docListWrapper, final String name) throws IOException { final AtomicReference<String> idSaver = new AtomicReference<String>(); boolean success = docListWrapper.runQuery(new QueryFunction<GDataServiceClient>() { @Override public void query(GDataServiceClient client) throws IOException, GDataWrapper.AuthenticationException { // Construct and send request URL url = new URL(DOCS_FEED_URL); URLConnection conn = url.openConnection(); conn.addRequestProperty(CONTENT_TYPE_PARAM, OPENDOCUMENT_SPREADSHEET_MIME_TYPE); conn.addRequestProperty("Slug", name); conn.addRequestProperty("Authorization", "GoogleLogin auth=" + docListWrapper.getAuthManager().getAuthToken()); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); ResourceUtils.readBinaryFileToOutputStream( context, R.raw.mytracks_empty_spreadsheet, os); // Get the response // TODO: The following is a horrible ugly hack. // Hopefully we can retire it when there is a proper gdata api. BufferedReader rd = null; String line; StringBuilder resultBuilder = new StringBuilder(); try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { resultBuilder.append(line); } os.close(); rd.close(); } catch (FileNotFoundException e) { // The GData API sometimes throws an error, even though creation of // the document succeeded. In that case let's just return. The caller // then needs to check if the doc actually exists. return; } finally { os.close(); if (rd != null) { rd.close(); } } String result = resultBuilder.toString(); // Try to find the id. int idTagIndex = result.indexOf("<id>"); if (idTagIndex == -1) { return; } int idTagCloseIndex = result.indexOf("</id>", idTagIndex); if (idTagCloseIndex == -1) { return; } int idStringStart = result.indexOf(DOCS_SPREADSHEET_URL, idTagIndex); if (idStringStart == -1) { return; } String id = result.substring( idStringStart + DOCS_SPREADSHEET_URL.length(), idTagCloseIndex); Log.i(Constants.TAG, "Created new spreadsheet: " + id); idSaver.set(id); }}); if (!success) { throw newIOException(docListWrapper, "Failed to create new spreadsheet."); } return idSaver.get(); } /** * Retrieve the ID of a spreadsheet with the given name. * * @param docListWrapper The GData handle for the Document List service. * @param title The name of the spreadsheet whose ID is to be retrieved. * @return The spreadsheet ID, if it can be retrieved. {@code null} will * be returned if no spreadsheet exists by the given name. * @throws IOException If an error occurs during the GData request. */ public String requestSpreadsheetId(final GDataWrapper<GDataServiceClient> docListWrapper, final String title) throws IOException { final AtomicReference<String> idSaver = new AtomicReference<String>(); boolean result = docListWrapper.runQuery(new QueryFunction<GDataServiceClient>() { @Override public void query(GDataServiceClient client) throws IOException, GDataWrapper.ParseException, GDataWrapper.HttpException, GDataWrapper.AuthenticationException { GDataParser listParser; try { listParser = client.getParserForFeed(Entry.class, DOCS_MY_SPREADSHEETS_FEED_URL, docListWrapper.getAuthManager().getAuthToken()); listParser.init(); while (listParser.hasMoreData()) { Entry entry = listParser.readNextEntry(null); String entryTitle = entry.getTitle(); Log.i(Constants.TAG, "Found docs entry: " + entryTitle); if (entryTitle.equals(title)) { String entryId = entry.getId(); int lastSlash = entryId.lastIndexOf('/'); idSaver.set(entryId.substring(lastSlash + 15)); break; } } } catch (ParseException e) { throw new GDataWrapper.ParseException(e); } catch (HttpException e) { throw new GDataWrapper.HttpException(e.getStatusCode(), e.getMessage()); } } }); if (!result) { throw newIOException(docListWrapper, "Failed to retrieve spreadsheet list."); } return idSaver.get(); } /** * Retrieve the ID of the first worksheet in the named spreadsheet. * * @param trixWrapper The GData handle for the spreadsheet service. * @param spreadsheetId The GData ID for the given spreadsheet. * @return The worksheet ID, if it can be retrieved. {@code null} will be * returned if the GData request returns without error, but without an * ID. * @throws IOException If an error occurs during the GData request. */ public String getWorksheetId(final GDataWrapper<GDataServiceClient> trixWrapper, final String spreadsheetId) throws IOException { final AtomicReference<String> idSaver = new AtomicReference<String>(); boolean result = trixWrapper.runQuery(new QueryFunction<GDataServiceClient>() { @Override public void query(GDataServiceClient client) throws GDataWrapper.AuthenticationException, IOException, GDataWrapper.ParseException, GDataWrapper.HttpException { String uri = String.format(DOCS_WORKSHEETS_URL_FORMAT, spreadsheetId); GDataParser sheetParser; try { sheetParser = ((SpreadsheetsClient) client).getParserForWorksheetsFeed(uri, trixWrapper.getAuthManager().getAuthToken()); sheetParser.init(); if (!sheetParser.hasMoreData()) { Log.i(Constants.TAG, "Found no worksheets"); return; } // Grab the first worksheet. WorksheetEntry worksheetEntry = (WorksheetEntry) sheetParser.readNextEntry(new WorksheetEntry()); int lastSlash = worksheetEntry.getId().lastIndexOf('/'); idSaver.set(worksheetEntry.getId().substring(lastSlash + 1)); } catch (ParseException e) { throw new GDataWrapper.ParseException(e); } catch (AuthenticationException e) { throw new GDataWrapper.AuthenticationException(e); } } }); if (!result) { throw newIOException(trixWrapper, "Failed to retrieve worksheet ID."); } return idSaver.get(); } /** * Add a row to a worksheet containing the stats for a given track. * * @param context The context associated with this request. * @param trixAuth The GData authorization for the spreadsheet service. * @param spreadsheetId The spreadsheet to be modified. * @param worksheetId The worksheet to be modified. * @param track The track whose stats are to be written. * @param metricUnits True if metric units are to be used. If false, * imperial units will be used. * @throws IOException If an error occurs while updating the worksheet. */ public void addTrackRow(Context context, AuthManager trixAuth, String spreadsheetId, String worksheetId, Track track, boolean metricUnits) throws IOException { String worksheetUri = String.format(DOCS_SPREADSHEET_URL_FORMAT, spreadsheetId, worksheetId); TripStatistics stats = track.getStatistics(); String distanceUnit = context.getString(metricUnits ? R.string.unit_kilometer : R.string.unit_mile); String speedUnit = context.getString(metricUnits ? R.string.unit_kilometer_per_hour : R.string.unit_mile_per_hour); String elevationUnit = context.getString(metricUnits ? R.string.unit_meter : R.string.unit_feet); // Prepare the Post-Text we are going to send. DocsTagBuilder tagBuilder = new DocsTagBuilder(metricUnits) .append("name", track.getName()) .append("description", track.getDescription()) .append("date", getDisplayDate(stats.getStartTime())) .append("totaltime", StringUtils.formatTimeAlwaysShowingHours( stats.getTotalTime())) .append("movingtime", StringUtils.formatTimeAlwaysShowingHours( stats.getMovingTime())) .appendLargeUnits("distance", stats.getTotalDistance() / 1000) .append("distanceunit", distanceUnit) .appendLargeUnits("averagespeed", stats.getAverageSpeed() * 3.6) .appendLargeUnits("averagemovingspeed", stats.getAverageMovingSpeed() * 3.6) .appendLargeUnits("maxspeed", stats.getMaxSpeed() * 3.6) .append("speedunit", speedUnit) .appendSmallUnits("elevationgain", stats.getTotalElevationGain()) .appendSmallUnits("minelevation", stats.getMinElevation()) .appendSmallUnits("maxelevation", stats.getMaxElevation()) .append("elevationunit", elevationUnit); if (track.getMapId().length() > 0) { tagBuilder.append("map", String.format("%s?msa=0&msid=%s", Constants.MAPSHOP_BASE_URL, track.getMapId())); } String postText = new StringBuilder() .append("<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/" + "2006/extended'>") .append(tagBuilder.build()) .append("</entry>") .toString(); Log.i(Constants.TAG, "Inserting at: " + spreadsheetId + " => " + worksheetUri); Log.i(Constants.TAG, postText); writeRowData(trixAuth, worksheetUri, postText); Log.i(Constants.TAG, "Post finished."); } /** * Gets the display string for a time. * * @param time the time * @return the display string of the time */ private String getDisplayDate(long time) { DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); Date startTime = new Date(time); String dateString = format.format(startTime); return dateString; } /** * Writes spreadsheet row data to the indicated worksheet. * * @param trixAuth The GData authorization for the spreadsheet service. * @param worksheetUri The URI of the worksheet to be altered. * @param postText The XML tags describing the change to be made. * @throws IOException Thrown if an error occurs during the write. */ protected void writeRowData(AuthManager trixAuth, String worksheetUri, String postText) throws IOException { // No need for a wrapper because we know that the authorization was good // enough to get this far. URL url = new URL(worksheetUri); URLConnection conn = url.openConnection(); conn.addRequestProperty(CONTENT_TYPE_PARAM, ATOM_FEED_MIME_TYPE); conn.addRequestProperty("Authorization", "GoogleLogin auth=" + trixAuth.getAuthToken()); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(postText); wr.flush(); // Get the response. // TODO: Should we parse the response, rather than simply throwing it away? BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { // Process line. Log.i(Constants.TAG, "r: " + line); } wr.close(); rd.close(); } private static IOException newIOException(GDataWrapper<GDataServiceClient> wrapper, String message) { return new IOException(String.format("%s: %d: %s", message, wrapper.getErrorType(), wrapper.getErrorMessage())); } }
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.io.gdata; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.client.QueryParams; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.serializer.GDataSerializer; import android.text.TextUtils; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; /** * Implementation of a GDataClient using GoogleHttpClient to make HTTP requests. * Always issues GETs and POSTs, using the X-HTTP-Method-Override header when a * PUT or DELETE is desired, to avoid issues with firewalls, etc., that do not * allow methods other than GET or POST. */ public class AndroidGDataClient implements GDataClient { private static final String TAG = "GDataClient"; private static final boolean DEBUG = false; private static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override"; private static final int MAX_REDIRECTS = 10; private final HttpClient httpClient; /** * Interface for creating HTTP requests. Used by * {@link AndroidGDataClient#createAndExecuteMethod}, since HttpUriRequest * does not allow for changing the URI after creation, e.g., when you want to * follow a redirect. */ private interface HttpRequestCreator { HttpUriRequest createRequest(URI uri); } private static class GetRequestCreator implements HttpRequestCreator { public HttpUriRequest createRequest(URI uri) { return new HttpGet(uri); } } private static class PostRequestCreator implements HttpRequestCreator { private final String mMethodOverride; private final HttpEntity mEntity; public PostRequestCreator(String methodOverride, HttpEntity entity) { mMethodOverride = methodOverride; mEntity = entity; } public HttpUriRequest createRequest(URI uri) { HttpPost post = new HttpPost(uri); if (mMethodOverride != null) { post.addHeader(X_HTTP_METHOD_OVERRIDE, mMethodOverride); } post.setEntity(mEntity); return post; } } // MAJOR TODO: make this work across redirects (if we can reset the // InputStream). // OR, read the bits into a local buffer (yuck, the media could be large). private static class MediaPutRequestCreator implements HttpRequestCreator { private final InputStream mMediaInputStream; private final String mContentType; public MediaPutRequestCreator(InputStream mediaInputStream, String contentType) { mMediaInputStream = mediaInputStream; mContentType = contentType; } public HttpUriRequest createRequest(URI uri) { HttpPost post = new HttpPost(uri); post.addHeader(X_HTTP_METHOD_OVERRIDE, "PUT"); InputStreamEntity entity = new InputStreamEntity(mMediaInputStream, -1 /* read until EOF */); entity.setContentType(mContentType); post.setEntity(entity); return post; } } /** * Creates a new AndroidGDataClient. */ public AndroidGDataClient() { httpClient = new DefaultHttpClient(); } public void close() { } /* * (non-Javadoc) * * @see GDataClient#encodeUri(java.lang.String) */ public String encodeUri(String uri) { String encodedUri; try { encodedUri = URLEncoder.encode(uri, "UTF-8"); } catch (UnsupportedEncodingException uee) { // should not happen. Log.e("JakartaGDataClient", "UTF-8 not supported -- should not happen. " + "Using default encoding.", uee); encodedUri = URLEncoder.encode(uri); } return encodedUri; } /* * (non-Javadoc) * * @see com.google.wireless.gdata.client.GDataClient#createQueryParams() */ public QueryParams createQueryParams() { return new QueryParamsImpl(); } // follows redirects private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null; int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException( "StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); } /** * Gets the input stream from a response entity. If the entity is gzipped * then this will get a stream over the uncompressed data. * * @param entity the entity whose content should be read * @return the input stream to read from * @throws IOException */ private static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) { return responseStream; } Header header = entity.getContentEncoding(); if (header == null) { return responseStream; } String contentEncoding = header.getValue(); if (contentEncoding == null) { return responseStream; } if (contentEncoding.contains("gzip")){ responseStream = new GZIPInputStream(responseStream); } return responseStream; } /* * (non-Javadoc) * * @see GDataClient#getFeedAsStream(java.lang.String, java.lang.String) */ public InputStream getFeedAsStream(String feedUrl, String authToken) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new GetRequestCreator(), feedUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to access feed."); } public InputStream getMediaEntryAsStream(String mediaEntryUrl, String authToken) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new GetRequestCreator(), mediaEntryUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to access media entry."); } /* * (non-Javadoc) * * @see GDataClient#createEntry */ public InputStream createEntry(String feedUrl, String authToken, GDataSerializer entry) throws HttpException, IOException { HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_CREATE); InputStream in = createAndExecuteMethod(new PostRequestCreator(null /* override */, entity), feedUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to create entry."); } /* * (non-Javadoc) * * @see GDataClient#updateEntry */ public InputStream updateEntry(String editUri, String authToken, GDataSerializer entry) throws HttpException, IOException { HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_UPDATE); InputStream in = createAndExecuteMethod(new PostRequestCreator("PUT", entity), editUri, authToken); if (in != null) { return in; } throw new IOException("Unable to update entry."); } /* * (non-Javadoc) * * @see GDataClient#deleteEntry */ public void deleteEntry(String editUri, String authToken) throws HttpException, IOException { if (StringUtils.isEmpty(editUri)) { throw new IllegalArgumentException( "you must specify an non-empty edit url"); } InputStream in = createAndExecuteMethod( new PostRequestCreator("DELETE", null /* entity */), editUri, authToken); if (in == null) { throw new IOException("Unable to delete entry."); } try { in.close(); } catch (IOException ioe) { // ignore } } public InputStream updateMediaEntry(String editUri, String authToken, InputStream mediaEntryInputStream, String contentType) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new MediaPutRequestCreator( mediaEntryInputStream, contentType), editUri, authToken); if (in != null) { return in; } throw new IOException("Unable to write media entry."); } private HttpEntity createEntityForEntry(GDataSerializer entry, int format) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { entry.serialize(baos, format); } catch (IOException ioe) { Log.e(TAG, "Unable to serialize entry.", ioe); throw ioe; } catch (ParseException pe) { Log.e(TAG, "Unable to serialize entry.", pe); throw new IOException("Unable to serialize entry: " + pe.getMessage()); } byte[] entryBytes = baos.toByteArray(); if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) { try { Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8")); } catch (UnsupportedEncodingException uee) { // should not happen throw new IllegalStateException("UTF-8 should be supported!", uee); } } AbstractHttpEntity entity = new ByteArrayEntity(entryBytes); entity.setContentType(entry.getContentType()); return entity; } }
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.io.gdata; import com.google.wireless.gdata.client.QueryParams; import android.text.TextUtils; import android.util.Log; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Simple implementation of the QueryParams interface. */ // TODO: deal with categories public class QueryParamsImpl extends QueryParams { private final Map<String, String> mParams = new HashMap<String, String>(); @Override public void clear() { setEntryId(null); mParams.clear(); } @Override public String generateQueryUrl(String feedUrl) { if (TextUtils.isEmpty(getEntryId()) && mParams.isEmpty()) { // nothing to do return feedUrl; } // handle entry IDs if (!TextUtils.isEmpty(getEntryId())) { if (!mParams.isEmpty()) { throw new IllegalStateException("Cannot set both an entry ID " + "and other query paramters."); } return feedUrl + '/' + getEntryId(); } // otherwise, append the querystring params. StringBuilder sb = new StringBuilder(); sb.append(feedUrl); Set<String> params = mParams.keySet(); boolean first = true; if (feedUrl.contains("?")) { first = false; } else { sb.append('?'); } for (String param : params) { if (first) { first = false; } else { sb.append('&'); } sb.append(param); sb.append('='); String value = mParams.get(param); String encodedValue = null; try { encodedValue = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException uee) { // should not happen. Log.w("QueryParamsImpl", "UTF-8 not supported -- should not happen. " + "Using default encoding.", uee); encodedValue = URLEncoder.encode(value); } sb.append(encodedValue); } return sb.toString(); } @Override public String getParamValue(String param) { if (!(mParams.containsKey(param))) { return null; } return mParams.get(param); } @Override public void setParamValue(String param, String value) { mParams.put(param, value); } }
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.io.gdata; import com.google.android.apps.mytracks.Constants; import com.google.wireless.gdata.client.GDataClient; import android.content.Context; import android.util.Log; /** * This factory will fetch the right class for the platform. * * @author Sandor Dornbush */ public class GDataClientFactory { private GDataClientFactory() { } /** * Creates a new GData client. * This factory will fetch the right class for the platform. * @return A GDataClient appropriate for this platform */ public static GDataClient getGDataClient(Context context) { try { // Try to use the official unbundled gdata client implementation. // This should work on Froyo and beyond. return new com.google.android.common.gdata.AndroidGDataClient(context); } catch (LinkageError e) { // On all other platforms use the client implementation packaged in the // apk. Log.i(Constants.TAG, "Using mytracks AndroidGDataClient.", e); return new com.google.android.apps.mytracks.io.gdata.AndroidGDataClient(); } } }
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.io.gdata; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManager.AuthCallback; import android.util.Log; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; /** * GDataWrapper provides a wrapper around GData operations that maintains the * GData client, and provides a method to run GData queries with proper error * handling. After a query is run, the wrapper can be queried about the error * that occurred. * * @param <C> the GData service client * @author Sandor Dornbush */ public class GDataWrapper<C> { public static class AuthenticationException extends Exception { private Exception exception; private static final long serialVersionUID = 1L; public AuthenticationException(Exception caught) { this.exception = caught; } public Exception getException() { return exception; } }; public static class ParseException extends Exception { private Exception exception; private static final long serialVersionUID = 1L; public ParseException(Exception caught) { this.exception = caught; } public Exception getException() { return exception; } }; public static class ConflictDetectedException extends Exception { private Exception exception; private static final long serialVersionUID = 1L; public ConflictDetectedException(Exception caught) { this.exception = caught; } public Exception getException() { return exception; } }; public static class HttpException extends Exception { private static final long serialVersionUID = 1L; private int statusCode; private String statusMessage; public HttpException(int statusCode, String statusMessage) { super(); this.statusCode = statusCode; this.statusMessage = statusMessage; } public int getStatusCode() { return statusCode; } public String getStatusMessage() { return statusMessage; } }; /** * A QueryFunction is passed in when executing a query. The query function of * the class is called with the GData client as a parameter. The function * should execute whatever operations it desires on the client without concern * for whether the client will throw an error. */ public interface QueryFunction<C> { public abstract void query(C client) throws AuthenticationException, IOException, ParseException, ConflictDetectedException, HttpException; } /** * A AuthenticatedFunction is passed in when executing the google * authenticated service. The authenticated function of the class is called * with the current authentication token for the service. The function should * execute whatever operations with the google service without concern for * whether the client will throw an error. */ public interface AuthenticatedFunction { public abstract void run(String authenticationToken) throws AuthenticationException, IOException; } // The types of error that may be encountered // No error occurred. public static final int ERROR_NO_ERROR = 0; // There was an authentication error, the auth token may be invalid. public static final int ERROR_AUTH = 1; // There was an internal error on the server side. public static final int ERROR_INTERNAL = 2; // There was an error connecting to the server. public static final int ERROR_CONNECTION = 3; // The item queried did not exit. public static final int ERROR_NOT_FOUND = 4; // There was an error parsing or serializing locally. public static final int ERROR_LOCAL = 5; // There was a conflict, update the entry and try again. public static final int ERROR_CONFLICT = 6; // A query was run after cleaning up the wrapper, so the client was invalid. public static final int ERROR_CLEANED_UP = 7; // An unknown error occurred. public static final int ERROR_UNKNOWN = 100; private static final int AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES = 1; private static final int AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT = 5000; private String errorMessage; private int errorType; private C gdataServiceClient; private AuthManager auth; private boolean retryOnAuthFailure; public GDataWrapper() { errorType = ERROR_NO_ERROR; errorMessage = null; auth = null; retryOnAuthFailure = false; } public void setClient(C gdataServiceClient) { this.gdataServiceClient = gdataServiceClient; } public boolean runAuthenticatedFunction( final AuthenticatedFunction function) { return runCommon(function, null); } public boolean runQuery(final QueryFunction<C> query) { return runCommon(null, query); } /** * Runs an arbitrary piece of code. */ private boolean runCommon(final AuthenticatedFunction function, final QueryFunction<C> query) { for (int i = 0; i <= AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES; i++) { runOne(function, query); if (errorType == ERROR_NO_ERROR) { return true; } Log.d(Constants.TAG, "GData error encountered: " + errorMessage); if (errorType == ERROR_AUTH && auth != null) { if (!retryOnAuthFailure || !invalidateAndRefreshAuthToken()) { return false; } } Log.d(Constants.TAG, "retrying function/query"); } return false; } /** * Execute a given function or query. If one is executed, errorType and * errorMessage will contain the result/status of the function/query. */ private void runOne(final AuthenticatedFunction function, final QueryFunction<C> query) { try { if (function != null) { function.run(this.auth.getAuthToken()); } else if (query != null) { query.query(gdataServiceClient); } else { throw new IllegalArgumentException( "invalid invocation of runOne; one of function/query " + "must be non-null"); } errorType = ERROR_NO_ERROR; errorMessage = null; } catch (AuthenticationException e) { Log.e(Constants.TAG, "AuthenticationException", e); errorType = ERROR_AUTH; errorMessage = e.getMessage(); } catch (HttpException e) { Log.e(Constants.TAG, "HttpException, code " + e.getStatusCode() + " message " + e.getMessage(), e); errorMessage = e.getMessage(); if (e.getStatusCode() == 401) { errorType = ERROR_AUTH; } else { errorType = ERROR_CONNECTION; } } catch (FileNotFoundException e) { Log.e(Constants.TAG, "Exception", e); errorType = ERROR_AUTH; errorMessage = e.getMessage(); } catch (IOException e) { Log.e(Constants.TAG, "Exception", e); errorMessage = e.getMessage(); if (errorMessage != null && errorMessage.contains("503")) { errorType = ERROR_INTERNAL; } else { errorType = ERROR_CONNECTION; } } catch (ParseException e) { Log.e(Constants.TAG, "Exception", e); errorType = ERROR_LOCAL; errorMessage = e.getMessage(); } catch (ConflictDetectedException e) { Log.e(Constants.TAG, "Exception", e); errorType = ERROR_CONFLICT; errorMessage = e.getMessage(); } } /** * Invalidates and refreshes the auth token. Blocks until the refresh has * completed or until we deem the refresh as having timed out. * * @return true If the invalidate/refresh succeeds, false if it fails or * times out. */ private boolean invalidateAndRefreshAuthToken() { Log.d(Constants.TAG, "Retrying due to auth failure"); // This FutureTask doesn't do anything -- it exists simply to be // blocked upon using get(). final FutureTask<?> whenFinishedFuture = new FutureTask<Object>(new Runnable() { public void run() {} }, null); final AtomicBoolean finalSuccess = new AtomicBoolean(false); auth.invalidateAndRefresh(new AuthCallback() { @Override public void onAuthResult(boolean success) { finalSuccess.set(success); whenFinishedFuture.run(); } }); try { Log.d(Constants.TAG, "waiting for invalidate"); whenFinishedFuture.get(AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT, TimeUnit.MILLISECONDS); boolean success = finalSuccess.get(); Log.d(Constants.TAG, "invalidate finished, success = " + success); return success; } catch (InterruptedException e) { Log.e(Constants.TAG, "Failed to invalidate", e); } catch (ExecutionException e) { Log.e(Constants.TAG, "Failed to invalidate", e); } catch (TimeoutException e) { Log.e(Constants.TAG, "Invalidate didn't complete in time", e); } finally { whenFinishedFuture.cancel(false); } return false; } public int getErrorType() { return errorType; } public String getErrorMessage() { return errorMessage; } public void setAuthManager(AuthManager auth) { this.auth = auth; } public AuthManager getAuthManager() { return auth; } public void setRetryOnAuthFailure(boolean retry) { retryOnAuthFailure = retry; } }
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.io; import com.google.android.googlelogindist.GoogleLoginServiceConstants; import com.google.android.googlelogindist.GoogleLoginServiceHelper; import android.app.Activity; import android.content.Intent; import android.os.Bundle; /** * AuthManager keeps track of the current auth token for a user. The advantage * over just passing around a String is that this class can renew the auth * token if necessary, and it will change for all classes using this * AuthManager. */ public class AuthManagerOld implements AuthManager { /** The activity that will handle auth result callbacks. */ private final Activity activity; /** The code used to tell the activity that it is an auth result. */ private final int code; /** Extras to pass into the getCredentials function. */ private final Bundle extras; /** True if the account must be a Google account (not a domain account). */ private final boolean requireGoogle; /** The name of the service to authorize for. */ private final String service; /** The handler to call when a new auth token is fetched. */ private AuthCallback authCallback; /** The most recently fetched auth token or null if none is available. */ private String authToken; /** * AuthManager requires many of the same parameters as * {@link GoogleLoginServiceHelper#getCredentials(Activity, int, Bundle, * boolean, String, boolean)}. The activity must have * a handler in {@link Activity#onActivityResult} that calls * {@link #authResult(int, Intent)} if the request code is the code given * here. * * @param activity An activity with a handler in * {@link Activity#onActivityResult} that calls * {@link #authResult(int, Intent)} when {@literal code} is the request * code * @param code The request code to pass to * {@link Activity#onActivityResult} when * {@link #authResult(int, Intent)} should be called * @param extras A {@link Bundle} of extras for * {@link GoogleLoginServiceHelper} * @param requireGoogle True if the account must be a Google account * @param service The name of the service to authenticate as */ public AuthManagerOld(Activity activity, int code, Bundle extras, boolean requireGoogle, String service) { this.activity = activity; this.code = code; this.extras = extras; this.requireGoogle = requireGoogle; this.service = service; } @Override public void doLogin(AuthCallback callback, Object o) { authCallback = callback; activity.runOnUiThread(new LoginRunnable()); } /** * Runnable which actually gets login credentials. */ private class LoginRunnable implements Runnable { @Override public void run() { GoogleLoginServiceHelper.getCredentials( activity, code, extras, requireGoogle, service, true); } } @Override public void authResult(int resultCode, Intent results) { if (resultCode != Activity.RESULT_OK) { runAuthCallback(false); return; } authToken = results.getStringExtra(GoogleLoginServiceConstants.AUTHTOKEN_KEY); if (authToken == null) { // Retry, without prompting the user. GoogleLoginServiceHelper.getCredentials( activity, code, extras, requireGoogle, service, false); } else { // Notify all active listeners that we have a new auth token. runAuthCallback(true); } } private void runAuthCallback(boolean success) { authCallback.onAuthResult(success); authCallback = null; } @Override public String getAuthToken() { return authToken; } @Override public void invalidateAndRefresh(AuthCallback callback) { authCallback = callback; activity.runOnUiThread(new Runnable() { public void run() { GoogleLoginServiceHelper.invalidateAuthToken(activity, code, authToken); } }); } @Override public Object getAccountObject(String accountName, String accountType) { throw new UnsupportedOperationException("Legacy auth manager knows nothing about accounts"); } }
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.io; import android.content.Intent; /** * This interface describes a class that will fetch and maintain a Google * authentication token. * * @author Sandor Dornbush */ public interface AuthManager { /** * Callback for authentication token retrieval operations. */ public interface AuthCallback { /** * Indicates that we're done fetching an auth token. * * @param success if true, indicates we have the requested auth token available * to be retrieved using {@link AuthManager#getAuthToken} */ void onAuthResult(boolean success); } /** * Initializes the login process. The user should be asked to login if they * haven't already. The {@link AuthCallback} provided will be executed when the * auth token fetching is done (successfully or not). * * @param whenFinished A {@link AuthCallback} to execute when the auth token * fetching is done */ void doLogin(AuthCallback whenFinished, Object o); /** * The {@link android.app.Activity} owner of this class should call this * function when it gets {@link android.app.Activity#onActivityResult} with * the request code passed into the constructor. The resultCode and results * should come directly from the {@link android.app.Activity#onActivityResult} * function. This function will return true if an auth token was successfully * fetched or the process is not finished. * * @param resultCode The result code passed in to the * {@link android.app.Activity}'s * {@link android.app.Activity#onActivityResult} function * @param results The data passed in to the {@link android.app.Activity}'s * {@link android.app.Activity#onActivityResult} function */ void authResult(int resultCode, Intent results); /** * Returns the current auth token. Response may be null if no valid auth * token has been fetched. * * @return The current auth token or null if no auth token has been * fetched */ String getAuthToken(); /** * Invalidates the existing auth token and request a new one. The * {@link Runnable} provided will be executed when the new auth token is * successfully fetched. * * @param whenFinished A {@link Runnable} to execute when a new auth token * is successfully fetched */ void invalidateAndRefresh(AuthCallback whenFinished); /** * Returns an object that represents the given account, if possible. * * @param accountName the name of the account * @param accountType the type of the account * @return the account object */ Object getAccountObject(String accountName, String accountType); }
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.io.backup; import static com.google.android.apps.mytracks.content.ContentTypeIds.*; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; public class BackupColumns { /** Columns that go into the backup. */ public static final String[] POINTS_BACKUP_COLUMNS = { TrackPointsColumns._ID, TrackPointsColumns.TRACKID, TrackPointsColumns.LATITUDE, TrackPointsColumns.LONGITUDE, TrackPointsColumns.ALTITUDE, TrackPointsColumns.BEARING, TrackPointsColumns.TIME, TrackPointsColumns.ACCURACY, TrackPointsColumns.SPEED, TrackPointsColumns.SENSOR }; public static final byte[] POINTS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, BLOB_TYPE_ID }; public static final String[] TRACKS_BACKUP_COLUMNS = { TracksColumns._ID, TracksColumns.NAME, TracksColumns.DESCRIPTION, TracksColumns.CATEGORY, TracksColumns.STARTID, TracksColumns.STOPID, TracksColumns.STARTTIME, TracksColumns.STOPTIME, TracksColumns.NUMPOINTS, TracksColumns.TOTALDISTANCE, TracksColumns.TOTALTIME, TracksColumns.MOVINGTIME, TracksColumns.AVGSPEED, TracksColumns.AVGMOVINGSPEED, TracksColumns.MAXSPEED, TracksColumns.MINELEVATION, TracksColumns.MAXELEVATION, TracksColumns.ELEVATIONGAIN, TracksColumns.MINGRADE, TracksColumns.MAXGRADE, TracksColumns.MINLAT, TracksColumns.MAXLAT, TracksColumns.MINLON, TracksColumns.MAXLON, TracksColumns.MAPID, TracksColumns.TABLEID}; public static final byte[] TRACKS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID}; public static final String[] WAYPOINTS_BACKUP_COLUMNS = { WaypointsColumns._ID, WaypointsColumns.TRACKID, WaypointsColumns.NAME, WaypointsColumns.DESCRIPTION, WaypointsColumns.CATEGORY, WaypointsColumns.ICON, WaypointsColumns.TYPE, WaypointsColumns.LENGTH, WaypointsColumns.DURATION, WaypointsColumns.STARTTIME, WaypointsColumns.STARTID, WaypointsColumns.STOPID, WaypointsColumns.LATITUDE, WaypointsColumns.LONGITUDE, WaypointsColumns.ALTITUDE, WaypointsColumns.BEARING, WaypointsColumns.TIME, WaypointsColumns.ACCURACY, WaypointsColumns.SPEED, WaypointsColumns.TOTALDISTANCE, WaypointsColumns.TOTALTIME, WaypointsColumns.MOVINGTIME, WaypointsColumns.AVGSPEED, WaypointsColumns.AVGMOVINGSPEED, WaypointsColumns.MAXSPEED, WaypointsColumns.MINELEVATION, WaypointsColumns.MAXELEVATION, WaypointsColumns.ELEVATIONGAIN, WaypointsColumns.MINGRADE, WaypointsColumns.MAXGRADE }; public static final byte[] WAYPOINTS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID }; }
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.io.backup; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.util.FileUtils; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * Handler for writing or reading single-file backups. * * @author Rodrigo Damazio */ class ExternalFileBackup { // Filename format - in UTC private static final SimpleDateFormat BACKUP_FILENAME_FORMAT = new SimpleDateFormat("'backup-'yyyy-MM-dd_HH-mm-ss'.zip'"); static { BACKUP_FILENAME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final String BACKUPS_SUBDIR = "backups"; private static final int BACKUP_FORMAT_VERSION = 1; private static final String ZIP_ENTRY_NAME = "backup.mytracks.v" + BACKUP_FORMAT_VERSION; private static final int COMPRESSION_LEVEL = 8; private final Context context; private final FileUtils fileUtils; public ExternalFileBackup(Context context, FileUtils fileUtils) { this.context = context; this.fileUtils = fileUtils; } /** * Returns whether the backups directory is (or can be made) available. * * @param create whether to try creating the directory if it doesn't exist */ public boolean isBackupsDirectoryAvailable(boolean create) { return getBackupsDirectory(create) != null; } /** * Returns the backup directory, or null if not available. * * @param create whether to try creating the directory if it doesn't exist */ private File getBackupsDirectory(boolean create) { String dirName = fileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR); final File dir = new File(dirName); Log.d(Constants.TAG, "Dir: " + dir.getAbsolutePath()); if (create) { // Try to create - if that fails, return null return fileUtils.ensureDirectoryExists(dir) ? dir : null; } else { // Return it if it already exists, otherwise return null return dir.isDirectory() ? dir : null; } } /** * Returns a list of available backups to be restored. */ public Date[] getAvailableBackups() { File dir = getBackupsDirectory(false); if (dir == null) { return null; } String[] fileNames = dir.list(); List<Date> backupDates = new ArrayList<Date>(fileNames.length); for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; try { backupDates.add(BACKUP_FILENAME_FORMAT.parse(fileName)); } catch (ParseException e) { // Not a backup file, ignore } } return backupDates.toArray(new Date[backupDates.size()]); } /** * Writes the backup to the default file. */ public void writeToDefaultFile() throws IOException { writeToFile(getFileForDate(new Date())); } /** * Restores the backup from the given date. */ public void restoreFromDate(Date when) throws IOException { restoreFromFile(getFileForDate(when)); } /** * Produces the proper file descriptor for the given backup date. */ private File getFileForDate(Date when) { File dir = getBackupsDirectory(false); String fileName = BACKUP_FILENAME_FORMAT.format(when); File file = new File(dir, fileName); return file; } /** * Synchronously writes a backup to the given file. */ private void writeToFile(File outputFile) throws IOException { Log.d(Constants.TAG, "Writing backup to file " + outputFile.getAbsolutePath()); // Create all the auxiliary classes that will do the writing PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); DatabaseDumper trackDumper = new DatabaseDumper( BackupColumns.TRACKS_BACKUP_COLUMNS, BackupColumns.TRACKS_BACKUP_COLUMN_TYPES, false); DatabaseDumper waypointDumper = new DatabaseDumper( BackupColumns.WAYPOINTS_BACKUP_COLUMNS, BackupColumns.WAYPOINTS_BACKUP_COLUMN_TYPES, false); DatabaseDumper pointDumper = new DatabaseDumper( BackupColumns.POINTS_BACKUP_COLUMNS, BackupColumns.POINTS_BACKUP_COLUMN_TYPES, false); // Open the target for writing FileOutputStream outputStream = new FileOutputStream(outputFile); ZipOutputStream compressedStream = new ZipOutputStream(outputStream); compressedStream.setLevel(COMPRESSION_LEVEL); compressedStream.putNextEntry(new ZipEntry(ZIP_ENTRY_NAME)); DataOutputStream outWriter = new DataOutputStream(compressedStream); try { // Dump the entire contents of each table ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query( TracksColumns.CONTENT_URI, null, null, null, null); try { trackDumper.writeAllRows(tracksCursor, outWriter); } finally { tracksCursor.close(); } Cursor waypointsCursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null, null, null, null); try { waypointDumper.writeAllRows(waypointsCursor, outWriter); } finally { waypointsCursor.close(); } Cursor pointsCursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, null, null, null); try { pointDumper.writeAllRows(pointsCursor, outWriter); } finally { pointsCursor.close(); } // Dump preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.exportPreferences(preferences, outWriter); } catch (IOException e) { // We tried to delete the partially created file, but do nothing // if that also fails. if (!outputFile.delete()) { Log.w(TAG, "Failed to delete file " + outputFile.getAbsolutePath()); } throw e; } finally { compressedStream.closeEntry(); compressedStream.close(); } } /** * Synchronously restores the backup from the given file. */ private void restoreFromFile(File inputFile) throws IOException { Log.d(Constants.TAG, "Restoring from file " + inputFile.getAbsolutePath()); PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); ContentResolver resolver = context.getContentResolver(); DatabaseImporter trackImporter = new DatabaseImporter(TracksColumns.CONTENT_URI, resolver, false); DatabaseImporter waypointImporter = new DatabaseImporter(WaypointsColumns.CONTENT_URI, resolver, false); DatabaseImporter pointImporter = new DatabaseImporter(TrackPointsColumns.CONTENT_URI, resolver, false); ZipFile zipFile = new ZipFile(inputFile, ZipFile.OPEN_READ); ZipEntry zipEntry = zipFile.getEntry(ZIP_ENTRY_NAME); if (zipEntry == null) { throw new IOException("Invalid backup ZIP file"); } InputStream compressedStream = zipFile.getInputStream(zipEntry); DataInputStream reader = new DataInputStream(compressedStream); try { // Delete all previous contents of the tables and preferences. resolver.delete(TracksColumns.CONTENT_URI, null, null); resolver.delete(TrackPointsColumns.CONTENT_URI, null, null); resolver.delete(WaypointsColumns.CONTENT_URI, null, null); // Import the new contents of each table trackImporter.importAllRows(reader); waypointImporter.importAllRows(reader); pointImporter.importAllRows(reader); // Restore preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.importPreferences(reader, preferences); } finally { compressedStream.close(); zipFile.close(); } } }
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.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import com.google.android.apps.mytracks.util.ApiFeatures; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; /** * Helper for backing up and restoring shared preferences. * * @author Rodrigo Damazio */ class PreferenceBackupHelper { private static final int BUFFER_SIZE = 2048; /** * Exports all shared preferences from the given object as a byte array. * * @param preferences the preferences to export * @return the corresponding byte array * @throws IOException if there are any errors while writing to the byte array */ public byte[] exportPreferences(SharedPreferences preferences) throws IOException { ByteArrayOutputStream bufStream = new ByteArrayOutputStream(BUFFER_SIZE); DataOutputStream outWriter = new DataOutputStream(bufStream); exportPreferences(preferences, outWriter); return bufStream.toByteArray(); } /** * Exports all shared preferences from the given object into the given output * stream. * * @param preferences the preferences to export * @param outWriter the stream to write them to * @throws IOException if there are any errors while writing the output */ public void exportPreferences( SharedPreferences preferences, DataOutputStream outWriter) throws IOException { Map<String, ?> values = preferences.getAll(); outWriter.writeInt(values.size()); for (Map.Entry<String, ?> entry : values.entrySet()) { writePreference(entry.getKey(), entry.getValue(), outWriter); } outWriter.flush(); } /** * Imports all preferences from the given byte array. * * @param data the byte array to read preferences from * @param preferences the shared preferences to edit * @throws IOException if there are any errors while reading */ public void importPreferences(byte[] data, SharedPreferences preferences) throws IOException { ByteArrayInputStream bufStream = new ByteArrayInputStream(data); DataInputStream reader = new DataInputStream(bufStream); importPreferences(reader, preferences); } /** * Imports all preferences from the given stream. * * @param reader the stream to read from * @param preferences the shared preferences to edit * @throws IOException if there are any errors while reading */ public void importPreferences(DataInputStream reader, SharedPreferences preferences) throws IOException { Editor editor = preferences.edit(); editor.clear(); int numPreferences = reader.readInt(); for (int i = 0; i < numPreferences; i++) { String name = reader.readUTF(); byte typeId = reader.readByte(); readAndSetPreference(name, typeId, reader, editor); } ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } /** * Reads a single preference and sets it into the given editor. * * @param name the name of the preference to read * @param typeId the type ID of the preference to read * @param reader the reader to read from * @param editor the editor to set the preference in * @throws IOException if there are errors while reading */ private void readAndSetPreference(String name, byte typeId, DataInputStream reader, Editor editor) throws IOException { switch (typeId) { case ContentTypeIds.BOOLEAN_TYPE_ID: editor.putBoolean(name, reader.readBoolean()); return; case ContentTypeIds.LONG_TYPE_ID: editor.putLong(name, reader.readLong()); return; case ContentTypeIds.FLOAT_TYPE_ID: editor.putFloat(name, reader.readFloat()); return; case ContentTypeIds.INT_TYPE_ID: editor.putInt(name, reader.readInt()); return; case ContentTypeIds.STRING_TYPE_ID: editor.putString(name, reader.readUTF()); return; } } /** * Writes a single preference. * * @param name the name of the preference to write * @param value the correctly-typed value of the preference * @param writer the writer to write to * @throws IOException if there are errors while writing */ private void writePreference(String name, Object value, DataOutputStream writer) throws IOException { writer.writeUTF(name); if (value instanceof Boolean) { writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID); writer.writeBoolean((Boolean) value); } else if (value instanceof Integer) { writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeInt((Integer) value); } else if (value instanceof Long) { writer.writeByte(ContentTypeIds.LONG_TYPE_ID); writer.writeLong((Long) value); } else if (value instanceof Float) { writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID); writer.writeFloat((Float) value); } else if (value instanceof String) { writer.writeByte(ContentTypeIds.STRING_TYPE_ID); writer.writeUTF((String) value); } else { throw new IllegalArgumentException( "Type " + value.getClass().getName() + " not supported"); } } }
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.io.backup; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracks; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.util.Log; import android.widget.Toast; import java.io.IOException; import java.text.DateFormat; import java.util.Arrays; import java.util.Comparator; import java.util.Date; /** * Helper which shows a UI for writing or restoring a backup, * and calls the appropriate handler for actually executing those * operations. * * @author Rodrigo Damazio */ public class BackupActivityHelper { // Since the user sees this format, we use the local timezone private static final DateFormat DISPLAY_BACKUP_FORMAT = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT); private static final Comparator<Date> REVERSE_DATE_ORDER = new Comparator<Date>() { @Override public int compare(Date s1, Date s2) { return s2.compareTo(s1); } }; private final FileUtils fileUtils; private final ExternalFileBackup backup; private final Activity activity; public BackupActivityHelper(Activity activity) { this.activity = activity; this.fileUtils = new FileUtils(); this.backup = new ExternalFileBackup(activity, fileUtils); } /** * Writes a full backup to the default file. * This shows the results to the user. */ public void writeBackup() { if (!fileUtils.isSdCardAvailable()) { showToast(R.string.sd_card_error_no_storage); return; } if (!backup.isBackupsDirectoryAvailable(true)) { showToast(R.string.sd_card_error_create_dir); return; } final ProgressDialog progressDialog = ProgressDialog.show( activity, activity.getString(R.string.generic_progress_title), activity.getString(R.string.settings_backup_now_progress_message), true); // Do the writing in another thread new Thread() { @Override public void run() { try { backup.writeToDefaultFile(); showToast(R.string.sd_card_success_write_file); } catch (IOException e) { Log.e(Constants.TAG, "Failed to write backup", e); showToast(R.string.sd_card_error_write_file); } finally { dismissDialog(progressDialog); } } }.start(); } /** * Restores a full backup from the SD card. * The user will be given a choice of which backup to restore as well as a * confirmation dialog. */ public void restoreBackup() { // Get the list of existing backups if (!fileUtils.isSdCardAvailable()) { showToast(R.string.sd_card_error_no_storage); return; } if (!backup.isBackupsDirectoryAvailable(false)) { showToast(R.string.settings_backup_restore_no_backup); return; } final Date[] backupDates = backup.getAvailableBackups(); if (backupDates == null || backupDates.length == 0) { showToast(R.string.settings_backup_restore_no_backup); return; } Arrays.sort(backupDates, REVERSE_DATE_ORDER); // Show a confirmation dialog Builder confirmationDialogBuilder = new AlertDialog.Builder(activity); confirmationDialogBuilder.setMessage(R.string.settings_backup_restore_confirm_message); confirmationDialogBuilder.setCancelable(true); confirmationDialogBuilder.setPositiveButton(android.R.string.yes, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pickBackupForRestore(backupDates); } }); confirmationDialogBuilder.setNegativeButton(android.R.string.no, null); confirmationDialogBuilder.create().show(); } /** * Shows a backup list for the user to pick, then restores it. * * @param backupDates the list of available backup files */ private void pickBackupForRestore(final Date[] backupDates) { if (backupDates.length == 1) { // Only one choice, don't bother showing the list restoreFromDateAsync(backupDates[0]); return; } // Make a user-visible version of the backup filenames final String backupDateStrs[] = new String[backupDates.length]; for (int i = 0; i < backupDates.length; i++) { backupDateStrs[i] = DISPLAY_BACKUP_FORMAT.format(backupDates[i]); } // Show a dialog for the user to pick which backup to restore Builder dialogBuilder = new AlertDialog.Builder(activity); dialogBuilder.setCancelable(true); dialogBuilder.setTitle(R.string.settings_backup_restore_select_title); dialogBuilder.setItems(backupDateStrs, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // User picked to restore this one restoreFromDateAsync(backupDates[which]); } }); dialogBuilder.create().show(); } /** * Shows a progress dialog, then starts restoring the backup asynchronously. * * @param date the date */ private void restoreFromDateAsync(final Date date) { // Show a progress dialog ProgressDialog.show( activity, activity.getString(R.string.generic_progress_title), activity.getString(R.string.settings_backup_restore_progress_message), true); // Do the actual importing in another thread (don't block the UI) new Thread() { @Override public void run() { try { backup.restoreFromDate(date); showToast(R.string.sd_card_success_read_file); } catch (IOException e) { Log.e(Constants.TAG, "Failed to restore backup", e); showToast(R.string.sd_card_error_read_file); } finally { // Data may have been restored, "reboot" the app to catch it restartApplication(); } } }.start(); } /** * Restarts My Tracks completely. * This forces any modified data to be re-read. */ private void restartApplication() { Intent intent = new Intent(activity, MyTracks.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); } /** * Shows a toast with the given contents. */ private void showToast(final int resId) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, resId, Toast.LENGTH_LONG).show(); } }); } /** * Safely dismisses the given dialog. */ private void dismissDialog(final Dialog dialog) { activity.runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); } }); } }
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.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.database.Cursor; import android.database.MergeCursor; import java.io.DataOutputStream; import java.io.IOException; /** * Database dumper which is able to write only part of the database * according to some query. * * This dumper is symmetrical to {@link DatabaseImporter}. * * @author Rodrigo Damazio */ class DatabaseDumper { /** The names of the columns being dumped. */ private final String[] columnNames; /** The types of the columns being dumped. */ private final byte[] columnTypes; /** Whether to output null fields. */ private final boolean outputNullFields; // Temporary state private int[] columnIndices; private boolean[] hasFields; public DatabaseDumper(String[] columnNames, byte[] columnTypes, boolean outputNullFields) { if (columnNames.length != columnTypes.length) { throw new IllegalArgumentException("Names don't match types"); } this.columnNames = columnNames; this.columnTypes = columnTypes; this.outputNullFields = outputNullFields; } /** * Writes the header plus all rows that can be read from the given cursor. * This assumes the cursor will have the same column and column indices on * every row (and thus may not work with a {@link MergeCursor}). */ public void writeAllRows(Cursor cursor, DataOutputStream writer) throws IOException { writeHeaders(cursor, cursor.getCount(), writer); if (!cursor.moveToFirst()) { return; } do { writeOneRow(cursor, writer); } while (cursor.moveToNext()); } /** * Writes just the headers for the data that will come from the given cursor. * The headers include column information and the number of rows that will be * written. * * @param cursor the cursor to get columns from * @param numRows the number of rows that will be later written * @param writer the output to write to * @throws IOException if there are errors while writing */ public void writeHeaders(Cursor cursor, int numRows, DataOutputStream writer) throws IOException { initializeCachedValues(cursor); writeQueryMetadata(numRows, writer); } /** * Writes the current row from the cursor. The cursor is not advanced. * This must be called after {@link #writeHeaders}. * * @param cursor the cursor to write data from * @param writer the output to write to * @throws IOException if there are any errors while writing */ public void writeOneRow(Cursor cursor, DataOutputStream writer) throws IOException { if (columnIndices == null) { throw new IllegalStateException( "Cannot write rows before writing the header"); } if (columnIndices.length > Long.SIZE) { throw new IllegalArgumentException("Too many fields"); } // Build a bitmap of which fields are present long fields = 0; for (int i = 0; i < columnIndices.length; i++) { hasFields[i] = !cursor.isNull(columnIndices[i]); fields |= (hasFields[i] ? 1 : 0) << i; } writer.writeLong(fields); // Actually write the present fields for (int i = 0; i < columnIndices.length; i++) { if (hasFields[i]) { writeCell(columnIndices[i], columnTypes[i], cursor, writer); } else if (outputNullFields) { writeDummyCell(columnTypes[i], writer); } } } /** * Initializes the column indices and other temporary state for reading from * the given cursor. */ private void initializeCachedValues(Cursor cursor) { // These indices are constant for every row (unless we're fed a MergeCursor) if (cursor instanceof MergeCursor) { throw new IllegalArgumentException("Cannot use a MergeCursor"); } columnIndices = new int[columnNames.length]; for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; columnIndices[i] = cursor.getColumnIndexOrThrow(columnName); } hasFields = new boolean[columnIndices.length]; } /** * Writes metadata about the query to be dumped. * * @param numRows the number of rows that will be dumped * @param writer the output to write to * @throws IOException if there are any errors while writing */ private void writeQueryMetadata( int numRows, DataOutputStream writer) throws IOException { // Write column data writer.writeInt(columnNames.length); for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; byte columnType = columnTypes[i]; writer.writeUTF(columnName); writer.writeByte(columnType); } // Write the number of rows writer.writeInt(numRows); } /** * Writes a single cell of the database to the output. * * @param columnIdx the column index to read from * @param columnTypeId the type of the column to be read * @param cursor the cursor to read from * @param writer the output to write to * @throws IOException if there are any errors while writing */ private void writeCell( int columnIdx, byte columnTypeId, Cursor cursor, DataOutputStream writer) throws IOException { switch (columnTypeId) { case ContentTypeIds.LONG_TYPE_ID: writer.writeLong(cursor.getLong(columnIdx)); return; case ContentTypeIds.DOUBLE_TYPE_ID: writer.writeDouble(cursor.getDouble(columnIdx)); return; case ContentTypeIds.FLOAT_TYPE_ID: writer.writeFloat(cursor.getFloat(columnIdx)); return; case ContentTypeIds.BOOLEAN_TYPE_ID: writer.writeBoolean(cursor.getInt(columnIdx) != 0); return; case ContentTypeIds.INT_TYPE_ID: writer.writeInt(cursor.getInt(columnIdx)); return; case ContentTypeIds.STRING_TYPE_ID: writer.writeUTF(cursor.getString(columnIdx)); return; case ContentTypeIds.BLOB_TYPE_ID: { byte[] blob = cursor.getBlob(columnIdx); writer.writeInt(blob.length); writer.write(blob); return; } default: throw new IllegalArgumentException( "Type " + columnTypeId + " not supported"); } } /** * Writes a dummy cell value to the output. * * @param columnTypeId the type of the value to write * @throws IOException if there are any errors while writing */ private void writeDummyCell(byte columnTypeId, DataOutputStream writer) throws IOException { switch (columnTypeId) { case ContentTypeIds.LONG_TYPE_ID: writer.writeLong(0L); return; case ContentTypeIds.DOUBLE_TYPE_ID: writer.writeDouble(0.0); return; case ContentTypeIds.FLOAT_TYPE_ID: writer.writeFloat(0.0f); return; case ContentTypeIds.BOOLEAN_TYPE_ID: writer.writeBoolean(false); return; case ContentTypeIds.INT_TYPE_ID: writer.writeInt(0); return; case ContentTypeIds.STRING_TYPE_ID: writer.writeUTF(""); return; case ContentTypeIds.BLOB_TYPE_ID: writer.writeInt(0); return; default: throw new IllegalArgumentException( "Type " + columnTypeId + " not supported"); } } }
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.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.content.ContentResolver; import android.content.ContentValues; import android.net.Uri; import java.io.DataInputStream; import java.io.IOException; /** * Database importer which reads values written by {@link DatabaseDumper}. * * @author Rodrigo Damazio */ public class DatabaseImporter { /** Maximum number of entries in a bulk insertion */ private static final int DEFAULT_BULK_SIZE = 1024; private final Uri destinationUri; private final ContentResolver resolver; private final boolean readNullFields; private final int bulkSize; // Metadata read from the reader private String[] columnNames; private byte[] columnTypes; public DatabaseImporter(Uri destinationUri, ContentResolver resolver, boolean readNullFields) { this(destinationUri, resolver, readNullFields, DEFAULT_BULK_SIZE); } protected DatabaseImporter(Uri destinationUri, ContentResolver resolver, boolean readNullFields, int bulkSize) { this.destinationUri = destinationUri; this.resolver = resolver; this.readNullFields = readNullFields; this.bulkSize = bulkSize; } /** * Reads the header which includes metadata about the table being imported. * * @throws IOException if there are any problems while reading */ private void readHeaders(DataInputStream reader) throws IOException { int numColumns = reader.readInt(); columnNames = new String[numColumns]; columnTypes = new byte[numColumns]; for (int i = 0; i < numColumns; i++) { columnNames[i] = reader.readUTF(); columnTypes[i] = reader.readByte(); } } /** * Imports all rows from the reader into the database. * Insertion is done in bulks for efficiency. * * @throws IOException if there are any errors while reading */ public void importAllRows(DataInputStream reader) throws IOException { readHeaders(reader); ContentValues[] valueBulk = new ContentValues[bulkSize]; int numValues = 0; int numRows = reader.readInt(); int numColumns = columnNames.length; // For each row for (int r = 0; r < numRows; r++) { if (valueBulk[numValues] == null) { valueBulk[numValues] = new ContentValues(numColumns); } else { // Reuse values objects valueBulk[numValues].clear(); } // Read the fields bitmap long fields = reader.readLong(); for (int c = 0; c < numColumns; c++) { if ((fields & 1) == 1) { // Field is present, read into values readOneCell(columnNames[c], columnTypes[c], valueBulk[numValues], reader); } else if (readNullFields) { // Field not present but still written, read and discard readOneCell(columnNames[c], columnTypes[c], null, reader); } fields >>= 1; } numValues++; // If we have enough values, flush them as a bulk insertion if (numValues >= bulkSize) { doBulkInsert(valueBulk); numValues = 0; } } // Do a final bulk insert with the leftovers if (numValues > 0) { ContentValues[] leftovers = new ContentValues[numValues]; System.arraycopy(valueBulk, 0, leftovers, 0, numValues); doBulkInsert(leftovers); } } protected void doBulkInsert(ContentValues[] values) { resolver.bulkInsert(destinationUri, values); } /** * Reads a single cell from the reader. * * @param name the name of the column to be read * @param typeId the type ID of the column to be read * @param values the {@link ContentValues} object to put the read cell value * in - if null, the value is just discarded * @throws IOException if there are any problems while reading */ private void readOneCell(String name, byte typeId, ContentValues values, DataInputStream reader) throws IOException { switch (typeId) { case ContentTypeIds.BOOLEAN_TYPE_ID: { boolean value = reader.readBoolean(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.LONG_TYPE_ID: { long value = reader.readLong(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.DOUBLE_TYPE_ID: { double value = reader.readDouble(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.FLOAT_TYPE_ID: { Float value = reader.readFloat(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.INT_TYPE_ID: { int value = reader.readInt(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.STRING_TYPE_ID: { String value = reader.readUTF(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.BLOB_TYPE_ID: { int blobLength = reader.readInt(); if (blobLength != 0) { byte[] blob = new byte[blobLength]; int readBytes = reader.read(blob, 0, blobLength); if (readBytes != blobLength) { throw new IOException(String.format( "Short read on column %s; expected %d bytes, read %d", name, blobLength, readBytes)); } if (values != null) { values.put(name, blob); } } return; } default: throw new IOException("Read unknown type " + typeId); } } }
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.io.backup; import com.google.android.apps.mytracks.Constants; import android.app.backup.BackupAgent; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.content.Context; import android.content.SharedPreferences; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.IOException; /** * Backup agent used to backup and restore all preferences. * We use a regular {@link BackupAgent} instead of the convenient helpers in * order to be future-proof (assuming we'll want to back up tracks later). * * @author Rodrigo Damazio */ public class MyTracksBackupAgent extends BackupAgent { private static final String PREFERENCES_ENTITY = "prefs"; @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { Log.i(Constants.TAG, "Performing backup"); SharedPreferences preferences = this.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); backupPreferences(data, preferences); Log.i(Constants.TAG, "Backup complete"); } private void backupPreferences(BackupDataOutput data, SharedPreferences preferences) throws IOException { PreferenceBackupHelper preferenceDumper = createPreferenceBackupHelper(); byte[] dumpedContents = preferenceDumper.exportPreferences(preferences); data.writeEntityHeader(PREFERENCES_ENTITY, dumpedContents.length); data.writeEntityData(dumpedContents, dumpedContents.length); } protected PreferenceBackupHelper createPreferenceBackupHelper() { return new PreferenceBackupHelper(); } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { Log.i(Constants.TAG, "Restoring from backup"); while (data.readNextHeader()) { String key = data.getKey(); Log.d(Constants.TAG, "Restoring entity " + key); if (key.equals(PREFERENCES_ENTITY)) { restorePreferences(data); } else { Log.e(Constants.TAG, "Found unknown backup entity: " + key); data.skipEntityData(); } } Log.i(Constants.TAG, "Done restoring from backup"); } /** * Restores all preferences from the backup. * * @param data the backup data to read from * @throws IOException if there are any errors while reading */ private void restorePreferences(BackupDataInput data) throws IOException { int dataSize = data.getDataSize(); byte[] dataBuffer = new byte[dataSize]; int read = data.readEntityData(dataBuffer, 0, dataSize); if (read != dataSize) { throw new IOException("Failed to read all the preferences data"); } SharedPreferences preferences = this.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); PreferenceBackupHelper importer = createPreferenceBackupHelper(); importer.importPreferences(dataBuffer, preferences); } }
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.io.backup; import android.app.backup.BackupManager; import android.content.Context; import android.content.SharedPreferences; /** * Implementation of {@link BackupPreferencesListener} that calls the * {@link BackupManager}. * * @author Jimmy Shih */ public class BackupPreferencesListenerImpl implements BackupPreferencesListener { private final BackupManager backupManager; public BackupPreferencesListenerImpl(Context context) { this.backupManager = new BackupManager(context); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { backupManager.dataChanged(); } }
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.io.backup; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; /** * Shared preferences listener which notifies the backup system about new data * being available for backup. * * @author Rodrigo Damazio */ public interface BackupPreferencesListener extends OnSharedPreferenceChangeListener { }
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.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.SystemUtils; import android.content.Context; import android.location.Location; import android.os.Build; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.Date; import java.util.Locale; /** * Write out a a track in the Garmin training center database, tcx format. * As defined by: * http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 * * The TCX file written by this class has been verified as compatible with * Garmin Training Center 3.5.3. * * @author Sandor Dornbush * @author Dominik Ršttsches */ public class TcxTrackWriter implements TrackFormatWriter { // These are the only sports allowed by the TCX v2 specification for fields // of type Sport_t. private static final String TCX_SPORT_BIKING = "Biking"; private static final String TCX_SPORT_RUNNING = "Running"; private static final String TCX_SPORT_OTHER = "Other"; // Values for fields of type Build_t/Type. private static final String TCX_TYPE_RELEASE = "Release"; private static final String TCX_TYPE_INTERNAL = "Internal"; private final Context context; private PrintWriter pw = null; private Track track; // Determines whether to encode cadence value as running or cycling cadence. private boolean sportIsCycling; public TcxTrackWriter(Context context) { this.context = context; } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); this.sportIsCycling = categoryToTcxSport(track.getCategory()).equals(TCX_SPORT_BIKING); } @Override public void close() { if (pw != null) { pw.close(); pw = null; } } @Override public String getExtension() { return TrackFileFormat.TCX.getExtension(); } @Override public void writeHeader() { if (pw == null) { return; } pw.format("<?xml version=\"1.0\" encoding=\"%s\" standalone=\"no\" ?>\n", Charset.defaultCharset().name()); pw.print("<TrainingCenterDatabase "); pw.print("xmlns=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2\" "); pw.print("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "); pw.print("xsi:schemaLocation=\"http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 "); pw.println("http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd\">"); pw.println(); } @Override public void writeBeginTrack(Location firstPoint) { if (pw == null) { return; } String startTime = FileUtils.FILE_TIMESTAMP_FORMAT.format(track.getStatistics().getStartTime()); pw.println(" <Activities>"); pw.format(" <Activity Sport=\"%s\">\n", categoryToTcxSport(track.getCategory())); pw.format(" <Id>%s</Id>\n", startTime); pw.format(" <Lap StartTime=\"%s\">\n", startTime); pw.print(" <TotalTimeSeconds>"); pw.print(track.getStatistics().getTotalTime() / 1000); pw.println("</TotalTimeSeconds>"); pw.print(" <DistanceMeters>"); pw.print(track.getStatistics().getTotalDistance()); pw.println("</DistanceMeters>"); // TODO max speed etc. // Calories are a required element just put in 0. pw.print("<Calories>0</Calories>"); pw.println("<Intensity>Active</Intensity>"); pw.println("<TriggerMethod>Manual</TriggerMethod>"); } @Override public void writeOpenSegment() { if (pw != null) { pw.println(" <Track>"); } } @Override public void writeLocation(Location location) { if (pw == null) { return; } pw.println(" <Trackpoint>"); Date d = new Date(location.getTime()); pw.println(" <Time>" + FileUtils.FILE_TIMESTAMP_FORMAT.format(d) + "</Time>"); pw.println(" <Position>"); pw.print(" <LatitudeDegrees>"); pw.print(location.getLatitude()); pw.println("</LatitudeDegrees>"); pw.print(" <LongitudeDegrees>"); pw.print(location.getLongitude()); pw.println("</LongitudeDegrees>"); pw.println(" </Position>"); pw.print(" <AltitudeMeters>"); pw.print(location.getAltitude()); pw.println("</AltitudeMeters>"); if (location instanceof MyTracksLocation) { SensorDataSet sensorData = ((MyTracksLocation) location).getSensorDataSet(); if (sensorData != null) { if (sensorData.hasHeartRate() && sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorData.getHeartRate().hasValue()) { pw.print(" <HeartRateBpm>"); pw.print("<Value>"); pw.print(sensorData.getHeartRate().getValue()); pw.print("</Value>"); pw.println("</HeartRateBpm>"); } boolean cadenceAvailable = sensorData.hasCadence() && sensorData.getCadence().getState() == Sensor.SensorState.SENDING && sensorData.getCadence().hasValue(); // TCX Trackpoint_t contains a sequence. Thus, the legacy XML element // <Cadence> needs to be put before <Extensions>. // This field should only be used for the case that activity was marked as biking. // Otherwise cadence is interpreted as running cadence data which // is written in the <Extensions> as <RunCadence>. if (sportIsCycling && cadenceAvailable) { pw.print(" <Cadence>"); pw.print(Math.min(254, sensorData.getCadence().getValue())); pw.println("</Cadence>"); } boolean powerAvailable = sensorData.hasPower() && sensorData.getPower().getState() == Sensor.SensorState.SENDING && sensorData.getPower().hasValue(); if(powerAvailable || (!sportIsCycling && cadenceAvailable)) { pw.print(" <Extensions>"); pw.print("<TPX xmlns=\"http://www.garmin.com/xmlschemas/ActivityExtension/v2\">"); // RunCadence needs to be put before power in order to be understood // by Garmin Training Center. if (!sportIsCycling && cadenceAvailable) { pw.print("<RunCadence>"); pw.print(Math.min(254, sensorData.getCadence().getValue())); pw.print("</RunCadence>"); } if (powerAvailable) { pw.print("<Watts>"); pw.print(sensorData.getPower().getValue()); pw.print("</Watts>"); } pw.println("</TPX></Extensions>"); } } } pw.println(" </Trackpoint>"); } @Override public void writeCloseSegment() { if (pw != null) { pw.println(" </Track>"); } } @Override public void writeEndTrack(Location lastPoint) { if (pw == null) { return; } pw.println(" </Lap>"); pw.print(" <Creator xsi:type=\"Device_t\">"); pw.format("<Name>My Tracks running on %s</Name>\n", Build.MODEL); // The following code is correct. ID is inconsistently capitalized in the // TCX schema. pw.println("<UnitId>0</UnitId>"); pw.println("<ProductID>0</ProductID>"); writeVersion(); pw.println("</Creator>"); pw.println(" </Activity>"); pw.println(" </Activities>"); } @Override public void writeFooter() { if (pw == null) { return; } pw.println(" <Author xsi:type=\"Application_t\">"); // We put the version in the name because there isn't a better place for // it. The TCX schema tightly defined the Version tag, so we can't put it // there. They've similarly constrained the PartNumber tag, so it can't go // there either. pw.format("<Name>My Tracks %s by Google</Name>\n", SystemUtils.getMyTracksVersion(context)); pw.println("<Build>"); writeVersion(); pw.format("<Type>%s</Type>\n", SystemUtils.isRelease(context) ? TCX_TYPE_RELEASE : TCX_TYPE_INTERNAL); pw.println("</Build>"); pw.format("<LangID>%s</LangID>\n", Locale.getDefault().getLanguage()); pw.println("<PartNumber>000-00000-00</PartNumber>"); pw.println("</Author>"); pw.println("</TrainingCenterDatabase>"); } @Override public void writeWaypoint(Waypoint waypoint) { // TODO Write out the waypoints somewhere. } private void writeVersion() { if (pw == null) { return; } // Splitting the myTracks version code into VersionMajor, VersionMinor and BuildMajor // to fit the integer type requirement for these fields in the TCX spec. // Putting a string like "x.x.x" into VersionMajor breaks XML validation. // We also set the BuildMinor version to 1 if this is a development build to // signify that this build is newer than the one associated with the // version code given in BuildMajor. String[] myTracksVersionComponents = SystemUtils.getMyTracksVersion(context).split("\\."); pw.println("<Version>"); pw.format("<VersionMajor>%d</VersionMajor>\n", Integer.valueOf(myTracksVersionComponents[0])); pw.format("<VersionMinor>%d</VersionMinor>\n", Integer.valueOf(myTracksVersionComponents[1])); // TCX schema says these are optional but http://connect.garmin.com only accepts // the TCX file when they are present. pw.format("<BuildMajor>%d</BuildMajor>\n", Integer.valueOf(myTracksVersionComponents[2])); pw.format("<BuildMinor>%d</BuildMinor>\n", SystemUtils.isRelease(context) ? 0 : 1); pw.println("</Version>"); } private String categoryToTcxSport(String category) { category = category.trim(); if (category.equalsIgnoreCase(TCX_SPORT_RUNNING)) { return TCX_SPORT_RUNNING; } else if (category.equalsIgnoreCase(TCX_SPORT_BIKING)) { return TCX_SPORT_BIKING; } else { return TCX_SPORT_OTHER; } } }
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.io.file; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Imports GPX XML files to the my tracks provider. * * TODO: Show progress indication to the user. * * @author Leif Hendrik Wilden * @author Steffen Horlacher * @author Rodrigo Damazio */ public class GpxImporter extends DefaultHandler { /* * GPX-XML tag names and attributes. */ private static final String TAG_TRACK = "trk"; private static final String TAG_TRACK_POINT = "trkpt"; private static final Object TAG_TRACK_SEGMENT = "trkseg"; private static final String TAG_NAME = "name"; private static final String TAG_DESCRIPTION = "desc"; private static final String TAG_ALTITUDE = "ele"; private static final String TAG_TIME = "time"; private static final String ATT_LAT = "lat"; private static final String ATT_LON = "lon"; /** * The maximum number of locations to buffer for bulk-insertion into the database. */ private static final int MAX_BUFFERED_LOCATIONS = 512; /** * Utilities for accessing the contnet provider. */ private final MyTracksProviderUtils providerUtils; /** * List of track ids written in the database. Only contains successfully * written tracks. */ private final List<Long> tracksWritten; /** * Contains the current elements content. */ private String content; /** * Currently reading location. */ private Location location; /** * Previous location, required for calculations. */ private Location lastLocation; /** * Currently reading track. */ private Track track; /** * Statistics builder for the current track. */ private TripStatisticsBuilder statsBuilder; /** * Buffer of locations to be bulk-inserted into the database. */ private Location[] bufferedPointInserts = new Location[MAX_BUFFERED_LOCATIONS]; /** * Number of locations buffered to be inserted into the database. */ private int numBufferedPointInserts = 0; /** * Number of locations already processed. */ private int numberOfLocations; /** * Number of segments already processed. */ private int numberOfSegments; /** * Used to identify if a track was written to the database but not yet * finished successfully. */ private boolean isCurrentTrackRollbackable; /** * Flag to indicate if we're inside a track's xml element. * Some sub elements like name may be used in other parts of the gpx file, * and we use this to ignore them. */ private boolean isInTrackElement; /** * Counter to find out which child level of track we are processing. */ private int trackChildDepth; /** * SAX-Locator to get current line information. */ private Locator locator; private Location lastSegmentLocation; /** * Reads GPS tracks from a GPX file and writes tracks and their coordinates to * the database. * * @param is a input steam with gpx-xml data * @return long[] array of track ids written in the database * @throws SAXException a parsing error * @throws ParserConfigurationException internal error * @throws IOException a file reading problem */ public static long[] importGPXFile(final InputStream is, final MyTracksProviderUtils providerUtils) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); GpxImporter handler = new GpxImporter(providerUtils); SAXParser parser = factory.newSAXParser(); long[] trackIds = null; try { long start = System.currentTimeMillis(); parser.parse(is, handler); long end = System.currentTimeMillis(); Log.d(Constants.TAG, "Total import time: " + (end - start) + "ms"); trackIds = handler.getImportedTrackIds(); } finally { // delete track if not finished handler.rollbackUnfinishedTracks(); } return trackIds; } /** * Constructor, requires providerUtils for writing tracks the database. */ public GpxImporter(MyTracksProviderUtils providerUtils) { this.providerUtils = providerUtils; tracksWritten = new ArrayList<Long>(); } @Override public void characters(char[] ch, int start, int length) throws SAXException { String newContent = new String(ch, start, length); if (content == null) { content = newContent; } else { // In 99% of the cases, a single call to this method will be made for each // sequence of characters we're interested in, so we'll rarely be // concatenating strings, thus not justifying the use of a StringBuilder. content += newContent; } } @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { if (isInTrackElement) { trackChildDepth++; if (localName.equals(TAG_TRACK_POINT)) { onTrackPointElementStart(attributes); } else if (localName.equals(TAG_TRACK_SEGMENT)) { onTrackSegmentElementStart(); } else if (localName.equals(TAG_TRACK)) { String msg = createErrorMessage("Invalid GPX-XML detected"); throw new SAXException(msg); } } else if (localName.equals(TAG_TRACK)) { isInTrackElement = true; trackChildDepth = 0; onTrackElementStart(); } } @Override public void endElement(String uri, String localName, String name) throws SAXException { if (!isInTrackElement) { content = null; return; } // process these elements only as sub-elements of track if (localName.equals(TAG_TRACK_POINT)) { onTrackPointElementEnd(); } else if (localName.equals(TAG_ALTITUDE)) { onAltitudeElementEnd(); } else if (localName.equals(TAG_TIME)) { onTimeElementEnd(); } else if (localName.equals(TAG_NAME)) { // we are only interested in the first level name element if (trackChildDepth == 1) { onNameElementEnd(); } } else if (localName.equals(TAG_DESCRIPTION)) { // we are only interested in the first level description element if (trackChildDepth == 1) { onDescriptionElementEnd(); } } else if (localName.equals(TAG_TRACK_SEGMENT)) { onTrackSegmentElementEnd(); } else if (localName.equals(TAG_TRACK)) { onTrackElementEnd(); isInTrackElement = false; trackChildDepth = 0; } trackChildDepth--; // reset element content content = null; } @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } /** * Create a new Track object and insert empty track in database. Track will be * updated with missing values later. */ private void onTrackElementStart() { track = new Track(); numberOfLocations = 0; Uri trackUri = providerUtils.insertTrack(track); long trackId = Long.parseLong(trackUri.getLastPathSegment()); track.setId(trackId); isCurrentTrackRollbackable = true; } private void onDescriptionElementEnd() { track.setDescription(content.toString().trim()); } private void onNameElementEnd() { track.setName(content.toString().trim()); } /** * Track segment started. */ private void onTrackSegmentElementStart() { if (numberOfSegments > 0) { // Add a segment separator: location = new Location(LocationManager.GPS_PROVIDER); location.setLatitude(100.0); location.setLongitude(100.0); location.setAltitude(0); if (lastLocation != null) { location.setTime(lastLocation.getTime()); } insertTrackPoint(location); lastLocation = location; lastSegmentLocation = null; location = null; } numberOfSegments++; } /** * Reads trackpoint attributes and assigns them to the current location. * * @param attributes xml attributes */ private void onTrackPointElementStart(Attributes attributes) throws SAXException { if (location != null) { String errorMsg = createErrorMessage("Found a track point inside another one."); throw new SAXException(errorMsg); } location = createLocationFromAttributes(attributes); } /** * Creates and returns a location with the position parsed from the given * attributes. * * @param attributes the attributes to parse * @return the created location * @throws SAXException if the attributes cannot be parsed */ private Location createLocationFromAttributes(Attributes attributes) throws SAXException { String latitude = attributes.getValue(ATT_LAT); String longitude = attributes.getValue(ATT_LON); if (latitude == null || longitude == null) { throw new SAXException(createErrorMessage("Point with no longitude or latitude")); } // create new location and set attributes Location loc = new Location(LocationManager.GPS_PROVIDER); try { loc.setLatitude(Double.parseDouble(latitude)); loc.setLongitude(Double.parseDouble(longitude)); } catch (NumberFormatException e) { String msg = createErrorMessage( "Unable to parse lat/long: " + latitude + "/" + longitude); throw new SAXException(msg, e); } return loc; } /** * Track point finished, write in database. * * @throws SAXException - thrown if track point is invalid */ private void onTrackPointElementEnd() throws SAXException { if (LocationUtils.isValidLocation(location)) { if (statsBuilder == null) { // first point did not have a time, start stats builder without it statsBuilder = new TripStatisticsBuilder(0); } statsBuilder.addLocation(location, location.getTime()); // insert in db insertTrackPoint(location); // first track point? if (lastLocation == null && numberOfSegments == 1) { track.setStartId(getLastPointId()); } lastLocation = location; lastSegmentLocation = location; location = null; } else { // invalid location - abort import String msg = createErrorMessage("Invalid location detected: " + location); throw new SAXException(msg); } } private void insertTrackPoint(Location loc) { bufferedPointInserts[numBufferedPointInserts] = loc; numBufferedPointInserts++; numberOfLocations++; if (numBufferedPointInserts >= MAX_BUFFERED_LOCATIONS) { flushPointInserts(); } } private void flushPointInserts() { if (numBufferedPointInserts <= 0) { return; } providerUtils.bulkInsertTrackPoints(bufferedPointInserts, numBufferedPointInserts, track.getId()); numBufferedPointInserts = 0; } /** * Track segment finished. */ private void onTrackSegmentElementEnd() { // Nothing to be done } /** * Track finished - update in database. */ private void onTrackElementEnd() { if (lastLocation != null) { flushPointInserts(); // Calculate statistics for the imported track and update statsBuilder.pauseAt(lastLocation.getTime()); track.setStopId(getLastPointId()); track.setNumberOfPoints(numberOfLocations); track.setStatistics(statsBuilder.getStatistics()); providerUtils.updateTrack(track); tracksWritten.add(track.getId()); isCurrentTrackRollbackable = false; lastSegmentLocation = null; lastLocation = null; statsBuilder = null; } else { // track contains no track points makes no real // sense to import it as we have no location // information -> roll back rollbackUnfinishedTracks(); } } /** * Setting time and doing additional calculations as this is the last value * required. Also sets the start time for track and statistics as there is no * start time in the track root element. * * @throws SAXException on parsing errors */ private void onTimeElementEnd() throws SAXException { if (location == null) { return; } // Parse the time long time; try { time = StringUtils.parseXmlDateTime(content.trim()); } catch (IllegalArgumentException e) { String msg = createErrorMessage("Unable to parse time: " + content); throw new SAXException(msg, e); } // Calculate derived attributes from previous point if (lastSegmentLocation != null) { long timeDifference = time - lastSegmentLocation.getTime(); // check for negative time change if (timeDifference < 0) { Log.w(Constants.TAG, "Found negative time change."); } else { // We don't have a speed and bearing in GPX, make something up from // the last two points. // TODO GPS points tend to have some inherent imprecision, // speed and bearing will likely be off, so the statistics for things like // max speed will also be off. float speed = location.distanceTo(lastLocation) * 1000.0f / timeDifference; location.setSpeed(speed); location.setBearing(lastSegmentLocation.bearingTo(location)); } } // Fill in the time location.setTime(time); // initialize start time with time of first track point if (statsBuilder == null) { statsBuilder = new TripStatisticsBuilder(time); } } private void onAltitudeElementEnd() throws SAXException { if (location != null) { try { location.setAltitude(Double.parseDouble(content)); } catch (NumberFormatException e) { String msg = createErrorMessage("Unable to parse altitude: " + content); throw new SAXException(msg, e); } } } /** * Deletes the last track if it was not completely imported. */ public void rollbackUnfinishedTracks() { if (isCurrentTrackRollbackable) { providerUtils.deleteTrack(track.getId()); isCurrentTrackRollbackable = false; } } /** * Get all track ids of the tracks created by this importer run. * * @return array of track ids */ private long[] getImportedTrackIds() { // Convert from java.lang.Long for convenience long[] result = new long[tracksWritten.size()]; for (int i = 0; i < result.length; i++) { result[i] = tracksWritten.get(i); } return result; } /** * Returns the ID of the last point inserted into the database. */ private long getLastPointId() { flushPointInserts(); return providerUtils.getLastLocationId(track.getId()); } /** * Builds a parsing error message with current line information. * * @param details details about the error, will be appended * @return error message string with current line information */ private String createErrorMessage(String details) { StringBuffer msg = new StringBuffer(); msg.append("Parsing error at line: "); msg.append(locator.getLineNumber()); msg.append(" column: "); msg.append(locator.getColumnNumber()); msg.append(". "); msg.append(details); return msg.toString(); } }
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.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import android.content.Context; import android.util.Log; /** * A factory to produce track writers for any format. * * @author Rodrigo Damazio */ public class TrackWriterFactory { /** * Definition of all possible track formats. */ public enum TrackFileFormat { GPX { @Override TrackFormatWriter newFormatWriter(Context context) { return new GpxTrackWriter(); } }, KML { @Override TrackFormatWriter newFormatWriter(Context context) { return new KmlTrackWriter(context); } }, CSV { @Override public TrackFormatWriter newFormatWriter(Context context) { return new CsvTrackWriter(); } }, TCX { @Override public TrackFormatWriter newFormatWriter(Context context) { return new TcxTrackWriter(context); } }; /** * Creates and returns a new format writer for each format. */ abstract TrackFormatWriter newFormatWriter(Context context); /** * Returns the mime type for each format. */ public String getMimeType() { return "application/" + getExtension() + "+xml"; } /** * Returns the file extension for each format. */ public String getExtension() { return this.name().toLowerCase(); } } /** * Creates a new track writer to write the track with the given ID. * * @param context the context in which the track will be read * @param providerUtils the data provider utils to read the track with * @param trackId the ID of the track to be written * @param format the output format to write in * @return the new track writer */ public static TrackWriter newWriter(Context context, MyTracksProviderUtils providerUtils, long trackId, TrackFileFormat format) { Track track = providerUtils.getTrack(trackId); if (track == null) { Log.w(TAG, "Trying to create a writer for an invalid track, id=" + trackId); return null; } return newWriter(context, providerUtils, track, format); } /** * Creates a new track writer to write the given track. * * @param context the context in which the track will be read * @param providerUtils the data provider utils to read the track with * @param track the track to be written * @param format the output format to write in * @return the new track writer */ private static TrackWriter newWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFileFormat format) { TrackFormatWriter writer = format.newFormatWriter(context); return new TrackWriterImpl(context, providerUtils, track, writer); } private TrackWriterFactory() { } }
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.io.file; import java.io.File; /** * Implementations of this class export tracks to the SD card. This class is * intended to be format-neutral - it handles creating the output file and * reading the track to be exported, but requires an instance of * {@link TrackFormatWriter} to actually format the data. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public interface TrackWriter { /** This listener is used to signal completion of track write */ public interface OnCompletionListener { public void onComplete(); } /** This listener is used to signal track writes. */ public interface OnWriteListener { /** * This method is invoked whenever a location within a track is written. * @param number the location number * @param max the maximum number of locations, for calculation of * completion percentage */ public void onWrite(int number, int max); } /** * Sets listener to be invoked when the writer has finished. */ void setOnCompletionListener(OnCompletionListener onCompletionListener); /** * Sets a listener to be invoked for each location writer. */ void setOnWriteListener(OnWriteListener onWriteListener); /** * Sets a custom directory where the file will be written. */ void setDirectory(File directory); /** * Returns the absolute path to the file which was created. */ String getAbsolutePath(); /** * Writes the given track id to the SD card. * This is non-blocking. */ void writeTrackAsync(); /** * Writes the given track id to the SD card. * This is blocking. */ void writeTrack(); /** * Stop any in-progress writes */ void stopWriteTrack(); /** * Returns true if the write completed successfully. */ boolean wasSuccess(); /** * Returns the error message (if any) generated by a writer failure. */ int getErrorMessage(); }
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.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.io.File; /** * Activity for saving a track to a file (and optionally sending that file). * * @author Rodrigo Damazio */ public class SaveActivity extends Activity { public static final String EXTRA_SHARE_FILE = "share_file"; public static final String EXTRA_FILE_FORMAT = "file_format"; private static final int RESULT_DIALOG = 1; /* VisibleForTesting */ static final int PROGRESS_DIALOG = 2; private MyTracksProviderUtils providerUtils; private long trackId; private TrackWriter writer; private boolean shareFile; private TrackFileFormat format; private WriteProgressController controller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); } @Override protected void onStart() { super.onStart(); Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); Uri data = intent.getData(); if (!getString(R.string.track_action_save).equals(action) || !TracksColumns.CONTENT_ITEMTYPE.equals(type) || !UriUtils.matchesContentUri(data, TracksColumns.CONTENT_URI)) { Log.e(TAG, "Got bad save intent: " + intent); finish(); return; } trackId = ContentUris.parseId(data); int formatIdx = intent.getIntExtra(EXTRA_FILE_FORMAT, -1); format = TrackFileFormat.values()[formatIdx]; shareFile = intent.getBooleanExtra(EXTRA_SHARE_FILE, false); writer = TrackWriterFactory.newWriter(this, providerUtils, trackId, format); if (writer == null) { Log.e(TAG, "Unable to build writer"); finish(); return; } if (shareFile) { // If the file is for sending, save it to a temporary location instead. FileUtils fileUtils = new FileUtils(); String extension = format.getExtension(); String dirName = fileUtils.buildExternalDirectoryPath(extension, "tmp"); File dir = new File(dirName); writer.setDirectory(dir); } controller = new WriteProgressController(this, writer, PROGRESS_DIALOG); controller.setOnCompletionListener(new WriteProgressController.OnCompletionListener() { @Override public void onComplete() { onWriteComplete(); } }); controller.startWrite(); } private void onWriteComplete() { if (shareFile) { shareWrittenFile(); } else { showResultDialog(); } } private void shareWrittenFile() { if (!writer.wasSuccess()) { showResultDialog(); return; } // Share the file. Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getText(R.string.share_track_subject).toString()); shareIntent.putExtra(Intent.EXTRA_TEXT, getResources().getText(R.string.share_track_file_body_format) .toString()); shareIntent.setType(format.getMimeType()); Uri u = Uri.fromFile(new File(writer.getAbsolutePath())); shareIntent.putExtra(Intent.EXTRA_STREAM, u); shareIntent.putExtra(getString(R.string.track_id_broadcast_extra), trackId); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_track_picker_title).toString())); } private void showResultDialog() { removeDialog(RESULT_DIALOG); showDialog(RESULT_DIALOG); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case RESULT_DIALOG: return createResultDialog(); case PROGRESS_DIALOG: if (controller != null) { return controller.createProgressDialog(); } //$FALL-THROUGH$ default: return super.onCreateDialog(id); } } private Dialog createResultDialog() { boolean success = writer.wasSuccess(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(writer.getErrorMessage()); builder.setPositiveButton(R.string.generic_ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { dialog.dismiss(); finish(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); finish(); } }); builder.setIcon(success ? android.R.drawable.ic_dialog_info : android.R.drawable.ic_dialog_alert); builder.setTitle(success ? R.string.generic_success_title : R.string.generic_error_title); return builder.create(); } public static void handleExportTrackAction(Context ctx, long trackId, int actionCode) { if (trackId < 0) { return; } TrackFileFormat exportFormat = null; switch (actionCode) { case Constants.SAVE_GPX_FILE: case Constants.SHARE_GPX_FILE: exportFormat = TrackFileFormat.GPX; break; case Constants.SAVE_KML_FILE: case Constants.SHARE_KML_FILE: exportFormat = TrackFileFormat.KML; break; case Constants.SAVE_CSV_FILE: case Constants.SHARE_CSV_FILE: exportFormat = TrackFileFormat.CSV; break; case Constants.SAVE_TCX_FILE: case Constants.SHARE_TCX_FILE: exportFormat = TrackFileFormat.TCX; break; default: throw new IllegalArgumentException("Warning unhandled action code: " + actionCode); } boolean shareFile = false; switch (actionCode) { case Constants.SHARE_GPX_FILE: case Constants.SHARE_KML_FILE: case Constants.SHARE_CSV_FILE: case Constants.SHARE_TCX_FILE: shareFile = true; } Uri uri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, trackId); Intent intent = new Intent(ctx, SaveActivity.class); intent.setAction(ctx.getString(R.string.track_action_save)); intent.setDataAndType(uri, TracksColumns.CONTENT_ITEMTYPE); intent.putExtra(EXTRA_FILE_FORMAT, exportFormat.ordinal()); intent.putExtra(EXTRA_SHARE_FILE, shareFile); ctx.startActivity(intent); } }
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.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.ImportAllTracks; import com.google.android.apps.mytracks.util.UriUtils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.util.Log; /** * An activity that imports a track from a file and displays the track in My Tracks. * * @author Rodrigo Damazio */ public class ImportActivity extends Activity { @Override public void onStart() { super.onStart(); Intent intent = getIntent(); String action = intent.getAction(); Uri data = intent.getData(); if (!(Intent.ACTION_VIEW.equals(action) || Intent.ACTION_ATTACH_DATA.equals(action))) { Log.e(TAG, "Received an intent with unsupported action: " + intent); finish(); return; } if (!UriUtils.isFileUri(data)) { Log.e(TAG, "Received an intent with unsupported data: " + intent); finish(); return; } String path = data.getPath(); Log.i(TAG, "Importing GPX file at " + path); new ImportAllTracks(this, path); } }
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.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import android.location.Location; import java.io.OutputStream; import java.io.PrintWriter; import java.text.NumberFormat; import java.util.Date; /** * Exports a track as a CSV file, according to RFC 4180. * * The first field is a type: * TRACK - track description * P - point * WAYPOINT - waypoint * * For each type, the fields are: * * TRACK,,,,,,,,name,description, * P,time,lat,lon,alt,bearing,accurancy,speed,,,segmentIdx * WAYPOINT,time,lat,lon,alt,bearing,accuracy,speed,name,description, * * @author Rodrigo Damazio */ public class CsvTrackWriter implements TrackFormatWriter { private static final NumberFormat SHORT_FORMAT = NumberFormat.getInstance(); static { SHORT_FORMAT.setMaximumFractionDigits(4); } private int segmentIdx = 0; private int numFields = -1; private PrintWriter pw; private Track track; @Override public String getExtension() { return TrackFileFormat.CSV.getExtension(); } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public void writeHeader() { writeCommaSeparatedLine("TYPE", "TIME", "LAT", "LON", "ALT", "BEARING", "ACCURACY", "SPEED", "NAME", "DESCRIPTION", "SEGMENT"); } @Override public void writeBeginTrack(Location firstPoint) { writeCommaSeparatedLine("TRACK", null, null, null, null, null, null, null, track.getName(), track.getDescription(), null); } @Override public void writeOpenSegment() { // Do nothing } @Override public void writeLocation(Location location) { String timeStr = FileUtils.FILE_TIMESTAMP_FORMAT.format(new Date(location.getTime())); writeCommaSeparatedLine("P", timeStr, Double.toString(location.getLatitude()), Double.toString(location.getLongitude()), Double.toString(location.getAltitude()), Double.toString(location.getBearing()), SHORT_FORMAT.format(location.getAccuracy()), SHORT_FORMAT.format(location.getSpeed()), null, null, Integer.toString(segmentIdx)); } @Override public void writeWaypoint(Waypoint waypoint) { Location location = waypoint.getLocation(); String timeStr = FileUtils.FILE_TIMESTAMP_FORMAT.format(new Date(location.getTime())); writeCommaSeparatedLine("WAYPOINT", timeStr, Double.toString(location.getLatitude()), Double.toString(location.getLongitude()), Double.toString(location.getAltitude()), Double.toString(location.getBearing()), SHORT_FORMAT.format(location.getAccuracy()), SHORT_FORMAT.format(location.getSpeed()), waypoint.getName(), waypoint.getDescription(), null); } /** * Writes a single line of a comma-separated-value file. * * @param strs the values to be written as comma-separated */ private void writeCommaSeparatedLine(String... strs) { if (numFields == -1) { numFields = strs.length; } else if (strs.length != numFields) { throw new IllegalArgumentException( "CSV lines with different number of fields"); } boolean isFirst = true; for (String str : strs) { if (!isFirst) { pw.print(','); } isFirst = false; if (str != null) { pw.print('"'); pw.print(str.replaceAll("\"", "\"\"")); pw.print('"'); } } pw.println(); } @Override public void writeCloseSegment() { segmentIdx++; } @Override public void writeEndTrack(Location lastPoint) { // Do nothing } @Override public void writeFooter() { // Do nothing } @Override public void close() { pw.close(); } }
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.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; /** * This class exports tracks to the SD card. It is intended to be format- * neutral -- it handles creating the output file and reading the track to be * exported, but requires an instance of {@link TrackFormatWriter} to actually * format the data. * * @author Sandor Dornbush * @author Rodrigo Damazio */ class TrackWriterImpl implements TrackWriter { private final Context context; private final MyTracksProviderUtils providerUtils; private final Track track; private final TrackFormatWriter writer; private final FileUtils fileUtils; private boolean success = false; private int errorMessage = -1; private File directory = null; private File file = null; private OnCompletionListener onCompletionListener; private OnWriteListener onWriteListener; private Thread writeThread; TrackWriterImpl(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer) { this.context = context; this.providerUtils = providerUtils; this.track = track; this.writer = writer; this.fileUtils = new FileUtils(); } @Override public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } @Override public void setOnWriteListener(OnWriteListener onWriteListener) { this.onWriteListener = onWriteListener; } @Override public void setDirectory(File directory) { this.directory = directory; } @Override public String getAbsolutePath() { return file.getAbsolutePath(); } @Override public void writeTrackAsync() { writeThread = new Thread() { @Override public void run() { doWriteTrack(); } }; writeThread.start(); } @Override public void writeTrack() { writeTrackAsync(); try { writeThread.join(); } catch (InterruptedException e) { Log.e(Constants.TAG, "Interrupted waiting for write to complete", e); } } private void doWriteTrack() { // Open the input and output success = false; errorMessage = R.string.sd_card_error_write_file; if (track != null) { if (openFile()) { try { writeDocument(); } catch (InterruptedException e) { Log.i(Constants.TAG, "The track write was interrupted"); if (file != null) { if (!file.delete()) { Log.w(TAG, "Failed to delete file " + file.getAbsolutePath()); } } success = false; errorMessage = R.string.sd_card_canceled; } } } finished(); } public void stopWriteTrack() { if (writeThread != null && writeThread.isAlive()) { Log.i(Constants.TAG, "Attempting to stop track write"); writeThread.interrupt(); try { writeThread.join(); Log.i(Constants.TAG, "Track write stopped"); } catch (InterruptedException e) { Log.e(Constants.TAG, "Failed to wait for writer to stop", e); } } } @Override public int getErrorMessage() { return errorMessage; } @Override public boolean wasSuccess() { return success; } /* * Helper methods: * =============== */ private void finished() { if (onCompletionListener != null) { runOnUiThread(new Runnable() { @Override public void run() { onCompletionListener.onComplete(); } }); return; } } /** * Runs the given runnable in the UI thread. */ protected void runOnUiThread(Runnable runnable) { if (context instanceof Activity) { ((Activity) context).runOnUiThread(runnable); } } /** * Opens the file and prepares the format writer for it. * * @return true on success, false otherwise (and errorMessage is set) */ protected boolean openFile() { if (!canWriteFile()) { return false; } // Make sure the file doesn't exist yet (possibly by changing the filename) String fileName = fileUtils.buildUniqueFileName( directory, track.getName(), writer.getExtension()); if (fileName == null) { Log.e(Constants.TAG, "Unable to get a unique filename for " + track.getName()); return false; } Log.i(Constants.TAG, "Writing track to: " + fileName); try { writer.prepare(track, newOutputStream(fileName)); } catch (FileNotFoundException e) { Log.e(Constants.TAG, "Failed to open output file.", e); errorMessage = R.string.sd_card_error_write_file; return false; } return true; } /** * Checks and returns whether we're ready to create the output file. */ protected boolean canWriteFile() { if (directory == null) { String dirName = fileUtils.buildExternalDirectoryPath(writer.getExtension()); directory = newFile(dirName); } if (!fileUtils.isSdCardAvailable()) { Log.i(Constants.TAG, "Could not find SD card."); errorMessage = R.string.sd_card_error_no_storage; return false; } if (!fileUtils.ensureDirectoryExists(directory)) { Log.i(Constants.TAG, "Could not create export directory."); errorMessage = R.string.sd_card_error_create_dir; return false; } return true; } /** * Creates a new output stream to write to the given filename. * * @throws FileNotFoundException if the file could't be created */ protected OutputStream newOutputStream(String fileName) throws FileNotFoundException { file = new File(directory, fileName); return new FileOutputStream(file); } /** * Creates a new file object for the given path. */ protected File newFile(String path) { return new File(path); } /** * Writes the waypoints for the given track. * * @param trackId the ID of the track to write waypoints for */ private void writeWaypoints(long trackId) { // TODO: Stream through he waypoints in chunks. // I am leaving the number of waypoints very high which should not be a // problem because we don't try to load them into objects all at the // same time. Cursor cursor = null; cursor = providerUtils.getWaypointsCursor(trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null) { try { if (cursor.moveToFirst()) { // Yes, this will skip the 1st way point and that is intentional // as the 1st points holds the stats for the current/last segment. while (cursor.moveToNext()) { Waypoint wpt = providerUtils.createWaypoint(cursor); writer.writeWaypoint(wpt); } } } finally { cursor.close(); } } } /** * Does the actual work of writing the track to the now open file. */ void writeDocument() throws InterruptedException { Log.d(Constants.TAG, "Started writing track."); writer.writeHeader(); writeWaypoints(track.getId()); writeLocations(); writer.writeFooter(); writer.close(); success = true; Log.d(Constants.TAG, "Done writing track."); errorMessage = R.string.sd_card_success_write_file; } private void writeLocations() throws InterruptedException { boolean wroteFirst = false; boolean segmentOpen = false; boolean isLastValid = false; class TrackWriterLocationFactory implements MyTracksProviderUtils.LocationFactory { Location currentLocation; Location lastLocation; @Override public Location createLocation() { if (currentLocation == null) { currentLocation = new MyTracksLocation(""); } return currentLocation; } public void swapLocations() { Location tmpLoc = lastLocation; lastLocation = currentLocation; currentLocation = tmpLoc; if (currentLocation != null) { currentLocation.reset(); } } }; TrackWriterLocationFactory locationFactory = new TrackWriterLocationFactory(); LocationIterator it = providerUtils.getLocationIterator(track.getId(), 0, false, locationFactory); try { if (!it.hasNext()) { Log.w(Constants.TAG, "Unable to get any points to write"); return; } int pointNumber = 0; while (it.hasNext()) { Location loc = it.next(); if (Thread.interrupted()) { throw new InterruptedException(); } pointNumber++; boolean isValid = LocationUtils.isValidLocation(loc); boolean validSegment = isValid && isLastValid; if (!wroteFirst && validSegment) { // Found the first two consecutive points which are valid writer.writeBeginTrack(locationFactory.lastLocation); wroteFirst = true; } if (validSegment) { if (!segmentOpen) { // Start a segment for this point writer.writeOpenSegment(); segmentOpen = true; // Write the previous point, which we had previously skipped writer.writeLocation(locationFactory.lastLocation); } // Write the current point writer.writeLocation(loc); if (onWriteListener != null) { onWriteListener.onWrite(pointNumber, track.getNumberOfPoints()); } } else { if (segmentOpen) { writer.writeCloseSegment(); segmentOpen = false; } } locationFactory.swapLocations(); isLastValid = isValid; } if (segmentOpen) { writer.writeCloseSegment(); segmentOpen = false; } if (wroteFirst) { writer.writeEndTrack(locationFactory.lastLocation); } } finally { it.close(); } } }
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.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.location.Location; import java.io.OutputStream; /** * Interface for writing data to a specific track file format. * * The expected sequence of calls is: * <ol> * <li>{@link #prepare} * <li>{@link #writeHeader} * <li>{@link #writeBeginTrack} * <li>For each segment: * <ol> * <li>{@link #writeOpenSegment} * <li>For each location in the segment: {@link #writeLocation} * <li>{@link #writeCloseSegment} * </ol> * <li>{@link #writeEndTrack} * <li>For each waypoint: {@link #writeWaypoint} * <li>{@link #writeFooter} * </ol> * * @author Rodrigo Damazio */ public interface TrackFormatWriter { /** * Sets up the writer to write the given track to the given output. * * @param track the track to write * @param out the stream to write the track contents to */ void prepare(Track track, OutputStream out); /** * @return The file extension (i.e. gpx, kml, ...) */ String getExtension(); /** * Writes the header. * This is chance for classes to write out opening information. */ void writeHeader(); /** * Writes the footer. * This is chance for classes to write out closing information. */ void writeFooter(); /** * Write the given location object. * * TODO Add some flexible handling of other sensor data. * * @param location the location to write */ void writeLocation(Location location) throws InterruptedException; /** * Write a way point. * * @param waypoint */ void writeWaypoint(Waypoint waypoint); /** * Write the beginning of a track. */ void writeBeginTrack(Location firstPoint); /** * Write the end of a track. */ void writeEndTrack(Location lastPoint); /** * Write the statements necessary to open a new segment. */ void writeOpenSegment(); /** * Write the statements necessary to close a segment. */ void writeCloseSegment(); /** * Close the underlying file handle. */ void close(); }
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.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.StringUtils; import android.content.Context; import android.location.Location; import android.os.Build; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Vector; /** * Write track as KML to a file. * * @author Leif Hendrik Wilden */ public class KmlTrackWriter implements TrackFormatWriter { private final Vector<Double> distances = new Vector<Double>(); private final Vector<Double> elevations = new Vector<Double>(); private final StringUtils stringUtils; private PrintWriter pw = null; private Track track; public KmlTrackWriter(Context context) { stringUtils = new StringUtils(context); } /** * Testing constructor. */ KmlTrackWriter(StringUtils stringUtils) { this.stringUtils = stringUtils; } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public String getExtension() { return TrackFileFormat.KML.getExtension(); } @Override public void writeHeader() { if (pw != null) { pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); pw.print("<kml"); pw.print(" xmlns=\"http://earth.google.com/kml/2.0\""); pw.println(" xmlns:atom=\"http://www.w3.org/2005/Atom\">"); pw.println("<Document>"); pw.format("<atom:author><atom:name>My Tracks running on %s" + "</atom:name></atom:author>\n", Build.MODEL); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<description>" + StringUtils.stringAsCData(track.getDescription()) + "</description>"); writeStyles(); } } @Override public void writeFooter() { if (pw != null) { pw.println("</Document>"); pw.println("</kml>"); } } @Override public void writeBeginTrack(Location firstPoint) { if (pw != null) { writePlacemark("(Start)", track.getDescription(), "#sh_green-circle", firstPoint); pw.println("<Placemark>"); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<description>" + StringUtils.stringAsCData(track.getDescription()) + "</description>"); pw.println("<styleUrl>#track</styleUrl>"); pw.println("<MultiGeometry>"); } } @Override public void writeEndTrack(Location lastPoint) { if (pw != null) { pw.println("</MultiGeometry>"); pw.println("</Placemark>"); String description = stringUtils.generateTrackDescription( track, distances, elevations); writePlacemark("(End)", description, "#sh_red-circle", lastPoint); } } @Override public void writeOpenSegment() { if (pw != null) { pw.print("<LineString><coordinates>"); } } @Override public void writeCloseSegment() { if (pw != null) { pw.println("</coordinates></LineString>"); } } @Override public void writeLocation(Location l) { if (pw != null) { pw.print(l.getLongitude() + "," + l.getLatitude() + "," + l.getAltitude() + " "); } } private String getPinStyle(Waypoint waypoint) { if (waypoint.getType() == Waypoint.TYPE_STATISTICS) { return "#sh_ylw-pushpin"; } // Try to find the icon color. // The string should be of the form: // "http://maps.google.com/mapfiles/ms/micons/XXX.png" int slash = waypoint.getIcon().lastIndexOf('/'); int png = waypoint.getIcon().lastIndexOf('.'); if ((slash != -1) && (slash < png)) { String color = waypoint.getIcon().substring(slash + 1, png); return "#sh_" + color + "-pushpin"; } return "#sh_blue-pushpin"; } @Override public void writeWaypoint(Waypoint waypoint) { if (pw != null) { writePlacemark( waypoint.getName(), waypoint.getDescription(), getPinStyle(waypoint), waypoint.getLocation()); } } @Override public void close() { if (pw != null) { pw.close(); pw = null; } } private void writeStyles() { pw.println("<Style id=\"track\"><LineStyle><color>7f0000ff</color>" + "<width>4</width></LineStyle></Style>"); pw.print("<Style id=\"sh_green-circle\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/paddle/" + "grn-circle.png</href></Icon>"); pw.println("<hotSpot x=\"32\" y=\"1\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_red-circle\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/paddle/" + "red-circle.png</href></Icon>"); pw.println("<hotSpot x=\"32\" y=\"1\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_ylw-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "ylw-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_blue-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "blue-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_green-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "grn-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); pw.print("<Style id=\"sh_red-pushpin\"><IconStyle><scale>1.3</scale>"); pw.print("<Icon><href>http://maps.google.com/mapfiles/kml/pushpin/" + "red-pushpin.png</href></Icon>"); pw.println("<hotSpot x=\"20\" y=\"2\" xunits=\"pixels\" yunits=\"pixels\"/>" + "</IconStyle></Style>"); } private void writePlacemark(String name, String description, String style, Location location) { if (location != null) { pw.println("<Placemark>"); pw.println(" <name>" + StringUtils.stringAsCData(name) + "</name>"); pw.println(" <description>" + StringUtils.stringAsCData(description) + "</description>"); pw.println(" <styleUrl>" + style + "</styleUrl>"); pw.println(" <Point>"); pw.println(" <coordinates>" + location.getLongitude() + "," + location.getLatitude() + "</coordinates>"); pw.println(" </Point>"); pw.println("</Placemark>"); } } }
Java