diff --git a/MyTracks/AndroidManifest.xml b/MyTracks/AndroidManifest.xml index 34fbb187e..6c21fd846 100755 --- a/MyTracks/AndroidManifest.xml +++ b/MyTracks/AndroidManifest.xml @@ -180,9 +180,6 @@ limitations under the License. - @@ -210,6 +207,14 @@ limitations under the License. + + + + + + + + - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/MyTracks/res/layout/stats_settings.xml b/MyTracks/res/layout/stats_settings.xml deleted file mode 100644 index ed8b8f9ac..000000000 --- a/MyTracks/res/layout/stats_settings.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/MyTracks/res/menu/map.xml b/MyTracks/res/menu/map.xml new file mode 100644 index 000000000..761acc539 --- /dev/null +++ b/MyTracks/res/menu/map.xml @@ -0,0 +1,22 @@ + + + + + \ No newline at end of file diff --git a/MyTracks/res/menu/track_detail.xml b/MyTracks/res/menu/track_detail.xml index 9ac4de21e..ccc42927c 100644 --- a/MyTracks/res/menu/track_detail.xml +++ b/MyTracks/res/menu/track_detail.xml @@ -18,21 +18,25 @@ limitations under the License. @@ -51,15 +55,19 @@ limitations under the License. + @@ -71,33 +79,26 @@ limitations under the License. - - - \ No newline at end of file diff --git a/MyTracks/res/values/arrays_do_not_translate.xml b/MyTracks/res/values/arrays_do_not_translate.xml index 9f4c74502..fb5aeb571 100644 --- a/MyTracks/res/values/arrays_do_not_translate.xml +++ b/MyTracks/res/values/arrays_do_not_translate.xml @@ -16,7 +16,6 @@ limitations under the License. --> - @string/activity_type_airplane @string/activity_type_atv @@ -84,35 +83,28 @@ limitations under the License. @string/activity_type_water_skiing @string/activity_type_wind_surfing - - - @string/settings_display_track_color_single - @string/settings_display_track_color_fixed - @string/settings_display_track_color_dynamic - - - - @string/display_track_color_value_none - @string/display_track_color_value_fixed - @string/display_track_color_value_dynamic - - - - GPX - KML - CSV - TCX - - - + 0 5 10 15 -1 - - + + GPX + KML + CSV + TCX + + + 50 + 100 + 200 + 500 + 1000 + 5000 + + 1 2 3 @@ -121,20 +113,7 @@ limitations under the License. 10 100 - - - 10 - 20 - 50 - 100 - 200 - 500 - 1000 - 2000 - 5000 - - - + -2 -1 0 @@ -152,66 +131,77 @@ limitations under the License. 900 1800 - - - 0 - -100 - -50 - -25 - -10 - -5 - -1 - 60 - 30 - 15 + 10 - 5 - 2 - 1 - - - + 20 50 100 200 500 1000 + 2000 5000 - - - @string/sensor_type_value_ant - @string/sensor_type_value_srm_ant_bridge + + 0 + 1 + 2 + 5 + 10 + 15 + 30 + 60 + -1 + -5 + -10 + -25 + -50 + -100 - - + @string/settings_sensor_type_none @string/settings_sensor_type_ant @string/settings_sensor_type_srm @string/settings_sensor_type_polar @string/settings_sensor_type_zephyr - - + @string/sensor_type_value_none @string/sensor_type_value_ant @string/sensor_type_value_srm_ant_bridge @string/sensor_type_value_polar @string/sensor_type_value_zephyr - - + + @string/settings_sensor_type_none + @string/settings_sensor_type_polar + @string/settings_sensor_type_zephyr + + + @string/sensor_type_value_none + @string/sensor_type_value_polar + @string/sensor_type_value_zephyr + + + @string/settings_map_track_color_mode_single + @string/settings_map_track_color_mode_fixed + @string/settings_map_track_color_mode_dynamic + + + @string/settings_map_track_color_mode_single_value + @string/settings_map_track_color_mode_fixed_value + @string/settings_map_track_color_mode_dynamic_value + + @string/settings_recording_track_name_date_local_option @string/settings_recording_track_name_date_iso_8601_option @string/settings_recording_track_name_number_option - - + @string/settings_recording_track_name_date_local_value @string/settings_recording_track_name_date_iso_8601_value @string/settings_recording_track_name_number_value - @string/waypoint_type_atm @string/waypoint_type_bank diff --git a/MyTracks/res/values/do_not_translate.xml b/MyTracks/res/values/do_not_translate.xml index b1dcb20eb..3bad2cdf7 100644 --- a/MyTracks/res/values/do_not_translate.xml +++ b/MyTracks/res/values/do_not_translate.xml @@ -16,36 +16,25 @@ limitations under the License. --> - 25 - 15 - 9 - DYNAMIC - FIXED - NONE - - http://maps.google.com/mapfiles/ms/micons/ylw-pushpin.png - - - http://maps.google.com/mapfiles/ms/micons/blue-pushpin.png - - UA-7222692-2 + http://maps.google.com/mapfiles/ms/micons/ylw-pushpin.png + http://maps.google.com/mapfiles/ms/micons/blue-pushpin.png + UA-7222692-2 www.google.com/policies/privacy/ My Tracks Recording Service - - groups.google.com/a/googleproductforums.com/forum/#!categories/maps/mytracks - + groups.google.com/a/googleproductforums.com/forum/#!categories/maps/mytracks www.google.com/mobile/mytracks - - com.google.android.apps.mytracks.MYTRACKS_NOTIFICATIONS - + com.google.android.apps.mytracks.MYTRACKS_NOTIFICATIONS docs.google.com google.com/fusiontables maps.google.com - ANT + ANT NONE POLAR SRM_ANT_BRIDGE ZEPHYR + DYNAMIC + FIXED + SINGLE DATE_ISO_8601 DATE_LOCAL NUMBER @@ -53,4 +42,4 @@ limitations under the License. android.intent.action.SAVE com.google.android.apps.mytracks.START_NEW_TRACK - - + \ No newline at end of file diff --git a/MyTracks/res/values/keys.xml b/MyTracks/res/values/keys.xml index 915b265b9..2d8f93aa9 100644 --- a/MyTracks/res/values/keys.xml +++ b/MyTracks/res/values/keys.xml @@ -15,18 +15,22 @@ See the License for the specific language governing permissions and limitations under the License. --> - - + allowAccess announcementFrequency antCadenceSensorId antCadenceSpeedSensorId antHeartRateSensorId - antSRMBridgeSensorId + antSrmBridgeSensorId autoResumeTrackCurrentRetry autoResumeTrackTimeout - bluetoothPairing bluetoothSensor + chartByDistance + chartShowCadence + chartShowElevation + chartShowHeartRate + chartShowPower + chartShowSpeed defaultActivity defaultMapPublic maxRecordingDistance @@ -51,20 +55,28 @@ limitations under the License. statsShowCoordinate statsShowElevation statsShowGrade - statsShowTotalTime - trackColorModeDynamicVariation - trackColorModeFixedMediumDisplay - trackColorModeFixedMedium - trackColorModeFixedSlowDisplay - trackColorModeFixedSlow + statsUseTotalTime + trackColorModeMedium + trackColorModePercentage + trackColorModeSlow trackColorMode trackName - - - antOptions - backupToSd - resetToDefaults - restoreFromSd - sensorOptions - trackColorModeFixedOptions + + settingsBackup + settingsBackupNow + settingsBackupRestore + settingsChart + settingsMap + settingsMapMediumDisplay + settingsMapPercentageDisplay + settingsMapSlowDisplay + settingsRecording + settingsReset + settingsSensor + settingsSensorAnt + settingsSensorBluetooth + settingsSensorBluetoothPairing + settingsSensorRoot + settingsSharing + settingsStats \ No newline at end of file diff --git a/MyTracks/res/values/strings.xml b/MyTracks/res/values/strings.xml index 5e5fd1054..7e03389db 100644 --- a/MyTracks/res/values/strings.xml +++ b/MyTracks/res/values/strings.xml @@ -416,30 +416,6 @@ limitations under the License. Record and share your GPS tracks with My Tracks. - - - By distance - - - By time - - - X axis - - - Y axis - - Aggregated statistics - - Chart settings - Delete all @@ -1141,10 +1113,6 @@ limitations under the License. translation_description="In the menu, to show a marker on map."> Show on map - - Stats settings - Stop recording @@ -1213,23 +1181,6 @@ limitations under the License. write data to My Tracks and start/stop My Tracks recording - - - Imperial (mi, ft) - - - Metric (km, m) - - - Preferred Units - - Restore all tracks and settings from the SD card. - - SD card + + + By distance + + + By time + + + X axis - - Display + + + Top medium speed - - Use metric + + Percentage from average - - Use imperial units to display distances. - - - Use metric units to display distances. - - - Display speed - - - Display pace (e.g., hours/mile). - - - Display speed (e.g., miles/hour). - - - Color mode - - - Dynamic thresholds - - - Percentage - - Percentage from the average speed for the medium speed range. - + + Top slow speed + + + Track color mode + + + Dynamic thresholds + + Fixed thresholds - - Medium speed - - - Medium speed top value. - - - Slow speed - - - Slow speed top value. - - + Single color - + The way to color a track based on slow, medium, and fast speed. + + + + Show + Not available while recording a track. + + Time/distance between two voice announcements. + + Revert all your settings to the default values. + + Unpair SRM ANT+ bridge + + Remove any descriptive text when sharing a URL with friends. - - My Tracks settings + + + + Latitude/Longitude + + + Grade + + + Pace (hr/mi) + + + Pace (hr/km) + + + Speed (mi/hr) + + + Speed (km/hr) + + + Preferred rate + + + Time measurement + + + Imperial (mi, ft) + + + Metric (km, m) + + + Preferred units @@ -2145,28 +2099,6 @@ limitations under the License. Total time - - - Show - - - Grade - - - Latitude/Longitude - - - Time - - @@ -2300,7 +2232,7 @@ limitations under the License. %1$.2f: a float number. E.g., '2.22'"> %1$.2f km - @@ -2371,6 +2303,12 @@ limitations under the License. %1$d: an integer value. E.g., '2'"> %1$d km + + %1$d km/h + %1$d mi + + %1$d mi/h + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/chart_settings.xml b/MyTracks/res/xml/chart_settings.xml new file mode 100644 index 000000000..011a75e5a --- /dev/null +++ b/MyTracks/res/xml/chart_settings.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/map_settings.xml b/MyTracks/res/xml/map_settings.xml new file mode 100644 index 000000000..a3365a254 --- /dev/null +++ b/MyTracks/res/xml/map_settings.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/preferences.xml b/MyTracks/res/xml/preferences.xml deleted file mode 100644 index 3b6191c09..000000000 --- a/MyTracks/res/xml/preferences.xml +++ /dev/null @@ -1,235 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/MyTracks/res/xml/recording_settings.xml b/MyTracks/res/xml/recording_settings.xml new file mode 100644 index 000000000..b79455ec4 --- /dev/null +++ b/MyTracks/res/xml/recording_settings.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/sensor_settings.xml b/MyTracks/res/xml/sensor_settings.xml new file mode 100644 index 000000000..d7904d6a1 --- /dev/null +++ b/MyTracks/res/xml/sensor_settings.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/settings.xml b/MyTracks/res/xml/settings.xml new file mode 100644 index 000000000..ff24e55be --- /dev/null +++ b/MyTracks/res/xml/settings.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/sharing_settings.xml b/MyTracks/res/xml/sharing_settings.xml new file mode 100644 index 000000000..04276f123 --- /dev/null +++ b/MyTracks/res/xml/sharing_settings.xml @@ -0,0 +1,37 @@ + + + + + + + \ No newline at end of file diff --git a/MyTracks/res/xml/stats_settings.xml b/MyTracks/res/xml/stats_settings.xml new file mode 100644 index 000000000..9186c4a09 --- /dev/null +++ b/MyTracks/res/xml/stats_settings.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/MyTracks/src/com/google/android/apps/mytracks/AbstractMyTracksActivity.java b/MyTracks/src/com/google/android/apps/mytracks/AbstractMyTracksActivity.java index c409e06c7..b899016bc 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/AbstractMyTracksActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/AbstractMyTracksActivity.java @@ -34,8 +34,8 @@ public class AbstractMyTracksActivity extends FragmentActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); - ApiAdapterFactory.getApiAdapter().configureActionBarHomeAsUp(this); - } + ApiAdapterFactory.getApiAdapter().configureActionBarHomeAsUp(this); + } @Override public boolean onOptionsItemSelected(MenuItem item) { @@ -44,8 +44,8 @@ public class AbstractMyTracksActivity extends FragmentActivity { } onHomeSelected(); return true; - } - + } + /** * Callback when the home menu item is selected. */ diff --git a/MyTracks/src/com/google/android/apps/mytracks/AutoCompleteTextPreference.java b/MyTracks/src/com/google/android/apps/mytracks/AutoCompleteTextPreference.java index 0469acf04..5c1a0581a 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/AutoCompleteTextPreference.java +++ b/MyTracks/src/com/google/android/apps/mytracks/AutoCompleteTextPreference.java @@ -1,5 +1,6 @@ package com.google.android.apps.mytracks; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; @@ -31,9 +32,9 @@ public class AutoCompleteTextPreference extends EditTextPreference { mEditText.setThreshold(0); // Gets autocomplete values for 'Default Activity' preference - if (getKey().equals(context.getString(R.string.default_activity_key))) { - ArrayAdapter adapter = ArrayAdapter.createFromResource(context, - R.array.activity_types, android.R.layout.simple_dropdown_item_1line); + if (PreferencesUtils.getKey(context, R.string.default_activity_key).equals(getKey())) { + ArrayAdapter adapter = ArrayAdapter.createFromResource( + context, R.array.activity_types, android.R.layout.simple_dropdown_item_1line); mEditText.setAdapter(adapter); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/ChartView.java b/MyTracks/src/com/google/android/apps/mytracks/ChartView.java index a5169d830..af6c785fd 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/ChartView.java +++ b/MyTracks/src/com/google/android/apps/mytracks/ChartView.java @@ -156,12 +156,7 @@ public class ChartView extends View { 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; + private boolean chartByDistance = true; public ChartView(Context context) { super(context); @@ -394,22 +389,17 @@ public class ChartView extends View { } /** - * @return the current display mode (by distance, by time) + * Sets chart by distance value. It is expected that after changing this + * value, data will be reloaded. + * + * @param value true for by distance, false for 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; + public void setChartByDistance(boolean value) { + this.chartByDistance = value; } private int getWaypointX(Waypoint waypoint) { - if (mode == Mode.BY_DISTANCE) { + if (chartByDistance) { double lenghtInKm = waypoint.getLength() * UnitConversions.M_TO_KM; return getX(metricUnits ? lenghtInKm : lenghtInKm * UnitConversions.KM_TO_MI); } else { @@ -813,8 +803,7 @@ public class ChartView extends View { if (x < 0) { return; } - String s = - (mode == Mode.BY_DISTANCE) + String s = chartByDistance ? (shortFormat ? X_SHORT_FORMAT.format(x) : X_FORMAT.format(x)) : StringUtils.formatElapsedTime((long) x); c.drawText(s, @@ -841,7 +830,7 @@ public class ChartView extends View { final int y = effectiveHeight + topBorder; canvas.drawLine(leftBorder, y, rightEdge, y, borderPaint); Context c = getContext(); - String s = mode == Mode.BY_DISTANCE + String s = chartByDistance ? (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); @@ -875,17 +864,6 @@ public class ChartView extends View { } } - /** - * 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. * diff --git a/MyTracks/src/com/google/android/apps/mytracks/Constants.java b/MyTracks/src/com/google/android/apps/mytracks/Constants.java index 7b2da7c39..0d6a9eff3 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/Constants.java +++ b/MyTracks/src/com/google/android/apps/mytracks/Constants.java @@ -121,23 +121,10 @@ public abstract class Constants { * 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 final String + RESUME_TRACK_EXTRA_NAME = "com.google.android.apps.mytracks.RESUME_TRACK"; - 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 MAPSHOP_BASE_URL = "https://maps.google.com/maps/ms"; public static final String SETTINGS_NAME = "SettingsActivity"; diff --git a/MyTracks/src/com/google/android/apps/mytracks/ImportAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/ImportAsyncTask.java index 7c6d69927..4723b36cd 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/ImportAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/ImportAsyncTask.java @@ -21,6 +21,7 @@ import com.google.android.apps.mytracks.io.file.GpxImporter; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.SystemUtils; +import com.google.android.maps.mytracks.R; import android.os.AsyncTask; import android.os.PowerManager.WakeLock; @@ -82,7 +83,8 @@ public class ImportAsyncTask extends AsyncTask { myTracksProviderUtils = MyTracksProviderUtils.Factory.get(importActivity); // Get the wake lock if not recording - if (PreferencesUtils.getRecordingTrackId(importActivity) == -1L) { + if (PreferencesUtils.getLong(importActivity, R.string.recording_track_id_key) + == PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) { wakeLock = SystemUtils.acquireWakeLock(importActivity, wakeLock); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/MapOverlay.java b/MyTracks/src/com/google/android/apps/mytracks/MapOverlay.java index 57076921c..a7b3ef48c 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/MapOverlay.java +++ b/MyTracks/src/com/google/android/apps/mytracks/MapOverlay.java @@ -23,6 +23,7 @@ import com.google.android.apps.mytracks.maps.TrackPathPainterFactory; import com.google.android.apps.mytracks.maps.TrackPathUtilities; import com.google.android.apps.mytracks.util.IntentUtils; import com.google.android.apps.mytracks.util.LocationUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; @@ -462,10 +463,8 @@ public class MapOverlay extends Overlay implements OnSharedPreferenceChangeListe @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); - } + if (PreferencesUtils.getKey(context, R.string.track_color_mode_key).equals(key)) { + trackPathPainter = TrackPathPainterFactory.getTrackPathPainter(context); } } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/MarkerListActivity.java b/MyTracks/src/com/google/android/apps/mytracks/MarkerListActivity.java index 952287c43..e7cf087a3 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/MarkerListActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/MarkerListActivity.java @@ -81,16 +81,17 @@ public class MarkerListActivity extends AbstractMyTracksActivity { * Note that sharedPreferenceChangeListener cannot be an anonymous inner * class. Anonymous inner class will get garbage collected. */ - private final OnSharedPreferenceChangeListener sharedPreferenceChangeListener = - new OnSharedPreferenceChangeListener() { - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - // Note that key can be null - if (PreferencesUtils.getRecordingTrackIdKey(MarkerListActivity.this).equals(key)) { - updateMenu(); - } - } - }; + private final OnSharedPreferenceChangeListener + sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + // Note that key can be null + if (PreferencesUtils.getKey(MarkerListActivity.this, R.string.recording_track_id_key) + .equals(key)) { + updateMenu(); + } + } + }; private long trackId = -1; private ResourceCursorAdapter resourceCursorAdapter; @@ -113,9 +114,8 @@ public class MarkerListActivity extends AbstractMyTracksActivity { setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); setContentView(R.layout.marker_list); - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); ListView listView = (ListView) findViewById(R.id.marker_list); listView.setEmptyView(findViewById(R.id.marker_list_empty)); @@ -188,7 +188,8 @@ public class MarkerListActivity extends AbstractMyTracksActivity { private void updateMenu() { if (insertMarkerMenuItem != null) { - insertMarkerMenuItem.setVisible(trackId == PreferencesUtils.getRecordingTrackId(this)); + insertMarkerMenuItem.setVisible( + trackId == PreferencesUtils.getLong(this, R.string.recording_track_id_key)); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/SaveAllAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/SaveAllAsyncTask.java index e6eab71dd..b6e4b25c8 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/SaveAllAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/SaveAllAsyncTask.java @@ -66,7 +66,8 @@ public class SaveAllAsyncTask extends AsyncTask { myTracksProviderUtils = MyTracksProviderUtils.Factory.get(saveAllActivity); // Get the wake lock if not recording - if (PreferencesUtils.getRecordingTrackId(saveAllActivity) == -1L) { + if (PreferencesUtils.getLong(saveAllActivity, R.string.recording_track_id_key) + == PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) { wakeLock = SystemUtils.acquireWakeLock(saveAllActivity, wakeLock); } success = false; diff --git a/MyTracks/src/com/google/android/apps/mytracks/SearchListActivity.java b/MyTracks/src/com/google/android/apps/mytracks/SearchListActivity.java index 25a9d9c9f..4fac858ba 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/SearchListActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/SearchListActivity.java @@ -83,10 +83,12 @@ public class SearchListActivity extends AbstractMyTracksActivity { private final OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { - @Override + @Override public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - if (PreferencesUtils.getRecordingTrackIdKey(SearchListActivity.this).equals(key)) { - recordingTrackId = PreferencesUtils.getRecordingTrackId(SearchListActivity.this); + if (PreferencesUtils.getKey(SearchListActivity.this, R.string.recording_track_id_key) + .equals(key)) { + recordingTrackId = PreferencesUtils.getLong( + SearchListActivity.this, R.string.recording_track_id_key); arrayAdapter.notifyDataSetChanged(); } } @@ -123,10 +125,9 @@ public class SearchListActivity extends AbstractMyTracksActivity { searchEngine = new SearchEngine(myTracksProviderUtils); searchRecentSuggestions = SearchEngineProvider.newHelper(this); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); - recordingTrackId = PreferencesUtils.getRecordingTrackId(this); + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key); listView = (ListView) findViewById(R.id.search_list); listView.setEmptyView(findViewById(R.id.search_list_empty)); @@ -185,7 +186,8 @@ public class SearchListActivity extends AbstractMyTracksActivity { @Override protected void onResume() { super.onResume(); - metricUnits = PreferencesUtils.isMetricUnits(this); + metricUnits = PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); } @Override diff --git a/MyTracks/src/com/google/android/apps/mytracks/SettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/SettingsActivity.java deleted file mode 100644 index 11de9fecf..000000000 --- a/MyTracks/src/com/google/android/apps/mytracks/SettingsActivity.java +++ /dev/null @@ -1,717 +0,0 @@ -/* - * 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.BackupActivity; -import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; -import com.google.android.apps.mytracks.io.backup.RestoreChooserActivity; -import com.google.android.apps.mytracks.services.sensors.ant.AntUtils; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; -import com.google.android.apps.mytracks.util.BluetoothDeviceUtils; -import com.google.android.apps.mytracks.util.DialogUtils; -import com.google.android.apps.mytracks.util.IntentUtils; -import com.google.android.apps.mytracks.util.PreferencesUtils; -import com.google.android.apps.mytracks.util.UnitConversions; -import com.google.android.maps.mytracks.R; - -import android.app.Dialog; -import android.bluetooth.BluetoothAdapter; -import android.content.DialogInterface; -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.speech.tts.TextToSpeech; -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 { - - private static final int DIALOG_CONFIRM_RESET_ID = 0; - private static final int DIALOG_CONFIRM_ACCESS_ID = 1; - private static final int DIALOG_CONFIRM_RESTORE_ID = 2; - - // 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 - setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); - - // Tell it where to read/write preferences - PreferenceManager preferenceManager = getPreferenceManager(); - preferenceManager.setSharedPreferencesName(Constants.SETTINGS_NAME); - preferenceManager.setSharedPreferencesMode(0); - - // Set up automatic preferences backup - backupListener = ApiAdapterFactory.getApiAdapter().getBackupPreferencesListener(this); - preferences = preferenceManager.getSharedPreferences(); - preferences.registerOnSharedPreferenceChangeListener(backupListener); - - // Load the preferences to be displayed - addPreferencesFromResource(R.xml.preferences); - - setRecordingIntervalOptions(); - setAutoResumeTimeoutOptions(); - - // Hook up switching of displayed list entries between metric and imperial - // units - CheckBoxPreference metricUnitsPreference = - (CheckBoxPreference) findPreference(PreferencesUtils.getMetricUnitsKey(this)); - 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) { - showDialog(DIALOG_CONFIRM_RESET_ID); - return true; - } - }); - - // Add a confirmation dialog for the 'Allow access' preference. - 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) { - showDialog(DIALOG_CONFIRM_ACCESS_ID); - return false; - } else { - return true; - } - } - }); - } - - @Override - protected Dialog onCreateDialog(int id) { - switch (id) { - case DIALOG_CONFIRM_RESET_ID: - return DialogUtils.createConfirmationDialog( - this, R.string.settings_reset_confirm_message, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int button) { - onResetPreferencesConfirmed(); - } - }); - case DIALOG_CONFIRM_ACCESS_ID: - return DialogUtils.createConfirmationDialog(this, - R.string.settings_sharing_allow_access_confirm_message, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int button) { - CheckBoxPreference pref = (CheckBoxPreference) findPreference( - getString(R.string.allow_access_key)); - pref.setChecked(true); - } - }); - case DIALOG_CONFIRM_RESTORE_ID: - return DialogUtils.createConfirmationDialog(this, - R.string.settings_backup_restore_confirm_message, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Intent intent = IntentUtils.newIntent( - SettingsActivity.this, RestoreChooserActivity.class); - startActivity(intent); - } - }); - default: - return null; - } - } - - /** - * 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 toRemove = new HashSet(); - - 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 = PreferencesUtils.getRecordingTrackId(this) != -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) { - Intent intent = IntentUtils.newIntent(SettingsActivity.this, BackupActivity.class); - startActivity(intent); - return true; - } - }); - restoreNowPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - showDialog(DIALOG_CONFIRM_RESTORE_ID); - 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.FT_TO_MI; - 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.FT_TO_MI; - 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() { - // 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 entries = new ArrayList(); - List entryValues = new ArrayList(); - - // The actual devices - BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (bluetoothAdapter != null) { - BluetoothDeviceUtils.populateDeviceLists(bluetoothAdapter, 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 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() - .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - 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) { - if (PreferencesUtils.isMetricUnits(this)) { - 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.KM_TO_MI); - } 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) { - String metricspeed; - if (PreferencesUtils.isMetricUnits(this)) { - metricspeed = newValue; - } else { - // Convert miles/h to km/h - try { - metricspeed = String.valueOf( - (int) (Double.parseDouble(newValue) * UnitConversions.MI_TO_KM)); - } catch (NumberFormatException e) { - metricspeed = "0"; - } - } - SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); - Editor editor = prefs.edit(); - editor.putString(getString(id), metricspeed); - ApiAdapterFactory.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; - } - }); - } -} diff --git a/MyTracks/src/com/google/android/apps/mytracks/TrackDetailActivity.java b/MyTracks/src/com/google/android/apps/mytracks/TrackDetailActivity.java index 3c25dcedf..f1f56de4e 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/TrackDetailActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/TrackDetailActivity.java @@ -21,19 +21,17 @@ import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.fragments.ChartFragment; -import com.google.android.apps.mytracks.fragments.ChartSettingsDialogFragment; import com.google.android.apps.mytracks.fragments.DeleteOneTrackDialogFragment; import com.google.android.apps.mytracks.fragments.InstallEarthDialogFragment; import com.google.android.apps.mytracks.fragments.MapFragment; import com.google.android.apps.mytracks.fragments.MarkerAddDialogFragment; import com.google.android.apps.mytracks.fragments.StatsFragment; -import com.google.android.apps.mytracks.fragments.StatsSettingsDialogFragment; -import com.google.android.apps.mytracks.fragments.StatsSettingsDialogFragment.OnStatsSettingsChangedListener; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadServiceChooserActivity; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; +import com.google.android.apps.mytracks.settings.SettingsActivity; import com.google.android.apps.mytracks.util.AnalyticsUtils; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.IntentUtils; @@ -65,8 +63,7 @@ import java.util.List; * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ -public class TrackDetailActivity extends AbstractMyTracksActivity - implements OnStatsSettingsChangedListener { +public class TrackDetailActivity extends AbstractMyTracksActivity { public static final String EXTRA_TRACK_ID = "track_id"; public static final String EXTRA_MARKER_ID = "marker_id"; @@ -74,7 +71,6 @@ public class TrackDetailActivity extends AbstractMyTracksActivity private static final String TAG = TrackDetailActivity.class.getSimpleName(); private static final String CURRENT_TAG_KEY = "tab"; - private SharedPreferences sharedPreferences; private TrackDataHub trackDataHub; private TrackRecordingServiceConnection trackRecordingServiceConnection; private TabHost tabHost; @@ -96,12 +92,13 @@ public class TrackDetailActivity extends AbstractMyTracksActivity * Note that sharedPreferenceChangeListener cannot be an anonymous inner * class. Anonymous inner class will get garbage collected. */ - private final OnSharedPreferenceChangeListener sharedPreferenceChangeListener = - new OnSharedPreferenceChangeListener() { - @Override + private final OnSharedPreferenceChangeListener + sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { + @Override public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { // Note that key can be null - if (PreferencesUtils.getRecordingTrackIdKey(TrackDetailActivity.this).equals(key)) { + if (PreferencesUtils.getKey(TrackDetailActivity.this, R.string.recording_track_id_key) + .equals(key)) { updateMenu(); } } @@ -131,9 +128,9 @@ public class TrackDetailActivity extends AbstractMyTracksActivity super.onCreate(savedInstanceState); ApiAdapterFactory.getApiAdapter().hideTitle(this); setContentView(R.layout.track_detail); - - sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); trackDataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, null); @@ -230,31 +227,6 @@ public class TrackDetailActivity extends AbstractMyTracksActivity return true; } - @Override - public boolean onPrepareOptionsMenu(Menu menu) { - String currentTabTag = tabHost.getCurrentTabTag(); - menu.findItem(R.id.track_detail_chart_settings).setVisible( - ChartFragment.CHART_FRAGMENT_TAG.equals(currentTabTag)); - menu.findItem(R.id.track_detail_stats_settings).setVisible( - StatsFragment.STATS_FRAGMENT_TAG.equals(currentTabTag)); - MenuItem satelliteMode = menu.findItem(R.id.track_detail_satellite_mode) - .setVisible(MapFragment.MAP_FRAGMENT_TAG.equals(currentTabTag)); - - if (satelliteMode.isVisible()) { - MapFragment mapFragment = (MapFragment) getSupportFragmentManager() - .findFragmentByTag(MapFragment.MAP_FRAGMENT_TAG); - /* - * The current tag is mapFragment, thus safe to call its methods like - * isSatelliteView. - */ - boolean isSatelliteMode = mapFragment != null ? mapFragment.isSatelliteView() : false; - menu.findItem(R.id.track_detail_satellite_mode).setTitle( - isSatelliteMode ? R.string.menu_map_mode : R.string.menu_satellite_mode); - } - - return super.onPrepareOptionsMenu(menu); - } - @Override protected void onHomeSelected() { Intent intent = IntentUtils.newIntent(this, TrackListActivity.class); @@ -263,7 +235,6 @@ public class TrackDetailActivity extends AbstractMyTracksActivity @Override public boolean onOptionsItemSelected(MenuItem item) { - MapFragment mapFragment; Intent intent; switch (item.getItemId()) { case R.id.track_detail_stop_recording: @@ -340,25 +311,10 @@ public class TrackDetailActivity extends AbstractMyTracksActivity DeleteOneTrackDialogFragment.newInstance(trackId).show( getSupportFragmentManager(), DeleteOneTrackDialogFragment.DELETE_ONE_TRACK_DIALOG_TAG); return true; - case R.id.track_detail_satellite_mode: - mapFragment = (MapFragment) getSupportFragmentManager() - .findFragmentByTag(MapFragment.MAP_FRAGMENT_TAG); - if (mapFragment != null) { - mapFragment.setSatelliteView(!mapFragment.isSatelliteView()); - } - return true; case R.id.track_detail_sensor_state: intent = IntentUtils.newIntent(this, SensorStateActivity.class); startActivity(intent); return true; - case R.id.track_detail_chart_settings: - new ChartSettingsDialogFragment().show( - getSupportFragmentManager(), ChartSettingsDialogFragment.CHART_SETTINGS_DIALOG_TAG); - return true; - case R.id.track_detail_stats_settings: - new StatsSettingsDialogFragment().show( - getSupportFragmentManager(), StatsSettingsDialogFragment.STATS_SETTINGS_DIALOG_TAG); - return true; case R.id.track_detail_settings: intent = IntentUtils.newIntent(this, SettingsActivity.class); startActivity(intent); @@ -391,13 +347,6 @@ public class TrackDetailActivity extends AbstractMyTracksActivity return mapViewContainer; } - @Override - public void onStatsSettingsChanged() { - StatsFragment statsFragment = (StatsFragment) getSupportFragmentManager() - .findFragmentByTag(StatsFragment.STATS_FRAGMENT_TAG); - statsFragment.updateUi(); - } - /** * Handles the data in the intent. */ @@ -438,7 +387,7 @@ public class TrackDetailActivity extends AbstractMyTracksActivity * Updates the menu. */ private void updateMenu() { - updateMenuItems(trackId == PreferencesUtils.getRecordingTrackId(this)); + updateMenuItems(trackId == PreferencesUtils.getLong(this, R.string.recording_track_id_key)); } /** diff --git a/MyTracks/src/com/google/android/apps/mytracks/TrackListActivity.java b/MyTracks/src/com/google/android/apps/mytracks/TrackListActivity.java index 7025094fc..36f5efdd1 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/TrackListActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/TrackListActivity.java @@ -25,6 +25,7 @@ import com.google.android.apps.mytracks.fragments.WelcomeDialogFragment; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; +import com.google.android.apps.mytracks.settings.SettingsActivity; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.EulaUtils; import com.google.android.apps.mytracks.util.IntentUtils; @@ -119,12 +120,16 @@ public class TrackListActivity extends FragmentActivity { public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { boolean updateList = false; // Note that key can be null - if (PreferencesUtils.getMetricUnitsKey(TrackListActivity.this).equals(key)) { - metricUnits = PreferencesUtils.isMetricUnits(TrackListActivity.this); + if (PreferencesUtils.getKey(TrackListActivity.this, R.string.metric_units_key) + .equals(key)) { + metricUnits = PreferencesUtils.getBoolean(TrackListActivity.this, + R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); updateList = true; } - if (PreferencesUtils.getRecordingTrackIdKey(TrackListActivity.this).equals(key)) { - recordingTrackId = PreferencesUtils.getRecordingTrackId(TrackListActivity.this); + if (PreferencesUtils.getKey(TrackListActivity.this, R.string.recording_track_id_key) + .equals(key)) { + recordingTrackId = PreferencesUtils.getLong( + TrackListActivity.this, R.string.recording_track_id_key); if (TrackRecordingServiceConnectionUtils.isRecording( TrackListActivity.this, trackRecordingServiceConnection)) { trackRecordingServiceConnection.startAndBind(); @@ -173,11 +178,11 @@ public class TrackListActivity extends FragmentActivity { trackRecordingServiceConnection = new TrackRecordingServiceConnection( this, bindChangedCallback); - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); - metricUnits = PreferencesUtils.isMetricUnits(this); - recordingTrackId = PreferencesUtils.getRecordingTrackId(this); + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + metricUnits = PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + recordingTrackId = PreferencesUtils.getLong(this, R.string.recording_track_id_key); ImageButton recordImageButton = (ImageButton) findViewById(R.id.track_list_record_button); recordImageButton.setOnClickListener(new View.OnClickListener() { @@ -274,14 +279,16 @@ public class TrackListActivity extends FragmentActivity { EulaDialogFragment.newInstance(false) .show(getSupportFragmentManager(), EulaDialogFragment.EULA_DIALOG_TAG); } - } else if (PreferencesUtils.isShowWelcomeDialog(this)) { + } else if (PreferencesUtils.getBoolean( + this, R.string.show_welcome_dialog_key, PreferencesUtils.SHOW_WELCOME_DIALOG_DEFAULT)) { Fragment fragment = getSupportFragmentManager() .findFragmentByTag(WelcomeDialogFragment.WELCOME_DIALOG_TAG); if (fragment == null) { new WelcomeDialogFragment().show( getSupportFragmentManager(), WelcomeDialogFragment.WELCOME_DIALOG_TAG); } - } else if (PreferencesUtils.isShowCheckUnitsDialog(this)) { + } else if (PreferencesUtils.getBoolean(this, R.string.show_check_units_dialog_key, + PreferencesUtils.SHOW_CHECK_UNITS_DIALOG_DEFAULT)) { Fragment fragment = getSupportFragmentManager() .findFragmentByTag(CheckUnitsDialogFragment.CHECK_UNITS_DIALOG_TAG); if (fragment == null) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/content/MyTracksProvider.java b/MyTracks/src/com/google/android/apps/mytracks/content/MyTracksProvider.java index 2f959a575..5b0e01585 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/content/MyTracksProvider.java +++ b/MyTracks/src/com/google/android/apps/mytracks/content/MyTracksProvider.java @@ -16,13 +16,13 @@ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; 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; @@ -190,13 +190,11 @@ public class MyTracksProvider extends ContentProvider { 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); + return PreferencesUtils.getBoolean( + getContext(), R.string.allow_access_key, PreferencesUtils.ALLOW_ACCESS_DEFAULT); } } - + @Override public boolean onCreate() { if (!canAccess()) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java b/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java index 75bacccb9..fc5b8b7cd 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java +++ b/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java @@ -15,7 +15,6 @@ */ 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; @@ -58,9 +57,6 @@ import java.util.Set; */ public class TrackDataHub { - // Preference keys - private final String MIN_REQUIRED_ACCURACY_KEY; - // Overridable constants private final int targetNumPoints; @@ -219,8 +215,6 @@ public class TrackDataHub { this.targetNumPoints = targetNumPoints; this.locationFactory = new DoubleBufferedLocationFactory(); - MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key); - resetState(); } @@ -294,11 +288,13 @@ public class TrackDataHub { } private void loadSharedPreferences() { - selectedTrackId = PreferencesUtils.getSelectedTrackId(context); - metricUnits = PreferencesUtils.isMetricUnits(context); - reportSpeed = PreferencesUtils.isReportSpeed(context); - minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY, - DEFAULT_MIN_REQUIRED_ACCURACY); + selectedTrackId = PreferencesUtils.getLong(context, R.string.selected_track_id_key); + metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + reportSpeed = PreferencesUtils.getBoolean( + context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); + minRequiredAccuracy = PreferencesUtils.getInt(context, R.string.min_required_accuracy_key, + PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT); } /** Updates known magnetic declination if needed. */ @@ -372,8 +368,9 @@ public class TrackDataHub { if (!isStarted()) { loadSharedPreferences(); } - long recordingTrackId = PreferencesUtils.getRecordingTrackId(context); - return recordingTrackId != -1L && recordingTrackId == selectedTrackId; + long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key); + return recordingTrackId != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT + && recordingTrackId == selectedTrackId; } /** @@ -391,7 +388,7 @@ public class TrackDataHub { // Save the selection to memory and flush. selectedTrackId = trackId; - PreferencesUtils.setSelectedTrackId(context, selectedTrackId); + PreferencesUtils.setLong(context, R.string.selected_track_id_key, selectedTrackId); // Force it to reload data from the beginning. Log.d(TAG, "Loading track"); @@ -605,21 +602,23 @@ public class TrackDataHub { /** * 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 (PreferencesUtils.getMetricUnitsKey(context).equals(key)) { - metricUnits = PreferencesUtils.isMetricUnits(context); + if (PreferencesUtils.getKey(context, R.string.min_required_accuracy_key).equals(key)) { + minRequiredAccuracy = PreferencesUtils.getInt(context, R.string.min_required_accuracy_key, + PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT); + } else if (PreferencesUtils.getKey(context, R.string.metric_units_key).equals(key)) { + metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); notifyUnitsChanged(); - } else if (PreferencesUtils.getReportSpeedKey(context).equals(key)) { - reportSpeed = PreferencesUtils.isReportSpeed(context); + } else if (PreferencesUtils.getKey(context, R.string.report_speed_key).equals(key)) { + reportSpeed = PreferencesUtils.getBoolean( + context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); notifySpeedReportingChanged(); - } else if (PreferencesUtils.getSelectedTrackIdKey(context).equals(key)) { - loadTrack(PreferencesUtils.getSelectedTrackId(context)); + } else if (PreferencesUtils.getKey(context, R.string.selected_track_id_key).equals(key)) { + loadTrack(PreferencesUtils.getLong(context, R.string.selected_track_id_key)); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java index 50de47cd5..2424a37ce 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java @@ -17,7 +17,6 @@ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.ChartView; -import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracksApplication; import com.google.android.apps.mytracks.content.MyTracksLocation; @@ -31,6 +30,7 @@ import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; @@ -76,6 +76,9 @@ public class ChartFragment extends Fragment implements TrackDataListener { private boolean metricUnits = true; private boolean reportSpeed = true; + private boolean chartByDistance = true; + private boolean[] chartShow = new boolean[] {true, true, true, true, true}; + // UI elements private ChartView chartView; private ZoomControls zoomControls; @@ -143,6 +146,7 @@ public class ChartFragment extends Fragment implements TrackDataListener { public void onResume() { super.onResume(); resumeTrackDataHub(); + checkChartSettings(); getActivity().runOnUiThread(updateChart); } @@ -158,58 +162,6 @@ public class ChartFragment extends Fragment implements TrackDataListener { ViewGroup layout = (ViewGroup) getActivity().findViewById(R.id.chart_view_layout); layout.removeView(chartView); } - - /** - * Sets the chart view mode. - * - * @param mode the chart view mode - */ - public void setMode(Mode mode) { - if (chartView.getMode() != mode) { - chartView.setMode(mode); - reloadTrackDataHub(); - } - } - - /** - * Gets the chart view mode. - */ - public Mode getMode() { - return chartView.getMode(); - } - - /** - * Enables or disables the chart value series. - * - * @param index the index of the series - * @param enabled true to enable, false to disable - */ - public void setChartValueSeriesEnabled(int index, boolean enabled) { - chartView.setChartValueSeriesEnabled(index, enabled); - } - - /** - * Returns true if the chart value series is enabled. - * - * @param index the index of the series - */ - public boolean isChartValueSeriesEnabled(int index) { - return chartView.isChartValueSeriesEnabled(index); - } - - /** - * Returns true to report speed instead of pace. - */ - public boolean isReportSpeed() { - return reportSpeed; - } - - /** - * Updates the chart. - */ - public void update() { - chartView.postInvalidate(); - } @Override public void onProviderStateChange(ProviderState state) { @@ -338,6 +290,60 @@ public class ChartFragment extends Fragment implements TrackDataListener { return true; } + /** + * Checks the chart settings. + */ + private void checkChartSettings() { + boolean needUpdate = false; + if (chartByDistance != PreferencesUtils.getBoolean(getActivity(), + R.string.chart_by_distance_key, PreferencesUtils.CHART_BY_DISTANCE_DEFAULT)) { + chartByDistance = !chartByDistance; + chartView.setChartByDistance(chartByDistance); + reloadTrackDataHub(); + needUpdate = true; + } + if (setSeriesEnabled(ChartView.ELEVATION_SERIES, PreferencesUtils.getBoolean(getActivity(), + R.string.chart_show_elevation_key, PreferencesUtils.CHART_SHOW_ELEVATION_DEFAULT))) { + needUpdate = true; + } + if (setSeriesEnabled(ChartView.SPEED_SERIES, PreferencesUtils.getBoolean( + getActivity(), R.string.chart_show_speed_key, PreferencesUtils.CHART_SHOW_SPEED_DEFAULT))) { + needUpdate = true; + } + if (setSeriesEnabled(ChartView.POWER_SERIES, PreferencesUtils.getBoolean( + getActivity(), R.string.chart_show_power_key, PreferencesUtils.CHART_SHOW_POWER_DEFAULT))) { + needUpdate = true; + } + if (setSeriesEnabled(ChartView.CADENCE_SERIES, PreferencesUtils.getBoolean(getActivity(), + R.string.chart_show_cadence_key, PreferencesUtils.CHART_SHOW_CADENCE_DEFAULT))) { + needUpdate = true; + } + if (setSeriesEnabled(ChartView.HEART_RATE_SERIES, PreferencesUtils.getBoolean(getActivity(), + R.string.chart_show_heart_rate_key, PreferencesUtils.CHART_SHOW_HEART_RATE_DEFAULT))) { + needUpdate = true; + } + if (needUpdate) { + chartView.postInvalidate(); + } + } + + /** + * Sets the series enabled value. + * + * @param index the series index + * @param value the value + * @return true if changed + */ + private boolean setSeriesEnabled(int index, boolean value) { + if (chartShow[index] != value) { + chartShow[index] = value; + chartView.setChartValueSeriesEnabled(index, value); + return true; + } else { + return false; + } + } + /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. @@ -352,16 +358,16 @@ public class ChartFragment extends Fragment implements TrackDataListener { ListenerDataType.SAMPLED_OUT_POINT_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } - + /** - * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can be - * accessed by multiple threads. + * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can + * be accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } - + /** * Returns true if recording. Needs to be synchronized because trackDataHub * can be accessed by multiple threads. @@ -369,7 +375,7 @@ public class ChartFragment extends Fragment implements TrackDataListener { private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } - + /** * Reloads the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. @@ -420,7 +426,7 @@ public class ChartFragment extends Fragment implements TrackDataListener { double heartRate = Double.NaN; // TODO: Use TripStatisticsBuilder - if (chartView.getMode() == Mode.BY_DISTANCE) { + if (chartByDistance) { if (lastLocation != null) { double distance = lastLocation.distanceTo(location) * UnitConversions.M_TO_KM; if (metricUnits) { @@ -512,4 +518,8 @@ public class ChartFragment extends Fragment implements TrackDataListener { void setReportSpeed(boolean value) { reportSpeed = value; } + @VisibleForTesting + void setChartByDistance(boolean value) { + chartByDistance = value; + } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartSettingsDialogFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartSettingsDialogFragment.java deleted file mode 100644 index ddb9f81a2..000000000 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartSettingsDialogFragment.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2012 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.fragments; - -import com.google.android.apps.mytracks.ChartView; -import com.google.android.maps.mytracks.R; - -import android.app.AlertDialog; -import android.app.Dialog; -import android.content.DialogInterface; -import android.os.Bundle; -import android.support.v4.app.DialogFragment; -import android.view.View; -import android.widget.CheckBox; -import android.widget.RadioGroup; - -/** - * A DialogFragment to show chart settings. - * - * @author Jimmy Shih - */ -public class ChartSettingsDialogFragment extends DialogFragment { - - public static final String CHART_SETTINGS_DIALOG_TAG = "chartSettingsDialog"; - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - final ChartFragment chartFragment = (ChartFragment) getActivity() - .getSupportFragmentManager().findFragmentByTag(ChartFragment.CHART_FRAGMENT_TAG); - View view = getActivity().getLayoutInflater().inflate(R.layout.chart_settings, null); - final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.chart_settings_x); - radioGroup.check(chartFragment.getMode() == ChartView.Mode.BY_DISTANCE - ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); - - final CheckBox[] checkBoxes = new CheckBox[ChartView.NUM_SERIES]; - checkBoxes[ChartView.ELEVATION_SERIES] = (CheckBox) view.findViewById( - R.id.chart_settings_elevation); - checkBoxes[ChartView.SPEED_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_speed); - checkBoxes[ChartView.POWER_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_power); - checkBoxes[ChartView.CADENCE_SERIES] = (CheckBox) view.findViewById( - R.id.chart_settings_cadence); - checkBoxes[ChartView.HEART_RATE_SERIES] = (CheckBox) view.findViewById( - R.id.chart_settings_heart_rate); - - // set checkboxes values - for (int i = 0; i < ChartView.NUM_SERIES; i++) { - checkBoxes[i].setChecked(chartFragment.isChartValueSeriesEnabled(i)); - } - checkBoxes[ChartView.SPEED_SERIES].setText(chartFragment.isReportSpeed() - ? R.string.stats_speed : R.string.stats_pace); - - return new AlertDialog.Builder(getActivity()) - .setNegativeButton(R.string.generic_cancel, null) - .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - chartFragment.setMode( - radioGroup.getCheckedRadioButtonId() == R.id.chart_settings_by_distance - ? ChartView.Mode.BY_DISTANCE : ChartView.Mode.BY_TIME); - for (int i = 0; i < ChartView.NUM_SERIES; i++) { - chartFragment.setChartValueSeriesEnabled(i, checkBoxes[i].isChecked()); - } - chartFragment.update(); - } - }) - .setTitle(R.string.menu_chart_settings) - .setView(view) - .create(); - } -} \ No newline at end of file diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/CheckUnitsDialogFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/CheckUnitsDialogFragment.java index 128930625..41953a8c8 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/CheckUnitsDialogFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/CheckUnitsDialogFragment.java @@ -46,9 +46,9 @@ public class CheckUnitsDialogFragment extends DialogFragment { public Dialog onCreateDialog(Bundle savedInstanceState) { Locale defaultLocale = Locale.getDefault(); boolean defaultMetric = !defaultLocale.equals(Locale.US) && !defaultLocale.equals(Locale.UK); - PreferencesUtils.setMetricUnits(getActivity(), defaultMetric); - final String metric = getString(R.string.preferred_units_metric); - final String imperial = getString(R.string.preferred_units_imperial); + PreferencesUtils.setBoolean(getActivity(), R.string.metric_units_key, defaultMetric); + final String metric = getString(R.string.settings_stats_units_metric); + final String imperial = getString(R.string.settings_stats_units_imperial); final CharSequence[] items = defaultMetric ? new CharSequence[] { metric, imperial } : new CharSequence[] { imperial, metric }; return new AlertDialog.Builder(getActivity()) @@ -56,19 +56,20 @@ public class CheckUnitsDialogFragment extends DialogFragment { @Override public void onClick(DialogInterface dialog, int which) { int position = ((AlertDialog) dialog).getListView().getCheckedItemPosition(); - PreferencesUtils.setMetricUnits(getActivity(), items[position].equals(metric)); + PreferencesUtils.setBoolean( + getActivity(), R.string.metric_units_key, items[position].equals(metric)); onDone(); } }) .setSingleChoiceItems(items, 0, null) - .setTitle(R.string.preferred_units_title).create(); + .setTitle(R.string.settings_stats_units_title).create(); } /** * Tasks to perform when done. */ private void onDone() { - PreferencesUtils.setShowCheckUnitsDialog(getActivity()); + PreferencesUtils.setBoolean(getActivity(), R.string.show_check_units_dialog_key, false); TrackListActivity trackListActivity = (TrackListActivity) getActivity(); trackListActivity.showStartupDialogs(); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java index 03163f496..592793a87 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java @@ -40,6 +40,9 @@ import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; @@ -90,6 +93,12 @@ public class MapFragment extends Fragment private ImageButton myLocationImageButton; private TextView messageTextView; + @Override + public void onCreate(Bundle bundle) { + super.onCreate(bundle); + setHasOptionsMenu(true); + } + @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -156,6 +165,30 @@ public class MapFragment extends Fragment } } + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflator) { + menuInflator.inflate(R.menu.map, menu); + } + + @Override + public void onPrepareOptionsMenu(Menu menu) { + int titleId = R.string.menu_satellite_mode; + if (mapView != null) { + titleId = mapView.isSatellite() ? R.string.menu_map_mode : R.string.menu_satellite_mode; + } + menu.findItem(R.id.map_satellite_mode).setTitle(titleId); + super.onPrepareOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem menuItem) { + if (mapView != null && menuItem.getItemId() == R.id.map_satellite_mode) { + mapView.setSatellite(!mapView.isSatellite()); + return true; + } + return super.onOptionsItemSelected(menuItem); + } + /** * Shows my location. */ @@ -209,22 +242,6 @@ public class MapFragment extends Fragment } } - /** - * Returns true if in satellite mode. - */ - public boolean isSatelliteView() { - return mapView.isSatellite(); - } - - /** - * Sets the satellite mode - * - * @param enabled true for satellite mode, false for map mode - */ - public void setSatelliteView(boolean enabled) { - mapView.setSatellite(enabled); - } - @Override public boolean onTouch(View view, MotionEvent event) { if (keepMyLocationVisible && event.getAction() == MotionEvent.ACTION_MOVE) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/MarkerAddDialogFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/MarkerAddDialogFragment.java index 1c1b8a267..b1548da8a 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/MarkerAddDialogFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/MarkerAddDialogFragment.java @@ -97,8 +97,8 @@ public class MarkerAddDialogFragment extends DialogFragment { dismiss(); } }); - boolean pickStatisticsMarker = PreferencesUtils.getBoolean( - getActivity(), R.string.pick_statistics_marker_key, true); + boolean pickStatisticsMarker = PreferencesUtils.getBoolean(getActivity(), + R.string.pick_statistics_marker_key, PreferencesUtils.PICK_STATISTICS_MARKER_DEFAULT); radioGroup.check(pickStatisticsMarker ? R.id.marker_add_statistics : R.id.marker_add_waypoint); return new AlertDialog.Builder(getActivity()) .setNegativeButton(R.string.generic_cancel, null) diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java index a4d439d21..49b7b374d 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java @@ -74,7 +74,8 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void run() { Log.d(TAG, "UI update thread started"); - while (PreferencesUtils.getRecordingTrackId(getActivity()) != -1L) { + while (PreferencesUtils.getLong(getActivity(), R.string.recording_track_id_key) + != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) { getActivity().runOnUiThread(updateTotalTime); try { Thread.sleep(1000L); @@ -270,8 +271,11 @@ public class StatsFragment extends Fragment implements TrackDataListener { private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } - - public void updateUi() { + + /** + * Updates the UI. + */ + private void updateUi() { StatsUtils.setTripStatisticsValues(getActivity(), lastTripStatistics); StatsUtils.setLocationValues(getActivity(), lastLocation, true); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsSettingsDialogFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsSettingsDialogFragment.java deleted file mode 100644 index cf0470749..000000000 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsSettingsDialogFragment.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2012 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.fragments; - -import com.google.android.apps.mytracks.util.PreferencesUtils; -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.support.v4.app.DialogFragment; -import android.view.View; -import android.widget.CheckBox; -import android.widget.RadioGroup; - -/** - * A DialogFragment to show stats settings. - * - * @author Jimmy Shih - */ -public class StatsSettingsDialogFragment extends DialogFragment { - - public static final String STATS_SETTINGS_DIALOG_TAG = "statsSettingsDialog"; - - public interface OnStatsSettingsChangedListener { - public void onStatsSettingsChanged(); - } - - private OnStatsSettingsChangedListener listener; - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - try { - listener = (OnStatsSettingsChangedListener) activity; - } catch (ClassCastException e) { - throw new ClassCastException(activity.toString() - + " must implement OnArticleSelectedListener"); - } - } - - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - View view = getActivity().getLayoutInflater().inflate(R.layout.stats_settings, null); - final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.stats_settings_time); - boolean totalTime = PreferencesUtils.getBoolean( - getActivity(), R.string.stats_show_total_time_key, true); - radioGroup.check(totalTime ? R.id.stats_settings_total_time : R.id.stats_settings_moving_time); - - final CheckBox elevation = (CheckBox) view.findViewById(R.id.stats_settings_elevation); - final CheckBox grade = (CheckBox) view.findViewById(R.id.stats_settings_grade); - final CheckBox coordinate = (CheckBox) view.findViewById(R.id.stats_settings_coordinate); - - elevation.setChecked( - PreferencesUtils.getBoolean(getActivity(), R.string.stats_show_elevation_key, false)); - grade.setChecked( - PreferencesUtils.getBoolean(getActivity(), R.string.stats_show_grade_key, false)); - coordinate.setChecked( - PreferencesUtils.getBoolean(getActivity(), R.string.stats_show_coordinate_key, false)); - - return new AlertDialog.Builder(getActivity()).setNegativeButton(R.string.generic_cancel, null) - .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - PreferencesUtils.setBoolean(getActivity(), R.string.stats_show_total_time_key, - radioGroup.getCheckedRadioButtonId() == R.id.stats_settings_total_time); - PreferencesUtils.setBoolean( - getActivity(), R.string.stats_show_elevation_key, elevation.isChecked()); - PreferencesUtils.setBoolean( - getActivity(), R.string.stats_show_grade_key, grade.isChecked()); - PreferencesUtils.setBoolean( - getActivity(), R.string.stats_show_coordinate_key, coordinate.isChecked()); - listener.onStatsSettingsChanged(); - } - }) - .setTitle(R.string.menu_stats_settings) - .setView(view) - .create(); - } -} \ No newline at end of file diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/WelcomeDialogFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/WelcomeDialogFragment.java index 4dfafe461..c1d72d99e 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/WelcomeDialogFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/WelcomeDialogFragment.java @@ -55,7 +55,7 @@ public class WelcomeDialogFragment extends DialogFragment { } private void onDone() { - PreferencesUtils.setShowWelcome(getActivity()); + PreferencesUtils.setBoolean(getActivity(), R.string.show_welcome_dialog_key, false); TrackListActivity trackListActivity = (TrackListActivity) getActivity(); trackListActivity.showStartupDialogs(); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsUtils.java b/MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsUtils.java index 53953ba7c..922df8185 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsUtils.java @@ -270,7 +270,8 @@ public class SendDocsUtils { Track track, String spreadsheetId, String worksheetId, String authToken, Context context) throws IOException { String worksheetUri = String.format(GET_WORKSHEET_URI, spreadsheetId, worksheetId); - boolean metricUnits = PreferencesUtils.isMetricUnits(context); + boolean metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); addRow(worksheetUri, getRowContent(track, metricUnits, context), authToken); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java index 7b7d07d50..b93493ca8 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java @@ -205,7 +205,8 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { private boolean uploadAllTrackPoints(Track track) { Cursor locationsCursor = null; try { - boolean metricUnits = PreferencesUtils.isMetricUnits(context); + boolean metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); if (locationsCursor == null) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java index 98e6ebdc9..8d952c5bb 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java @@ -45,7 +45,6 @@ import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; -import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; @@ -225,15 +224,13 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { mapId = chooseMapId; return true; } else { - SharedPreferences sharedPreferences = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - boolean mapPublic = sharedPreferences.getBoolean( - context.getString(R.string.default_map_public_key), true); + boolean defaultMapPublic = PreferencesUtils.getBoolean( + context, R.string.default_map_public_key, PreferencesUtils.DEFAULT_MAP_PUBLIC_DEFAULT); try { String description = track.getCategory() + "\n" + track.getDescription() + "\n" + context.getString(R.string.send_google_by_my_tracks, "", ""); mapId = SendMapsUtils.createNewMap( - track.getName(), description, mapPublic, mapsClient, authToken); + track.getName(), description, defaultMapPublic, mapsClient, authToken); } catch (ParseException e) { Log.d(TAG, "Unable to create a new map", e); return false; @@ -258,7 +255,8 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { boolean uploadAllTrackPoints(Track track) { Cursor locationsCursor = null; try { - boolean metricUnits = PreferencesUtils.isMetricUnits(context); + boolean metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); if (locationsCursor == null) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java index 6e8cbffbc..f4d31ec07 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/AccountChooserActivity.java @@ -24,8 +24,8 @@ import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient; import com.google.android.apps.mytracks.io.gdata.maps.MapsConstants; import com.google.android.apps.mytracks.io.maps.ChooseMapActivity; import com.google.android.apps.mytracks.io.maps.SendMapsActivity; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.IntentUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.accounts.Account; @@ -37,11 +37,8 @@ import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.util.Log; @@ -93,8 +90,8 @@ public class AccountChooserActivity extends Activity { return; } - SharedPreferences prefs = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - String preferredAccount = prefs.getString(getString(R.string.preferred_account_key), ""); + String preferredAccount = PreferencesUtils.getString(this, R.string.preferred_account_key, + PreferencesUtils.PREFERRED_ACCOUNT_DEFAULT); selectedAccountIndex = 0; for (int i = 0; i < accounts.length; i++) { @@ -166,12 +163,8 @@ public class AccountChooserActivity extends Activity { .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Account account = accounts[selectedAccountIndex]; - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = sharedPreferences.edit(); - editor.putString(getString(R.string.preferred_account_key), account.name); - ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); - + PreferencesUtils.setString( + AccountChooserActivity.this, R.string.preferred_account_key, account.name); sendRequest.setAccount(account); getPermission(MapsConstants.SERVICE_NAME, sendRequest.isSendMaps(), mapsCallback); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java index 259c8c69f..bb523282b 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadResultActivity.java @@ -15,21 +15,19 @@ */ package com.google.android.apps.mytracks.io.sendtogoogle; -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.io.fusiontables.SendFusionTablesUtils; import com.google.android.apps.mytracks.io.maps.SendMapsUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.ImageView; @@ -49,7 +47,7 @@ public class UploadResultActivity extends Activity { private SendRequest sendRequest; private Track track; private String shareUrl; - private Dialog dialog; + private Dialog resultDialog; @Override protected void onCreate(Bundle savedInstanceState) { @@ -169,19 +167,18 @@ public class UploadResultActivity extends Activity { } }); } - dialog = builder.create(); - return dialog; + resultDialog = builder.create(); + return resultDialog; } /** * Starts an activity to share the url. - * + * * @param url the url */ private void startShareUrlActivity(String url) { - SharedPreferences prefs = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - boolean shareUrlOnly = prefs.getBoolean(getString(R.string.share_url_only_key), false); - + boolean shareUrlOnly = PreferencesUtils.getBoolean( + this, R.string.share_url_only_key, PreferencesUtils.SHARE_URL_ONLY_DEFAULT); Intent intent = new Intent(Intent.ACTION_SEND) .setType(TEXT_PLAIN_TYPE) .putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_track_subject)) @@ -192,6 +189,6 @@ public class UploadResultActivity extends Activity { @VisibleForTesting Dialog getDialog() { - return dialog; + return resultDialog; } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivity.java b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivity.java index 63b646f23..80d4455db 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivity.java @@ -15,21 +15,17 @@ */ package com.google.android.apps.mytracks.io.sendtogoogle; -import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.AnalyticsUtils; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.IntentUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; -import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; @@ -153,16 +149,18 @@ public class UploadServiceChooserActivity extends Activity { */ @VisibleForTesting void initState() { - SharedPreferences prefs = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - boolean pickExistingMap = prefs.getBoolean(getString(R.string.pick_existing_map_key), false); + boolean pickExistingMap = PreferencesUtils.getBoolean( + this, R.string.pick_existing_map_key, PreferencesUtils.PICK_EXISTING_MAP_DEFAULT); newMapRadioButton.setChecked(!pickExistingMap); existingMapRadioButton.setChecked(pickExistingMap); - mapsCheckBox.setChecked(prefs.getBoolean(getString(R.string.send_to_maps_key), true)); - fusionTablesCheckBox.setChecked( - prefs.getBoolean(getString(R.string.send_to_fusion_tables_key), true)); - docsCheckBox.setChecked(prefs.getBoolean(getString(R.string.send_to_docs_key), true)); + mapsCheckBox.setChecked(PreferencesUtils.getBoolean( + this, R.string.send_to_maps_key, PreferencesUtils.SEND_TO_MAPS_DEFAULT)); + fusionTablesCheckBox.setChecked(PreferencesUtils.getBoolean( + this, R.string.send_to_fusion_tables_key, PreferencesUtils.SEND_TO_FUSION_TABLES_DEFAULT)); + docsCheckBox.setChecked(PreferencesUtils.getBoolean( + this, R.string.send_to_docs_key, PreferencesUtils.SEND_TO_DOCS_DEFAULT)); } /** @@ -195,16 +193,13 @@ public class UploadServiceChooserActivity extends Activity { */ @VisibleForTesting void saveState() { - SharedPreferences prefs = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = prefs.edit(); - editor.putBoolean( - getString(R.string.pick_existing_map_key), existingMapRadioButton.isChecked()); + PreferencesUtils.setBoolean( + this, R.string.pick_existing_map_key, existingMapRadioButton.isChecked()); if (sendRequest.isShowAll()) { - editor.putBoolean(getString(R.string.send_to_maps_key), sendMaps()); - editor.putBoolean(getString(R.string.send_to_fusion_tables_key), sendFusionTables()); - editor.putBoolean(getString(R.string.send_to_docs_key), sendDocs()); + PreferencesUtils.setBoolean(this, R.string.send_to_maps_key, sendMaps()); + PreferencesUtils.setBoolean(this, R.string.send_to_fusion_tables_key, sendFusionTables()); + PreferencesUtils.setBoolean(this, R.string.send_to_docs_key, sendDocs()); } - ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } /** diff --git a/MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java b/MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java index e9edc790b..84a07d5d8 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java +++ b/MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java @@ -42,7 +42,6 @@ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor, private int slowSpeed; private int normalSpeed; private int speedMargin; - private final int speedMarginDefault; private double averageMovingSpeed; private final Context context; @VisibleForTesting @@ -50,29 +49,11 @@ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor, public DynamicSpeedTrackPathDescriptor(Context context) { this.context = context; - speedMarginDefault = Integer.parseInt(context - .getString(R.string.color_mode_dynamic_percentage_default)); - SharedPreferences prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, - Context.MODE_PRIVATE); + context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(this); - if (prefs == null) { - speedMargin = speedMarginDefault; - return; - } - prefs.registerOnSharedPreferenceChangeListener(this); - - speedMargin = getSpeedMargin(prefs); - } - - @VisibleForTesting - int getSpeedMargin(SharedPreferences sharedPreferences) { - try { - return Integer.parseInt(sharedPreferences.getString( - context.getString(R.string.track_color_mode_dynamic_speed_variation_key), - Integer.toString(speedMarginDefault))); - } catch (NumberFormatException e) { - return speedMarginDefault; - } + speedMargin = PreferencesUtils.getInt(context, R.string.track_color_mode_percentage_key, + PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT); } /** @@ -98,23 +79,16 @@ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor, @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 = speedMarginDefault; - return; + if (PreferencesUtils.getKey(context, R.string.track_color_mode_percentage_key).equals(key)) { + speedMargin = PreferencesUtils.getInt(context, R.string.track_color_mode_percentage_key, + PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT); } - - speedMargin = getSpeedMargin(prefs); } @Override public boolean needsRedraw() { - long selectedTrackId = PreferencesUtils.getSelectedTrackId(context); - if (selectedTrackId == -1L) { + long selectedTrackId = PreferencesUtils.getLong(context, R.string.selected_track_id_key); + if (selectedTrackId == PreferencesUtils.SELECTED_TRACK_ID_DEFAULT) { // Could not find track. return false; } diff --git a/MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java b/MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java index a4ae7732d..4034fec57 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java +++ b/MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java @@ -13,104 +13,66 @@ * 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.util.PreferencesUtils; 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 { +public class FixedSpeedTrackPathDescriptor + implements TrackPathDescriptor, OnSharedPreferenceChangeListener { private int slowSpeed; private int normalSpeed; - private final int slowDefault; - private final int normalDefault; private final Context context; - + public FixedSpeedTrackPathDescriptor(Context context) { - this.context = context; - slowDefault = Integer.parseInt(context.getString(R.string.color_mode_fixed_slow_default)); - normalDefault = Integer.parseInt(context.getString(R.string.color_mode_fixed_medium_default)); - - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (prefs == null) { - slowSpeed = slowDefault; - normalSpeed = normalDefault; - return; - } - prefs.registerOnSharedPreferenceChangeListener(this); - - try { - slowSpeed = Integer.parseInt(prefs.getString(context.getString( - R.string.track_color_mode_fixed_speed_slow_key), Integer.toString(slowDefault))); - } catch (NumberFormatException e) { - slowSpeed = slowDefault; - } - - try { - normalSpeed = Integer.parseInt(prefs.getString(context.getString( - R.string.track_color_mode_fixed_speed_medium_key), Integer.toString(normalDefault))); - } catch (NumberFormatException e) { - normalSpeed = normalDefault; - } + + context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(this); + + slowSpeed = PreferencesUtils.getInt(context, R.string.track_color_mode_slow_key, + PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT); + normalSpeed = PreferencesUtils.getInt(context, R.string.track_color_mode_medium_key, + PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT); } - + /** * 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 = slowDefault; - normalSpeed = normalDefault; - return; - } - - try { - slowSpeed = Integer.parseInt(prefs.getString(context.getString( - R.string.track_color_mode_fixed_speed_slow_key), Integer.toString(slowDefault))); - } catch (NumberFormatException e) { - slowSpeed = slowDefault; - } - try { - normalSpeed = Integer.parseInt(prefs.getString(context.getString( - R.string.track_color_mode_fixed_speed_medium_key), Integer.toString(normalDefault))); - } catch (NumberFormatException e) { - normalSpeed = normalDefault; + if (PreferencesUtils.getKey(context, R.string.track_color_mode_slow_key).equals(key)) { + slowSpeed = PreferencesUtils.getInt(context, R.string.track_color_mode_slow_key, + PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT); + } else if (PreferencesUtils.getKey(context, R.string.track_color_mode_medium_key).equals(key)) { + normalSpeed = PreferencesUtils.getInt(context, R.string.track_color_mode_medium_key, + PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactory.java b/MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactory.java index 52924c5b3..f00d38ae1 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactory.java +++ b/MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactory.java @@ -17,11 +17,10 @@ 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.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; -import android.content.SharedPreferences; import android.util.Log; /** @@ -40,26 +39,18 @@ public class TrackPathPainterFactory { * @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); + String trackColorMode = PreferencesUtils.getString(context, R.string.track_color_mode_key, + context.getString(R.string.settings_map_track_color_mode_single_value)); + Log.i(TAG, "Creating track path painter of type: " + trackColorMode); - 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)); + if (context.getString(R.string.settings_map_track_color_mode_fixed_value) + .equals(trackColorMode)) { + return new DynamicSpeedTrackPathPainter(context, new FixedSpeedTrackPathDescriptor(context)); + } else if (context.getString(R.string.settings_map_track_color_mode_dynamic_value) + .equals(trackColorMode)) { + return new DynamicSpeedTrackPathPainter(context, new DynamicSpeedTrackPathDescriptor( + context)); } else { - Log.w(TAG, "Using default track path painter. Unrecognized painter: " + colorMode); return new SingleColorTrackPathPainter(context); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicy.java b/MyTracks/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicy.java index eab300f73..7d630e995 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicy.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicy.java @@ -16,6 +16,7 @@ package com.google.android.apps.mytracks.services; + /** * A LocationListenerPolicy that will change based on how long the user has been * stationary. @@ -39,7 +40,7 @@ public class AdaptiveLocationListenerPolicy implements LocationListenerPolicy { private final long maxInterval; private final int minDistance; - + /** * The time the user has been at the current location, in milliseconds. */ diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/ControlRecordingService.java b/MyTracks/src/com/google/android/apps/mytracks/services/ControlRecordingService.java index 11e6b2a13..7b7b9f378 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/ControlRecordingService.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/ControlRecordingService.java @@ -20,6 +20,7 @@ import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.widgets.TrackWidgetProvider; import com.google.android.maps.mytracks.R; +import com.google.common.annotations.VisibleForTesting; import android.app.IntentService; import android.content.ComponentName; @@ -94,6 +95,18 @@ public class ControlRecordingService extends IntentService implements ServiceCon @Override protected void onHandleIntent(Intent intent) { waitConnected(); + onHandleIntent(intent, trackRecordingService); + } + + + /** + * Handles the intent to start or stop a recording. + * + * @param intent to be handled + * @param trackRecordingService the trackRecordingService + */ + @VisibleForTesting + void onHandleIntent(Intent intent, @SuppressWarnings("hiding") ITrackRecordingService trackRecordingService) { String action = intent.getAction(); if (action != null) { try { diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/DefaultTrackNameFactory.java b/MyTracks/src/com/google/android/apps/mytracks/services/DefaultTrackNameFactory.java index be33b7e61..42a360a6c 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/DefaultTrackNameFactory.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/DefaultTrackNameFactory.java @@ -15,13 +15,12 @@ */ package com.google.android.apps.mytracks.services; -import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.content.Context; -import android.content.SharedPreferences; import java.text.SimpleDateFormat; @@ -59,7 +58,7 @@ public class DefaultTrackNameFactory { } else { // trackNameSetting equals // R.string.settings_recording_track_name_number_value - return String.format(context.getString(R.string.track_name_format), trackId); + return context.getString(R.string.track_name_format, trackId); } } @@ -68,10 +67,7 @@ public class DefaultTrackNameFactory { */ @VisibleForTesting String getTrackNameSetting() { - SharedPreferences sharedPreferences = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - return sharedPreferences.getString( - context.getString(R.string.track_name_key), + return PreferencesUtils.getString(context, R.string.track_name_key, context.getString(R.string.settings_recording_track_name_date_local_value)); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/PreferenceManager.java b/MyTracks/src/com/google/android/apps/mytracks/services/PreferenceManager.java index b5d244d26..1e92b11d8 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/PreferenceManager.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/PreferenceManager.java @@ -16,156 +16,120 @@ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.Constants; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A class that manages reading the shared preferences for the service. - * + * * @author Sandor Dornbush */ public class PreferenceManager implements OnSharedPreferenceChangeListener { private TrackRecordingService service; private SharedPreferences sharedPreferences; - private final String announcementFrequencyKey; - private final String autoResumeTrackCurrentRetryKey; - private final String autoResumeTrackTimeoutKey; - private final String maxRecordingDistanceKey; - private final String minRecordingDistanceKey; - private final String minRecordingIntervalKey; - private final String minRequiredAccuracyKey; - private final String splitFrequencyKey; public PreferenceManager(TrackRecordingService service) { this.service = service; this.sharedPreferences = service.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (sharedPreferences == null) { - Log.w(Constants.TAG, - "TrackRecordingService: Couldn't get shared preferences."); - throw new IllegalStateException("Couldn't get shared preferences"); - } sharedPreferences.registerOnSharedPreferenceChangeListener(this); - announcementFrequencyKey = - service.getString(R.string.announcement_frequency_key); - autoResumeTrackCurrentRetryKey = - service.getString(R.string.auto_resume_track_current_retry_key); - autoResumeTrackTimeoutKey = - service.getString(R.string.auto_resume_track_timeout_key); - maxRecordingDistanceKey = - service.getString(R.string.max_recording_distance_key); - minRecordingDistanceKey = - service.getString(R.string.min_recording_distance_key); - minRecordingIntervalKey = - service.getString(R.string.min_recording_interval_key); - minRequiredAccuracyKey = - service.getString(R.string.min_required_accuracy_key); - splitFrequencyKey = - service.getString(R.string.split_frequency_key); - // Refresh all properties. onSharedPreferenceChanged(sharedPreferences, null); } /** - * Notifies that preferences have changed. - * Call this with key == null to update all preferences in one call. - * + * Notifies that preferences have changed. Call this with key == null to + * update all preferences in one call. + * * @param key the key that changed (may be null to update all preferences) */ @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, - String key) { + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { if (service == null) { - Log.w(Constants.TAG, - "onSharedPreferenceChanged: a preference change (key = " + key + Log.w(Constants.TAG, "onSharedPreferenceChanged: a preference change (key = " + key + ") after a call to shutdown()"); return; } - if (key == null || key.equals(minRecordingDistanceKey)) { - int minRecordingDistance = sharedPreferences.getInt( - minRecordingDistanceKey, - Constants.DEFAULT_MIN_RECORDING_DISTANCE); - service.setMinRecordingDistance(minRecordingDistance); - Log.d(Constants.TAG, - "TrackRecordingService: minRecordingDistance = " - + minRecordingDistance); + if (key == null + || PreferencesUtils.getKey(service, R.string.recording_track_id_key).equals(key)) { + long recordingTrackId = PreferencesUtils.getLong(service, R.string.recording_track_id_key); + /* + * Only set the id if it is valid. Setting it to -1L should only happen + * in TrackRecordingService.endCurrentTrack() + */ + if (recordingTrackId != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) { + service.setRecordingTrackId(recordingTrackId); + } } - if (key == null || key.equals(maxRecordingDistanceKey)) { - service.setMaxRecordingDistance(sharedPreferences.getInt( - maxRecordingDistanceKey, - Constants.DEFAULT_MAX_RECORDING_DISTANCE)); + if (key == null || PreferencesUtils.getKey(service, R.string.metric_units_key).equals(key)) { + service.setMetricUnits(PreferencesUtils.getBoolean( + service, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT)); } - if (key == null || key.equals(minRecordingIntervalKey)) { - int minRecordingInterval = sharedPreferences.getInt( - minRecordingIntervalKey, - Constants.DEFAULT_MIN_RECORDING_INTERVAL); + if (key == null + || PreferencesUtils.getKey(service, R.string.announcement_frequency_key).equals(key)) { + service.setAnnouncementFrequency(PreferencesUtils.getInt( + service, R.string.announcement_frequency_key, + PreferencesUtils.ANNOUNCEMENT_FREQUENCY_DEFAULT)); + } + if (key == null || PreferencesUtils.getKey(service, R.string.split_frequency_key).equals(key)) { + service.setSplitFrequency(PreferencesUtils.getInt( + service, R.string.split_frequency_key, PreferencesUtils.SPLIT_FREQUENCY_DEFAULT)); + } + if (key == null + || PreferencesUtils.getKey(service, R.string.min_recording_interval_key).equals(key)) { + int minRecordingInterval = PreferencesUtils.getInt(service, + R.string.min_recording_interval_key, PreferencesUtils.MIN_RECORDING_INTERVAL_DEFAULT); switch (minRecordingInterval) { - case -2: - // Battery Miser - // min: 30 seconds - // max: 5 minutes - // minDist: 5 meters Choose battery life over moving time accuracy. - service.setLocationListenerPolicy( - new AdaptiveLocationListenerPolicy(30000, 300000, 5)); + case PreferencesUtils.MIN_RECORDING_INTERVAL_ADAPT_BATTERY_LIFE: + /* + * Choose battery life over moving time accuracy. min: 30 seconds, + * max: 5 minutes, inDist: 5 meters. + */ + service.setLocationListenerPolicy(new AdaptiveLocationListenerPolicy(30000, 300000, 5)); break; - case -1: - // High Accuracy - // min: 1 second - // max: 30 seconds - // minDist: 0 meters get all updates to properly measure moving time. - service.setLocationListenerPolicy( - new AdaptiveLocationListenerPolicy(1000, 30000, 0)); + case PreferencesUtils.MIN_RECORDING_INTERVAL_ADAPT_ACCURACY: + /* + * Get all the updates. min: 1 second, max: 30 seconds, minDist: 0 + * meter. + */ + service.setLocationListenerPolicy(new AdaptiveLocationListenerPolicy(1000, 30000, 0)); break; default: service.setLocationListenerPolicy( new AbsoluteLocationListenerPolicy(minRecordingInterval * 1000)); } } - if (key == null || key.equals(minRequiredAccuracyKey)) { - service.setMinRequiredAccuracy(sharedPreferences.getInt( - minRequiredAccuracyKey, - Constants.DEFAULT_MIN_REQUIRED_ACCURACY)); + if (key == null + || PreferencesUtils.getKey(service, R.string.min_recording_distance_key).equals(key)) { + service.setMinRecordingDistance(PreferencesUtils.getInt( + service, R.string.min_recording_distance_key, + PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT)); } - if (key == null || key.equals(announcementFrequencyKey)) { - service.setAnnouncementFrequency( - sharedPreferences.getInt(announcementFrequencyKey, -1)); + if (key == null + || PreferencesUtils.getKey(service, R.string.max_recording_distance_key).equals(key)) { + service.setMaxRecordingDistance(PreferencesUtils.getInt( + service, R.string.max_recording_distance_key, + PreferencesUtils.MAX_RECORDING_DISTANCE_DEFAULT)); } - if (key == null || key.equals(autoResumeTrackTimeoutKey)) { - service.setAutoResumeTrackTimeout(sharedPreferences.getInt( - autoResumeTrackTimeoutKey, - Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT)); - } - if (key == null || key.equals(PreferencesUtils.getRecordingTrackIdKey(service))) { - long recordingTrackId = PreferencesUtils.getRecordingTrackId(service); - // Only read the id if it is valid. - // Setting it to -1 should only happen in - // TrackRecordingService.endCurrentTrack() - if (recordingTrackId != -1L) { - service.setRecordingTrackId(recordingTrackId); - } - } - if (key == null || key.equals(splitFrequencyKey)) { - service.setSplitFrequency( - sharedPreferences.getInt(splitFrequencyKey, 0)); - } - if (key == null || key.equals(PreferencesUtils.getMetricUnitsKey(service))) { - service.setMetricUnits(PreferencesUtils.isMetricUnits(service)); - } - } - public void setAutoResumeTrackCurrentRetry(int retryAttempts) { - Editor editor = sharedPreferences.edit(); - editor.putInt(autoResumeTrackCurrentRetryKey, retryAttempts); - ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); + if (key == null + || PreferencesUtils.getKey(service, R.string.min_required_accuracy_key).equals(key)) { + service.setMinRequiredAccuracy(PreferencesUtils.getInt( + service, R.string.min_required_accuracy_key, + PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT)); + } + if (key == null + || PreferencesUtils.getKey(service, R.string.auto_resume_track_timeout_key).equals(key)) { + service.setAutoResumeTrackTimeout(PreferencesUtils.getInt( + service, R.string.auto_resume_track_timeout_key, + PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_DEFAULT)); + } } public void shutdown() { diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java b/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java index 87459a681..6dd08f493 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java @@ -50,7 +50,6 @@ import android.app.Service; import android.content.ContentValues; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.location.Location; @@ -84,14 +83,10 @@ public class TrackRecordingService extends Service { private LocationManager locationManager; private WakeLock wakeLock; - private int minRecordingDistance = - Constants.DEFAULT_MIN_RECORDING_DISTANCE; - private int maxRecordingDistance = - Constants.DEFAULT_MAX_RECORDING_DISTANCE; - private int minRequiredAccuracy = - Constants.DEFAULT_MIN_REQUIRED_ACCURACY; - private int autoResumeTrackTimeout = - Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT; + private int minRecordingDistance = PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT; + private int maxRecordingDistance = PreferencesUtils.MAX_RECORDING_DISTANCE_DEFAULT; + private int minRequiredAccuracy = PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT; + private int autoResumeTrackTimeout = PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_DEFAULT; private long recordingTrackId = -1; @@ -123,7 +118,7 @@ public class TrackRecordingService extends Service { private SensorManager sensorManager; - private PreferenceManager prefManager; + private PreferenceManager prefereceManager; /** * The interval in milliseconds that we have requested to be notified of gps @@ -248,7 +243,7 @@ public class TrackRecordingService extends Service { setUpTaskExecutors(); executorService = Executors.newSingleThreadExecutor(); - prefManager = new PreferenceManager(this); + prefereceManager = new PreferenceManager(this); registerLocationListener(); @@ -271,7 +266,7 @@ public class TrackRecordingService extends Service { + "Resetting an orphaned recording track = " + recordingTrackId); } recordingTrackId = -1L; - PreferencesUtils.setRecordingTrackId(this, recordingTrackId); + PreferencesUtils.setLong(this, R.string.recording_track_id_key, recordingTrackId); } showNotification(); } @@ -328,7 +323,7 @@ public class TrackRecordingService extends Service { + recordingTrack + ") doesn't exist or is too old"); isRecording = false; recordingTrackId = -1L; - PreferencesUtils.setRecordingTrackId(this, recordingTrackId); + PreferencesUtils.setLong(this, R.string.recording_track_id_key, recordingTrackId); stopSelfResult(startId); return; } @@ -354,8 +349,7 @@ public class TrackRecordingService extends Service { isRecording = false; showNotification(); - prefManager.shutdown(); - prefManager = null; + prefereceManager.shutdown(); checkLocationListener.cancel(); checkLocationListener = null; timer.cancel(); @@ -383,7 +377,7 @@ public class TrackRecordingService extends Service { private void setAutoResumeTrackRetries(int retryAttempts) { Log.d(TAG, "Updating auto-resume retry attempts to: " + retryAttempts); - prefManager.setAutoResumeTrackCurrentRetry(retryAttempts); + PreferencesUtils.setInt(this, R.string.auto_resume_track_current_retry_key, retryAttempts); } private boolean shouldResumeTrack(Track track) { @@ -391,10 +385,8 @@ public class TrackRecordingService extends Service { + autoResumeTrackTimeout); // Check if we haven't exceeded the maximum number of retry attempts. - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - int retries = sharedPreferences.getInt( - getString(R.string.auto_resume_track_current_retry_key), 0); + int retries = PreferencesUtils.getInt(this, R.string.auto_resume_track_current_retry_key, + PreferencesUtils.AUTO_RESUME_TRACK_CURRENT_RETRY_DEFAULT); Log.d(TAG, "shouldResumeTrack: Attempting to auto-resume the track (" + (retries + 1) + "/" + MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS + ")"); @@ -409,12 +401,12 @@ public class TrackRecordingService extends Service { setAutoResumeTrackRetries(retries + 1); // Check for special cases. - if (autoResumeTrackTimeout == 0) { + if (autoResumeTrackTimeout == PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_NEVER) { // Never resume. Log.d(TAG, "shouldResumeTrack: Auto-resume disabled (never resume)"); return false; - } else if (autoResumeTrackTimeout == -1) { + } else if (autoResumeTrackTimeout == PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_ALWAYS) { // Always resume. Log.d(TAG, "shouldResumeTrack: Auto-resume forced (always resume)"); @@ -565,12 +557,6 @@ public class TrackRecordingService extends Service { "Location listener now unregistered w/ TrackRecordingService."); } - private String getDefaultActivityType(Context context) { - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - return prefs.getString(context.getString(R.string.default_activity_key), ""); - } - /* * Recording lifecycle. */ @@ -593,7 +579,8 @@ public class TrackRecordingService extends Service { track.setId(recordingTrackId); track.setName(new DefaultTrackNameFactory(this).getDefaultTrackName( recordingTrackId, startTime)); - track.setCategory(getDefaultActivityType(this)); + track.setCategory(PreferencesUtils.getString( + this, R.string.default_activity_key, PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT)); isRecording = true; isMoving = true; @@ -611,7 +598,7 @@ public class TrackRecordingService extends Service { // Reset the number of auto-resume retries. setAutoResumeTrackRetries(0); // Persist the current recording track. - PreferencesUtils.setRecordingTrackId(this, recordingTrackId); + PreferencesUtils.setLong(this, R.string.recording_track_id_key, recordingTrackId); // Notify the world that we're now recording. sendTrackBroadcast( @@ -1054,7 +1041,7 @@ public class TrackRecordingService extends Service { showNotification(); long recordedTrackId = recordingTrackId; recordingTrackId = -1L; - PreferencesUtils.setRecordingTrackId(this, recordingTrackId); + PreferencesUtils.setLong(this, R.string.recording_track_id_key, recordingTrackId); if (sensorManager != null) { SensorManagerFactory.getInstance().releaseSensorManager(sensorManager); @@ -1075,10 +1062,8 @@ public class TrackRecordingService extends Service { .setAction(getString(actionResId)) .putExtra(getString(R.string.track_id_broadcast_extra), trackId); sendBroadcast(broadcastIntent, getString(R.string.permission_notification_value)); - - SharedPreferences sharedPreferences = getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (sharedPreferences.getBoolean(getString(R.string.allow_access_key), false)) { + if (PreferencesUtils.getBoolean( + this, R.string.allow_access_key, PreferencesUtils.ALLOW_ACCESS_DEFAULT)) { sendBroadcast(broadcastIntent, getString(R.string.broadcast_notifications_permission)); } } @@ -1224,20 +1209,17 @@ public class TrackRecordingService extends Service { /** * Returns true if the RPC caller is from the same application or if the - * "Allow access" setting indicates that another app can invoke this service's - * RPCs. + * "Allow access" setting indicates that another app can invoke this + * service's RPCs. */ private boolean canAccess() { - // As a precondition for access, must check if the service is available. checkService(); - if (Process.myPid() == Binder.getCallingPid()) { return true; } else { - SharedPreferences sharedPreferences = service.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - return sharedPreferences.getBoolean(service.getString(R.string.allow_access_key), false); + return PreferencesUtils.getBoolean( + service, R.string.allow_access_key, PreferencesUtils.ALLOW_ACCESS_DEFAULT); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothSensorManager.java b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothSensorManager.java index 11a4e3db1..759e4daa4 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothSensorManager.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothSensorManager.java @@ -19,12 +19,12 @@ import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; -import android.content.SharedPreferences; import android.os.Handler; import android.os.Looper; import android.os.Message; @@ -127,16 +127,20 @@ public class BluetoothSensorManager extends SensorManager { Log.w(Constants.TAG, "Disabled manager onStartTrack"); return; } - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - String address = - prefs.getString(context.getString(R.string.bluetooth_sensor_key), ""); - if (address == null || address.equals("")) { + String address = PreferencesUtils.getString( + context, R.string.bluetooth_sensor_key, PreferencesUtils.BLUETOOTH_SENSOR_DEFAULT); + if (PreferencesUtils.BLUETOOTH_SENSOR_DEFAULT.equals(address)) { return; } Log.w(Constants.TAG, "Connecting to bluetooth sensor: " + address); // Get the BluetoothDevice object - BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); + BluetoothDevice device; + try { + device = bluetoothAdapter.getRemoteDevice(address); + } catch (IllegalArgumentException e) { + Log.d(Constants.TAG, "Invalid address " + address, e); + return; + } // Attempt to connect to the device connectionManager.connect(device); diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManagerFactory.java b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManagerFactory.java index 9d98410bc..40fa7b2b6 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManagerFactory.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManagerFactory.java @@ -18,10 +18,10 @@ package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager; import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; -import android.content.SharedPreferences; import android.util.Log; /** @@ -53,41 +53,36 @@ public class SensorManagerFactory { * @return The sensor manager that corresponds to the sensor type setting. */ public SensorManager getSensorManager(Context context) { - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (prefs == null) { - return null; - } - context = context.getApplicationContext(); + String sensorTypeValueNone = context.getString(R.string.sensor_type_value_none); + String sensorType = PreferencesUtils.getString( + context, R.string.sensor_type_key, sensorTypeValueNone); + Log.i(Constants.TAG, "Creating sensor of type: " + sensorType); - String sensor = prefs.getString(context.getString(R.string.sensor_type_key), null); - Log.i(Constants.TAG, "Creating sensor of type: " + sensor); - - if (sensor == null) { + if (sensorTypeValueNone.equals(sensorType)) { reset(); return null; } - if (sensor.equals(activeSensorType)) { + if (sensorType.equals(activeSensorType)) { Log.i(Constants.TAG, "Returning existing sensor manager."); refCount++; return activeSensorManager; } reset(); - if (sensor.equals(context.getString(R.string.sensor_type_value_ant))) { + if (sensorType.equals(context.getString(R.string.sensor_type_value_ant))) { activeSensorManager = new AntDirectSensorManager(context); - } else if (sensor.equals(context.getString(R.string.sensor_type_value_srm_ant_bridge))) { + } else if (sensorType.equals(context.getString(R.string.sensor_type_value_srm_ant_bridge))) { activeSensorManager = new AntSrmBridgeSensorManager(context); - } else if (sensor.equals(context.getString(R.string.sensor_type_value_zephyr))) { + } else if (sensorType.equals(context.getString(R.string.sensor_type_value_zephyr))) { activeSensorManager = new ZephyrSensorManager(context); - } else if (sensor.equals(context.getString(R.string.sensor_type_value_polar))) { + } else if (sensorType.equals(context.getString(R.string.sensor_type_value_polar))) { activeSensorManager = new PolarSensorManager(context); } else { - Log.w(Constants.TAG, "Unable to find sensor type: " + sensor); + Log.w(Constants.TAG, "Unable to find sensor type: " + sensorType); return null; } - activeSensorType = sensor; + activeSensorType = sensorType; refCount = 1; activeSensorManager.onStartTrack(); return activeSensorManager; diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManager.java b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManager.java index 5cf6c14ca..669c8b040 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManager.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManager.java @@ -20,13 +20,11 @@ import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; -import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; -import android.content.SharedPreferences; import android.util.Log; /** @@ -107,11 +105,7 @@ public class AntDirectSensorManager extends AntSensorManager } Log.i(TAG, "Found ANT device id: " + deviceNumber + " on channel: " + channel); - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt(context.getString(sensorIdKeys[channel]), deviceNumber); - ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); + PreferencesUtils.setInt(context, sensorIdKeys[channel], deviceNumber); return deviceNumber; } @@ -171,12 +165,8 @@ public class AntDirectSensorManager extends AntSensorManager protected void setupAntSensorChannels() { short devIds[] = new short[sensorIdKeys.length]; - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (prefs != null) { - for (int i = 0; i < sensorIdKeys.length; ++i) { - devIds[i] = (short) prefs.getInt(context.getString(sensorIdKeys[i]), WILDCARD); - } + for (int i = 0; i < sensorIdKeys.length; ++i) { + devIds[i] = (short) PreferencesUtils.getInt(context, sensorIdKeys[i], WILDCARD); } sensors = new AntSensorBase[] { diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSrmBridgeSensorManager.java b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSrmBridgeSensorManager.java index 2a16fb743..be6c172ec 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSrmBridgeSensorManager.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSrmBridgeSensorManager.java @@ -20,14 +20,12 @@ import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; -import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; -import com.google.android.apps.mytracks.util.ApiAdapterFactory; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.BuildConfig; import com.google.android.maps.mytracks.R; import android.content.Context; -import android.content.SharedPreferences; import android.util.Log; /** @@ -68,13 +66,8 @@ public class AntSrmBridgeSensorManager extends AntSensorManager { deviceNumber = WILDCARD; // First read the the device id that we will be pairing with. - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (prefs != null) { - deviceNumber = - (short) prefs.getInt(context.getString( - R.string.ant_srm_bridge_sensor_id_key), 0); - } + deviceNumber = (short) PreferencesUtils.getInt( + context, R.string.ant_srm_bridge_sensor_id_key, WILDCARD); Log.i(TAG, "Will pair with device: " + deviceNumber); } @@ -194,12 +187,7 @@ public class AntSrmBridgeSensorManager extends AntSensorManager { AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); deviceNumber = message.getDeviceNumber(); Log.d(TAG, "Found device id: " + deviceNumber); - - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - SharedPreferences.Editor editor = prefs.edit(); - editor.putInt(context.getString(R.string.ant_srm_bridge_sensor_id_key), deviceNumber); - ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); + PreferencesUtils.setInt(context, R.string.ant_srm_bridge_sensor_id_key, deviceNumber); } private void handleMessageResponse(byte[] rawMessage) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskExecutor.java b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskExecutor.java index 27b1b5769..4f108732d 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskExecutor.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskExecutor.java @@ -18,6 +18,7 @@ package com.google.android.apps.mytracks.services.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.services.TrackRecordingService; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; import android.util.Log; @@ -34,7 +35,7 @@ public class PeriodicTaskExecutor { * A value greater than zero is a frequency in time. * A value less than zero is considered a frequency in distance. */ - private int taskFrequency = 0; + private int taskFrequency = PreferencesUtils.PERIODIC_TASK_OFF; /** * The next distance when the task should execute. @@ -74,7 +75,7 @@ public class PeriodicTaskExecutor { timerExecutor = null; } } - if (taskFrequency == 0) { + if (taskFrequency == PreferencesUtils.PERIODIC_TASK_OFF) { return; } diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java index e41a366b3..08ae7cb76 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java @@ -150,9 +150,11 @@ public class StatusAnnouncerTask implements PeriodicTask { */ // @VisibleForTesting protected String getAnnouncement(TripStatistics stats) { - boolean metricUnits = PreferencesUtils.isMetricUnits(context); - boolean reportSpeed = PreferencesUtils.isReportSpeed(context); - double d = stats.getTotalDistance() * UnitConversions.M_TO_KM; + boolean metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + boolean reportSpeed = PreferencesUtils.getBoolean( + context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); + double d = stats.getTotalDistance() * UnitConversions.M_TO_KM; double s = stats.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH; if (d == 0) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/AbstractSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/AbstractSettingsActivity.java new file mode 100644 index 000000000..12f315107 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/AbstractSettingsActivity.java @@ -0,0 +1,74 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; +import com.google.android.apps.mytracks.util.ApiAdapterFactory; + +import android.content.Context; +import android.os.Bundle; +import android.preference.PreferenceActivity; +import android.preference.PreferenceManager; +import android.speech.tts.TextToSpeech; +import android.view.MenuItem; + +/** + * An abstract activity for all the settings activities. + * + * @author Jimmy Shih + */ +public class AbstractSettingsActivity extends PreferenceActivity { + + private BackupPreferencesListener backupPreferencesListener; + + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); + ApiAdapterFactory.getApiAdapter().configureActionBarHomeAsUp(this); + + @SuppressWarnings("deprecation") + PreferenceManager preferenceManager = getPreferenceManager(); + preferenceManager.setSharedPreferencesName(Constants.SETTINGS_NAME); + preferenceManager.setSharedPreferencesMode(Context.MODE_PRIVATE); + + // Set up automatic preferences backup + backupPreferencesListener = ApiAdapterFactory.getApiAdapter() + .getBackupPreferencesListener(this); + preferenceManager.getSharedPreferences() + .registerOnSharedPreferenceChangeListener(backupPreferencesListener); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() != android.R.id.home) { + return super.onOptionsItemSelected(item); + } + finish(); + return true; + } + + @Override + protected void onDestroy() { + super.onDestroy(); + @SuppressWarnings("deprecation") + PreferenceManager preferenceManager = getPreferenceManager(); + preferenceManager.getSharedPreferences() + .unregisterOnSharedPreferenceChangeListener(backupPreferencesListener); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/BackupSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/BackupSettingsActivity.java new file mode 100644 index 000000000..416ce4978 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/BackupSettingsActivity.java @@ -0,0 +1,127 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.io.backup.BackupActivity; +import com.google.android.apps.mytracks.io.backup.RestoreChooserActivity; +import com.google.android.apps.mytracks.util.DialogUtils; +import com.google.android.apps.mytracks.util.IntentUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.maps.mytracks.R; + +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; + +/** + * An activity for accessing the backup settings. + * + * @author Jimmy Shih + */ +public class BackupSettingsActivity extends AbstractSettingsActivity { + + private static final int DIALOG_CONFIRM_RESTORE_ID = 0; + + Preference backupPreference; + Preference restorePreference; + + /* + * Note that sharedPreferenceChangeListenr cannot be an anonymous inner class. + * Anonymous inner class will get garbage collected. + */ + private final OnSharedPreferenceChangeListener + sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + // Note that key can be null + if (PreferencesUtils.getKey(BackupSettingsActivity.this, R.string.recording_track_id_key) + .equals(key)) { + updateUi(); + } + } + }; + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + + addPreferencesFromResource(R.xml.backup_settings); + backupPreference = findPreference(getString(R.string.settings_backup_now_key)); + backupPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(BackupSettingsActivity.this, BackupActivity.class); + startActivity(intent); + return true; + } + }); + restorePreference = findPreference(getString(R.string.settings_backup_restore_key)); + restorePreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + showDialog(DIALOG_CONFIRM_RESTORE_ID); + return true; + } + }); + } + + @Override + protected Dialog onCreateDialog(int id) { + if (id != DIALOG_CONFIRM_RESTORE_ID) { + return null; + } + return DialogUtils.createConfirmationDialog(this, + R.string.settings_backup_restore_confirm_message, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Intent intent = IntentUtils.newIntent( + BackupSettingsActivity.this, RestoreChooserActivity.class); + startActivity(intent); + } + }); + } + + @Override + protected void onResume() { + super.onResume(); + updateUi(); + } + + /** + * Updates the UI based on the recording state. + */ + private void updateUi() { + boolean isRecording = PreferencesUtils.getLong(this, R.string.recording_track_id_key) + != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT; + backupPreference.setEnabled(!isRecording); + restorePreference.setEnabled(!isRecording); + backupPreference.setSummary(isRecording ? R.string.settings_not_while_recording + : R.string.settings_backup_now_summary); + restorePreference.setSummary(isRecording ? R.string.settings_not_while_recording + : R.string.settings_backup_restore_summary); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/ChartSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/ChartSettingsActivity.java new file mode 100644 index 000000000..faab87cec --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/ChartSettingsActivity.java @@ -0,0 +1,54 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.maps.mytracks.R; + +import android.os.Bundle; +import android.preference.CheckBoxPreference; + +/** + * An activity for accessing chart settings. + * + * @author Jimmy Shih + */ +public class ChartSettingsActivity extends AbstractSettingsActivity { + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.chart_settings); + } + + @Override + protected void onResume() { + super.onResume(); + updateUi(); + } + + @SuppressWarnings("deprecation") + private void updateUi() { + CheckBoxPreference speedCheckBoxPreference = (CheckBoxPreference) findPreference( + getString(R.string.chart_show_speed_key)); + boolean reportSpeed = PreferencesUtils.getBoolean( + this, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); + speedCheckBoxPreference.setTitle(reportSpeed ? R.string.stats_speed + : R.string.stats_pace); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/MapSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/MapSettingsActivity.java new file mode 100644 index 000000000..a68efa3f4 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/MapSettingsActivity.java @@ -0,0 +1,273 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.apps.mytracks.util.UnitConversions; +import com.google.android.maps.mytracks.R; + +import android.app.Dialog; +import android.os.Bundle; +import android.preference.EditTextPreference; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceChangeListener; +import android.preference.Preference.OnPreferenceClickListener; +import android.util.Log; +import android.view.KeyEvent; +import android.view.inputmethod.EditorInfo; +import android.widget.TextView; + +/** + * An activity for accessing map settings. + * + * @author Jimmy Shih + */ +public class MapSettingsActivity extends AbstractSettingsActivity { + + private static final String TAG = MapSettingsActivity.class.getSimpleName(); + + private EditTextPreference slowEditTextPreference; + private EditTextPreference mediumEditTextPreference; + private EditTextPreference percentageEditTextPreference; + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.map_settings); + + ListPreference trackColorModeListPreference = (ListPreference) findPreference( + getString(R.string.track_color_mode_key)); + trackColorModeListPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + updateUiByTrackColorMode((String) newValue); + return true; + } + }); + + slowEditTextPreference = (EditTextPreference) findPreference( + getString(R.string.settings_map_slow_display_key)); + configureSpeedEditTextPreference(R.string.track_color_mode_slow_key); + + mediumEditTextPreference = (EditTextPreference) findPreference( + getString(R.string.settings_map_medium_display_key)); + configureSpeedEditTextPreference(R.string.track_color_mode_medium_key); + + percentageEditTextPreference = (EditTextPreference) findPreference( + getString(R.string.settings_map_percentage_display_key)); + configurePercentageEditTextPreference(); + updatePercentageSummary(); + + configureImeActionDone(slowEditTextPreference); + configureImeActionDone(mediumEditTextPreference); + configureImeActionDone(percentageEditTextPreference); + + updateUiByTrackColorMode(trackColorModeListPreference.getValue()); + } + + /** + * Configures the speed edit text preference. + * + * @param keyId the key id + */ + private void configureSpeedEditTextPreference(final int keyId) { + final EditTextPreference editTextPreference = keyId == R.string.track_color_mode_slow_key ? slowEditTextPreference + : mediumEditTextPreference; + editTextPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + storeSpeedValue(keyId, (String) newValue); + updateSpeedSummary(keyId); + return true; + } + }); + editTextPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + int value = getSpeedDisplayValue(keyId); + ((EditTextPreference) preference).getEditText().setText(String.valueOf(value)); + return true; + } + }); + } + + /** + * Configures the percentage edit text preference. + */ + private void configurePercentageEditTextPreference() { + percentageEditTextPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + String displayValue = (String) newValue; + int value; + try { + value = Integer.parseInt(displayValue); + } catch (NumberFormatException e) { + Log.e(TAG, "invalid value " + displayValue); + value = PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT; + } + if (value < 0) { + value = PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT; + } + PreferencesUtils.setInt( + MapSettingsActivity.this, R.string.track_color_mode_percentage_key, value); + updatePercentageSummary(); + return true; + } + }); + percentageEditTextPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + int value = PreferencesUtils.getInt( + MapSettingsActivity.this, R.string.track_color_mode_percentage_key, + PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT); + ((EditTextPreference) preference).getEditText().setText(String.valueOf(value)); + return true; + } + }); + } + + /** + * Configures the IME action done. + * + * @param editTextPreference the edit text preference + */ + private void configureImeActionDone(final EditTextPreference editTextPreference) { + editTextPreference.getEditText() + .setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (actionId == EditorInfo.IME_ACTION_DONE) { + Dialog dialog = editTextPreference.getDialog(); + editTextPreference.onClick(dialog, Dialog.BUTTON_POSITIVE); + dialog.dismiss(); + return true; + } + return false; + } + }); + } + + @Override + protected void onResume() { + super.onResume(); + updateSpeedSummary(R.string.track_color_mode_slow_key); + updateSpeedSummary(R.string.track_color_mode_medium_key); + } + + /** + * Updates the UI by the track color mode. + * + * @param trackColorMode the track color mode + */ + private void updateUiByTrackColorMode(String trackColorMode) { + boolean isFixedValue = trackColorMode.equals( + getString(R.string.settings_map_track_color_mode_fixed_value)); + boolean isDynamicValue = trackColorMode.equals( + getString(R.string.settings_map_track_color_mode_dynamic_value)); + slowEditTextPreference.setEnabled(isFixedValue); + mediumEditTextPreference.setEnabled(isFixedValue); + percentageEditTextPreference.setEnabled(isDynamicValue); + } + + /** + * Stores the speed value, always in metric units. + * + * @param keyId the key id + * @param displayValue the display value + */ + private void storeSpeedValue(int keyId, String displayValue) { + int maxValue; + int minValue; + int defaultValue; + if (keyId == R.string.track_color_mode_slow_key) { + minValue = 0; + maxValue = PreferencesUtils.getInt(this, R.string.track_color_mode_medium_key, + PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT); + defaultValue = PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT; + } else { + minValue = PreferencesUtils.getInt( + this, R.string.track_color_mode_slow_key, PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT); + maxValue = Integer.MAX_VALUE; + defaultValue = PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT; + } + int value; + try { + value = Integer.parseInt(displayValue); + if (!PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT)) { + value = (int) (value * UnitConversions.MI_TO_KM); + } + } catch (NumberFormatException e) { + Log.e(TAG, "invalid value " + displayValue); + value = defaultValue; + } + + if (value > maxValue) { + value = maxValue; + } + if (value < minValue) { + value = minValue; + } + PreferencesUtils.setInt(this, keyId, value); + } + + /** + * Gets the speed display value, in metric or imperial depending on the preferred + * units. + * + * @param keyId the key id + */ + private int getSpeedDisplayValue(int keyId) { + int defaultValue = keyId == R.string.track_color_mode_slow_key ? PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT + : PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT; + int value = PreferencesUtils.getInt(this, keyId, defaultValue); + if (!PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT)) { + value = (int) (value * UnitConversions.KM_TO_MI); + } + return value; + } + + /** + * Updates the speed summary. + * + * @param keyId the key id + */ + private void updateSpeedSummary(int keyId) { + EditTextPreference editTextPreference = keyId == R.string.track_color_mode_slow_key ? slowEditTextPreference + : mediumEditTextPreference; + boolean metric = PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + int displayValue = getSpeedDisplayValue(keyId); + editTextPreference.setSummary(getString(metric ? R.string.value_integer_kilometer_hour + : R.string.value_integer_mile_hour, displayValue)); + } + + /** + * Updates the percentage summary. + */ + private void updatePercentageSummary() { + int value = PreferencesUtils.getInt( + MapSettingsActivity.this, R.string.track_color_mode_percentage_key, + PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT); + percentageEditTextPreference.setSummary(getString(R.string.settings_map_percentage_summary) + "\n" + + getString(R.string.value_integer_percent, value)); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/RecordingSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/RecordingSettingsActivity.java new file mode 100644 index 000000000..ccbea807b --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/RecordingSettingsActivity.java @@ -0,0 +1,243 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.apps.mytracks.util.UnitConversions; +import com.google.android.maps.mytracks.R; + +import android.os.Bundle; +import android.preference.ListPreference; + +/** + * An activity for accessing recording settings. + * + * @author Jimmy Shih + */ +public class RecordingSettingsActivity extends AbstractSettingsActivity { + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.recording_settings); + + boolean metricUnits = PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + + ListPreference announcementFrequencyListPreference = (ListPreference) findPreference( + getString(R.string.announcement_frequency_key)); + announcementFrequencyListPreference.setEntries(getPeriodicTaskDisplayOptions(metricUnits)); + + ListPreference splitFrequencyListPreference = (ListPreference) findPreference( + getString(R.string.split_frequency_key)); + splitFrequencyListPreference.setEntries(getPeriodicTaskDisplayOptions(metricUnits)); + + ListPreference minRecordingIntervalListPreference = (ListPreference) findPreference( + getString(R.string.min_recording_interval_key)); + minRecordingIntervalListPreference.setEntries(getMinRecordingIntervalDisplayOptions()); + + ListPreference minRecordingDistanceListPreference = (ListPreference) findPreference( + getString(R.string.min_recording_distance_key)); + minRecordingDistanceListPreference.setEntries( + getMinRecordingDistanceDisplayOptions(metricUnits)); + + ListPreference maxRecordingDistanceListPreference = (ListPreference) findPreference( + getString(R.string.max_recording_distance_key)); + maxRecordingDistanceListPreference.setEntries( + getMaxRecordingDistanceDisplayOptions(metricUnits)); + + ListPreference minRequiredAccuracyListPreference = (ListPreference) findPreference( + getString(R.string.min_required_accuracy_key)); + minRequiredAccuracyListPreference.setEntries(getMinRequiredAccuracyDisplayOptions(metricUnits)); + + ListPreference autoResumeTrackTimeoutListPreference = (ListPreference) findPreference( + getString(R.string.auto_resume_track_timeout_key)); + autoResumeTrackTimeoutListPreference.setEntries(getAutoResumeTrackTimeoutDisplayOptions()); + } + + /** + * Gets the periodic task display options. + * + * @param metricUnits true to display metric units + */ + private String[] getPeriodicTaskDisplayOptions(boolean metricUnits) { + String[] values = getResources().getStringArray(R.array.periodic_task_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + if (value == PreferencesUtils.PERIODIC_TASK_OFF) { + options[i] = getString(R.string.value_off); + } else if (value < 0) { + options[i] = getString(metricUnits ? R.string.value_integer_kilometer + : R.string.value_integer_mile, Math.abs(value)); + } else { + options[i] = getString(R.string.value_integer_minute, value); + } + } + return options; + } + + /** + * Gets the min recording interval display options. + */ + private String[] getMinRecordingIntervalDisplayOptions() { + String[] values = getResources().getStringArray(R.array.min_recording_interval_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + switch (value) { + case PreferencesUtils.MIN_RECORDING_INTERVAL_ADAPT_BATTERY_LIFE: + options[i] = getString(R.string.value_adapt_battery_life); + break; + case PreferencesUtils.MIN_RECORDING_INTERVAL_ADAPT_ACCURACY: + options[i] = getString(R.string.value_adapt_accuracy); + break; + case PreferencesUtils.MIN_RECORDING_INTERVAL_DEFAULT: + options[i] = getString(R.string.value_smallest_recommended); + break; + default: + options[i] = value < 60 ? getString(R.string.value_integer_second, value) + : getString(R.string.value_integer_minute, value / 60); + } + } + return options; + } + + /** + * Gets the min recording distance display options. + * + * @param metricUnits true to display metric units + */ + private String[] getMinRecordingDistanceDisplayOptions(boolean metricUnits) { + String[] values = getResources().getStringArray(R.array.min_recording_distance_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + if (metricUnits) { + options[i] = getString(value == PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT + ? R.string.value_integer_meter_recommended + : R.string.value_integer_meter, value); + } else { + int feet = (int) (value * UnitConversions.M_TO_FT); + options[i] = getString(value == PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT + ? R.string.value_integer_feet_recommended + : R.string.value_integer_feet, feet); + } + } + return options; + } + + /** + * Gets the max recording distance display options. + * + * @param metricUnits true to display metric units + */ + private String[] getMaxRecordingDistanceDisplayOptions(boolean metricUnits) { + String[] values = getResources().getStringArray(R.array.max_recording_distance_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + if (metricUnits) { + options[i] = getString(value == PreferencesUtils.MAX_RECORDING_DISTANCE_DEFAULT + ? R.string.value_integer_meter_recommended + : R.string.value_integer_meter, value); + } else { + int feet = (int) (value * UnitConversions.M_TO_FT); + if (feet < 2000) { + options[i] = getString(value == PreferencesUtils.MAX_RECORDING_DISTANCE_DEFAULT + ? R.string.value_integer_feet_recommended + : R.string.value_integer_feet, feet); + } else { + double mile = feet * UnitConversions.FT_TO_MI; + options[i] = getString(R.string.value_float_mile, mile); + } + } + } + return options; + } + + /** + * Gets the min required accuracy display options. + * + * @param metricUnits true to display metric units + */ + private String[] getMinRequiredAccuracyDisplayOptions(boolean metricUnits) { + String[] values = getResources().getStringArray(R.array.min_required_accuracy_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + if (metricUnits) { + switch (value) { + case PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT: + options[i] = getString(R.string.value_integer_meter_recommended, value); + break; + case PreferencesUtils.MIN_REQUIRED_ACCURACY_EXCELLENT: + options[i] = getString(R.string.value_integer_meter_excellent_gps, value); + break; + case PreferencesUtils.MIN_REQUIRED_ACCURACY_POOR: + options[i] = getString(R.string.value_integer_meter_poor_gps, value); + break; + default: + options[i] = getString(R.string.value_integer_meter, value); + } + } else { + int feet = (int) (value * UnitConversions.M_TO_FT); + if (feet < 2000) { + switch (value) { + case PreferencesUtils.MIN_REQUIRED_ACCURACY_DEFAULT: + options[i] = getString(R.string.value_integer_feet_recommended, feet); + break; + case PreferencesUtils.MIN_REQUIRED_ACCURACY_EXCELLENT: + options[i] = getString(R.string.value_integer_feet_excellent_gps, feet); + break; + default: + options[i] = getString(R.string.value_integer_feet, feet); + } + } else { + double mile = feet * UnitConversions.FT_TO_MI; + options[i] = getString(value == PreferencesUtils.MIN_REQUIRED_ACCURACY_POOR + ? R.string.value_float_mile_poor_gps + : R.string.value_float_mile, mile); + } + } + } + return options; + } + + /** + * Gets the auto resume track timeout display options. + */ + private String[] getAutoResumeTrackTimeoutDisplayOptions() { + String[] values = getResources().getStringArray(R.array.auto_resume_track_timeout_values); + String[] options = new String[values.length]; + for (int i = 0; i < values.length; i++) { + int value = Integer.parseInt(values[i]); + switch (value) { + case PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_NEVER: + options[i] = getString(R.string.value_never); + break; + case PreferencesUtils.AUTO_RESUME_TRACK_TIMEOUT_ALWAYS: + options[i] = getString(R.string.value_always); + break; + default: + options[i] = getString(R.string.value_integer_minute, value); + } + } + return options; + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/SensorSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/SensorSettingsActivity.java new file mode 100644 index 000000000..88f9b14e7 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/SensorSettingsActivity.java @@ -0,0 +1,141 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.services.sensors.ant.AntUtils; +import com.google.android.apps.mytracks.util.BluetoothDeviceUtils; +import com.google.android.maps.mytracks.R; + +import android.bluetooth.BluetoothAdapter; +import android.content.Intent; +import android.os.Bundle; +import android.preference.ListPreference; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceChangeListener; +import android.preference.Preference.OnPreferenceClickListener; +import android.preference.PreferenceScreen; +import android.provider.Settings; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * An activity for accessing sensor settings. + * + * @author Jimmy Shih + */ +public class SensorSettingsActivity extends AbstractSettingsActivity { + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.sensor_settings); + + ListPreference sensorTypeListPreference = (ListPreference) findPreference( + getString(R.string.sensor_type_key)); + List sensorTypeEntries = Arrays.asList(getResources().getStringArray( + AntUtils.hasAntSupport(this) ? R.array.sensor_type_all_options + : R.array.sensor_type_bluetooth_options)); + List sensorTypeEntryValues = Arrays.asList(getResources().getStringArray( + AntUtils.hasAntSupport(this) ? R.array.sensor_type_all_values + : R.array.sensor_type_bluetooth_values)); + sensorTypeListPreference.setEntries(sensorTypeEntries.toArray( + new CharSequence[sensorTypeEntries.size()])); + sensorTypeListPreference.setEntryValues( + sensorTypeEntryValues.toArray(new CharSequence[sensorTypeEntryValues.size()])); + sensorTypeListPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + updateUiBySensorType((String) newValue); + return true; + } + }); + + updateUiBySensorType(sensorTypeListPreference.getValue()); + + findPreference(getString(R.string.settings_sensor_bluetooth_pairing_key)) + .setOnPreferenceClickListener(new OnPreferenceClickListener() { + public boolean onPreferenceClick(Preference preference) { + Intent settingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); + startActivity(settingsIntent); + return true; + } + }); + + if (!AntUtils.hasAntSupport(this)) { + PreferenceScreen rootPreferenceScreen = (PreferenceScreen) findPreference( + getString(R.string.settings_sensor_root_key)); + rootPreferenceScreen.removePreference( + findPreference(getString(R.string.settings_sensor_ant_key))); + } + } + + /** + * Updates the UI based on the sensor type. + * + * @param sensorType the sensor type + */ + @SuppressWarnings("deprecation") + private void updateUiBySensorType(String sensorType) { + boolean isBluetooth = getString(R.string.sensor_type_value_polar).equals(sensorType) + || getString(R.string.sensor_type_value_zephyr).equals(sensorType); + findPreference(getString(R.string.settings_sensor_bluetooth_key)).setEnabled(isBluetooth); + + Preference antHeartRateSensorId = findPreference( + getString(R.string.ant_heart_rate_sensor_id_key)); + if (antHeartRateSensorId != null) { + antHeartRateSensorId.setEnabled(getString(R.string.sensor_type_value_ant).equals(sensorType)); + } + + Preference antSrmBridgetSensorId = findPreference( + getString(R.string.ant_srm_bridge_sensor_id_key)); + if (antSrmBridgetSensorId != null) { + antSrmBridgetSensorId.setEnabled( + getString(R.string.sensor_type_value_srm_ant_bridge).equals(sensorType)); + } + } + + @Override + protected void onResume() { + super.onResume(); + updateBluetoothSensorListPreference(); + } + + /** + * Updates the bluetooth sensor list preference. + */ + private void updateBluetoothSensorListPreference() { + @SuppressWarnings("deprecation") + ListPreference bluetoothSensorListPreference = (ListPreference) findPreference( + getString(R.string.bluetooth_sensor_key)); + List entries = new ArrayList(); + List entryValues = new ArrayList(); + BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + + if (bluetoothAdapter != null) { + BluetoothDeviceUtils.populateDeviceLists(bluetoothAdapter, entries, entryValues); + } + bluetoothSensorListPreference.setEntries(entries.toArray(new CharSequence[entries.size()])); + bluetoothSensorListPreference.setEntryValues(entryValues.toArray( + new CharSequence[entryValues.size()])); + if (entries.size() == 1) { + bluetoothSensorListPreference.setValueIndex(0); + } + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/SettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/SettingsActivity.java new file mode 100644 index 000000000..cbea11e9e --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/SettingsActivity.java @@ -0,0 +1,189 @@ +/* + * 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.settings; + +import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.DialogUtils; +import com.google.android.apps.mytracks.util.IntentUtils; +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.maps.mytracks.R; + +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceClickListener; +import android.util.Log; +import android.widget.Toast; + +/** + * An activity for accessing settings. + * + * @author Leif Hendrik Wilden + * @author Rodrigo Damazio + */ +public class SettingsActivity extends AbstractSettingsActivity { + + private static final String TAG = SettingsActivity.class.getSimpleName(); + private static final int DIALOG_CONFIRM_RESET_ID = 0; + + private Preference resetPreference; + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.settings); + + Preference mapPreference = findPreference(getString(R.string.settings_map_key)); + mapPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, MapSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference chartPreference = findPreference(getString(R.string.settings_chart_key)); + chartPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, ChartSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference statsPreference = findPreference(getString(R.string.settings_stats_key)); + statsPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, StatsSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference recordingPreference = findPreference(getString(R.string.settings_recording_key)); + recordingPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent( + SettingsActivity.this, RecordingSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference sharingPreference = findPreference(getString(R.string.settings_sharing_key)); + sharingPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, SharingSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference sensorPreference = findPreference(getString(R.string.settings_sensor_key)); + sensorPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, SensorSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + Preference backupPreference = findPreference(getString(R.string.settings_backup_key)); + backupPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference preference) { + Intent intent = IntentUtils.newIntent(SettingsActivity.this, BackupSettingsActivity.class); + startActivity(intent); + return true; + } + }); + + resetPreference = findPreference(getString(R.string.settings_reset_key)); + resetPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(Preference arg0) { + showDialog(DIALOG_CONFIRM_RESET_ID); + return true; + } + }); + } + + @Override + protected void onResume() { + super.onResume(); + boolean isRecording = PreferencesUtils.getLong(this, R.string.recording_track_id_key) + != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT; + resetPreference.setEnabled(!isRecording); + resetPreference.setSummary(isRecording ? R.string.settings_not_while_recording + : R.string.settings_reset_summary); + } + + @Override + protected Dialog onCreateDialog(int id) { + if (id != DIALOG_CONFIRM_RESET_ID) { + return null; + } + return DialogUtils.createConfirmationDialog( + this, R.string.settings_reset_confirm_message, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int button) { + onResetPreferencesConfirmed(); + } + }); + } + + /** + * Callback when the 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"); + SharedPreferences sharedPreferences = getSharedPreferences( + Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + // Actually wipe preferences and save synchronously + sharedPreferences.edit().clear().commit(); + + // Give UI feedback in the UI thread + runOnUiThread(new Runnable() { + @Override + public void run() { + 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() + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + } + }); + } + }.start(); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/SharingSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/SharingSettingsActivity.java new file mode 100644 index 000000000..a322ce262 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/SharingSettingsActivity.java @@ -0,0 +1,75 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.util.DialogUtils; +import com.google.android.maps.mytracks.R; + +import android.app.Dialog; +import android.content.DialogInterface; +import android.os.Bundle; +import android.preference.CheckBoxPreference; +import android.preference.Preference; +import android.preference.Preference.OnPreferenceChangeListener; + +/** + * An activity for accessing the sharing settings. + * + * @author Jimmy Shih + */ +public class SharingSettingsActivity extends AbstractSettingsActivity { + + private static final int DIALOG_CONFIRM_ALLOW_ACCESS_ID = 0; + + private CheckBoxPreference allowAccessCheckBoxPreference; + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.sharing_settings); + + allowAccessCheckBoxPreference = (CheckBoxPreference) findPreference( + getString(R.string.allow_access_key)); + allowAccessCheckBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + if ((Boolean) newValue) { + showDialog(DIALOG_CONFIRM_ALLOW_ACCESS_ID); + return false; + } else { + return true; + } + } + }); + } + + @Override + protected Dialog onCreateDialog(int id) { + if (id != DIALOG_CONFIRM_ALLOW_ACCESS_ID) { + return null; + } + return DialogUtils.createConfirmationDialog(this, + R.string.settings_sharing_allow_access_confirm_message, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int button) { + allowAccessCheckBoxPreference.setChecked(true); + } + }); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/settings/StatsSettingsActivity.java b/MyTracks/src/com/google/android/apps/mytracks/settings/StatsSettingsActivity.java new file mode 100644 index 000000000..7b5781756 --- /dev/null +++ b/MyTracks/src/com/google/android/apps/mytracks/settings/StatsSettingsActivity.java @@ -0,0 +1,81 @@ +/* + * Copyright 2012 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.settings; + +import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.maps.mytracks.R; + +import android.content.Context; +import android.content.SharedPreferences; +import android.content.SharedPreferences.OnSharedPreferenceChangeListener; +import android.os.Bundle; +import android.preference.CheckBoxPreference; + +/** + * An activity for accessing stats settings. + * + * @author Jimmy Shih + */ +public class StatsSettingsActivity extends AbstractSettingsActivity { + + /* + * Note that sharedPreferenceChangeListenr cannot be an anonymous inner class. + * Anonymous inner class will get garbage collected. + */ + private final OnSharedPreferenceChangeListener + sharedPreferenceChangeListener = new OnSharedPreferenceChangeListener() { + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + // Note that key can be null + if (PreferencesUtils.getKey(StatsSettingsActivity.this, R.string.metric_units_key) + .equals(key)) { + updateUi(); + } + } + }; + + @SuppressWarnings("deprecation") + @Override + protected void onCreate(Bundle bundle) { + super.onCreate(bundle); + addPreferencesFromResource(R.xml.stats_settings); + + getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE) + .registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); + } + + @Override + protected void onResume() { + super.onResume(); + updateUi(); + } + + @SuppressWarnings("deprecation") + private void updateUi() { + CheckBoxPreference reportSpeedCheckBoxPreference = (CheckBoxPreference) findPreference( + getString(R.string.report_speed_key)); + boolean metric = PreferencesUtils.getBoolean( + this, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + reportSpeedCheckBoxPreference.setSummaryOn( + metric ? getString(R.string.settings_stats_rate_speed_metric) + : getString(R.string.settings_stats_rate_speed_imperial)); + reportSpeedCheckBoxPreference.setSummaryOff( + metric ? getString(R.string.settings_stats_rate_pace_metric) + : getString(R.string.settings_stats_rate_pace_imperial)); + } +} diff --git a/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java b/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java index c1dd59442..3f6f7e770 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java +++ b/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java @@ -19,6 +19,7 @@ package com.google.android.apps.mytracks.stats; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; import android.location.Location; import android.util.Log; @@ -91,8 +92,7 @@ public class TripStatisticsBuilder { */ private long totalLocations = 0; - private int minRecordingDistance = - Constants.DEFAULT_MIN_RECORDING_DISTANCE; + private int minRecordingDistance = PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT; /** * Creates a new trip starting at the given time. diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java b/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java index 71d61cd2b..87c343190 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java @@ -37,7 +37,7 @@ import java.util.List; /** * API level 11 specific implementation of the {@link ApiAdapter}. - * + * * @author Jimmy Shih */ @TargetApi(11) @@ -54,12 +54,11 @@ public class Api11Adapter extends Api10Adapter { } @Override - public void configureListViewContextualMenu(final Activity activity, ListView listView, final int menuId, - final int actionModeTitleId, + public void configureListViewContextualMenu(final Activity activity, ListView listView, + final int menuId, final int actionModeTitleId, final ContextualActionModeCallback contextualActionModeCallback) { listView.setOnItemLongClickListener(new OnItemLongClickListener() { ActionMode actionMode; - @Override public boolean onItemLongClick( AdapterView parent, View view, final int position, final long id) { @@ -72,18 +71,15 @@ public class Api11Adapter extends Api10Adapter { mode.getMenuInflater().inflate(menuId, menu); return true; } - @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Return false to indicate no change. return false; } - @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; } - @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { mode.finish(); @@ -99,37 +95,13 @@ public class Api11Adapter extends Api10Adapter { } }); }; - + @Override public void configureSearchWidget(Activity activity, final MenuItem menuItem) { SearchManager searchManager = (SearchManager) activity.getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menuItem.getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(activity.getComponentName())); searchView.setQueryRefinementEnabled(true); - searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - menuItem.collapseActionView(); - return false; - } - - @Override - public boolean onQueryTextChange(String newText) { - return false; - } - }); - searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { - @Override - public boolean onSuggestionSelect(int position) { - return false; - } - - @Override - public boolean onSuggestionClick(int position) { - menuItem.collapseActionView(); - return false; - } - }); } @Override diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/Api14Adapter.java b/MyTracks/src/com/google/android/apps/mytracks/util/Api14Adapter.java index 6cc7fb5ee..cd86c0e1d 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/Api14Adapter.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/Api14Adapter.java @@ -20,10 +20,11 @@ import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.view.MenuItem; +import android.widget.SearchView; /** * API level 14 specific implementation of the {@link ApiAdapter}. - * + * * @author Jimmy Shih */ @TargetApi(14) @@ -35,7 +36,35 @@ public class Api14Adapter extends Api11Adapter { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } - + + @Override + public void configureSearchWidget(Activity activity, final MenuItem menuItem) { + super.configureSearchWidget(activity, menuItem); + SearchView searchView = (SearchView) menuItem.getActionView(); + searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { + @Override + public boolean onQueryTextSubmit(String query) { + menuItem.collapseActionView(); + return false; + } + @Override + public boolean onQueryTextChange(String newText) { + return false; + } + }); + searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { + @Override + public boolean onSuggestionSelect(int position) { + return false; + } + @Override + public boolean onSuggestionClick(int position) { + menuItem.collapseActionView(); + return false; + } + }); + } + @Override public boolean handleSearchKey(MenuItem menuItem) { menuItem.expandActionView(); diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/BluetoothDeviceUtils.java b/MyTracks/src/com/google/android/apps/mytracks/util/BluetoothDeviceUtils.java index 548d873c7..ed1631070 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/BluetoothDeviceUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/BluetoothDeviceUtils.java @@ -24,17 +24,17 @@ import java.util.Set; /** * Utilities for dealing with bluetooth devices. - * + * * @author Rodrigo Damazio */ public class BluetoothDeviceUtils { private BluetoothDeviceUtils() {} - + /** * Populates the device names and the device addresses with all the suitable * bluetooth devices. - * + * * @param bluetoothAdapter the bluetooth adapter * @param deviceNames list of device names * @param deviceAddresses list of device addresses diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/ChartURLGenerator.java b/MyTracks/src/com/google/android/apps/mytracks/util/ChartURLGenerator.java index 3c6a69f3c..469dfd45f 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/ChartURLGenerator.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/ChartURLGenerator.java @@ -47,7 +47,8 @@ public class ChartURLGenerator { */ public static String getChartUrl( Vector distances, Vector elevations, Track track, Context context) { - boolean metricUnits = PreferencesUtils.isMetricUnits(context); + boolean metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); return getChartUrl( distances, elevations, track, context.getString(R.string.stats_elevation), metricUnits); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/PreferencesUtils.java b/MyTracks/src/com/google/android/apps/mytracks/util/PreferencesUtils.java index 108d2f6d2..527593f1a 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/PreferencesUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/PreferencesUtils.java @@ -17,7 +17,6 @@ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; -import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; @@ -30,163 +29,74 @@ import android.content.SharedPreferences.Editor; */ public class PreferencesUtils { + /* + * Preferences values. The defaults need to match the defaults in the xml + * files. + */ + public static final boolean ALLOW_ACCESS_DEFAULT = false; + public static final int ANNOUNCEMENT_FREQUENCY_DEFAULT = 0; + public static final int AUTO_RESUME_TRACK_CURRENT_RETRY_DEFAULT = 0; + + public static final int AUTO_RESUME_TRACK_TIMEOUT_ALWAYS = -1; + public static final int AUTO_RESUME_TRACK_TIMEOUT_DEFAULT = 10; + public static final int AUTO_RESUME_TRACK_TIMEOUT_NEVER = 0; + + public static final String BLUETOOTH_SENSOR_DEFAULT = ""; + + public static final boolean CHART_BY_DISTANCE_DEFAULT = true; + public static final boolean CHART_SHOW_CADENCE_DEFAULT = true; + public static final boolean CHART_SHOW_ELEVATION_DEFAULT = true; + public static final boolean CHART_SHOW_HEART_RATE_DEFAULT = true; + public static final boolean CHART_SHOW_POWER_DEFAULT = true; + public static final boolean CHART_SHOW_SPEED_DEFAULT = true; + + public static final String DEFAULT_ACTIVITY_DEFAULT = ""; + public static final boolean DEFAULT_MAP_PUBLIC_DEFAULT = true; + public static final int MAX_RECORDING_DISTANCE_DEFAULT = 200; + public static final boolean METRIC_UNITS_DEFAULT = true; + public static final int MIN_RECORDING_DISTANCE_DEFAULT = 5; + + public static final int MIN_RECORDING_INTERVAL_ADAPT_ACCURACY = -1; + public static final int MIN_RECORDING_INTERVAL_ADAPT_BATTERY_LIFE = -2; + public static final int MIN_RECORDING_INTERVAL_DEFAULT = 0; + + public static final int MIN_REQUIRED_ACCURACY_DEFAULT = 200; + public static final int MIN_REQUIRED_ACCURACY_EXCELLENT = 10; + public static final int MIN_REQUIRED_ACCURACY_POOR = 5000; + + public static final int PERIODIC_TASK_OFF = 0; + public static final boolean PICK_EXISTING_MAP_DEFAULT = false; + public static final boolean PICK_STATISTICS_MARKER_DEFAULT = true; + public static final String PREFERRED_ACCOUNT_DEFAULT = ""; + public static final long RECORDING_TRACK_ID_DEFAULT = -1L; + public static final boolean REPORT_SPEED_DEFAULT = true; + public static final long SELECTED_TRACK_ID_DEFAULT = -1L; + public static final boolean SEND_TO_DOCS_DEFAULT = true; + public static final boolean SEND_TO_FUSION_TABLES_DEFAULT = true; + public static final boolean SEND_TO_MAPS_DEFAULT = true; + public static final boolean SHARE_URL_ONLY_DEFAULT = false; + public static final boolean SHOW_CHECK_UNITS_DIALOG_DEFAULT = true; + public static final boolean SHOW_WELCOME_DIALOG_DEFAULT = true; + public static final int SPLIT_FREQUENCY_DEFAULT = 0; + + public static final boolean STATS_SHOW_COORDINATE_DEFAULT = false; + public static final boolean STATS_SHOW_ELEVATION_DEFAULT = false; + public static final boolean STATS_SHOW_GRADE_DEFAULT = false; + public static final boolean STATS_USE_TOTAL_TIME_DEFAULT = true; + + public static final int TRACK_COLOR_MODE_MEDIUM_DEFAULT = 15; + public static final int TRACK_COLOR_MODE_PERCENTAGE_DEFAULT = 25; + public static final int TRACK_COLOR_MODE_SLOW_DEFAULT = 9; + private PreferencesUtils() {} - /** - * Gets the metric units key. - * - * @param context the context - */ - public static String getMetricUnitsKey(Context context) { - return getKey(context, R.string.metric_units_key); - } - - /** - * Returns the metric units value. - * - * @param context the context - */ - public static boolean isMetricUnits(Context context) { - return getBoolean(context, R.string.metric_units_key, true); - } - - /** - * Sets the metric units value. - * - * @param context the context - * @param value the value - */ - public static void setMetricUnits(Context context, boolean value) { - setBoolean(context, R.string.metric_units_key, value); - } - - /** - * Gets the recording track id key. - * - * @param context the context - */ - public static String getRecordingTrackIdKey(Context context) { - return getKey(context, R.string.recording_track_id_key); - } - - /** - * Gets the recording track id. - * - * @param context the context - */ - public static long getRecordingTrackId(Context context) { - return getLong(context, R.string.recording_track_id_key); - } - - /** - * Sets the recording track id. - * - * @param context the context - * @param trackId the track id - */ - public static void setRecordingTrackId(Context context, long trackId) { - setLong(context, R.string.recording_track_id_key, trackId); - } - - /** - * Gets the report speed key. - * - * @param context the context - */ - public static String getReportSpeedKey(Context context) { - return getKey(context, R.string.report_speed_key); - } - - /** - * Returns the report speed value. - * - * @param context the context - */ - public static boolean isReportSpeed(Context context) { - return getBoolean(context, R.string.report_speed_key, true); - } - - /** - * Sets the report speed value. - * - * @param context the context - * @param value the value - */ - public static void setReportSpeed(Context context, boolean value) { - setBoolean(context, R.string.report_speed_key, value); - } - - /** - * Gets the selected track id key. - * - * @param context the context - */ - public static String getSelectedTrackIdKey(Context context) { - return getKey(context, R.string.selected_track_id_key); - } - - /** - * Gets the selected track id. - * - * @param context the context - */ - public static long getSelectedTrackId(Context context) { - return getLong(context, R.string.selected_track_id_key); - } - - /** - * Sets the selected track id. - * - * @param context the context - * @param trackId the track id - */ - public static void setSelectedTrackId(Context context, long trackId) { - setLong(context, R.string.selected_track_id_key, trackId); - } - - /** - * Returns the show check units dialog value. - * - * @param context the context - */ - public static boolean isShowCheckUnitsDialog(Context context) { - return getBoolean(context, R.string.show_check_units_dialog_key, true); - } - - /** - * Sets the show check units dialog value to false. - * - * @param context the context - */ - public static void setShowCheckUnitsDialog(Context context) { - setBoolean(context, R.string.show_check_units_dialog_key, false); - } - - /** - * Returns the show welcomes dialog value. - * - * @param context the context - */ - public static boolean isShowWelcomeDialog(Context context) { - return getBoolean(context, R.string.show_welcome_dialog_key, true); - } - - /** - * Sets the show welcome dialog value to false. - * - * @param context the context - */ - public static void setShowWelcome(Context context) { - setBoolean(context, R.string.show_welcome_dialog_key, false); - } - /** * Gets a preference key * * @param context the context * @param keyId the key id */ - private static String getKey(Context context, int keyId) { + public static String getKey(Context context, int keyId) { return context.getString(keyId); } @@ -202,7 +112,7 @@ public class PreferencesUtils { Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(getKey(context, keyId), defaultValue); } - + /** * Sets a boolean preference value. * @@ -217,14 +127,42 @@ public class PreferencesUtils { editor.putBoolean(getKey(context, keyId), value); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } - + + /** + * Gets an integer preference value. + * + * @param context the context + * @param keyId the key id + * @param defaultValue the default value + */ + public static int getInt(Context context, int keyId, int defaultValue) { + SharedPreferences sharedPreferences = context.getSharedPreferences( + Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + return sharedPreferences.getInt(getKey(context, keyId), defaultValue); + } + + /** + * Sets an integer preference value. + * + * @param context the context + * @param keyId the key id + * @param value the value + */ + public static void setInt(Context context, int keyId, int value) { + SharedPreferences sharedPreferences = context.getSharedPreferences( + Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + Editor editor = sharedPreferences.edit(); + editor.putInt(getKey(context, keyId), value); + ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); + } + /** * Gets a long preference value. * * @param context the context * @param keyId the key id */ - private static long getLong(Context context, int keyId) { + public static long getLong(Context context, int keyId) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getLong(getKey(context, keyId), -1L); @@ -237,11 +175,39 @@ public class PreferencesUtils { * @param keyId the key id * @param value the value */ - private static void setLong(Context context, int keyId, long value) { + public static void setLong(Context context, int keyId, long value) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putLong(getKey(context, keyId), value); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } + + /** + * Gets a string preference value. + * + * @param context the context + * @param keyId the key id + * @param defaultValue default value + */ + public static String getString(Context context, int keyId, String defaultValue) { + SharedPreferences sharedPreferences = context.getSharedPreferences( + Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + return sharedPreferences.getString(getKey(context, keyId), defaultValue); + } + + /** + * Sets a string preference value. + * + * @param context the context + * @param keyId the key id + * @param value the value + */ + public static void setString(Context context, int keyId, String value) { + SharedPreferences sharedPreferences = context.getSharedPreferences( + Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + Editor editor = sharedPreferences.edit(); + editor.putString(getKey(context, keyId), value); + ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); + } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/StatsUtils.java b/MyTracks/src/com/google/android/apps/mytracks/util/StatsUtils.java index a5e317d8f..32e49af82 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/StatsUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/StatsUtils.java @@ -42,12 +42,14 @@ public class StatsUtils { * elevation field */ public static void setLocationValues(Activity activity, Location location, boolean showAll) { - boolean metricUnits = PreferencesUtils.getBoolean(activity, R.string.metric_units_key, true); - boolean reportSpeed = PreferencesUtils.getBoolean(activity, R.string.report_speed_key, true); + boolean metricUnits = PreferencesUtils.getBoolean( + activity, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + boolean reportSpeed = PreferencesUtils.getBoolean( + activity, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); // Set elevation boolean showElevation = PreferencesUtils.getBoolean( - activity, R.string.stats_show_elevation_key, false); + activity, R.string.stats_show_elevation_key, PreferencesUtils.STATS_SHOW_ELEVATION_DEFAULT); if (showElevation) { double altitude = location == null ? Double.NaN : location.getAltitude(); setElevationValue(activity, R.id.stats_elevation_value, altitude, metricUnits); @@ -64,8 +66,8 @@ public class StatsUtils { setSpeedValue(activity, R.id.stats_speed_value, speed, metricUnits, reportSpeed); // Set coordinate - boolean showCoordinate = PreferencesUtils.getBoolean( - activity, R.string.stats_show_coordinate_key, false); + boolean showCoordinate = PreferencesUtils.getBoolean(activity, + R.string.stats_show_coordinate_key, PreferencesUtils.STATS_SHOW_COORDINATE_DEFAULT); View coordinateLabelTableRow = activity.findViewById(R.id.stats_coordinate_label_table_row); View coordinateValueTableRow = activity.findViewById(R.id.stats_coordinate_value_table_row); coordinateLabelTableRow.setVisibility(showCoordinate ? View.VISIBLE : View.GONE); @@ -95,10 +97,12 @@ public class StatsUtils { * @param tripStatistics the trip statistics */ public static void setTripStatisticsValues(Activity activity, TripStatistics tripStatistics) { - boolean metricUnits = PreferencesUtils.getBoolean(activity, R.string.metric_units_key, true); - boolean reportSpeed = PreferencesUtils.getBoolean(activity, R.string.report_speed_key, true); - boolean showTotalTime = PreferencesUtils.getBoolean( - activity, R.string.stats_show_total_time_key, true); + boolean metricUnits = PreferencesUtils.getBoolean( + activity, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); + boolean reportSpeed = PreferencesUtils.getBoolean( + activity, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); + boolean useTotalTime = PreferencesUtils.getBoolean( + activity, R.string.stats_use_total_time_key, PreferencesUtils.STATS_USE_TOTAL_TIME_DEFAULT); // Set total distance double totalDistance = tripStatistics == null ? Double.NaN : tripStatistics.getTotalDistance(); @@ -106,17 +110,17 @@ public class StatsUtils { // Set total time/moving time setTimeLabel(activity, R.id.stats_total_time_label, R.string.stats_total_time, - R.string.stats_moving_time, showTotalTime); + R.string.stats_moving_time, useTotalTime); long totalTime; if (tripStatistics == null) { totalTime = -1L; } else { - totalTime = showTotalTime ? tripStatistics.getTotalTime() : tripStatistics.getMovingTime(); + totalTime = useTotalTime ? tripStatistics.getTotalTime() : tripStatistics.getMovingTime(); } setTimeValue(activity, R.id.stats_total_time_value, totalTime); // Set average speed/moving average speed - if (showTotalTime) { + if (useTotalTime) { setSpeedLabel(activity, R.id.stats_average_speed_label, R.string.stats_average_speed, R.string.stats_average_pace, reportSpeed); } else { @@ -127,7 +131,7 @@ public class StatsUtils { if (tripStatistics == null) { averageSpeed = Double.NaN; } else { - averageSpeed = showTotalTime ? tripStatistics.getAverageSpeed() + averageSpeed = useTotalTime ? tripStatistics.getAverageSpeed() : tripStatistics.getAverageMovingSpeed(); } setSpeedValue(activity, R.id.stats_average_speed_value, averageSpeed, metricUnits, reportSpeed); @@ -140,7 +144,7 @@ public class StatsUtils { // Set elevation boolean showElevation = PreferencesUtils.getBoolean( - activity, R.string.stats_show_elevation_key, false); + activity, R.string.stats_show_elevation_key, PreferencesUtils.STATS_SHOW_ELEVATION_DEFAULT); View elevationLabelTableRow1 = activity.findViewById(R.id.stats_elevation_label_table_row1); View elevationValueTableRow1 = activity.findViewById(R.id.stats_elevation_value_table_row1); View elevationLabelTableRow2 = activity.findViewById(R.id.stats_elevation_label_table_row2); @@ -160,7 +164,8 @@ public class StatsUtils { } // Set grade - boolean showGrade = PreferencesUtils.getBoolean(activity, R.string.stats_show_grade_key, false); + boolean showGrade = PreferencesUtils.getBoolean( + activity, R.string.stats_show_grade_key, PreferencesUtils.STATS_SHOW_GRADE_DEFAULT); View gradeLabelTableRow = activity.findViewById(R.id.stats_grade_label_table_row); View gradeValueTableRow = activity.findViewById(R.id.stats_grade_value_table_row); gradeLabelTableRow.setVisibility(showGrade ? View.VISIBLE : View.GONE); diff --git a/MyTracks/src/com/google/android/apps/mytracks/util/TrackRecordingServiceConnectionUtils.java b/MyTracks/src/com/google/android/apps/mytracks/util/TrackRecordingServiceConnectionUtils.java index 07fa15810..f38309cd4 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/util/TrackRecordingServiceConnectionUtils.java +++ b/MyTracks/src/com/google/android/apps/mytracks/util/TrackRecordingServiceConnectionUtils.java @@ -86,7 +86,8 @@ public class TrackRecordingServiceConnectionUtils { Log.e(TAG, "Failed to check if service is recording", e); } } - return PreferencesUtils.getRecordingTrackId(context) != -1L; + return PreferencesUtils.getLong(context, R.string.recording_track_id_key) + != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT; } /** @@ -106,9 +107,9 @@ public class TrackRecordingServiceConnectionUtils { * Need to remember the recordingTrackId before calling endCurrentTrack. * endCurrentTrack sets the value to -1L. */ - long recordingTrackId = PreferencesUtils.getRecordingTrackId(context); + long recordingTrackId = PreferencesUtils.getLong(context, R.string.recording_track_id_key); trackRecordingService.endCurrentTrack(); - if (recordingTrackId != -1L) { + if (recordingTrackId != PreferencesUtils.RECORDING_TRACK_ID_DEFAULT) { Intent intent = IntentUtils.newIntent(context, TrackEditActivity.class) .putExtra(TrackEditActivity.EXTRA_TRACK_ID, recordingTrackId) .putExtra(TrackEditActivity.EXTRA_NEW_TRACK, true); @@ -118,7 +119,8 @@ public class TrackRecordingServiceConnectionUtils { Log.e(TAG, "Unable to stop recording.", e); } } else { - PreferencesUtils.setRecordingTrackId(context, -1L); + PreferencesUtils.setLong( + context, R.string.recording_track_id_key, PreferencesUtils.RECORDING_TRACK_ID_DEFAULT); } trackRecordingServiceConnection.stop(); } @@ -134,7 +136,8 @@ public class TrackRecordingServiceConnectionUtils { Context context, TrackRecordingServiceConnection trackRecordingServiceConnection) { trackRecordingServiceConnection.bindIfRunning(); if (!isRecordingServiceRunning(context)) { - PreferencesUtils.setRecordingTrackId(context, -1L); + PreferencesUtils.setLong( + context, R.string.recording_track_id_key, PreferencesUtils.RECORDING_TRACK_ID_DEFAULT); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/widgets/TrackWidgetProvider.java b/MyTracks/src/com/google/android/apps/mytracks/widgets/TrackWidgetProvider.java index 620149579..c92f92984 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/widgets/TrackWidgetProvider.java +++ b/MyTracks/src/com/google/android/apps/mytracks/widgets/TrackWidgetProvider.java @@ -81,7 +81,7 @@ public class TrackWidgetProvider public TrackWidgetProvider() { super(); contentHandler = new Handler(); - selectedTrackId = -1; + selectedTrackId = PreferencesUtils.SELECTED_TRACK_ID_DEFAULT; } private void initialize(Context aContext) { @@ -134,7 +134,7 @@ public class TrackWidgetProvider private void updateTrack(String action) { Track track = null; - if (selectedTrackId != -1) { + if (selectedTrackId != PreferencesUtils.SELECTED_TRACK_ID_DEFAULT) { Log.d(TAG, "TrackWidgetProvider.updateTrack: Retrieving specified track."); track = providerUtils.getTrack(selectedTrackId); } else { @@ -230,16 +230,17 @@ public class TrackWidgetProvider @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { - if (key == null || key.equals(PreferencesUtils.getMetricUnitsKey(context))) { - metricUnits = PreferencesUtils.isMetricUnits(context); + if (key == null || PreferencesUtils.getKey(context, R.string.metric_units_key).equals(key)) { + metricUnits = PreferencesUtils.getBoolean( + context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT); } - - if (key == null || key.equals(PreferencesUtils.getReportSpeedKey(context))) { - reportSpeed = PreferencesUtils.isReportSpeed(context); + if (key == null || PreferencesUtils.getKey(context, R.string.report_speed_key).equals(key)) { + reportSpeed = PreferencesUtils.getBoolean( + context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT); } - - if (key == null || key.equals(PreferencesUtils.getSelectedTrackIdKey(context))) { - selectedTrackId = PreferencesUtils.getSelectedTrackId(context); + if (key == null + || PreferencesUtils.getKey(context, R.string.selected_track_id_key).equals(key)) { + selectedTrackId = PreferencesUtils.getLong(context, R.string.selected_track_id_key); Log.d(TAG, "TrackWidgetProvider setting selecting track from preference: " + selectedTrackId); } } diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java index 32762c1c5..e184ef950 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java @@ -30,6 +30,7 @@ import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.util.PreferencesUtils; +import com.google.android.maps.mytracks.R; import com.google.android.testing.mocking.AndroidMock; import android.content.Context; @@ -70,7 +71,7 @@ public class TrackDataHubTest extends AndroidTestCase { private TrackDataHub hub; private TrackDataListeners listeners; private DataSourcesWrapper dataSources; - private SharedPreferences prefs; + private SharedPreferences sharedPreferences; private TrackDataListener listener1; private TrackDataListener listener2; private Capture preferenceListenerCapture = @@ -87,12 +88,12 @@ public class TrackDataHubTest extends AndroidTestCase { getContext(), getContext(), "test."); context = new MockContext(mockContentResolver, targetContext); - prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); + sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class); dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class); listeners = new TrackDataListeners(); - hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) { + hub = new TrackDataHub(context, listeners, sharedPreferences, providerUtils, TARGET_POINTS) { @Override protected DataSourcesWrapper newDataSources() { return dataSources; @@ -112,8 +113,8 @@ public class TrackDataHubTest extends AndroidTestCase { listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class); listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class); - PreferencesUtils.setRecordingTrackId(context, TRACK_ID); - PreferencesUtils.setSelectedTrackId(context, TRACK_ID); + PreferencesUtils.setLong(context, R.string.recording_track_id_key, TRACK_ID); + PreferencesUtils.setLong(context, R.string.selected_track_id_key, TRACK_ID); } @Override @@ -797,13 +798,8 @@ public class TrackDataHubTest extends AndroidTestCase { } public void testDisplayPreferencesListen() throws Exception { - String metricUnitsKey = PreferencesUtils.getMetricUnitsKey(context); - String reportSpeedKey = PreferencesUtils.getReportSpeedKey(context); - - prefs.edit() - .putBoolean(metricUnitsKey, true) - .putBoolean(reportSpeedKey, true) - .apply(); + PreferencesUtils.setBoolean(context, R.string.report_speed_key, true); + PreferencesUtils.setBoolean(context, R.string.metric_units_key, true); Capture listenerCapture = new Capture(); @@ -827,11 +823,10 @@ public class TrackDataHubTest extends AndroidTestCase { replay(); - prefs.edit() - .putBoolean(reportSpeedKey, false) - .apply(); + PreferencesUtils.setBoolean(context, R.string.report_speed_key, false); OnSharedPreferenceChangeListener listener = listenerCapture.getValue(); - listener.onSharedPreferenceChanged(prefs, reportSpeedKey); + listener.onSharedPreferenceChanged( + sharedPreferences, PreferencesUtils.getKey(context, R.string.report_speed_key)); AndroidMock.verify(dataSources, providerUtils, listener1, listener2); AndroidMock.reset(dataSources, providerUtils, listener1, listener2); @@ -841,10 +836,9 @@ public class TrackDataHubTest extends AndroidTestCase { replay(); - prefs.edit() - .putBoolean(metricUnitsKey, false) - .apply(); - listener.onSharedPreferenceChanged(prefs, metricUnitsKey); + PreferencesUtils.setBoolean(context, R.string.metric_units_key, false); + listener.onSharedPreferenceChanged( + sharedPreferences, PreferencesUtils.getKey(context, R.string.metric_units_key)); verifyAndReset(); } diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java index c1d0c8a57..f171510a6 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java @@ -120,7 +120,7 @@ public class ChartFragmentTest extends AndroidTestCase { */ public void testFillDataPoint_distanceMetric() { // By distance. - chartFragment.getChartView().setMode(ChartView.Mode.BY_DISTANCE); + chartFragment.setChartByDistance(true); // Resets last location and writes first location. MyTracksLocation myTracksLocation1 = TrackStubUtils.createMyTracksLocation(); double[] point = fillDataPointTestHelper(myTracksLocation1); @@ -160,6 +160,8 @@ public class ChartFragmentTest extends AndroidTestCase { * {@link ChartFragment#fillDataPoint(Location, double[])}. */ public void testFillDataPoint_distanceImperial() { + // By distance. + chartFragment.setChartByDistance(true); // Setups to use imperial. chartFragment.setMetricUnits(false); @@ -204,7 +206,7 @@ public class ChartFragmentTest extends AndroidTestCase { */ public void testFillDataPoint_time() { // By time - chartFragment.getChartView().setMode(ChartView.Mode.BY_TIME); + chartFragment.setChartByDistance(false); MyTracksLocation myTracksLocation1 = TrackStubUtils.createMyTracksLocation(); double[] point = fillDataPointTestHelper(myTracksLocation1); assertEquals(0.0, point[0]); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivityTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivityTest.java index a4ca0b177..ff72cfb5b 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivityTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/io/sendtogoogle/UploadServiceChooserActivityTest.java @@ -15,14 +15,11 @@ */ package com.google.android.apps.mytracks.io.sendtogoogle; -import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.app.Instrumentation; -import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.test.ActivityInstrumentationTestCase2; import android.widget.CheckBox; import android.widget.RadioButton; @@ -123,14 +120,10 @@ public class UploadServiceChooserActivityTest extends public void testOnCreateDialog_initStateUnchecked() { initialActivity(true, true, true); // Initial all values to false in SharedPreferences. - SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = prefs.edit(); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), - false); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), false); - editor.commit(); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_maps_key, false); + PreferencesUtils.setBoolean( + uploadServiceChooserActivity, R.string.send_to_fusion_tables_key, false); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_docs_key, false); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); @@ -150,15 +143,11 @@ public class UploadServiceChooserActivityTest extends public void testOnCreateDialog_initStateChecked() { initialActivity(true, true, true); // Initial all values to true in SharedPreferences. - SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = prefs.edit(); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.pick_existing_map_key), true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), - true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); - editor.commit(); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.pick_existing_map_key, true); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_maps_key, true); + PreferencesUtils.setBoolean( + uploadServiceChooserActivity, R.string.send_to_fusion_tables_key, true); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_docs_key, true); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); @@ -181,14 +170,10 @@ public class UploadServiceChooserActivityTest extends public void testOnCreateDialog_saveState() { initialActivity(true, true, true); // Initial all values to true in SharedPreferences. - SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = prefs.edit(); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), - true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); - editor.commit(); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_maps_key, true); + PreferencesUtils.setBoolean( + uploadServiceChooserActivity, R.string.send_to_fusion_tables_key, true); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_docs_key, true); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); @@ -197,12 +182,13 @@ public class UploadServiceChooserActivityTest extends instrumentation.waitForIdleSync(); uploadServiceChooserActivity.saveState(); // All values in SharedPreferences must be changed. - assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), - false)); - assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), - false)); - assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), - false)); + assertTrue(PreferencesUtils.getBoolean(uploadServiceChooserActivity, R.string.send_to_maps_key, + PreferencesUtils.SEND_TO_MAPS_DEFAULT)); + assertTrue(PreferencesUtils.getBoolean( + uploadServiceChooserActivity, R.string.send_to_fusion_tables_key, + PreferencesUtils.SEND_TO_FUSION_TABLES_DEFAULT)); + assertTrue(PreferencesUtils.getBoolean(uploadServiceChooserActivity, R.string.send_to_docs_key, + PreferencesUtils.SEND_TO_DOCS_DEFAULT)); } /** @@ -213,14 +199,10 @@ public class UploadServiceChooserActivityTest extends public void testOnCreateDialog_startNextActivity() { initialActivity(true, true, true); // Initial all values to true or false in SharedPreferences. - SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - Editor editor = prefs.edit(); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true); - editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key), - false); - editor.commit(); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_maps_key, true); + PreferencesUtils.setBoolean(uploadServiceChooserActivity, R.string.send_to_docs_key, true); + PreferencesUtils.setBoolean( + uploadServiceChooserActivity, R.string.send_to_fusion_tables_key, false); uploadServiceChooserActivity.runOnUiThread(new Runnable() { public void run() { uploadServiceChooserActivity.initState(); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptorTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptorTest.java index e95cf5da6..6d00a0162 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptorTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptorTest.java @@ -13,6 +13,7 @@ * 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.Constants; @@ -21,26 +22,23 @@ import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.test.AndroidTestCase; /** * Tests for the {@link DynamicSpeedTrackPathDescriptor}. - * + * * @author Youtao Liu */ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase { private Context context; private SharedPreferences sharedPreferences; - private Editor sharedPreferencesEditor; @Override protected void setUp() throws Exception { super.setUp(); context = getContext(); sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferencesEditor = sharedPreferences.edit(); } /** @@ -48,96 +46,77 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase { * with zero, normal and illegal value. */ public void testGetSpeedMargin() { - String[] actuals = { "0", "50", "99", "" }; // The default value of speedMargin is 25. int[] expectations = { 0, 50, 99, 25 }; // Test for (int i = 0; i < expectations.length; i++) { - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]); - sharedPreferencesEditor.commit(); + PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, expectations[i]); DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); - assertEquals(expectations[i], - dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences)); + assertEquals(expectations[i], dynamicSpeedTrackPathDescriptor.getSpeedMargin()); } } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is null. */ public void testOnSharedPreferenceChanged_nullKey() { DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); - int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences); + int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(); // Change value in shared preferences. - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_dynamic_speed_variation_key), - Integer.toString(speedMargin + 2)); - sharedPreferencesEditor.commit(); + PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, speedMargin + 2); dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null); assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is not null, and not trackColorModeDynamicVariation. */ public void testOnSharedPreferenceChanged_otherKey() { DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); - int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences); + int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(); // Change value in shared preferences. - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_dynamic_speed_variation_key), - Integer.toString(speedMargin + 2)); - sharedPreferencesEditor.commit(); - + PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, speedMargin + 2); dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey"); assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is trackColorModeDynamicVariation. */ public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() { DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); - int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences); + int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(); // Change value in shared preferences. - sharedPreferencesEditor.putString( - "trackColorModeDynamicVariation", - Integer.toString(speedMargin + 2)); - sharedPreferencesEditor.commit(); + PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, speedMargin + 2); dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, - "trackColorModeDynamicVariation"); + PreferencesUtils.getKey(context, R.string.track_color_mode_percentage_key)); assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, - * String)} when the values of speedMargin is "". + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * String)} when the values of speedMargin is the default value. */ - public void testOnSharedPreferenceChanged_emptyValue() { + public void testOnSharedPreferenceChanged_defaultValue() { DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); // Change value in shared preferences - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_dynamic_speed_variation_key), ""); - sharedPreferencesEditor.commit(); - + PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, + PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT); dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, - context.getString(R.string.track_color_mode_dynamic_speed_variation_key)); + PreferencesUtils.getKey(context, R.string.track_color_mode_percentage_key)); // The default value of speedMargin is 25. - assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin()); + assertEquals(PreferencesUtils.TRACK_COLOR_MODE_PERCENTAGE_DEFAULT, + dynamicSpeedTrackPathDescriptor.getSpeedMargin()); } /** @@ -145,7 +124,8 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase { * id. */ public void testNeedsRedraw_WrongTrackId() { - PreferencesUtils.setSelectedTrackId(context, -1L); + PreferencesUtils.setLong( + context, R.string.selected_track_id_key, PreferencesUtils.SELECTED_TRACK_ID_DEFAULT); DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor( context); assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw()); @@ -160,9 +140,9 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase { context); double[] averageMovingSpeeds = { 0, 30, 30, 30 }; double[] newAverageMovingSpeed = { 20, 30, - // Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE + // Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE 30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2), - // Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE + // Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE 30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) }; boolean[] expectedValues = { true, false, false, true }; double[] expectedAverageMovingSpeed = { 20, 30, 30, @@ -172,8 +152,8 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase { dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]); assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant( averageMovingSpeeds[i], newAverageMovingSpeed[i])); - assertEquals(expectedAverageMovingSpeed[i], - dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed()); + assertEquals( + expectedAverageMovingSpeed[i], dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed()); } } } \ No newline at end of file diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptorTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptorTest.java index 347ab9bb4..1533214e0 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptorTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptorTest.java @@ -16,52 +16,42 @@ package com.google.android.apps.mytracks.maps; import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.test.AndroidTestCase; /** * Tests for the {@link DynamicSpeedTrackPathDescriptor}. - * + * * @author Youtao Liu */ public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase { + private Context context; private SharedPreferences sharedPreferences; - private Editor sharedPreferencesEditor; - private int slowDefault; - private int normalDefault; @Override protected void setUp() throws Exception { super.setUp(); context = getContext(); sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - sharedPreferencesEditor = sharedPreferences.edit(); - // Get the default value - slowDefault = 9; - normalDefault = 15; } /** - * Tests the initialization of slowSpeed and normalSpeed in {@link - * DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)}. + * Tests the initialization of slowSpeed and normalSpeed in {@link DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)} + * . */ public void testConstructor() { - String[] slowSpeedsInShPre = { "0", "1", "99", "" }; - int[] slowSpeedExpectations = { 0, 1, 99, slowDefault }; - String[] normalSpeedsInShPre = { "0", "1", "99", "" }; - int[] normalSpeedExpectations = { 0, 1, 99, normalDefault }; - for (int i = 0; i < slowSpeedsInShPre.length; i++) { - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), slowSpeedsInShPre[i]); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), - normalSpeedsInShPre[i]); - sharedPreferencesEditor.commit(); + int[] slowSpeedExpectations = { 0, 1, 99, PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT }; + int[] normalSpeedExpectations = { 0, 1, 99, PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT }; + for (int i = 0; i < slowSpeedExpectations.length; i++) { + PreferencesUtils.setInt( + context, R.string.track_color_mode_slow_key, slowSpeedExpectations[i]); + PreferencesUtils.setInt( + context, R.string.track_color_mode_medium_key, normalSpeedExpectations[i]); FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor( context); assertEquals(slowSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getSlowSpeed()); @@ -70,8 +60,7 @@ public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase { } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is null. */ public void testOnSharedPreferenceChanged_null_key() { @@ -80,22 +69,15 @@ public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase { int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed(); int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed(); // Change value in shared preferences - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), - Integer.toString(slowSpeed + 2)); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), - Integer.toString(normalSpeed + 2)); - sharedPreferencesEditor.commit(); - + PreferencesUtils.setInt(context, R.string.track_color_mode_slow_key, slowSpeed + 2); + PreferencesUtils.setInt(context, R.string.track_color_mode_medium_key, normalSpeed + 2); fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null); assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed()); assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is not null, and not slowSpeed and not normalSpeed. */ public void testOnSharedPreferenceChanged_other_key() { @@ -104,84 +86,59 @@ public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase { int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed(); int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed(); // Change value in shared preferences - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), - Integer.toString(slowSpeed + 2)); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), - Integer.toString(normalSpeed + 2)); - sharedPreferencesEditor.commit(); + PreferencesUtils.setInt(context, R.string.track_color_mode_slow_key, slowSpeed + 2); + PreferencesUtils.setInt(context, R.string.track_color_mode_medium_key, normalSpeed + 2); fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey"); assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed()); assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is slowSpeed. */ public void testOnSharedPreferenceChanged_slowSpeedKey() { FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor( context); int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed(); - int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed(); // Change value in shared preferences - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), - Integer.toString(slowSpeed + 2)); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), - Integer.toString(normalSpeed + 2)); - sharedPreferencesEditor.commit(); - fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, - context.getString(R.string.track_color_mode_fixed_speed_slow_key)); + PreferencesUtils.setInt(context, R.string.track_color_mode_slow_key, slowSpeed + 2); + fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged( + sharedPreferences, context.getString(R.string.track_color_mode_slow_key)); assertEquals(slowSpeed + 2, fixedSpeedTrackPathDescriptor.getSlowSpeed()); - assertEquals(normalSpeed + 2, fixedSpeedTrackPathDescriptor.getNormalSpeed()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the key is normalSpeed. */ public void testOnSharedPreferenceChanged_normalSpeedKey() { FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor( context); - int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed(); int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed(); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), - Integer.toString(slowSpeed + 4)); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), - Integer.toString(normalSpeed + 4)); - sharedPreferencesEditor.commit(); - - fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, - context.getString(R.string.track_color_mode_fixed_speed_medium_key)); - assertEquals(slowSpeed + 4, fixedSpeedTrackPathDescriptor.getSlowSpeed()); + PreferencesUtils.setInt(context, R.string.track_color_mode_medium_key, normalSpeed + 4); + fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged( + sharedPreferences, context.getString(R.string.track_color_mode_medium_key)); assertEquals(normalSpeed + 4, fixedSpeedTrackPathDescriptor.getNormalSpeed()); } /** - * Tests {@link - * DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, + * Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences, * String)} when the values of slowSpeed and normalSpeed in SharedPreference - * is "". In such situation, the default value should get returned. + * are the default values. */ - public void testOnSharedPreferenceChanged_emptyValue() { + public void testOnSharedPreferenceChanged_defaultValue() { FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor( context); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_slow_key), ""); - sharedPreferencesEditor.putString( - context.getString(R.string.track_color_mode_fixed_speed_medium_key), ""); - sharedPreferencesEditor.commit(); - - fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, - context.getString(R.string.track_color_mode_fixed_speed_medium_key)); - assertEquals(slowDefault, fixedSpeedTrackPathDescriptor.getSlowSpeed()); - assertEquals(normalDefault, fixedSpeedTrackPathDescriptor.getNormalSpeed()); + PreferencesUtils.setInt(context, R.string.track_color_mode_slow_key, + PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT); + PreferencesUtils.setInt(context, R.string.track_color_mode_medium_key, + PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT); + fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged( + sharedPreferences, context.getString(R.string.track_color_mode_medium_key)); + assertEquals(PreferencesUtils.TRACK_COLOR_MODE_SLOW_DEFAULT, + fixedSpeedTrackPathDescriptor.getSlowSpeed()); + assertEquals(PreferencesUtils.TRACK_COLOR_MODE_MEDIUM_DEFAULT, + fixedSpeedTrackPathDescriptor.getNormalSpeed()); } } \ No newline at end of file diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactoryTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactoryTest.java index 8673cbe1d..36bab1029 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactoryTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactoryTest.java @@ -15,11 +15,10 @@ */ package com.google.android.apps.mytracks.maps; -import com.google.android.apps.mytracks.Constants; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; -import android.content.SharedPreferences; import android.location.Location; /** @@ -41,25 +40,20 @@ public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase { } Context context = getContext(); - SharedPreferences prefs = context.getSharedPreferences( - Constants.SETTINGS_NAME, Context.MODE_PRIVATE); - if (prefs == null) { - return; - } - testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_none, - SingleColorTrackPathPainter.class); - testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_fixed, - DynamicSpeedTrackPathPainter.class); - testTrackPathPainterFactorySpecific(context, prefs, R.string.display_track_color_value_dynamic, + testTrackPathPainterFactorySpecific(context, + R.string.settings_map_track_color_mode_single_value, SingleColorTrackPathPainter.class); + testTrackPathPainterFactorySpecific(context, R.string.settings_map_track_color_mode_fixed_value, DynamicSpeedTrackPathPainter.class); + testTrackPathPainterFactorySpecific(context, + R.string.settings_map_track_color_mode_dynamic_value, DynamicSpeedTrackPathPainter.class); } - private void testTrackPathPainterFactorySpecific(Context context, SharedPreferences prefs, - int track_color_mode, Class c) { - prefs.edit().putString(context.getString(R.string.track_color_mode_key), - context.getString(track_color_mode)).apply(); - + private void testTrackPathPainterFactorySpecific( + Context context, int track_color_mode, Class c) { + PreferencesUtils.setString( + context, R.string.track_color_mode_key, context.getString(track_color_mode)); + int startLocationIdx = 0; Boolean alwaysVisible = true; diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicyTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicyTest.java new file mode 100644 index 000000000..22741cad5 --- /dev/null +++ b/MyTracksTest/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicyTest.java @@ -0,0 +1,76 @@ +/* + * Copyright 2012 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 junit.framework.TestCase; + +/** + * Tests the {@link AdaptiveLocationListenerPolicy}. + * + * @author youtaol + */ +public class AdaptiveLocationListenerPolicyTest extends TestCase { + + private AdaptiveLocationListenerPolicy adocationListenerPolicy; + private static final long MIN = 1000; + private static final long MAX = 3000; + private static final int MIN_DISTANCE = 10; + private static final long NEW_IDLE_TIME_BIG = 10000; + private static final long NEW_IDLE_TIME_NORMAL = 5000; + private static final long NEW_IDLE_TIME_SMALL = 2000; + private static final long NEW_IDLE_TIME_LESS_THAN_MIN = 500; + + @Override + protected void setUp() throws Exception { + super.setUp(); + adocationListenerPolicy = new AdaptiveLocationListenerPolicy(MIN, MAX, MIN_DISTANCE); + } + + /** + * Tests the + * {@link AdaptiveLocationListenerPolicy#getDesiredPollingInterval()} in four + * situations. + *
    + *
  • The newIdleTime is bigger than max interval.
  • + *
  • The newIdleTime is between min and max interval.
  • + *
  • The newIdleTime is smaller than max interval.
  • + *
  • The newIdleTime is smaller than the smallest interval unit.
  • + *
+ */ + public void testGetDesiredPollingInterval() { + adocationListenerPolicy.updateIdleTime(NEW_IDLE_TIME_BIG); + assertEquals(MAX, adocationListenerPolicy.getDesiredPollingInterval()); + + adocationListenerPolicy.updateIdleTime(NEW_IDLE_TIME_NORMAL); + // First get the half of NEW_IDLE_TIME_NORMAL, and then round it to the + // nearest second. + assertEquals((NEW_IDLE_TIME_NORMAL / 2 / 1000) * 1000, + adocationListenerPolicy.getDesiredPollingInterval()); + + adocationListenerPolicy.updateIdleTime(NEW_IDLE_TIME_SMALL); + assertEquals(MIN, adocationListenerPolicy.getDesiredPollingInterval()); + + adocationListenerPolicy.updateIdleTime(NEW_IDLE_TIME_LESS_THAN_MIN); + assertEquals(MIN, adocationListenerPolicy.getDesiredPollingInterval()); + } + + /** + * Tests the method {@link AdaptiveLocationListenerPolicy#getMinDistance()}. + */ + public void testGetMinDistance() { + assertEquals(MIN_DISTANCE, adocationListenerPolicy.getMinDistance()); + } +} diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/services/ControlRecordingServiceTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/services/ControlRecordingServiceTest.java new file mode 100644 index 000000000..e7c887a5f --- /dev/null +++ b/MyTracksTest/src/com/google/android/apps/mytracks/services/ControlRecordingServiceTest.java @@ -0,0 +1,105 @@ +/* + * Copyright 2012 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 com.google.android.maps.mytracks.R; +import com.google.android.testing.mocking.UsesMocks; + +import android.content.Context; +import android.content.Intent; +import android.os.RemoteException; +import android.test.ServiceTestCase; + +import org.easymock.EasyMock; + +/** + * Tests {@link ControlRecordingService}. + * + * @author Youtao Liu + */ +public class ControlRecordingServiceTest extends ServiceTestCase { + + private Context context; + private ControlRecordingService controlRecordingService; + + public ControlRecordingServiceTest() { + super(ControlRecordingService.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + context = getContext(); + } + + /** + * Tests the start of {@link ControlRecordingService} and tests the method + * {@link ControlRecordingService#onHandleIntent(Intent, ITrackRecordingService)} + * to start a track recording. + */ + @UsesMocks(ITrackRecordingService.class) + public void testStartRecording() { + assertNull(controlRecordingService); + Intent intent = startControlRecordingService(context.getString(R.string.track_action_start)); + assertNotNull(controlRecordingService); + + ITrackRecordingService iTrackRecordingServiceMock = EasyMock + .createStrictMock(ITrackRecordingService.class); + try { + EasyMock.expect(iTrackRecordingServiceMock.startNewTrack()).andReturn(1L); + EasyMock.replay(iTrackRecordingServiceMock); + controlRecordingService.onHandleIntent(intent, iTrackRecordingServiceMock); + EasyMock.verify(iTrackRecordingServiceMock); + } catch (RemoteException e) { + fail(); + } + } + + /** + * Tests the method + * {@link ControlRecordingService#onHandleIntent(Intent, ITrackRecordingService)} + * to stop a track recording. + */ + @UsesMocks(ITrackRecordingService.class) + public void testStopRecording() { + Intent intent = startControlRecordingService(context.getString(R.string.track_action_end)); + + ITrackRecordingService iTrackRecordingServiceMock = EasyMock + .createStrictMock(ITrackRecordingService.class); + try { + iTrackRecordingServiceMock.endCurrentTrack(); + EasyMock.replay(iTrackRecordingServiceMock); + controlRecordingService.onHandleIntent(intent, iTrackRecordingServiceMock); + EasyMock.verify(iTrackRecordingServiceMock); + } catch (RemoteException e) { + fail(); + } + } + + /** + * Starts a ControlRecordingService with a specified action. + * + * @param action the action string in the start intent + */ + private Intent startControlRecordingService(String action) { + Intent intent = new Intent(context, ControlRecordingService.class); + intent.setAction(action); + startService(intent); + controlRecordingService = getService(); + return intent; + } + +} diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/services/TrackRecordingServiceTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/services/TrackRecordingServiceTest.java index 0593e550b..bc3594eb4 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/services/TrackRecordingServiceTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/services/TrackRecordingServiceTest.java @@ -34,7 +34,6 @@ import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; -import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.location.Location; import android.net.Uri; @@ -66,7 +65,6 @@ public class TrackRecordingServiceTest extends ServiceTestCase= 0); providerUtils.insertTrack(track); assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId()); - PreferencesUtils.setRecordingTrackId(context, isRecording ? track.getId() : -1L); - } - - // TODO: We support multiple values for readability, however this test's - // base class doesn't properly shutdown the service, so it's not possible - // to pass more than 1 value at a time. - private void functionalTest(int resourceId, Object ...values) - throws Exception { - final String key = context.getString(resourceId); - for (Object value : values) { - // Remove all properties and set the property for the given key. - Editor editor = sharedPreferences.edit(); - editor.clear(); - if (value instanceof String) { - editor.putString(key, (String) value); - } else if (value instanceof Long) { - editor.putLong(key, (Long) value); - } else if (value instanceof Integer) { - editor.putInt(key, (Integer) value); - } else if (value instanceof Boolean) { - editor.putBoolean(key, (Boolean) value); - } else if (value == null) { - // Do nothing, as clear above has already removed this property. - } - editor.apply(); - - fullRecordingSession(); - } + PreferencesUtils.setLong(context, R.string.recording_track_id_key, isRecording ? track.getId() + : PreferencesUtils.RECORDING_TRACK_ID_DEFAULT); } private void fullRecordingSession() throws Exception { @@ -706,7 +708,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase c, int i) { - sharedPreferences.edit() - .putString(getContext().getString(R.string.sensor_type_key), - getContext().getString(i)) - .apply(); + PreferencesUtils.setString(getContext(), R.string.sensor_type_key, getContext().getString(i)); SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext()); assertNotNull(sm); assertTrue(c.isInstance(sm)); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManagerTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManagerTest.java index ed5e2c83e..01cdac80b 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManagerTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManagerTest.java @@ -18,6 +18,7 @@ package com.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntMesg; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; +import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.maps.mytracks.R; import android.content.Context; @@ -27,7 +28,6 @@ import android.test.suitebuilder.annotation.SmallTest; public class AntDirectSensorManagerTest extends AndroidTestCase { - private SharedPreferences sharedPreferences; private AntSensorBase heartRateSensor; private static final byte HEART_RATE_CHANNEL = 0; @@ -47,7 +47,7 @@ public class AntDirectSensorManagerTest extends AndroidTestCase { private AntDirectSensorManager manager; public void setUp() { - sharedPreferences = getContext().getSharedPreferences( + SharedPreferences sharedPreferences = getContext().getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // Let's use default values. sharedPreferences.edit().clear().apply(); @@ -87,9 +87,8 @@ public class AntDirectSensorManagerTest extends AndroidTestCase { manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff); assertEquals(43, heartRateSensor.getDeviceNumber()); - assertEquals(43, - sharedPreferences.getInt( - getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1)); + assertEquals(43, PreferencesUtils.getInt( + getContext(), R.string.ant_heart_rate_sensor_id_key, AntSensorManager.WILDCARD)); assertNull(manager.getSensorDataSet()); }