Add PreferencesUtils to access

- recording track id
- selected track id
This commit is contained in:
Jimmy Shih
2012-04-12 14:26:18 -07:00
parent 53c5ebbef9
commit 2aa4cdc442
18 changed files with 230 additions and 181 deletions
+2 -2
View File
@@ -55,8 +55,8 @@ limitations under the License.
<!-- Preference keys which keep transient state (not user preferences). Sorted alphabetically.
- DO NOT TRANSLATE -->
<string name="auto_resume_track_current_retry_key">autoResumeTrackCurrentRetry</string>
<string name="recording_track_key">recordingTrack</string>
<string name="selected_track_key">selectedTrack</string>
<string name="recording_track_id_key">recordingTrackId</string>
<string name="selected_track_id_key">selectedTrackId</string>
<!-- Keys for non-persisted preferences. Sorted alphabetically. - DO NOT TRANSLATE -->
<string name="ant_options_key">antOptions</string>
@@ -21,11 +21,11 @@ import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.io.file.TrackWriter;
import com.google.android.apps.mytracks.io.file.TrackWriterFactory;
import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.SystemUtils;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.PowerManager.WakeLock;
@@ -65,13 +65,8 @@ public class ExportAsyncTask extends AsyncTask<Void, Integer, Boolean> {
context = exportActivity.getApplicationContext();
myTracksProviderUtils = MyTracksProviderUtils.Factory.get(exportActivity);
SharedPreferences sharedPreferences = exportActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
long recordingTrackId = sharedPreferences.getLong(
exportActivity.getString(R.string.recording_track_key), -1L);
// Get the wake lock if not recording
if (recordingTrackId == -1L) {
if (PreferencesUtils.getRecordingTrackId(exportActivity) == -1L) {
wakeLock = SystemUtils.acquireWakeLock(exportActivity, wakeLock);
}
success = false;
@@ -19,11 +19,9 @@ package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
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.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.PowerManager.WakeLock;
import android.util.Log;
@@ -82,13 +80,9 @@ public class ImportAsyncTask extends AsyncTask<Void, Integer, Boolean> {
this.path = path;
myTracksProviderUtils = MyTracksProviderUtils.Factory.get(importActivity);
SharedPreferences sharedPreferences = importActivity.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
long recordingTrackId = sharedPreferences.getLong(
importActivity.getString(R.string.recording_track_key), -1L);
// Get the wake lock if not recording
if (recordingTrackId == -1L) {
if (PreferencesUtils.getRecordingTrackId(importActivity) == -1L) {
wakeLock = SystemUtils.acquireWakeLock(importActivity, wakeLock);
}
@@ -24,6 +24,7 @@ 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.PreferencesUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
@@ -345,8 +346,7 @@ public class SettingsActivity extends PreferenceActivity {
// If recording, disable backup/restore/reset
// (we don't want to get to inconsistent states)
boolean recording =
preferences.getLong(getString(R.string.recording_track_key), -1) != -1;
boolean recording = PreferencesUtils.getRecordingTrackId(this) != -1;
backupNowPreference.setEnabled(!recording);
restoreNowPreference.setEnabled(!recording);
resetPreference.setEnabled(!recording);
@@ -37,6 +37,7 @@ import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.AnalyticsUtils;
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;
@@ -102,7 +103,7 @@ public class TrackDetailActivity extends FragmentActivity {
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
// Note that key can be null
if (getString(R.string.recording_track_key).equals(key)) {
if (PreferencesUtils.getRecordingTrackIdKey(TrackDetailActivity.this).equals(key)) {
updateMenu();
}
}
@@ -446,8 +447,7 @@ public class TrackDetailActivity extends FragmentActivity {
* Updates the menu.
*/
private void updateMenu() {
updateMenuItems(
trackId == sharedPreferences.getLong(getString(R.string.recording_track_key), -1L));
updateMenuItems(trackId == PreferencesUtils.getRecordingTrackId(this));
}
/**
@@ -508,8 +508,7 @@ public class TrackDetailActivity extends FragmentActivity {
* Returns true if recording.
*/
private boolean isRecording() {
return ServiceUtils.isRecording(
this, trackRecordingServiceConnection.getServiceIfBound(), sharedPreferences);
return ServiceUtils.isRecording(this, trackRecordingServiceConnection.getServiceIfBound());
}
/**
@@ -528,7 +527,7 @@ public class TrackDetailActivity extends FragmentActivity {
}
trackRecordingServiceConnection.stop();
long recordingTrackId = sharedPreferences.getLong(getString(R.string.recording_track_key), -1L);
long recordingTrackId = PreferencesUtils.getRecordingTrackId(this);
if (recordingTrackId != -1L) {
Intent intent = new Intent(this, TrackEditActivity.class)
.putExtra(TrackEditActivity.EXTRA_SHOW_CANCEL, false)
@@ -26,6 +26,7 @@ import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.ApiAdapterFactory;
import com.google.android.apps.mytracks.util.EulaUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
@@ -115,8 +116,8 @@ public class TrackListActivity extends FragmentActivity {
if (getString(R.string.metric_units_key).equals(key)) {
metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true);
}
if (getString(R.string.recording_track_key).equals(key)) {
recordingTrackId = sharedPreferences.getLong(getString(R.string.recording_track_key), -1L);
if (PreferencesUtils.getRecordingTrackIdKey(TrackListActivity.this).equals(key)) {
recordingTrackId = PreferencesUtils.getRecordingTrackId(TrackListActivity.this);
if (isRecording()) {
trackRecordingServiceConnection.startAndBind();
}
@@ -136,7 +137,6 @@ public class TrackListActivity extends FragmentActivity {
};
private TrackRecordingServiceConnection trackRecordingServiceConnection;
private SharedPreferences sharedPreferences;
private boolean metricUnits;
private long recordingTrackId;
private ListView listView;
@@ -162,10 +162,11 @@ public class TrackListActivity extends FragmentActivity {
trackRecordingServiceConnection = new TrackRecordingServiceConnection(
this, bindChangedCallback);
sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
SharedPreferences sharedPreferences = getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
metricUnits = sharedPreferences.getBoolean(getString(R.string.metric_units_key), true);
recordingTrackId = sharedPreferences.getLong(getString(R.string.recording_track_key), -1L);
recordingTrackId = PreferencesUtils.getRecordingTrackId(this);
listView = (ListView) findViewById(R.id.track_list);
listView.setOnItemClickListener(new OnItemClickListener() {
@@ -421,8 +422,7 @@ public class TrackListActivity extends FragmentActivity {
* Returns true if recording.
*/
private boolean isRecording() {
return ServiceUtils.isRecording(
this, trackRecordingServiceConnection.getServiceIfBound(), sharedPreferences);
return ServiceUtils.isRecording(this, trackRecordingServiceConnection.getServiceIfBound());
}
/**
@@ -25,15 +25,14 @@ import com.google.android.apps.mytracks.content.WaypointsColumns;
import com.google.android.apps.mytracks.services.ITrackRecordingService;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.DialogUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
@@ -156,19 +155,11 @@ public class WaypointsList extends ListActivity implements View.OnClickListener
insertStatisticsButton =
(Button) findViewById(R.id.waypointslist_btn_insert_statistics);
insertStatisticsButton.setOnClickListener(this);
SharedPreferences preferences = getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// TODO: Get rid of selected and recording track IDs
long selectedTrackId = -1;
if (preferences != null) {
recordingTrackId =
preferences.getLong(getString(R.string.recording_track_key), -1);
selectedTrackId =
preferences.getLong(getString(R.string.selected_track_key), -1);
}
boolean selectedRecording = selectedTrackId > 0
&& selectedTrackId == recordingTrackId;
recordingTrackId = PreferencesUtils.getRecordingTrackId(this);
long selectedTrackId = PreferencesUtils.getSelectedTrackId(this);
boolean selectedRecording = selectedTrackId != -1L && selectedTrackId == recordingTrackId;
insertWaypointButton.setEnabled(selectedRecording);
insertStatisticsButton.setEnabled(selectedRecording);
@@ -28,8 +28,8 @@ import com.google.android.apps.mytracks.content.MyTracksProviderUtils.DoubleBuff
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.content.TrackDataListeners.ListenerRegistration;
import com.google.android.apps.mytracks.util.ApiAdapterFactory;
import com.google.android.apps.mytracks.util.LocationUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
import android.content.Context;
@@ -59,8 +59,6 @@ import java.util.Set;
public class TrackDataHub {
// Preference keys
private final String SELECTED_TRACK_KEY;
private final String RECORDING_TRACK_KEY;
private final String MIN_REQUIRED_ACCURACY_KEY;
private final String METRIC_UNITS_KEY;
private final String SPEED_REPORTING_KEY;
@@ -223,8 +221,6 @@ public class TrackDataHub {
this.targetNumPoints = targetNumPoints;
this.locationFactory = new DoubleBufferedLocationFactory();
SELECTED_TRACK_KEY = context.getString(R.string.selected_track_key);
RECORDING_TRACK_KEY = context.getString(R.string.recording_track_key);
MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key);
METRIC_UNITS_KEY = context.getString(R.string.metric_units_key);
SPEED_REPORTING_KEY = context.getString(R.string.report_speed_key);
@@ -302,7 +298,7 @@ public class TrackDataHub {
}
private void loadSharedPreferences() {
selectedTrackId = preferences.getLong(SELECTED_TRACK_KEY, -1);
selectedTrackId = PreferencesUtils.getSelectedTrackId(context);
useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true);
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY,
@@ -380,8 +376,8 @@ public class TrackDataHub {
if (!isStarted()) {
loadSharedPreferences();
}
long recordingTrackId = preferences.getLong(RECORDING_TRACK_KEY, -1);
return recordingTrackId > 0 && recordingTrackId == selectedTrackId;
long recordingTrackId = PreferencesUtils.getRecordingTrackId(context);
return recordingTrackId != -1L && recordingTrackId == selectedTrackId;
}
/**
@@ -399,8 +395,7 @@ public class TrackDataHub {
// Save the selection to memory and flush.
selectedTrackId = trackId;
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(
preferences.edit().putLong(SELECTED_TRACK_KEY, trackId));
PreferencesUtils.setSelectedTrackId(context, selectedTrackId);
// Force it to reload data from the beginning.
Log.d(TAG, "Loading track");
@@ -627,9 +622,8 @@ public class TrackDataHub {
} else if (SPEED_REPORTING_KEY.equals(key)) {
reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true);
notifySpeedReportingChanged();
} else if (SELECTED_TRACK_KEY.equals(key)) {
long trackId = preferences.getLong(SELECTED_TRACK_KEY, -1);
loadTrack(trackId);
} else if (PreferencesUtils.getSelectedTrackIdKey(context).equals(key)) {
loadTrack(PreferencesUtils.getSelectedTrackId(context));
}
}
@@ -16,7 +16,6 @@
package com.google.android.apps.mytracks.fragments;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.MyTracksApplication;
import com.google.android.apps.mytracks.StatsUtilities;
import com.google.android.apps.mytracks.content.Track;
@@ -28,8 +27,6 @@ import com.google.android.apps.mytracks.services.ServiceUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
@@ -51,7 +48,6 @@ public class StatsFragment extends Fragment implements TrackDataListener {
private static final String TAG = StatsFragment.class.getSimpleName();
private SharedPreferences sharedPreferences;
private StatsUtilities statsUtilities;
private TrackDataHub trackDataHub;
private UiUpdateThread uiUpdateThread;
@@ -76,7 +72,7 @@ public class StatsFragment extends Fragment implements TrackDataListener {
@Override
public void run() {
Log.d(TAG, "UI update thread started");
while (ServiceUtils.isRecording(getActivity(), null, sharedPreferences)) {
while (ServiceUtils.isRecording(getActivity(), null)) {
getActivity().runOnUiThread(updateTotalTime);
try {
Thread.sleep(1000L);
@@ -92,8 +88,6 @@ public class StatsFragment extends Fragment implements TrackDataListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = getActivity()
.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
statsUtilities = new StatsUtilities(getActivity());
}
@@ -21,6 +21,7 @@ import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.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;
@@ -112,14 +113,12 @@ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor,
@Override
public boolean needsRedraw() {
SharedPreferences prefs = context.getSharedPreferences(Constants.SETTINGS_NAME,
Context.MODE_PRIVATE);
long currentTrackId = prefs.getLong(context.getString(R.string.selected_track_key), -1);
if (currentTrackId == -1) {
long selectedTrackId = PreferencesUtils.getSelectedTrackId(context);
if (selectedTrackId == -1L) {
// Could not find track.
return false;
}
Track track = MyTracksProviderUtils.Factory.get(context).getTrack(currentTrackId);
Track track = MyTracksProviderUtils.Factory.get(context).getTrack(selectedTrackId);
TripStatistics stats = track.getStatistics();
double newAverageMovingSpeed = (int) Math.floor(
stats.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH);
@@ -17,6 +17,7 @@ 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;
@@ -41,8 +42,6 @@ public class PreferenceManager implements OnSharedPreferenceChangeListener {
private final String minRecordingDistanceKey;
private final String minRecordingIntervalKey;
private final String minRequiredAccuracyKey;
private final String recordingTrackKey;
private final String selectedTrackKey;
private final String splitFrequencyKey;
public PreferenceManager(TrackRecordingService service) {
@@ -72,10 +71,6 @@ public class PreferenceManager implements OnSharedPreferenceChangeListener {
service.getString(R.string.min_recording_interval_key);
minRequiredAccuracyKey =
service.getString(R.string.min_required_accuracy_key);
recordingTrackKey =
service.getString(R.string.recording_track_key);
selectedTrackKey =
service.getString(R.string.selected_track_key);
splitFrequencyKey =
service.getString(R.string.split_frequency_key);
@@ -152,12 +147,12 @@ public class PreferenceManager implements OnSharedPreferenceChangeListener {
autoResumeTrackTimeoutKey,
Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT));
}
if (key == null || key.equals(recordingTrackKey)) {
long recordingTrackId = sharedPreferences.getLong(recordingTrackKey, -1);
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 > 0) {
if (recordingTrackId != -1L) {
service.setRecordingTrackId(recordingTrackId);
}
}
@@ -177,18 +172,6 @@ public class PreferenceManager implements OnSharedPreferenceChangeListener {
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
}
public void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(recordingTrackKey, id);
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
}
public void setSelectedTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(selectedTrackKey, id);
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
}
public void shutdown() {
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
service = null;
@@ -17,14 +17,12 @@ package com.google.android.apps.mytracks.services;
import static com.google.android.apps.mytracks.Constants.TAG;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.RemoteException;
import android.util.Log;
@@ -38,16 +36,16 @@ import java.util.List;
public class ServiceUtils {
/**
* Checks whether we're currently recording.
* The checking is done by calling the service, if provided, or alternatively by reading
* recording state saved to preferences.
*
* @param ctx the current context
* Checks whether we're currently recording. The checking is done by calling
* the service, if provided, or alternatively by reading recording state saved
* to preferences.
*
* @param context the current context
* @param service the service, or null if not bound to it
* @param preferences the preferences, or null if not available
* @return true if the service is recording (or supposed to be recording), false otherwise
* @return true if the service is recording (or supposed to be recording),
* false otherwise
*/
public static boolean isRecording(Context ctx, ITrackRecordingService service, SharedPreferences preferences) {
public static boolean isRecording(Context context, ITrackRecordingService service) {
if (service != null) {
try {
return service.isRecording();
@@ -57,11 +55,7 @@ public class ServiceUtils {
Log.e(TAG, "Failed to check if service is recording", e);
}
}
if (preferences == null) {
preferences = ctx.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
}
return preferences.getLong(ctx.getString(R.string.recording_track_key), -1) > 0;
return PreferencesUtils.getRecordingTrackId(context) != -1L;
}
/**
@@ -39,6 +39,7 @@ import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory;
import com.google.android.apps.mytracks.stats.TripStatistics;
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.maps.mytracks.R;
import com.google.common.annotations.VisibleForTesting;
@@ -263,12 +264,13 @@ public class TrackRecordingService extends Service {
restoreStats(recordingTrack);
isRecording = true;
} else {
if (recordingTrackId != -1) {
if (recordingTrackId != -1L) {
// Make sure we have consistent state in shared preferences.
Log.w(TAG, "TrackRecordingService.onCreate: "
+ "Resetting an orphaned recording track = " + recordingTrackId);
}
prefManager.setRecordingTrack(recordingTrackId = -1);
recordingTrackId = -1L;
PreferencesUtils.setRecordingTrackId(this, recordingTrackId);
}
showNotification();
}
@@ -324,7 +326,8 @@ public class TrackRecordingService extends Service {
"TrackRecordingService: Not resuming, because the previous track ("
+ recordingTrack + ") doesn't exist or is too old");
isRecording = false;
prefManager.setRecordingTrack(recordingTrackId = -1);
recordingTrackId = -1L;
PreferencesUtils.setRecordingTrackId(this, recordingTrackId);
stopSelfResult(startId);
return;
}
@@ -609,7 +612,7 @@ public class TrackRecordingService extends Service {
// Reset the number of auto-resume retries.
setAutoResumeTrackRetries(0);
// Persist the current recording track.
prefManager.setRecordingTrack(recordingTrackId);
PreferencesUtils.setRecordingTrackId(this, recordingTrackId);
// Notify the world that we're now recording.
sendTrackBroadcast(
@@ -1035,7 +1038,8 @@ public class TrackRecordingService extends Service {
}
showNotification();
long recordedTrackId = recordingTrackId;
prefManager.setRecordingTrack(recordingTrackId = -1);
recordingTrackId = -1L;
PreferencesUtils.setRecordingTrackId(this, recordingTrackId);
if (sensorManager != null) {
SensorManagerFactory.getInstance().releaseSensorManager(sensorManager);
@@ -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.util;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* Utilities to access preferences stored in {@link SharedPreferences}.
*
* @author Jimmy Shih
*/
public class PreferencesUtils {
private PreferencesUtils() {}
/**
* 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 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);
}
/**
* Gets a preference key
*
* @param context the context
* @param keyId the key id
*/
private static String getKey(Context context, int keyId) {
return context.getString(keyId);
}
/**
* Gets a long preference value.
*
* @param context the context
* @param keyId the key id
*/
private static long getLong(Context context, int keyId) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getLong(getKey(context, keyId), -1L);
}
/**
* Sets a long preference value.
*
* @param context the context
* @param keyId the key id
* @param value the value
*/
private 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);
}
}
@@ -25,6 +25,7 @@ import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.TracksColumns;
import com.google.android.apps.mytracks.services.ControlRecordingService;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
@@ -235,9 +236,8 @@ public class TrackWidgetProvider
reportSpeed = prefs.getBoolean(reportSpeedKey, true);
}
String selectedTrackKey = context.getString(R.string.selected_track_key);
if (key == null || key.equals(selectedTrackKey)) {
selectedTrackId = prefs.getLong(selectedTrackKey, -1);
if (key == null || key.equals(PreferencesUtils.getSelectedTrackIdKey(context))) {
selectedTrackId = PreferencesUtils.getSelectedTrackId(context);
Log.d(TAG, "TrackWidgetProvider setting selecting track from preference: " + selectedTrackId);
}
}
@@ -29,6 +29,7 @@ import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIt
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;
@@ -112,6 +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);
}
@Override
@@ -138,8 +141,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
@@ -297,8 +298,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
@@ -411,8 +410,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
@@ -498,8 +495,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
@@ -570,8 +565,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
@@ -628,8 +621,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
@@ -661,8 +652,6 @@ public class TrackDataHubTest extends AndroidTestCase {
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
@@ -16,6 +16,7 @@
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;
@@ -144,9 +145,7 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
long trackId = -1;
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
sharedPreferencesEditor.commit();
PreferencesUtils.setSelectedTrackId(context, -1L);
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
@@ -24,6 +24,7 @@ import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
import android.content.BroadcastReceiver;
@@ -166,9 +167,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// Disable auto resume by default.
updateAutoResumePrefs(0, -1);
// No recording track.
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), -1);
editor.apply();
PreferencesUtils.setRecordingTrackId(context, -1L);
}
@SmallTest
@@ -186,7 +185,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
@MediumTest
public void testResumeAfterReboot_shouldResume() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), true);
createDummyTrack(123L, System.currentTimeMillis(), true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
@@ -200,7 +199,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// We expect to resume the previous track.
assertTrue(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(123, service.getRecordingTrackId());
assertEquals(123L, service.getRecordingTrackId());
}
// TODO: shutdownService() has a bug and doesn't set mServiceCreated
@@ -220,8 +219,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertTrue(service.isRecording());
assertEquals(id, service.getRecordingTrackId());
shutdownService();
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, PreferencesUtils.getRecordingTrackId(context));
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
@@ -235,7 +233,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
@MediumTest
public void testResumeAfterReboot_noRecordingTrack() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), false);
createDummyTrack(123L, System.currentTimeMillis(), false);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
@@ -249,13 +247,13 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// We don't expect to resume the previous track, because it was stopped.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_expiredTrack() throws Exception {
// Insert a dummy track last updated 20 min ago.
createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true);
createDummyTrack(123L, System.currentTimeMillis() - 20 * 60 * 1000, true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
@@ -269,13 +267,13 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// We don't expect to resume the previous track, because it has expired.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_tooManyAttempts() throws Exception {
// Insert a dummy track.
createDummyTrack(123, System.currentTimeMillis(), true);
createDummyTrack(123L, System.currentTimeMillis(), true);
// Set the number of attempts to max.
updateAutoResumePrefs(
@@ -291,7 +289,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// too many attempts.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
@@ -302,28 +300,28 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
ITrackRecordingService service = bindAndGetService(createStartIntent());
// Test if we start in no-recording mode by default.
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_oldTracks() throws Exception {
createDummyTrack(123, -1, false);
createDummyTrack(123L, -1L, false);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_orphanedRecordingTrack() throws Exception {
// Just set recording track to a bogus value.
setRecordingTrack(256);
PreferencesUtils.setRecordingTrackId(context, 256L);
// Make sure that the service will not start recording and will clear
// the bogus track.
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
}
/**
@@ -391,8 +389,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertEquals(id, track.getId());
assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""),
track.getCategory());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, PreferencesUtils.getRecordingTrackId(context));
assertEquals(id, service.getRecordingTrackId());
// Verify that the start broadcast was received.
@@ -402,14 +399,14 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(startAction, broadcastIntent.getAction());
assertEquals(id, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.getString(R.string.track_id_broadcast_extra), -1L));
context.unregisterReceiver(startReceiver);
}
@MediumTest
public void testStartNewTrack_alreadyRecording() throws Exception {
createDummyTrack(123, -1, true);
createDummyTrack(123L, -1L, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
@@ -418,9 +415,8 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
long newTrack = service.startNewTrack();
assertEquals(-1L, newTrack);
assertEquals(123, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(123, service.getRecordingTrackId());
assertEquals(123L, PreferencesUtils.getRecordingTrackId(context));
assertEquals(123L, service.getRecordingTrackId());
}
@MediumTest
@@ -430,7 +426,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
String stopAction = context.getString(R.string.track_stopped_broadcast_action);
context.registerReceiver(stopReceiver, new IntentFilter(stopAction));
createDummyTrack(123, -1, true);
createDummyTrack(123L, -1L, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
@@ -438,9 +434,8 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// End the current track.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, PreferencesUtils.getRecordingTrackId(context));
assertEquals(-1L, service.getRecordingTrackId());
// Verify that the stop broadcast was received.
assertTrue(stopReceiver.waitUntilReceived(1));
@@ -448,8 +443,8 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(stopAction, broadcastIntent.getAction());
assertEquals(123, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
assertEquals(123L, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1L));
context.unregisterReceiver(stopReceiver);
}
@@ -462,9 +457,8 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// Ending the current track when there is no recording should not result in any error.
service.endCurrentTrack();
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, PreferencesUtils.getRecordingTrackId(context));
assertEquals(-1L, service.getRecordingTrackId());
}
@MediumTest
@@ -489,7 +483,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
@MediumTest
public void testInsertStatisticsMarker_validLocation() throws Exception {
createDummyTrack(123, -1, true);
createDummyTrack(123L, -1L, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
@@ -503,7 +497,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertEquals(getContext().getString(R.string.marker_type_statistics),
wpt.getName());
assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(123L, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNotNull(wpt.getStatistics());
@@ -527,7 +521,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
@MediumTest
public void testInsertWaypointMarker_validWaypoint() throws Exception {
createDummyTrack(123, -1, true);
createDummyTrack(123L, -1L, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
@@ -539,7 +533,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertEquals(getContext().getString(R.string.marker_type_waypoint),
wpt.getName());
assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(123L, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNull(wpt.getStatistics());
@@ -674,13 +668,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
assertTrue(track.getId() >= 0);
providerUtils.insertTrack(track);
assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId());
setRecordingTrack(isRecording ? track.getId() : -1);
}
private void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), id);
editor.apply();
PreferencesUtils.setRecordingTrackId(context, isRecording ? track.getId() : -1L);
}
// TODO: We support multiple values for readability, however this test's
@@ -721,8 +709,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, PreferencesUtils.getRecordingTrackId(context));
assertEquals(id, service.getRecordingTrackId());
// Insert a few points, markers and statistics.
@@ -747,7 +734,7 @@ public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingServ
// Stop the track. Validate if it has correct data.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
assertEquals(-1L, service.getRecordingTrackId());
track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());