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