Merging Sandor's second head by ignoring it

This commit is contained in:
Rodrigo Damazio
2010-11-19 18:37:27 -08:00
16 changed files with 309 additions and 278 deletions
+13 -2
View File
@@ -13,7 +13,6 @@
android:value="AEdPqrEAAAAIi-_QiwoRSc9_bAC9cmuNXTQyU8ajJmGtKdhskQ" /> android:value="AEdPqrEAAAAIi-_QiwoRSc9_bAC9cmuNXTQyU8ajJmGtKdhskQ" />
<provider android:name="com.google.android.apps.mytracks.content.MyTracksProvider" <provider android:name="com.google.android.apps.mytracks.content.MyTracksProvider"
android:process=":trackrecord"
android:authorities="com.google.android.maps.mytracks" /> android:authorities="com.google.android.maps.mytracks" />
<activity android:name="com.google.android.apps.mytracks.MyTracks" <activity android:name="com.google.android.apps.mytracks.MyTracks"
@@ -70,7 +69,6 @@
android:label="@string/welcome"/> android:label="@string/welcome"/>
<service android:name="com.google.android.apps.mytracks.services.TrackRecordingService" <service android:name="com.google.android.apps.mytracks.services.TrackRecordingService"
android:process=":trackrecord"
android:label="Track Recording Service" android:label="Track Recording Service"
android:icon="@drawable/arrow_320" android:icon="@drawable/arrow_320"
android:enabled="true" android:enabled="true"
@@ -105,6 +103,19 @@
<!-- Permissions for misc services --> <!-- Permissions for misc services -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Features required -->
<uses-feature android:name="android.hardware.location" android:required="true"/>
<uses-feature android:name="android.hardware.location.gps" android:required="true"/>
<uses-feature android:name="android.hardware.touchscreen" android:required="true"/>
<!-- Features optional -->
<uses-feature android:name="android.hardware.bluetooth" android:required="false"/>
<uses-feature android:name="android.hardware.location.network" android:required="false"/>
<uses-feature android:name="android.hardware.sensor.compass" android:required="false"/>
<uses-feature android:name="android.hardware.telephony" android:required="false"/>
<uses-feature android:name="android.hardware.telephony.gsm" android:required="false"/>
<uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false"/>
<uses-sdk android:minSdkVersion="3"/> <uses-sdk android:minSdkVersion="3"/>
<supports-screens <supports-screens
android:largeScreens="true" android:largeScreens="true"
+2
View File
@@ -9,9 +9,11 @@
<booleanAttribute key="com.android.ide.eclipse.adt.wipedata" value="false"/> <booleanAttribute key="com.android.ide.eclipse.adt.wipedata" value="false"/>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS"> <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS">
<listEntry value="/MyTracks"/> <listEntry value="/MyTracks"/>
<listEntry value="/MyTracks/AndroidManifest.xml"/>
</listAttribute> </listAttribute>
<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES"> <listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES">
<listEntry value="4"/> <listEntry value="4"/>
<listEntry value="1"/>
</listAttribute> </listAttribute>
<listAttribute key="org.eclipse.debug.ui.favoriteGroups"> <listAttribute key="org.eclipse.debug.ui.favoriteGroups">
<listEntry value="org.eclipse.debug.ui.launchGroup.debug"/> <listEntry value="org.eclipse.debug.ui.launchGroup.debug"/>
@@ -35,7 +35,6 @@ public class AggregatedStatsActivity extends Activity implements
public AggregatedStatsActivity() { public AggregatedStatsActivity() {
this.utils = new StatsUtilities(this); this.utils = new StatsUtilities(this);
this.tracksProvider = MyTracksProviderUtils.Factory.get(this);
} }
@Override @Override
@@ -58,6 +57,8 @@ public class AggregatedStatsActivity extends Activity implements
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.tracksProvider = MyTracksProviderUtils.Factory.get(this);
// We don't need a window title bar: // We don't need a window title bar:
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.stats); setContentView(R.layout.stats);
@@ -31,10 +31,10 @@ import com.google.android.apps.mytracks.io.AuthManagerFactory;
import com.google.android.apps.mytracks.io.GpxImporter; import com.google.android.apps.mytracks.io.GpxImporter;
import com.google.android.apps.mytracks.io.SendToDocs; import com.google.android.apps.mytracks.io.SendToDocs;
import com.google.android.apps.mytracks.io.SendToMyMaps; import com.google.android.apps.mytracks.io.SendToMyMaps;
import com.google.android.apps.mytracks.io.SendToMyMaps.OnSendCompletedListener;
import com.google.android.apps.mytracks.io.TempFileCleaner; import com.google.android.apps.mytracks.io.TempFileCleaner;
import com.google.android.apps.mytracks.io.TrackWriter; import com.google.android.apps.mytracks.io.TrackWriter;
import com.google.android.apps.mytracks.io.TrackWriterFactory; import com.google.android.apps.mytracks.io.TrackWriterFactory;
import com.google.android.apps.mytracks.io.SendToMyMaps.OnSendCompletedListener;
import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat;
import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.ITrackRecordingService;
import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory;
@@ -173,8 +173,8 @@ public class MyTracks extends TabActivity implements OnTouchListener,
ITrackRecordingService trackRecordingService = ITrackRecordingService trackRecordingService =
ITrackRecordingService.Stub.asInterface(service); ITrackRecordingService.Stub.asInterface(service);
try { try {
// TODO: Send a start service intent and broadcast service started message // TODO: Send a start service intent and broadcast service started
// to avoid the hack below and a race condition. // message to avoid the hack below and a race condition.
if (startNewTrackRequested) { if (startNewTrackRequested) {
startNewTrackRequested = false; startNewTrackRequested = false;
startRecordingNewTrack(trackRecordingService); startRecordingNewTrack(trackRecordingService);
@@ -237,9 +237,8 @@ public class MyTracks extends TabActivity implements OnTouchListener,
} }
private boolean isRecordingBasedOnSharedPreferences() { private boolean isRecordingBasedOnSharedPreferences() {
// TrackRecordingServices guarantees that recordingTrackId is set to // TrackRecordingService guarantees that recordingTrackId is set to
// -1 if the track has been stopped. // -1 if the track has been stopped.
// TODO: Refresh recordingTrackId.
return recordingTrackId >= 0; return recordingTrackId >= 0;
} }
@@ -256,6 +255,7 @@ public class MyTracks extends TabActivity implements OnTouchListener,
providerUtils = MyTracksProviderUtils.Factory.get(this); providerUtils = MyTracksProviderUtils.Factory.get(this);
menuManager = new MenuManager(this); menuManager = new MenuManager(this);
sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
dialogManager = new DialogManager(this);
// The volume we want to control is the Text-To-Speech volume // The volume we want to control is the Text-To-Speech volume
int volumeStream = int volumeStream =
@@ -359,7 +359,6 @@ public class MyTracks extends TabActivity implements OnTouchListener,
// to the user. // to the user.
Log.d(MyTracksConstants.TAG, "MyTracks.onResume"); Log.d(MyTracksConstants.TAG, "MyTracks.onResume");
tryBindTrackRecordingService(); tryBindTrackRecordingService();
dialogManager = new DialogManager(this);
super.onResume(); super.onResume();
} }
@@ -693,58 +692,18 @@ public class MyTracks extends TabActivity implements OnTouchListener,
} }
@Override @Override
public void onSharedPreferenceChanged( public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
SharedPreferences sharedPreferences, String key) { String key) {
// The service itself cannot listen to changes (not supported by Android for
// services that run in a separate process). So we'll notify it manually:
if (key != null && trackRecordingService != null) {
try {
trackRecordingService.sharedPreferenceChanged(key);
} catch (RemoteException e) {
Log.w(MyTracksConstants.TAG,
"MyTracks: Cannot notify track recording service of changes "
+ "to shared preferences: ", e);
}
}
if (key != null && key.equals(getString(R.string.selected_track_key))) { if (key != null && key.equals(getString(R.string.selected_track_key))) {
selectedTrackId = selectedTrackId = sharedPreferences.getLong(
sharedPreferences.getLong(getString(R.string.selected_track_key), -1); getString(R.string.selected_track_key), -1);
}
if (key != null && key.equals(getString(R.string.recording_track_key))) {
recordingTrackId = sharedPreferences.getLong(
getString(R.string.recording_track_key), -1);
} }
} }
/**
* Simulates the recording of a random location.
* This is for debugging and testing only. Useful if there is no GPS signal
* available.
*/
// public void recordRandomLocation() {
// if (trackRecordingService != null) {
// Location loc = new Location("gps");
// double latitude = 37.5 + random.nextDouble() / 1000;
// double longitude = -120.0 + random.nextDouble() / 1000;
// loc.setLatitude(latitude);
// loc.setLongitude(longitude);
// loc.setAltitude(random.nextDouble() * 100);
// loc.setTime(System.currentTimeMillis());
// loc.setSpeed(random.nextFloat());
// MyTracksMap map =
// (MyTracksMap) getLocalActivityManager().getActivity("tab1");
// if (map != null) {
// map.onLocationChanged(loc);
// }
// StatsActivity stats =
// (StatsActivity) getLocalActivityManager().getActivity("tab2");
// if (stats != null) {
// stats.onLocationChanged(loc);
// }
// try {
// trackRecordingService.recordLocation(loc);
// } catch (RemoteException e) {
// Log.e(MyTracksConstants.TAG, "MyTracks", e);
// }
// }
// }
/** /**
* Resets status information for sending to MyMaps/Docs. * Resets status information for sending to MyMaps/Docs.
*/ */
@@ -1053,8 +1012,6 @@ public class MyTracks extends TabActivity implements OnTouchListener,
ITrackRecordingService trackRecordingService) { ITrackRecordingService trackRecordingService) {
try { try {
recordingTrackId = trackRecordingService.startNewTrack(); recordingTrackId = trackRecordingService.startNewTrack();
// TODO: This is a hack to propagate recordingTrackId in multiprocess env.
setRecordingTrackId(recordingTrackId);
// Select the recording track. // Select the recording track.
setSelectedTrackId(recordingTrackId); setSelectedTrackId(recordingTrackId);
Toast.makeText(this, getString(R.string.status_now_recording), Toast.makeText(this, getString(R.string.status_now_recording),
@@ -1088,16 +1045,16 @@ public class MyTracks extends TabActivity implements OnTouchListener,
*/ */
public void stopRecording() { public void stopRecording() {
if (trackRecordingService != null) { if (trackRecordingService != null) {
// Save the track id as the shared preference will overwrite the recording track id.
long currentTrackId = recordingTrackId;
try { try {
trackRecordingService.endCurrentTrack(); trackRecordingService.endCurrentTrack();
} catch (RemoteException e) { } catch (RemoteException e) {
Log.e(MyTracksConstants.TAG, "Unable to stop recording.", e); Log.e(MyTracksConstants.TAG, "Unable to stop recording.", e);
} }
Intent intent = new Intent(MyTracks.this, MyTracksDetails.class); Intent intent = new Intent(MyTracks.this, MyTracksDetails.class);
intent.putExtra("trackid", recordingTrackId); intent.putExtra("trackid", currentTrackId);
intent.putExtra("hasCancelButton", false); intent.putExtra("hasCancelButton", false);
// TODO: This is a hack to propagate recordingTrackId in multiprocess env.
setRecordingTrackId(recordingTrackId = -1);
startActivity(intent); startActivity(intent);
} }
tryUnbindTrackRecordingService(); tryUnbindTrackRecordingService();
@@ -1148,29 +1105,16 @@ public class MyTracks extends TabActivity implements OnTouchListener,
* @param trackId the id of the track * @param trackId the id of the track
*/ */
public void setSelectedTrackId(final long trackId) { public void setSelectedTrackId(final long trackId) {
runOnUiThread(new Runnable() { sharedPreferences
public void run() { .edit()
SharedPreferences.Editor editor = sharedPreferences.edit(); .putLong(getString(R.string.selected_track_key), trackId)
editor.putLong(getString(R.string.selected_track_key), trackId); .commit();
editor.commit();
}
});
} }
long getSelectedTrackId() { long getSelectedTrackId() {
return selectedTrackId; return selectedTrackId;
} }
private void setRecordingTrackId(final long trackId) {
runOnUiThread(new Runnable() {
public void run() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(getString(R.string.recording_track_key), trackId);
editor.commit();
}
});
}
/** /**
* Binds to track recording service if it is running. * Binds to track recording service if it is running.
*/ */
@@ -1335,4 +1279,9 @@ public class MyTracks extends TabActivity implements OnTouchListener,
static void clearInstance() { static void clearInstance() {
instance = null; instance = null;
} }
// @VisibleForTesting
ITrackRecordingService getTrackRecordingService() {
return trackRecordingService;
}
} }
@@ -26,10 +26,10 @@ import android.os.Bundle;
import android.preference.CheckBoxPreference; import android.preference.CheckBoxPreference;
import android.preference.ListPreference; import android.preference.ListPreference;
import android.preference.Preference; import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity; import android.preference.PreferenceActivity;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
/** /**
* An activity that let's the user see and edit the settings. * An activity that let's the user see and edit the settings.
@@ -158,7 +158,7 @@ public class MyTracksSettings extends PreferenceActivity {
getPreferenceManager().getSharedPreferences() getPreferenceManager().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(backupListener); .unregisterOnSharedPreferenceChangeListener(backupListener);
super.onPause(); super.onDestroy();
} }
/** /**
@@ -209,7 +209,7 @@ public class SendToDocs {
androidClient = GDataClientFactory.getGDataClient(activity); androidClient = GDataClientFactory.getGDataClient(activity);
SpreadsheetsClient gdataClient = new SpreadsheetsClient(androidClient, SpreadsheetsClient gdataClient = new SpreadsheetsClient(androidClient,
new XmlMapsGDataParserFactory(new AndroidXmlParserFactory())); new XmlMapsGDataParserFactory(new AndroidXmlParserFactory()));
wiseWrapper.setClient(androidClient, gdataClient); wiseWrapper.setClient(gdataClient);
Log.d(MyTracksConstants.TAG, Log.d(MyTracksConstants.TAG,
"GData connection prepared: " + this.writelyAuth); "GData connection prepared: " + this.writelyAuth);
String sheetTitle = "My Tracks"; String sheetTitle = "My Tracks";
@@ -220,7 +220,7 @@ public class SendToDocs {
DocumentsClient docsGdataClient = new DocumentsClient(androidClient, DocumentsClient docsGdataClient = new DocumentsClient(androidClient,
new XmlMapsGDataParserFactory(new AndroidXmlParserFactory())); new XmlMapsGDataParserFactory(new AndroidXmlParserFactory()));
writelyWrapper.setClient(androidClient, docsGdataClient); writelyWrapper.setClient(docsGdataClient);
// First try to find the spreadsheet: // First try to find the spreadsheet:
if (!getSpreadsheetId(writelyWrapper, sheetTitle)) { if (!getSpreadsheetId(writelyWrapper, sheetTitle)) {
@@ -17,7 +17,6 @@ package com.google.android.apps.mytracks.io.gdata;
import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksConstants;
import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManager;
import com.google.wireless.gdata.client.GDataClient;
import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.client.GDataServiceClient;
import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.client.HttpException;
import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.ParseException;
@@ -28,6 +27,10 @@ import android.util.Log;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/** /**
@@ -84,43 +87,63 @@ public class GDataWrapper {
// An unknown error occurred. // An unknown error occurred.
public static final int ERROR_UNKNOWN = 100; public static final int ERROR_UNKNOWN = 100;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES = 1;
private static final int AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT = 5000;
private String errorMessage; private String errorMessage;
private int errorType; private int errorType;
private GDataClient androidGDataClient;
private GDataServiceClient gdataServiceClient; private GDataServiceClient gdataServiceClient;
private AuthManager auth; private AuthManager auth;
private boolean retryOnAuthFailure; private boolean retryOnAuthFailure;
private int retriesPending;
private boolean cleanupCalled;
public GDataWrapper() { public GDataWrapper() {
errorType = ERROR_NO_ERROR; errorType = ERROR_NO_ERROR;
errorMessage = null; errorMessage = null;
auth = null; auth = null;
retryOnAuthFailure = false; retryOnAuthFailure = false;
retriesPending = 0;
cleanupCalled = false;
} }
public void setClient(GDataClient androidGDataClient, public void setClient(GDataServiceClient gdataServiceClient) {
GDataServiceClient gdataServiceClient) {
this.androidGDataClient = androidGDataClient;
this.gdataServiceClient = gdataServiceClient; this.gdataServiceClient = gdataServiceClient;
} }
public boolean runAuthenticatedFunction( public boolean runAuthenticatedFunction(
final AuthenticatedFunction function) { final AuthenticatedFunction function) {
return runOne(function, null); return runCommon(function, null);
} }
public boolean runQuery(final QueryFunction query) { public boolean runQuery(final QueryFunction query) {
return runOne(null, query); return runCommon(null, query);
} }
/** /**
* Runs an arbitrary piece of code. * Runs an arbitrary piece of code.
*/ */
private boolean runOne(final AuthenticatedFunction function, private boolean runCommon(final AuthenticatedFunction function,
final QueryFunction query) {
for (int i = 0; i <= AUTH_TOKEN_INVALIDATE_REFRESH_NUM_RETRIES; i++) {
runOne(function, query);
if (errorType == ERROR_NO_ERROR) {
return true;
}
Log.d(MyTracksConstants.TAG, "GData error encountered: " + errorMessage);
if (errorType == ERROR_AUTH && auth != null) {
if (!retryOnAuthFailure || !invalidateAndRefreshAuthToken()) {
return false;
}
}
Log.d(MyTracksConstants.TAG, "retrying function/query");
}
return false;
}
/**
* Execute a given function or query. If one is executed, errorType and
* errorMessage will contain the result/status of the function/query.
*/
private void runOne(final AuthenticatedFunction function,
final QueryFunction query) { final QueryFunction query) {
try { try {
if (function != null) { if (function != null) {
@@ -128,11 +151,14 @@ public class GDataWrapper {
} else if (query != null) { } else if (query != null) {
query.query(gdataServiceClient); query.query(gdataServiceClient);
} else { } else {
return false; throw new IllegalArgumentException(
"invalid invocation of runOne; one of function/query " +
"must be non-null");
} }
errorType = ERROR_NO_ERROR; errorType = ERROR_NO_ERROR;
errorMessage = null; errorMessage = null;
return true;
} catch (AuthenticationException e) { } catch (AuthenticationException e) {
Log.e(MyTracksConstants.TAG, "Exception", e); Log.e(MyTracksConstants.TAG, "Exception", e);
errorType = ERROR_AUTH; errorType = ERROR_AUTH;
@@ -166,32 +192,42 @@ public class GDataWrapper {
errorType = ERROR_CONFLICT; errorType = ERROR_CONFLICT;
errorMessage = e.getMessage(); errorMessage = e.getMessage();
} }
}
Log.d(MyTracksConstants.TAG, "GData error encountered: " + errorMessage); /**
if (errorType == ERROR_AUTH && auth != null) { * Invalidates and refreshes the auth token. Blocks until the refresh has
Runnable whenFinished = null; * completed or until we deem the refresh as having timed out.
if (retryOnAuthFailure) { *
retriesPending++; * @return true If the invalidate/refresh succeeds, false if it fails or
// This is a little odd. This method cannot return in the the thread * times out.
// that called the original runQuery(). We should look at reworking this */
// API. private boolean invalidateAndRefreshAuthToken() {
whenFinished = new Runnable() { Log.d(MyTracksConstants.TAG, "Retrying due to auth failure");
public void run() { // This FutureTask doesn't do anything -- it exists simply to be
retriesPending--; // blocked upon using get().
try { FutureTask<?> whenFinishedFuture = new FutureTask<Object>(new Runnable() {
runOne(function, query); public void run() {}
} catch (IllegalStateException ise) { }, null);
// This can happen if the connection pool was shut down.
Log.e(MyTracksConstants.TAG, "Failed to rerun query.", ise); auth.invalidateAndRefresh(whenFinishedFuture);
}
if (cleanupCalled && retriesPending == 0) { try {
cleanUp(); Log.d(MyTracksConstants.TAG, "waiting for invalidate");
} whenFinishedFuture.get(AUTH_TOKEN_INVALIDATE_REFRESH_TIMEOUT,
} TimeUnit.MILLISECONDS);
}; Log.d(MyTracksConstants.TAG, "invalidate finished");
} return true;
auth.invalidateAndRefresh(whenFinished);
} catch (InterruptedException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (ExecutionException e) {
Log.e(MyTracksConstants.TAG, "Failed to invalidate", e);
} catch (TimeoutException e) {
Log.e(MyTracksConstants.TAG, "Invalidate didn't complete in time", e);
} finally {
whenFinishedFuture.cancel(false);
} }
return false; return false;
} }
@@ -203,17 +239,6 @@ public class GDataWrapper {
return errorMessage; return errorMessage;
} }
// cleanUp must be called when done using this wrapper to close the client.
// Note that the cleanup will be delayed if auth failure retries were
// requested and there is a pending retry.
public void cleanUp() {
cleanupCalled = true;
if (retriesPending == 0) {
androidGDataClient.close();
androidGDataClient = null;
}
}
public void setAuthManager(AuthManager auth) { public void setAuthManager(AuthManager auth) {
this.auth = auth; this.auth = auth;
} }
@@ -20,7 +20,6 @@ import com.google.android.maps.mytracks.R;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.text.format.Time;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@@ -84,13 +84,4 @@ interface ITrackRecordingService {
* Deletes all the stored tracks. * Deletes all the stored tracks.
*/ */
void deleteAllTracks(); void deleteAllTracks();
/**
* Notifies the service that its preferences may have been changed.
* This is necessary because the service running on a separate process cannot
* listen to the changes itself.
*
* @param key the preference key which may have changed
*/
void sharedPreferenceChanged(in String key);
} }
@@ -20,7 +20,7 @@ import com.google.android.apps.mytracks.MyTracksSettings;
import com.google.android.maps.mytracks.R; import com.google.android.maps.mytracks.R;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Log; import android.util.Log;
/** /**
@@ -28,8 +28,9 @@ import android.util.Log;
* *
* @author Sandor Dornbush * @author Sandor Dornbush
*/ */
public class PreferenceManager { public class PreferenceManager implements OnSharedPreferenceChangeListener {
private TrackRecordingService service; private TrackRecordingService service;
private SharedPreferences sharedPreferences;
private final String announcementFrequencyKey; private final String announcementFrequencyKey;
private final String autoResumeTrackCurrentRetryKey; private final String autoResumeTrackCurrentRetryKey;
private final String autoResumeTrackTimeoutKey; private final String autoResumeTrackTimeoutKey;
@@ -44,6 +45,14 @@ public class PreferenceManager {
public PreferenceManager(TrackRecordingService service) { public PreferenceManager(TrackRecordingService service) {
this.service = service; this.service = service;
this.sharedPreferences = service.getSharedPreferences(
MyTracksSettings.SETTINGS_NAME, 0);
if (sharedPreferences == null) {
Log.w(MyTracksConstants.TAG,
"TrackRecordingService: Couldn't get shared preferences.");
throw new IllegalStateException("Couldn't get shared preferences");
}
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
announcementFrequencyKey = announcementFrequencyKey =
service.getString(R.string.announcement_frequency_key); service.getString(R.string.announcement_frequency_key);
@@ -67,17 +76,9 @@ public class PreferenceManager {
service.getString(R.string.signal_sampling_frequency_key); service.getString(R.string.signal_sampling_frequency_key);
splitFrequencyKey = splitFrequencyKey =
service.getString(R.string.split_frequency_key); service.getString(R.string.split_frequency_key);
}
private SharedPreferences getSharedPreference() { // Refresh all properties.
SharedPreferences sharedPreferences = onSharedPreferenceChanged(sharedPreferences, null);
service.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0);
if (sharedPreferences == null) {
Log.w(MyTracksConstants.TAG,
"TrackRecordingService: Couldn't get shared preferences.");
throw new IllegalStateException("Couldn't get shared preferences");
}
return sharedPreferences;
} }
/** /**
@@ -86,11 +87,9 @@ public class PreferenceManager {
* *
* @param key the key that changed (may be null to update all preferences) * @param key the key that changed (may be null to update all preferences)
*/ */
public void onSharedPreferenceChanged(String key) { @Override
// This is a hack! public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
// Ideally we should not have to reload the shared pref here. String key) {
// We have to reload it since the in memory version will not match the values from the activity.
SharedPreferences sharedPreferences = getSharedPreference();
if (key == null || key.equals(minRecordingDistanceKey)) { if (key == null || key.equals(minRecordingDistanceKey)) {
service.setMinRecordingDistance( service.setMinRecordingDistance(
sharedPreferences.getInt( sharedPreferences.getInt(
@@ -169,16 +168,16 @@ public class PreferenceManager {
} }
public void setAutoResumeTrackCurrentRetry(int retryAttempts) { public void setAutoResumeTrackCurrentRetry(int retryAttempts) {
SharedPreferences sharedPreferences = getSharedPreference(); sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit(); .edit()
editor.putInt(autoResumeTrackCurrentRetryKey, retryAttempts); .putInt(autoResumeTrackCurrentRetryKey, retryAttempts)
editor.commit(); .commit();
} }
public void setRecordingTrack(long id) { public void setRecordingTrack(long id) {
SharedPreferences sharedPreferences = getSharedPreference(); sharedPreferences
Editor editor = sharedPreferences.edit(); .edit()
editor.putLong(recordingTrackKey, id); .putLong(recordingTrackKey, id)
editor.commit(); .commit();
} }
} }
@@ -125,6 +125,8 @@ public class SplitManager {
* @param splitFrequency The frequency in time or distance * @param splitFrequency The frequency in time or distance
*/ */
public void setSplitFrequency(int splitFrequency) { public void setSplitFrequency(int splitFrequency) {
Log.d(MyTracksConstants.TAG,
"setSplitFrequency: splitFrequency = " + splitFrequency);
this.splitFrequency = splitFrequency; this.splitFrequency = splitFrequency;
// TODO: Decouple service from this class once and forever. // TODO: Decouple service from this class once and forever.
@@ -34,7 +34,7 @@ import android.util.Log;
import java.util.Locale; import java.util.Locale;
/** /**
* This class will periodically announce the user's trip statitics. * This class will periodically announce the user's trip statistics.
* *
* @author Sandor Dornbush * @author Sandor Dornbush
*/ */
@@ -98,7 +98,7 @@ public class StatusAnnouncerTask implements PeriodicTask {
* Called when the TTS engine is initialized. * Called when the TTS engine is initialized.
*/ */
private void onTtsInit(int status) { private void onTtsInit(int status) {
Log.i(MyTracksConstants.TAG, "StatusAnnouncerTask.TTS init: " + status); Log.i(MyTracksConstants.TAG, "TrackRecordingService.TTS init: " + status);
this.ready = (status == TextToSpeech.SUCCESS); this.ready = (status == TextToSpeech.SUCCESS);
if (ready) { if (ready) {
@@ -261,7 +261,9 @@ public class StatusAnnouncerTask implements PeriodicTask {
protected void listenToPhoneState(PhoneStateListener listener, int events) { protected void listenToPhoneState(PhoneStateListener listener, int events) {
TelephonyManager telephony = TelephonyManager telephony =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(listener, events); if (telephony != null) {
telephony.listen(listener, events);
}
} }
/** /**
@@ -15,24 +15,23 @@
*/ */
package com.google.android.apps.mytracks.services; package com.google.android.apps.mytracks.services;
import android.util.Log;
import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksConstants;
import android.util.Log;
/** /**
* This class will manage a period task executer. * This class manages a period task executer.
* *
* @author Sandor Dornbush * @author Sandor Dornbush
*/ */
public class TaskExecuterManager { public class TaskExecuterManager {
int frequency; private int frequency;
PeriodicTask task; private final PeriodicTask task;
PeriodicTaskExecuter executer; private PeriodicTaskExecuter executer;
public TaskExecuterManager(int frequency, public TaskExecuterManager(int frequency, PeriodicTask task,
PeriodicTask task, TrackRecordingService service) {
TrackRecordingService service) {
this.task = task; this.task = task;
setFrequency(frequency, service); setFrequency(frequency, service);
} }
@@ -50,7 +49,7 @@ public class TaskExecuterManager {
*/ */
public void setFrequency(int frequency, TrackRecordingService service) { public void setFrequency(int frequency, TrackRecordingService service) {
this.frequency = frequency; this.frequency = frequency;
Log.i(MyTracksConstants.TAG, "Frequency " + task.getClass().getSimpleName() + " set to: " + frequency); Log.i(MyTracksConstants.TAG, "Frequency set to: " + frequency);
if (frequency == -1) { if (frequency == -1) {
if (executer != null) { if (executer != null) {
@@ -69,7 +68,7 @@ public class TaskExecuterManager {
} }
/** /**
* Restore the task at the current frequency. * Restores the task at the current frequency.
*/ */
public void restore() { public void restore() {
if (frequency > 0) { if (frequency > 0) {
@@ -77,4 +76,13 @@ public class TaskExecuterManager {
executer.scheduleTask(frequency * 60000); executer.scheduleTask(frequency * 60000);
} }
} }
/**
* Shuts down this executer.
*/
public void shutdown() {
if (executer != null) {
executer.shutdown();
}
}
} }
@@ -103,7 +103,7 @@ public class TrackRecordingService extends Service implements LocationListener {
* recorded points (as compared to each location fix). It's used to overlay * recorded points (as compared to each location fix). It's used to overlay
* waypoints precisely in the elevation profile chart. * waypoints precisely in the elevation profile chart.
*/ */
private double length = 0; private double length;
/** /**
* Status announcer executer. * Status announcer executer.
@@ -118,7 +118,7 @@ public class TrackRecordingService extends Service implements LocationListener {
* The interval in milliseconds that we have requested to be notified of gps * The interval in milliseconds that we have requested to be notified of gps
* readings. * readings.
*/ */
private long currentRecordingInterval = 0; private long currentRecordingInterval;
/** /**
* The policy used to decide how often we should request gps updates. * The policy used to decide how often we should request gps updates.
@@ -166,17 +166,17 @@ public class TrackRecordingService extends Service implements LocationListener {
/** /**
* Is the service currently recording a track? * Is the service currently recording a track?
*/ */
private boolean isRecording = false; private boolean isRecording;
/** /**
* Last good location the service has received from the location listener * Last good location the service has received from the location listener
*/ */
private Location lastLocation = null; private Location lastLocation;
/** /**
* Last valid location (i.e. not a marker) that was recorded. * Last valid location (i.e. not a marker) that was recorded.
*/ */
private Location lastValidLocation = null; private Location lastValidLocation;
/** /**
* The frequency of status announcements. * The frequency of status announcements.
@@ -295,7 +295,7 @@ public class TrackRecordingService extends Service implements LocationListener {
* Tries to acquire a partial wake lock if not already acquired. Logs errors * Tries to acquire a partial wake lock if not already acquired. Logs errors
* and gives up trying in case the wake lock cannot be acquired. * and gives up trying in case the wake lock cannot be acquired.
*/ */
public void acquireWakeLock() { private void acquireWakeLock() {
try { try {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm == null) { if (pm == null) {
@@ -326,6 +326,16 @@ public class TrackRecordingService extends Service implements LocationListener {
} }
} }
/**
* Releases the wake lock if it's currently held.
*/
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
/** /**
* Shows the notification message and icon in the notification bar. * Shows the notification message and icon in the notification bar.
*/ */
@@ -605,28 +615,6 @@ public class TrackRecordingService extends Service implements LocationListener {
// Do nothing // Do nothing
} }
/*
* SharedPreferencesChangeListener interface implementation. Note that
* services don't currently receive this event (Android platform limitation).
* This should be called from an activity whenever settings change.
*/
/**
* Notifies that preferences have changed.
* Call this with key == null to update all preferences in one call.
*
* @param key the key that changed (may be null to update all preferences)
*/
public void onSharedPreferenceChanged(String key) {
Log.d(MyTracksConstants.TAG,
"TrackRecordingService.onSharedPreferenceChanged");
prefManager.onSharedPreferenceChanged(key);
if (isRecording) {
registerLocationListener();
}
}
/* /*
* Application lifetime events: ============================ * Application lifetime events: ============================
*/ */
@@ -647,9 +635,7 @@ public class TrackRecordingService extends Service implements LocationListener {
new TaskExecuterManager(-1, strengthTaskFactory.create(this), this); new TaskExecuterManager(-1, strengthTaskFactory.create(this), this);
prefManager = new PreferenceManager(this); prefManager = new PreferenceManager(this);
prefManager.onSharedPreferenceChanged(null);
registerLocationListener(); registerLocationListener();
acquireWakeLock();
/** /**
* After 5 min, check every minute that location listener still is * After 5 min, check every minute that location listener still is
* registered and spit out additional debugging info to the logs: * registered and spit out additional debugging info to the logs:
@@ -681,24 +667,25 @@ public class TrackRecordingService extends Service implements LocationListener {
private void setUpAnnouncer() { private void setUpAnnouncer() {
Log.d(MyTracksConstants.TAG, "TrackRecordingService.setUpAnnouncer: " Log.d(MyTracksConstants.TAG, "TrackRecordingService.setUpAnnouncer: "
+ announcementExecuter); + announcementExecuter);
if (announcementFrequency == -1 || recordingTrackId == -1) { if (announcementFrequency != -1 && recordingTrackId != -1) {
shutdownAnnouncer(); handler.post(new Runnable() {
return; @Override
} public void run() {
handler.post(new Runnable() { if (announcementExecuter == null) {
public void run() { StatusAnnouncerFactory statusAnnouncerFactory =
if (announcementExecuter == null) { new StatusAnnouncerFactory(ApiFeatures.getInstance());
StatusAnnouncerFactory statusAnnouncerFactory = PeriodicTask announcer = statusAnnouncerFactory.create(
new StatusAnnouncerFactory(ApiFeatures.getInstance()); TrackRecordingService.this);
PeriodicTask announcer = statusAnnouncerFactory.create(TrackRecordingService.this); if (announcer == null) {
if (announcer == null) return; return;
}
announcer.start(); announcementExecuter = new PeriodicTaskExecuter(announcer,
announcementExecuter = new PeriodicTaskExecuter(announcer, TrackRecordingService.this); TrackRecordingService.this);
}
announcementExecuter.scheduleTask(announcementFrequency * 60000);
} }
announcementExecuter.scheduleTask(announcementFrequency * 60000); });
} }
});
} }
private void shutdownAnnouncer() { private void shutdownAnnouncer() {
@@ -718,14 +705,13 @@ public class TrackRecordingService extends Service implements LocationListener {
Log.d(MyTracksConstants.TAG, "TrackRecordingService.onDestroy"); Log.d(MyTracksConstants.TAG, "TrackRecordingService.onDestroy");
checkLocationListener.cancel(); checkLocationListener.cancel();
timer.cancel(); timer.cancel();
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
}
isRecording = false; isRecording = false;
showNotification(); showNotification();
unregisterLocationListener(); unregisterLocationListener();
shutdownAnnouncer(); shutdownAnnouncer();
signalManager.shutdown();
splitManager.shutdown(); splitManager.shutdown();
releaseWakeLock();
super.onDestroy(); super.onDestroy();
} }
@@ -951,32 +937,7 @@ public class TrackRecordingService extends Service implements LocationListener {
@Override @Override
public void endCurrentTrack() { public void endCurrentTrack() {
Log.d(MyTracksConstants.TAG, "TrackRecordingService.endCurrentTrack"); TrackRecordingService.this.endCurrentTrack();
if (recordingTrackId == -1 || !isRecording) {
throw new IllegalStateException("No recording track in progress!");
}
isRecording = false;
shutdownAnnouncer();
Track recordingTrack = providerUtils.getTrack(recordingTrackId);
if (recordingTrack != null) {
TripStatistics stats = recordingTrack.getStatistics();
stats.setStopTime(System.currentTimeMillis());
stats.setTotalTime(stats.getStopTime() - stats.getStartTime());
long lastRecordedLocationId =
providerUtils.getLastLocationId(recordingTrackId);
ContentValues values = new ContentValues();
if (lastRecordedLocationId >= 0
&& recordingTrack.getStopId() >= 0) {
values.put(TracksColumns.STOPID, lastRecordedLocationId);
}
values.put(TracksColumns.STOPTIME, stats.getStopTime());
values.put(TracksColumns.TOTALTIME, stats.getTotalTime());
getContentResolver().update(TracksColumns.CONTENT_URI, values,
"_id=" + recordingTrack.getId(), null);
}
showNotification();
prefManager.setRecordingTrack(recordingTrackId = -1);
} }
@Override @Override
@@ -992,13 +953,6 @@ public class TrackRecordingService extends Service implements LocationListener {
public void recordLocation(Location loc) { public void recordLocation(Location loc) {
onLocationChanged(loc); onLocationChanged(loc);
} }
@Override
public void sharedPreferenceChanged(String key) {
Log.d(MyTracksConstants.TAG,
"TrackRecordingService.sharedPreferenceChanged: " + key);
onSharedPreferenceChanged(key);
}
}; };
public long startNewTrack() { public long startNewTrack() {
@@ -1008,6 +962,7 @@ public class TrackRecordingService extends Service implements LocationListener {
} }
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
acquireWakeLock();
Track track = new Track(); Track track = new Track();
TripStatistics trackStats = track.getStatistics(); TripStatistics trackStats = track.getStatistics();
@@ -1041,6 +996,36 @@ public class TrackRecordingService extends Service implements LocationListener {
return recordingTrackId; return recordingTrackId;
} }
private void endCurrentTrack() {
Log.d(MyTracksConstants.TAG, "TrackRecordingService.endCurrentTrack");
if (recordingTrackId == -1 || !isRecording) {
throw new IllegalStateException("No recording track in progress!");
}
shutdownAnnouncer();
isRecording = false;
Track recordingTrack = providerUtils.getTrack(recordingTrackId);
if (recordingTrack != null) {
TripStatistics stats = recordingTrack.getStatistics();
stats.setStopTime(System.currentTimeMillis());
stats.setTotalTime(stats.getStopTime() - stats.getStartTime());
long lastRecordedLocationId =
providerUtils.getLastLocationId(recordingTrackId);
ContentValues values = new ContentValues();
if (lastRecordedLocationId >= 0
&& recordingTrack.getStopId() >= 0) {
values.put(TracksColumns.STOPID, lastRecordedLocationId);
}
values.put(TracksColumns.STOPTIME, stats.getStopTime());
values.put(TracksColumns.TOTALTIME, stats.getTotalTime());
getContentResolver().update(TracksColumns.CONTENT_URI, values,
"_id=" + recordingTrack.getId(), null);
}
showNotification();
prefManager.setRecordingTrack(recordingTrackId = -1);
releaseWakeLock();
}
public TripStatistics getTripStatistics() { public TripStatistics getTripStatistics() {
return statsBuilder.getStatistics(); return statsBuilder.getStatistics();
} }
@@ -1063,8 +1048,6 @@ public class TrackRecordingService extends Service implements LocationListener {
public void setAnnouncementFrequency(int announcementFrequency) { public void setAnnouncementFrequency(int announcementFrequency) {
this.announcementFrequency = announcementFrequency; this.announcementFrequency = announcementFrequency;
Log.d(MyTracksConstants.TAG, "TrackRecordingService.setAnnouncerFrequency:"
+ this.announcementFrequency);
if (announcementFrequency == -1) { if (announcementFrequency == -1) {
shutdownAnnouncer(); shutdownAnnouncer();
} else { } else {
@@ -17,11 +17,14 @@ package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R; import com.google.android.maps.mytracks.R;
import android.app.Activity;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.Editor;
import android.net.Uri; import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2; import android.test.ActivityInstrumentationTestCase2;
import android.widget.Button;
import java.io.File; import java.io.File;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@@ -47,6 +50,7 @@ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
clearSelectedAndRecordingTracks(); clearSelectedAndRecordingTracks();
waitForIdle();
super.tearDown(); super.tearDown();
} }
@@ -138,6 +142,7 @@ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
// Check if not recording. // Check if not recording.
clearSelectedAndRecordingTracks(); clearSelectedAndRecordingTracks();
waitForIdle(); waitForIdle();
assertFalse(getActivity().isRecording()); assertFalse(getActivity().isRecording());
assertEquals(-1, getActivity().getRecordingTrackId()); assertEquals(-1, getActivity().getRecordingTrackId());
long selectedTrackId = getActivity().getSharedPreferences().getLong( long selectedTrackId = getActivity().getSharedPreferences().getLong(
@@ -158,9 +163,26 @@ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
assertEquals(recordingTrackId, selectedTrackId); assertEquals(recordingTrackId, selectedTrackId);
assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); assertEquals(selectedTrackId, getActivity().getSelectedTrackId());
// Watch for MyTracksDetails activity.
ActivityMonitor monitor = getInstrumentation().addMonitor(
MyTracksDetails.class.getName(), null, false);
// Now, stop the track and make sure that it is still selected, but // Now, stop the track and make sure that it is still selected, but
// no longer recording. // no longer recording.
getActivity().stopRecording(); getActivity().stopRecording();
// Check if we got back MyTracksDetails activity.
Activity activity = getInstrumentation().waitForMonitor(monitor);
assertTrue(activity instanceof MyTracksDetails);
// TODO: Update track name and other properties and test if they were
// properly saved.
// Simulate a click on Save button.
Button save = (Button) activity.findViewById(R.id.trackdetails_save);
save.performClick();
// Check the remaining properties.
recordingTrackId = awaitRecordingStatus(5000, false); recordingTrackId = awaitRecordingStatus(5000, false);
assertEquals(-1, recordingTrackId); assertEquals(-1, recordingTrackId);
assertEquals(recordingTrackId, getActivity().getRecordingTrackId()); assertEquals(recordingTrackId, getActivity().getRecordingTrackId());
@@ -197,10 +219,11 @@ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{
* Clears {selected,recording}TrackId in the {@link SharedPreferences}. * Clears {selected,recording}TrackId in the {@link SharedPreferences}.
*/ */
private void clearSelectedAndRecordingTracks() { private void clearSelectedAndRecordingTracks() {
// TODO: Consider clearing all preferences.
Editor editor = getActivity().getSharedPreferences().edit(); Editor editor = getActivity().getSharedPreferences().edit();
editor.putLong(getActivity().getString(R.string.selected_track_key), -1); editor.putLong(getActivity().getString(R.string.selected_track_key), -1);
editor.putLong(getActivity().getString(R.string.recording_track_key), -1); editor.putLong(getActivity().getString(R.string.recording_track_key), -1);
editor.clear();
editor.commit(); editor.commit();
} }
@@ -600,9 +600,26 @@ public class TrackRecordingServiceTest
functionalTest(R.string.metric_units_key, false); functionalTest(R.string.metric_units_key, false);
} }
// TODO: Add the following tests: @MediumTest
// R.string.min_recording_interval_key public void testWithProperties_noMinRecordingInterval() throws Exception {
// R.string.min_required_accuracy_key functionalTest(R.string.min_recording_interval_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingInterval()
throws Exception {
functionalTest(R.string.min_recording_interval_key, 3);
}
@MediumTest
public void testWithProperties_noMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, 500);
}
private ITrackRecordingService bindAndGetService(Intent intent) { private ITrackRecordingService bindAndGetService(Intent intent) {
ITrackRecordingService service = ITrackRecordingService.Stub.asInterface( ITrackRecordingService service = ITrackRecordingService.Stub.asInterface(
@@ -692,7 +709,26 @@ public class TrackRecordingServiceTest
context.getString(R.string.recording_track_key), -1)); context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId()); assertEquals(id, service.getRecordingTrackId());
// TODO: Add a few locations, insert markers, etc. // Insert a few points, markers and statistics.
long startTime = System.currentTimeMillis();
for (int i = 0; i < 30; i++) {
Location loc = new Location("gps");
loc.setLongitude(35.0f + i / 10.0f);
loc.setLatitude(45.0f - i / 5.0f);
loc.setAccuracy(5);
loc.setSpeed(10);
loc.setTime(startTime + i * 10000);
loc.setBearing(3.0f);
service.recordLocation(loc);
if (i % 10 == 0) {
service.insertStatisticsMarker(loc);
} else if (i % 7 == 0) {
Waypoint waypoint = new Waypoint();
waypoint.setLocation(loc);
service.insertWaypointMarker(waypoint);
}
}
// Stop the track. Validate if it has correct data. // Stop the track. Validate if it has correct data.
service.endCurrentTrack(); service.endCurrentTrack();