code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import junit.framework.TestCase; /** * Tests for {@link TripStatistics}. * This only tests non-trivial pieces of that class. * * @author Rodrigo Damazio */ public class TripStatisticsTest extends TestCase { private TripStatistics statistics; @Override protected void setUp() throws Exception { super.setUp(); statistics = new TripStatistics(); } public void testSetBounds() { // This is not a trivial setter, conversion happens in it statistics.setBounds(12345, -34567, 56789, -98765); assertEquals(12345, statistics.getLeft()); assertEquals(-34567, statistics.getTop()); assertEquals(56789, statistics.getRight()); assertEquals(-98765, statistics.getBottom()); } public void testMerge() { TripStatistics statistics2 = new TripStatistics(); statistics.setStartTime(1000L); // Resulting start time statistics.setStopTime(2500L); statistics2.setStartTime(3000L); statistics2.setStopTime(4000L); // Resulting stop time statistics.setTotalTime(1500L); statistics2.setTotalTime(1000L); // Result: 1500+1000 statistics.setMovingTime(700L); statistics2.setMovingTime(600L); // Result: 700+600 statistics.setTotalDistance(750.0); statistics2.setTotalDistance(350.0); // Result: 750+350 statistics.setTotalElevationGain(50.0); statistics2.setTotalElevationGain(850.0); // Result: 850+50 statistics.setMaxSpeed(60.0); // Resulting max speed statistics2.setMaxSpeed(30.0); statistics.setMaxElevation(1250.0); statistics.setMinElevation(1200.0); // Resulting min elevation statistics2.setMaxElevation(3575.0); // Resulting max elevation statistics2.setMinElevation(2800.0); statistics.setMaxGrade(15.0); statistics.setMinGrade(-25.0); // Resulting min grade statistics2.setMaxGrade(35.0); // Resulting max grade statistics2.setMinGrade(0.0); // Resulting bounds: -10000, 35000, 30000, -40000 statistics.setBounds(-10000, 20000, 30000, -40000); statistics2.setBounds(-5000, 35000, 0, 20000); statistics.merge(statistics2); assertEquals(1000L, statistics.getStartTime()); assertEquals(4000L, statistics.getStopTime()); assertEquals(2500L, statistics.getTotalTime()); assertEquals(1300L, statistics.getMovingTime()); assertEquals(1100.0, statistics.getTotalDistance()); assertEquals(900.0, statistics.getTotalElevationGain()); assertEquals(60.0, statistics.getMaxSpeed()); assertEquals(-10000, statistics.getLeft()); assertEquals(30000, statistics.getRight()); assertEquals(35000, statistics.getTop()); assertEquals(-40000, statistics.getBottom()); assertEquals(1200.0, statistics.getMinElevation()); assertEquals(3575.0, statistics.getMaxElevation()); assertEquals(-25.0, statistics.getMinGrade()); assertEquals(35.0, statistics.getMaxGrade()); } public void testGetAverageSpeed() { statistics.setTotalDistance(1000.0); statistics.setTotalTime(50000); // in milliseconds assertEquals(20.0, statistics.getAverageSpeed()); } public void testGetAverageMovingSpeed() { statistics.setTotalDistance(1000.0); statistics.setMovingTime(20000); // in milliseconds assertEquals(50.0, statistics.getAverageMovingSpeed()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.test.ActivityInstrumentationTestCase2; /** * @author Sandor Dornbush */ public class DialogManagerTest extends ActivityInstrumentationTestCase2<MyTracks> { public DialogManagerTest() { super(MyTracks.class); } @Override protected void setUp() throws Exception { super.setUp(); MyTracks.clearInstance(); assertNull(MyTracks.getInstance()); } public void test_onCreateChartSettings() { Dialog d = getActivity().onCreateDialog(DialogManager.DIALOG_CHART_SETTINGS, null); assertNotNull(d); assertTrue(d instanceof ChartSettingsDialog); } public void test_onCreateImportProgress() { Dialog d = getActivity().onCreateDialog( DialogManager.DIALOG_IMPORT_PROGRESS, null); assertNotNull(d); assertTrue(d instanceof ProgressDialog); } public void test_onCreateProgress() { Dialog d = getActivity().onCreateDialog(DialogManager.DIALOG_PROGRESS, null); assertNotNull(d); assertTrue(d instanceof ProgressDialog); ProgressDialog pd = (ProgressDialog) d; assertEquals(100, pd.getMax()); assertEquals(10, pd.getProgress()); } public void test_onCreateSendToGoogle() { Dialog d = getActivity().onCreateDialog(DialogManager.DIALOG_SEND_TO_GOOGLE, null); assertNotNull(d); assertTrue(d instanceof SendToGoogleDialog); } public void test_onCreateSendToGoogleResult() { Dialog d = getActivity().onCreateDialog( DialogManager.DIALOG_SEND_TO_GOOGLE_RESULT, null); assertNotNull(d); assertTrue(d instanceof AlertDialog); } public void test_onCreateWriteProgress() { Dialog d = getActivity().onCreateDialog( DialogManager.DIALOG_WRITE_PROGRESS, null); assertNotNull(d); assertTrue(d instanceof ProgressDialog); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Instrumentation.ActivityMonitor; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.widget.Button; import java.io.File; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; /** * A unit test for {@link MyTracks} activity. * * @author Bartlomiej Niechwiej */ public class MyTracksTest extends ActivityInstrumentationTestCase2<MyTracks>{ public MyTracksTest() { super(MyTracks.class); } @Override protected void setUp() throws Exception { super.setUp(); MyTracks.clearInstance(); assertNull(MyTracks.getInstance()); } @Override protected void tearDown() throws Exception { clearSelectedAndRecordingTracks(); waitForIdle(); super.tearDown(); } public void testInitialization_mainAction() { // Make sure we can start MyTracks and the activity doesn't start recording. assertNotNull(getActivity()); assertNotNull(MyTracks.getInstance()); assertNotNull(getActivity().getSharedPreferences()); // Check if not recording. assertFalse(getActivity().isRecording()); assertEquals(-1, getActivity().getRecordingTrackId()); long selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } public void testInitialization_viewActionWithNoData() { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); setActivityIntent(startIntent); assertNotNull(getActivity()); assertNotNull(MyTracks.getInstance()); assertNotNull(getActivity().getSharedPreferences()); // Check if not recording. assertFalse(getActivity().isRecording()); assertEquals(-1, getActivity().getRecordingTrackId()); long selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } public void testInitialization_viewActionWithValidData() throws Exception { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(File.createTempFile("valid", ".gpx")); // TODO: Add a valid GPX. startIntent.setData(uri); setActivityIntent(startIntent); assertNotNull(getActivity()); assertNotNull(MyTracks.getInstance()); assertNotNull(getActivity().getSharedPreferences()); // Check if not recording. assertFalse(getActivity().isRecording()); assertEquals(-1, getActivity().getRecordingTrackId()); long selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // TODO: Finish this test. } public void testInitialization_viewActionWithInvalidData() throws Exception { // Simulate start with ACTION_VIEW intent. Intent startIntent = new Intent(); startIntent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(File.createTempFile("invalid", ".gpx")); startIntent.setData(uri); setActivityIntent(startIntent); assertNotNull(getActivity()); assertNotNull(MyTracks.getInstance()); assertNotNull(getActivity().getSharedPreferences()); // Check if not recording. assertFalse(getActivity().isRecording()); assertEquals(-1, getActivity().getRecordingTrackId()); long selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // TODO: Finish this test. } public void testRecording_startAndStop() throws Exception { // Make sure we can start MyTracks and the activity doesn't start recording. assertNotNull(getActivity()); assertNotNull(MyTracks.getInstance()); assertNotNull(getActivity().getSharedPreferences()); // Check if not recording. clearSelectedAndRecordingTracks(); waitForIdle(); assertFalse(getActivity().isRecording()); assertEquals(-1, getActivity().getRecordingTrackId()); long selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); // Start a new track. getActivity().startRecording(); long recordingTrackId = awaitRecordingStatus(5000, true); assertTrue(recordingTrackId >= 0); // Wait until we are done and make sure that selectedTrack = recordingTrack. waitForIdle(); assertEquals(recordingTrackId, getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.recording_track_key), -1)); selectedTrackId = getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.selected_track_key), -1); assertEquals(recordingTrackId, selectedTrackId); 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 // no longer recording. 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); assertEquals(-1, recordingTrackId); assertEquals(recordingTrackId, getActivity().getRecordingTrackId()); assertEquals(recordingTrackId, getActivity().getSharedPreferences().getLong( getActivity().getString(R.string.recording_track_key), -1)); // Make sure this is the same track as the last recording track ID. assertEquals(selectedTrackId, getActivity().getSelectedTrackId()); } /** * Waits until the UI thread becomes idle. */ private void waitForIdle() throws InterruptedException { // Note: We can't use getInstrumentation().waitForIdleSync() here. final Object semaphore = new Object(); synchronized (semaphore) { final AtomicBoolean isIdle = new AtomicBoolean(); getInstrumentation().waitForIdle(new Runnable() { @Override public void run() { synchronized (semaphore) { isIdle.set(true); semaphore.notify(); } } }); while (!isIdle.get()) { semaphore.wait(); } } } /** * Clears {selected,recording}TrackId in the {@link SharedPreferences}. */ private void clearSelectedAndRecordingTracks() { Editor editor = getActivity().getSharedPreferences().edit(); editor.putLong(getActivity().getString(R.string.selected_track_key), -1); editor.putLong(getActivity().getString(R.string.recording_track_key), -1); editor.clear(); editor.commit(); } /** * Waits until the recording state changes to the given status. * * @param timeout the maximum time to wait, in milliseconds. * @param isRecording the final status to await. * @return the recording track ID. */ private long awaitRecordingStatus(long timeout, boolean isRecording) throws TimeoutException, InterruptedException { long startTime = System.nanoTime(); while (getActivity().isRecording() != isRecording) { if (System.nanoTime() - startTime > timeout * 1000000) { throw new TimeoutException("Timeout while waiting for recording!"); } Thread.sleep(20); } waitForIdle(); assertEquals(isRecording, getActivity().isRecording()); return getActivity().getRecordingTrackId(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import android.content.Context; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.location.Location; import android.test.AndroidTestCase; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Tests for the MyTracks map overlay. * * @author Bartlomiej Niechwiej */ public class MyTracksOverlayTest extends AndroidTestCase { private Canvas canvas; private MockMyTracksOverlay myTracksOverlay; private MapView mockView; private Projection mockProjection; /** * A mock version of {@code MyTracksOverlay} that does not use * {@class MapView}. */ private class MockMyTracksOverlay extends MyTracksOverlay { public MockMyTracksOverlay(Context context) { super(context); } @Override Projection getMapProjection(MapView mapView) { return mockProjection; } @Override Rect getMapViewRect(MapView mapView) { return new Rect(0, 0, 100, 100); } @Override Path newPath() { return new MockPath(); } } /** * A mock class that intercepts {@code Path}'s and records calls to * {@code #moveTo()} and {@code #lineTo()}. */ private static class MockPath extends Path { /** A list of disjoined path segments. */ public final List<List<PointF>> segments = new LinkedList<List<PointF>>(); /** The total number of points in this path. */ public int totalPoints; private List<PointF> currentSegment; @Override public void lineTo(float x, float y) { super.lineTo(x, y); assertNotNull(currentSegment); currentSegment.add(new PointF(x, y)); totalPoints++; } @Override public void moveTo(float x, float y) { super.moveTo(x, y); segments.add(currentSegment = new ArrayList<PointF>(Arrays.asList(new PointF(x, y)))); totalPoints++; } } /** * A mock {@code Projection} that acts as the identity matrix. */ private static class MockProjection implements Projection { @Override public Point toPixels(GeoPoint in, Point out) { return out; } @Override public float metersToEquatorPixels(float meters) { return meters; } @Override public GeoPoint fromPixels(int x, int y) { return new GeoPoint(y, x); } } @Override protected void setUp() throws Exception { super.setUp(); canvas = new Canvas(); myTracksOverlay = new MockMyTracksOverlay(getContext()); // Enable drawing. myTracksOverlay.setTrackDrawingEnabled(true); mockView = null; mockProjection = new MockProjection(); } public void testAddLocation() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); location.setLatitude(20); location.setLongitude(30); myTracksOverlay.addLocation(location); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNull(myTracksOverlay.getLastPath()); // Draw and make sure that we don't lose any point. myTracksOverlay.draw(canvas, mockView, false); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getLastPath()); assertEquals(2, ((MockPath)myTracksOverlay.getLastPath()).totalPoints); myTracksOverlay.draw(canvas, mockView, true); assertEquals(2, myTracksOverlay.getNumLocations()); assertEquals(0, myTracksOverlay.getNumWaypoints()); assertNotNull(myTracksOverlay.getLastPath()); } public void testClearPoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); myTracksOverlay.addLocation(location); assertEquals(1, myTracksOverlay.getNumLocations()); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); // Same after drawing on canvas. final int locations = 100; for (int i = 0; i < locations; ++i) { myTracksOverlay.addLocation(location); } assertEquals(locations, myTracksOverlay.getNumLocations()); myTracksOverlay.draw(canvas, mockView, false); myTracksOverlay.draw(canvas, mockView, true); myTracksOverlay.clearPoints(); assertEquals(0, myTracksOverlay.getNumLocations()); } public void testAddWaypoint() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getLastPath()); final int waypoints = 10; for (int i = 0; i < waypoints; ++i) { waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints()); assertEquals(0, myTracksOverlay.getNumLocations()); assertNull(myTracksOverlay.getLastPath()); } public void testClearWaypoints() throws Exception { Location location = new Location("gps"); location.setLatitude(10); location.setLongitude(20); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); assertEquals(1, myTracksOverlay.getNumWaypoints()); myTracksOverlay.clearWaypoints(); assertEquals(0, myTracksOverlay.getNumWaypoints()); } public void testDrawing() { Location location = new Location("gps"); location.setLatitude(10); for (int i = 0; i < 40; ++i) { location.setLongitude(20 + i); Waypoint waypoint = new Waypoint(); waypoint.setLocation(location); myTracksOverlay.addWaypoint(waypoint); } for (int i = 0; i < 100; ++i) { location = new Location("gps"); location.setLatitude(20 + i / 2); location.setLongitude(150 - i); myTracksOverlay.addLocation(location); } // Shadow. myTracksOverlay.draw(canvas, mockView, true); // We don't expect to do anything if assertNull(myTracksOverlay.getLastPath()); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); // No shadow. myTracksOverlay.draw(canvas, mockView, false); assertNotNull(myTracksOverlay.getLastPath()); assertTrue(myTracksOverlay.getLastPath() instanceof MockPath); MockPath path = (MockPath) myTracksOverlay.getLastPath(); assertEquals(40, myTracksOverlay.getNumWaypoints()); assertEquals(100, myTracksOverlay.getNumLocations()); assertEquals(100, path.totalPoints); // TODO: Check the points from the path (and the segments). } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.testing; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import android.content.Context; /** * A fake factory for {@link MyTracksProviderUtils} which always returns a * predefined instance. * * @author Rodrigo Damazio */ public class TestingProviderUtilsFactory extends Factory { private MyTracksProviderUtils instance; public TestingProviderUtilsFactory(MyTracksProviderUtils instance) { this.instance = instance; } @Override protected MyTracksProviderUtils newForContext(Context context) { return instance; } public static Factory installWithInstance(MyTracksProviderUtils instance) { Factory oldFactory = Factory.getInstance(); Factory factory = new TestingProviderUtilsFactory(instance); MyTracksProviderUtils.Factory.overrideInstance(factory); return oldFactory; } public static void restoreOldFactory(Factory factory) { MyTracksProviderUtils.Factory.overrideInstance(factory); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings; import com.google.android.maps.mytracks.R; import android.graphics.Paint.Style; import android.test.AndroidTestCase; /** * @author Sandor Dornbush */ public class ChartValueSeriesTest extends AndroidTestCase { private ChartValueSeries series; @Override protected void setUp() throws Exception { series = new ChartValueSeries(getContext(), "###,###", R.color.elevation_fill, R.color.elevation_border, new ZoomSettings(5, new int[] {100}), R.string.elevation); } public void testInitialConditions() { assertEquals(0, series.getInterval()); assertEquals(1, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(0, series.getMax()); assertEquals(0.0, series.getSpread()); assertEquals(Style.STROKE, series.getPaint().getStyle()); assertEquals(getContext().getString(R.string.elevation), series.getTitle()); assertTrue(series.isEnabled()); } public void testEnabled() { series.setEnabled(false); assertFalse(series.isEnabled()); } public void testSmallUpdates() { series.update(0); series.update(10); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(3, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(100, series.getMax()); assertEquals(100.0, series.getSpread()); } public void testBigUpdates() { series.update(0); series.update(901); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(0, series.getMin()); assertEquals(1000, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testNotZeroBasedUpdates() { series.update(500); series.update(1401); series.updateDimension(); assertEquals(100, series.getInterval()); assertEquals(5, series.getMaxLabelLength()); assertEquals(500, series.getMin()); assertEquals(1500, series.getMax()); assertEquals(1000.0, series.getSpread()); } public void testZoomSettings_invalidArgs() { try { new ZoomSettings(0, new int[] {10, 50, 100}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, null); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } try { new ZoomSettings(1, new int[] {1, 3, 2}); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // OK. } } public void testZoomSettings_minAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(10, settings.calculateInterval(0, 15)); assertEquals(10, settings.calculateInterval(0, 50)); assertEquals(50, settings.calculateInterval(0, 111)); assertEquals(50, settings.calculateInterval(0, 250)); assertEquals(100, settings.calculateInterval(0, 251)); assertEquals(100, settings.calculateInterval(0, 10000)); } public void testZoomSettings_minNotAligned() { ZoomSettings settings = new ZoomSettings(5, new int[] {10, 50, 100}); assertEquals(50, settings.calculateInterval(5, 55)); assertEquals(10, settings.calculateInterval(10, 60)); assertEquals(50, settings.calculateInterval(7, 250)); assertEquals(100, settings.calculateInterval(7, 257)); assertEquals(100, settings.calculateInterval(11, 10000)); // A regression test. settings = new ZoomSettings(5, new int[] {5, 10, 20}); assertEquals(10, settings.calculateInterval(-37.14, -11.89)); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import java.util.Vector; import junit.framework.TestCase; /** * Tests for the Chart URL generator. * * @author Sandor Dornbush */ public class ChartURLGeneratorTest extends TestCase { public void testgetChartUrl() { Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); Track t = new Track(); TripStatistics stats = t.getStatistics(); stats.setMinElevation(0); stats.setMaxElevation(2000); stats.setTotalDistance(100); distances.add(0.0); elevations.add(10.0); distances.add(10.0); elevations.add(300.0); distances.add(20.0); elevations.add(800.0); distances.add(50.0); elevations.add(1900.0); distances.add(75.0); elevations.add(1200.0); distances.add(90.0); elevations.add(700.0); distances.add(100.0); elevations.add(70.0); String chart = ChartURLGenerator.getChartUrl(distances, elevations, t, "Title", true); assertEquals( "http://chart.apis.google.com/chart?&chs=600x350&cht=lxy&" + "chtt=Title&chxt=x,y&chxr=0,0,0,0|1,0.0,2100.0,300&chco=009A00&" + "chm=B,00AA00,0,0,0&chg=100000,14.285714285714286,1,0&" + "chd=e:AAGZMzf.v.5l..,ATJJYY55kkVVCI", chart); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import junit.framework.TestCase; /** * Tests the API feature detection code in {@link ApiFeatures}. * This test requires Froyo+ to run. * * @author Rodrigo Damazio */ public class ApiFeaturesTest extends TestCase { private TestableApiFeatures features; private class TestableApiFeatures extends ApiFeatures { private int apiLevel; public void setApiLevel(int apiLevel) { this.apiLevel = apiLevel; } @Override protected int getApiLevel() { return apiLevel; } } @Override protected void setUp() throws Exception { super.setUp(); features = new TestableApiFeatures(); } public void testHasBackup() { for (int i = 3; i <= 7; i++) { features.setApiLevel(i); assertFalse(features.hasBackup()); } features.setApiLevel(8); assertTrue(features.hasBackup()); } public void testHasTextToSpeech() { features.setApiLevel(3); assertFalse(features.hasTextToSpeech()); for (int i = 4; i <= 8; i++) { features.setApiLevel(i); assertTrue(features.hasTextToSpeech()); } } public void testGetApiPlatformAdapter() { assertNotNull(features.getApiPlatformAdapter()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.MyTracksConstants; import android.os.Environment; import java.io.File; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; /** * Tests for {@link FileUtils}. * * @author Rodrigo Damazio */ public class FileUtilsTest extends TestCase { private static final String ORIGINAL_NAME = "Swim\10ming-^across: the/ pacific (ocean)."; private static final String SANITIZED_NAME = "Swimming-across the pacific (ocean)."; private FileUtils fileUtils; private Set<String> existingFiles; @Override protected void setUp() throws Exception { super.setUp(); existingFiles = new HashSet<String>(); fileUtils = new FileUtils() { @Override protected boolean fileExists(File directory, String fullName) { return existingFiles.contains(fullName); } }; } public void testBuildExternalDirectoryPath() { String expectedName = Environment.getExternalStorageDirectory() + File.separator + MyTracksConstants.SDCARD_TOP_DIR + File.separator + "a" + File.separator + "b" + File.separator + "c"; String dirName = fileUtils.buildExternalDirectoryPath("a", "b", "c"); assertEquals(expectedName, dirName); } public void testSanitizeName() { assertEquals(SANITIZED_NAME, fileUtils.sanitizeName(ORIGINAL_NAME)); } public void testBuildUniqueFileName_someExist() { existingFiles = new HashSet<String>(); existingFiles.add("Filename.ext"); existingFiles.add("Filename (1).ext"); existingFiles.add("Filename (2).ext"); existingFiles.add("Filename (3).ext"); existingFiles.add("Filename (4).ext"); String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename (5).ext", filename); } public void testBuildUniqueFileName_oneExists() { existingFiles.add("Filename.ext"); String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename (1).ext", filename); } public void testBuildUniqueFileName_noneExists() { String filename = fileUtils.buildUniqueFileName(null, "Filename", "ext"); assertEquals("Filename.ext", filename); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import java.util.GregorianCalendar; import java.util.TimeZone; import junit.framework.TestCase; /** * Tests for {@link StringUtils}. * * @author Rodrigo Damazio */ public class StringUtilsTest extends TestCase { public void testParseXmlDateTime() { assertParseXmlDateTime("2010-05-04T03:02:01", 2010, 5, 4, 3, 2, 1, 0); } public void testParseXmlDateTime_fractional() { assertParseXmlDateTime("2010-05-04T03:02:01.3", 2010, 5, 4, 3, 2, 1, 300); assertParseXmlDateTime("2010-05-04T03:02:01.35", 2010, 5, 4, 3, 2, 1, 350); assertParseXmlDateTime("2010-05-04T03:02:01.352", 2010, 5, 4, 3, 2, 1, 352); assertParseXmlDateTime("2010-05-04T03:02:01.3525", 2010, 5, 4, 3, 2, 1, 352); } public void testParseXmlDateTime_timezone() { assertParseXmlDateTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+00:00", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-00:00", 2010, 5, 4, 3, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+01:00", 2010, 5, 4, 2, 2, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01+10:30", 2010, 5, 3, 16, 32, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-09:30", 2010, 5, 4, 12, 32, 1, 0); assertParseXmlDateTime("2010-05-04T03:02:01-05:00", 2010, 5, 4, 8, 2, 1, 0); } public void testParseXmlDateTime_fractionalAndTimezone() { assertParseXmlDateTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352); assertParseXmlDateTime("2010-05-04T03:02:01.47+00:00", 2010, 5, 4, 3, 2, 1, 470); assertParseXmlDateTime("2010-05-04T03:02:01.5791+03:00", 2010, 5, 4, 0, 2, 1, 579); assertParseXmlDateTime("2010-05-04T03:02:01.8-05:30", 2010, 5, 4, 8, 32, 1, 800); } private void assertParseXmlDateTime(String dateTime, int year, int month, int day, int hour, int min, int second, int millis) { long timestamp = StringUtils.parseXmlDateTime(dateTime); GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.set(year, month - 1, day, hour, min, second); calendar.set(GregorianCalendar.MILLISECOND, millis); assertEquals(calendar.getTimeInMillis(), timestamp); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import junit.framework.TestCase; /** * A unit test for {@link ChartsExtendedEncoder}. * * @author Bartlomiej Niechwiej */ public class ChartsExtendedEncoderTest extends TestCase { public void testGetEncodedValue_validArguments() { // Valid arguments. assertEquals("AK", ChartsExtendedEncoder.getEncodedValue(10)); assertEquals("JO", ChartsExtendedEncoder.getEncodedValue(590)); assertEquals("AA", ChartsExtendedEncoder.getEncodedValue(0)); // 64^2 = 4096. assertEquals("..", ChartsExtendedEncoder.getEncodedValue(4095)); } public void testGetEncodedValue_invalidArguments() { // Invalid arguments. assertEquals("__", ChartsExtendedEncoder.getEncodedValue(4096)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(1234564096)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-10)); assertEquals("__", ChartsExtendedEncoder.getEncodedValue(-12324435)); } public void testGetSeparator() { assertEquals(",", ChartsExtendedEncoder.getSeparator()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.testing.mocking.AndroidMock.eq; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.ContentUris; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.test.AndroidTestCase; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.SimpleTimeZone; import javax.xml.parsers.ParserConfigurationException; import org.easymock.Capture; import org.easymock.IArgumentMatcher; import org.xml.sax.SAXException; /** * Tests for the GPX importer. * * @author Steffen Horlacher */ public class GpxImporterTest extends AndroidTestCase { private static final String TRACK_NAME = "blablub"; private static final String TRACK_DESC = "s'Laebe isch koi Schlotzer"; private static final String TRACK_LAT_1 = "48.768364"; private static final String TRACK_LON_1 = "9.177886"; private static final String TRACK_ELE_1 = "324.0"; private static final String TRACK_TIME_1 = "2010-04-22T18:21:00Z"; private static final String TRACK_LAT_2 = "48.768374"; private static final String TRACK_LON_2 = "9.177816"; private static final String TRACK_ELE_2 = "333.0"; private static final String TRACK_TIME_2 = "2010-04-22T18:21:50.123"; private static final SimpleDateFormat DATE_FORMAT1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); private static final SimpleDateFormat DATE_FORMAT2 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); static { // We can't omit the timezones in the test, otherwise it'll use the local // timezone and fail depending on where the test runner is. SimpleTimeZone utc = new SimpleTimeZone(0, "UTC"); DATE_FORMAT1.setTimeZone(utc); DATE_FORMAT2.setTimeZone(utc); } // TODO: use real files from different sources with more track points. private static final String VALID_TEST_GPX = "<gpx><trk><name><![CDATA[" + TRACK_NAME + "]]></name><desc><![CDATA[" + TRACK_DESC + "]]></desc><trkseg>" + "<trkpt lat=\"" + TRACK_LAT_1 + "\" lon=\"" + TRACK_LON_1 + "\"><ele>" + TRACK_ELE_1 + "</ele><time>" + TRACK_TIME_1 + "</time></trkpt> +" + "<trkpt lat=\"" + TRACK_LAT_2 + "\" lon=\"" + TRACK_LON_2 + "\"><ele>" + TRACK_ELE_2 + "</ele><time>" + TRACK_TIME_2 + "</time></trkpt>" + "</trkseg></trk></gpx>"; // invalid xml private static final String INVALID_XML_TEST_GPX = VALID_TEST_GPX.substring( 0, VALID_TEST_GPX.length() - 50); private static final String INVALID_LOCATION_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "1000.0"); private static final String INVALID_TIME_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_TIME_1, "invalid"); private static final String INVALID_ALTITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_ELE_1, "invalid"); private static final String INVALID_LATITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LAT_1, "invalid"); private static final String INVALID_LONGITUDE_TEST_GPX = VALID_TEST_GPX .replaceAll(TRACK_LON_1, "invalid"); private static final long TRACK_ID = 1; private static final long TRACK_POINT_ID_1 = 1; private static final long TRACK_POINT_ID_2 = 2; private static final Uri TRACK_ID_URI = ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), TRACK_ID).build(); private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; @UsesMocks(MyTracksProviderUtils.class) @Override protected void setUp() throws Exception { super.setUp(); providerUtils = AndroidMock.createMock(MyTracksProviderUtils.class); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } /** * Test import success. */ public void testImportSuccess() throws Exception { Capture<Track> trackParam = new Capture<Track>(); Location loc1 = new Location(LocationManager.GPS_PROVIDER); loc1.setTime(DATE_FORMAT2.parse(TRACK_TIME_1).getTime()); loc1.setLatitude(Double.parseDouble(TRACK_LAT_1)); loc1.setLongitude(Double.parseDouble(TRACK_LON_1)); loc1.setAltitude(Double.parseDouble(TRACK_ELE_1)); Location loc2 = new Location(LocationManager.GPS_PROVIDER); loc2.setTime(DATE_FORMAT1.parse(TRACK_TIME_2).getTime()); loc2.setLatitude(Double.parseDouble(TRACK_LAT_2)); loc2.setLongitude(Double.parseDouble(TRACK_LON_2)); loc2.setAltitude(Double.parseDouble(TRACK_ELE_2)); expect(providerUtils.insertTrack(AndroidMock.capture(trackParam))) .andReturn(TRACK_ID_URI); expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2); // A flush happens after the first insertion to get the starting point ID, // which is why we get two calls expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc1), eq(1), eq(TRACK_ID))).andReturn(1); expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc2), eq(1), eq(TRACK_ID))).andReturn(1); providerUtils.updateTrack(AndroidMock.capture(trackParam)); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(VALID_TEST_GPX.getBytes()); GpxImporter.importGPXFile(is, providerUtils); AndroidMock.verify(providerUtils); // verify track parameter Track track = trackParam.getValue(); assertEquals(TRACK_NAME, track.getName()); assertEquals(TRACK_DESC, track.getDescription()); assertEquals(DATE_FORMAT2.parse(TRACK_TIME_1).getTime(), track.getStatistics() .getStartTime()); assertNotSame(-1, track.getStartId()); assertNotSame(-1, track.getStopId()); } /** * Test with invalid location - track should be deleted. */ public void testImportLocationFailure() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_LOCATION_TEST_GPX); } /** * Test with invalid time - track should be deleted. */ public void testImportTimeFailure() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_TIME_TEST_GPX); } /** * Test with invalid xml - track should be deleted. */ public void testImportXMLFailure() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_XML_TEST_GPX); } /** * Test with invalid altitude - track should be deleted. */ public void testImportInvalidAltitude() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_ALTITUDE_TEST_GPX); } /** * Test with invalid latitude - track should be deleted. */ public void testImportInvalidLatitude() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_LATITUDE_TEST_GPX); } /** * Test with invalid longitude - track should be deleted. */ public void testImportInvalidLongitude() throws ParserConfigurationException, SAXException, IOException { testInvalidXML(INVALID_LONGITUDE_TEST_GPX); } private void testInvalidXML(String xml) throws ParserConfigurationException, IOException { expect(providerUtils.insertTrack((Track) AndroidMock.anyObject())) .andReturn(TRACK_ID_URI); expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(), AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1); expect(providerUtils.getLastLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1); providerUtils.deleteTrack(TRACK_ID); AndroidMock.replay(providerUtils); InputStream is = new ByteArrayInputStream(xml.getBytes()); try { GpxImporter.importGPXFile(is, providerUtils); } catch (SAXException e) { // expected exception } AndroidMock.verify(providerUtils); } /** * Workaround because of capture bug 2617107 in easymock: * http://sourceforge.net * /tracker/?func=detail&aid=2617107&group_id=82958&atid=567837 */ private static class LocationsMatcher implements IArgumentMatcher { private final Location[] matchLocs; private LocationsMatcher(Location[] expected) { this.matchLocs = expected; } public static Location[] eqLoc(Location[] expected) { IArgumentMatcher matcher = new LocationsMatcher(expected); AndroidMock.reportMatcher(matcher); return null; } public static Location[] eqLoc(Location expected) { return eqLoc(new Location[] { expected}); } @Override public void appendTo(StringBuffer buf) { buf.append("eqLoc(").append(Arrays.toString(matchLocs)).append(")"); } @Override public boolean matches(Object obj) { if (! (obj instanceof Location[])) { return false; } Location[] locs = (Location[]) obj; if (locs.length < matchLocs.length) { return false; } // Only check the first elements (those that will be taken into account) for (int i = 0; i < matchLocs.length; i++) { if (!locationsMatch(locs[i], matchLocs[i])) { return false; } } return true; } private boolean locationsMatch(Location loc1, Location loc2) { return (loc1.getTime() == loc2.getTime()) && (loc1.getLatitude() == loc2.getLatitude()) && (loc1.getLongitude() == loc2.getLongitude()) && (loc1.getAltitude() == loc2.getAltitude()); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import junit.framework.TestCase; /** * This class tests {@link DocsTagBuilder} * * @author Matthew Simmons */ public class DocsTagBuilderTest extends TestCase { public void testAppend() { assertEquals("<gsx:tag><![CDATA[value]]></gsx:tag>", new DocsTagBuilder(false).append("tag", "value").build()); } public void testMultiAppend() { String actual = new DocsTagBuilder(false) .append("tag1", "value1") .append("tag2", "value2") .build(); assertEquals("<gsx:tag1><![CDATA[value1]]></gsx:tag1>" + "<gsx:tag2><![CDATA[value2]]></gsx:tag2>", actual); } public void testAppendLargeUnits_imperial() { assertEquals("<gsx:tag><![CDATA[62.14]]></gsx:tag>", new DocsTagBuilder(false).appendLargeUnits("tag", 100.0).build()); } public void testAppendLargeUnits_metric() { assertEquals("<gsx:tag><![CDATA[100.00]]></gsx:tag>", new DocsTagBuilder(true).appendLargeUnits("tag", 100.0).build()); } public void testAppendSmallUnits_imperial() { assertEquals("<gsx:tag><![CDATA[328]]></gsx:tag>", new DocsTagBuilder(false).appendSmallUnits("tag", 100.0).build()); } public void testAppendSmallUnits_metric() { assertEquals("<gsx:tag><![CDATA[100]]></gsx:tag>", new DocsTagBuilder(true).appendSmallUnits("tag", 100.0).build()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.io.gdata.GDataWrapper; import android.content.Context; import android.test.mock.MockContext; import junit.framework.TestCase; import java.io.IOException; /** * Tests for {@link DocsHelper}, with the exception of * {@link DocsHelper#addTrackRow}, which is in * {@link DocsHelper_AddTrackRowTest}. * * @author Matthew Simmons */ public class DocsHelperTest extends TestCase { private Context mockContext = new MockContext(); // TODO(simmonmt): Use AndroidMock to mock this class. We do it the hard // way because use of AndroidMock to mock GDataWrapper triggers a compile // error in an unrelated file. Specifically, it causes a NoClassDefFound // exception for com.google.wireless.gdata2.client.AuthenticationException, // (wrongly) attributed to the first source file in the project. Using the // @UsesMocks(GDataWrapper.class) annotation is enough -- you don't have to // touch AndroidMock at all to get this failure. // The bug is filed with Android Mock as // http://code.google.com/p/android-mock/issues/detail?id=3 private class MockGDataWrapper extends GDataWrapper { private final boolean returnValue; MockGDataWrapper(boolean returnValue) { this.returnValue = returnValue; } @Override public boolean runQuery(QueryFunction queryFunction) { return returnValue; } } public void testCreateSpreadsheet_noException() throws Exception { // Our mock GDataWrapper isn't able to affect the return value from // DocsHelper#createSpreadsheet. As such, we're only able to simulate the // case where there weren't any GData errors, but not spreadsheet ID was // actually returned. createSpreadsheet is defined to return null in that // situation. assertNull(new DocsHelper().createSpreadsheet( mockContext, new MockGDataWrapper(true), "sheetName")); } public void testCreateSpreadsheet_exception() throws Exception { try { new DocsHelper().createSpreadsheet( mockContext, new MockGDataWrapper(false), "sheetName"); fail(); } catch (IOException expected) {} } public void testRequestSpreadsheetId_noException() throws Exception { assertNull(new DocsHelper().requestSpreadsheetId( new MockGDataWrapper(true), "sheetName")); } public void testRequestSpreadsheetId_exception() throws Exception { try { new DocsHelper().requestSpreadsheetId(new MockGDataWrapper(false), "sheetName"); fail(); } catch (IOException expected) {} } public void testGetWorksheetId_noException() throws Exception { assertNull(new DocsHelper().getWorksheetId(new MockGDataWrapper(true), "sheetId")); } public void testGetWorksheetId_exception() throws Exception { try { new DocsHelper().getWorksheetId(new MockGDataWrapper(false), "sheetId"); fail(); } catch (IOException expected) {} } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.res.Resources; import android.test.mock.MockContext; import android.test.mock.MockResources; import junit.framework.TestCase; import java.io.IOException; /** * Tests for {@link DocsHelper#addTrackRow} * * @author Matthew Simmons */ public class DocsHelper_AddTrackRowTest extends TestCase { private static final long TIME = 1288721514000L; private static class StringWritingDocsHelper extends DocsHelper { String writtenSheetUri = null; String writtenData = null; @Override protected void writeRowData(AuthManager trixAuth, String worksheetUri, String postText) { writtenSheetUri = worksheetUri; writtenData = postText; } } public void testAddTrackRow_imperial() throws Exception { StringWritingDocsHelper docsHelper = new StringWritingDocsHelper(); addTrackRow(docsHelper, false); String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>" + "<gsx:name><![CDATA[trackName]]></gsx:name>" + "<gsx:description><![CDATA[trackDescription]]></gsx:description>" // We format the date here because we can't guarantee/force the timezone + "<gsx:date><![CDATA[" + String.format("%tc", TIME) + "]]></gsx:date>" + "<gsx:totaltime><![CDATA[0:00:05]]></gsx:totaltime>" + "<gsx:movingtime><![CDATA[0:00:04]]></gsx:movingtime>" + "<gsx:distance><![CDATA[12.43]]></gsx:distance>" + "<gsx:distanceunit><![CDATA[mile]]></gsx:distanceunit>" + "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>" + "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>" + "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>" + "<gsx:speedunit><![CDATA[mph]]></gsx:speedunit>" + "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>" + "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>" + "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>" + "<gsx:elevationunit><![CDATA[feet]]></gsx:elevationunit>" + "<gsx:map>" + "<![CDATA[http://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>" + "</entry>"; assertEquals( "http://spreadsheets.google.com/feeds/list/ssid/wsid/private/full", docsHelper.writtenSheetUri); assertEquals(expectedData, docsHelper.writtenData); } public void testAddTrackRow_metric() throws Exception { StringWritingDocsHelper docsHelper = new StringWritingDocsHelper(); addTrackRow(docsHelper, true); // The imperial test verifies that the tags come out in the proper order, // and with the proper names. We need only verify that the labels are // correct, and that at least one of the unit-dependent value tags is // correct. assertTrue(docsHelper.writtenData.contains( "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:speedunit><![CDATA[kph]]></gsx:speedunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:elevationunit><![CDATA[meter]]></gsx:elevationunit>")); assertTrue(docsHelper.writtenData.contains( "<gsx:distance><![CDATA[20.00]]></gsx:distance>")); } @UsesMocks({AuthManager.class, MockContext.class, MockResources.class, Track.class}) /** Adds a row to the spreadsheet, using the provided helper. */ private void addTrackRow(DocsHelper docsHelper, boolean useMetric) throws IOException { Resources mockResources = AndroidMock.createMock(MockResources.class); if (useMetric) { AndroidMock.expect(mockResources.getString(R.string.kilometer)) .andReturn("km"); AndroidMock.expect(mockResources.getString(R.string.kilometer_per_hour)) .andReturn("kph"); AndroidMock.expect(mockResources.getString(R.string.meter)) .andReturn("meter"); } else { AndroidMock.expect(mockResources.getString(R.string.mile)) .andReturn("mile"); AndroidMock.expect(mockResources.getString(R.string.mile_per_hour)) .andReturn("mph"); AndroidMock.expect(mockResources.getString(R.string.feet)) .andReturn("feet"); } AndroidMock.replay(mockResources); Context mockContext = AndroidMock.createMock(MockContext.class); AndroidMock.expect(mockContext.getResources()) .andReturn(mockResources).anyTimes(); AndroidMock.replay(mockContext); AuthManager mockAuthManager = AndroidMock.createMock(AuthManager.class); AndroidMock.replay(mockAuthManager); TripStatistics stats = new TripStatistics(); stats.setStartTime(TIME); stats.setTotalTime(5000); stats.setMovingTime(4000); stats.setTotalDistance(20000); stats.setMaxSpeed(1500); stats.setTotalElevationGain(6000); stats.setMinElevation(-500); stats.setMaxElevation(550); Track track = new Track(); track.setName("trackName"); track.setDescription("trackDescription"); track.setMapId("trackMapId"); track.setStatistics(stats); docsHelper.addTrackRow(mockContext, mockAuthManager, "ssid", "wsid", track, useMetric); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.List; import java.util.Vector; /** * Tests for the KML track exporter. * * @author Rodrigo Damazio */ public class KmlTrackWriterTest extends TrackFormatWriterTest { private static final String FULL_TRACK_DESCRIPTION = "full track description"; /** * A fake version of {@link StringUtils} which returns a fixed track * description, thus not depending on the context. */ private class FakeStringUtils extends StringUtils { public FakeStringUtils() { super(null); } @Override public String generateTrackDescription(Track track, Vector<Double> distances, Vector<Double> elevations) { assertSame(KmlTrackWriterTest.super.track, track); assertTrue(distances.isEmpty()); assertTrue(elevations.isEmpty()); return FULL_TRACK_DESCRIPTION; } } public void testXmlOutput() throws Exception { KmlTrackWriter writer = new KmlTrackWriter(new FakeStringUtils()); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element kmlTag = getChildElement(doc, "kml"); Element docTag = getChildElement(kmlTag, "Document"); assertEquals(TRACK_NAME, getChildTextValue(docTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(docTag, "description")); // There are 5 placemarks - start, segments, end, waypoint 1, waypoint 2 List<Element> placemarkTags = getChildElements(docTag, "Placemark", 5); assertTagIsPlacemark(placemarkTags.get(0), "(Start)", TRACK_DESCRIPTION, location1); assertTagIsPlacemark(placemarkTags.get(2), "(End)", FULL_TRACK_DESCRIPTION, location4); assertTagIsPlacemark(placemarkTags.get(3), WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2); assertTagIsPlacemark(placemarkTags.get(4), WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3); Element trackPlacemarkTag = placemarkTags.get(1); assertEquals(TRACK_NAME, getChildTextValue(trackPlacemarkTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackPlacemarkTag, "description")); Element geometryTag = getChildElement(trackPlacemarkTag, "MultiGeometry"); List<Element> segmentTags = getChildElements(geometryTag, "LineString", 2); assertTagHasPoints(segmentTags.get(0), location1, location2); assertTagHasPoints(segmentTags.get(1), location3, location4); } /** * Asserts that the given XML tag is a placemark with the given properties. * * @param tag the tag to analyze * @param name the expected name for the placemark * @param description the expected description for the placemark * @param location the expected location of the placemark */ private void assertTagIsPlacemark(Element tag, String name, String description, Location location) { assertEquals(name, getChildTextValue(tag, "name")); assertEquals(description, getChildTextValue(tag, "description")); Element pointTag = getChildElement(tag, "Point"); String expectedCoords = location.getLongitude() + "," + location.getLatitude(); String actualCoords = getChildTextValue(pointTag, "coordinates"); assertEquals(expectedCoords, actualCoords); } /** * Asserts that the given tag has a "coordinates" subtag with the given * locations. * * @param tag the tag to analyze * @param locs the locations to expect in the coordinates */ private void assertTagHasPoints(Element tag, Location... locs) { StringBuilder expectedBuilder = new StringBuilder(); for (Location loc : locs) { expectedBuilder.append(loc.getLongitude()); expectedBuilder.append(','); expectedBuilder.append(loc.getLatitude()); expectedBuilder.append(','); expectedBuilder.append(loc.getAltitude()); expectedBuilder.append(' '); } String expectedCoordinates = expectedBuilder.toString().trim(); String actualCoordinates = getChildTextValue(tag, "coordinates").trim(); assertEquals(expectedCoordinates, actualCoordinates); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.content.ContentValues; import android.net.Uri; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import junit.framework.TestCase; /** * Tests for {@link DatabaseImporter}. * * @author Rodrigo Damazio */ public class DatabaseImporterTest extends TestCase { private static final Uri DESTINATION_URI = Uri.parse("http://www.google.com/"); private static final int TEST_BULK_SIZE = 10; private ArrayList<ContentValues> insertedValues; private class TestableDatabaseImporter extends DatabaseImporter { public TestableDatabaseImporter(boolean readNullFields) { super(DESTINATION_URI, null, readNullFields, TEST_BULK_SIZE); } @Override protected void doBulkInsert(ContentValues[] values) { insertedValues.ensureCapacity(insertedValues.size() + values.length); // We need to make a copy of the values since the objects are re-used for (ContentValues contentValues : values) { insertedValues.add(new ContentValues(contentValues)); } } } @Override protected void setUp() throws Exception { super.setUp(); insertedValues = new ArrayList<ContentValues>(); } public void testImportAllRows() throws Exception { testImportAllRows(false); } public void testImportAllRows_readNullFields() throws Exception { testImportAllRows(true); } private void testImportAllRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(2); // Add a row with all fields present writer.writeLong(0x7F); writer.writeInt(42); writer.writeBoolean(true); writer.writeUTF("lolcat"); writer.writeFloat(3.1415f); writer.writeDouble(2.72); writer.writeLong(123456789L); writer.writeInt(4); writer.writeBytes("blob"); // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(2, insertedValues.size()); // Verify the first row ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 7, value.size()); assertValue(42, "col1", value); assertValue(true, "col2", value); assertValue("lolcat", "col3", value); assertValue(3.1415f, "col4", value); assertValue(2.72, "col5", value); assertValue(123456789L, "col6", value); assertBlobValue("blob", "col7", value); // Verify the second row value = insertedValues.get(1); assertEquals(value.toString(), 3, value.size()); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_noRows() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(0); writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertTrue(insertedValues.isEmpty()); } public void testImportAllRows_emptyRows() throws Exception { testImportAllRowsWithEmptyRows(false); } public void testImportAllRows_emptyRowsWithNulls() throws Exception { testImportAllRowsWithEmptyRows(true); } private void testImportAllRowsWithEmptyRows(boolean readNullFields) throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); writeFullHeader(writer); // Add the number of rows writer.writeInt(3); // Add 2 rows with no fields for (int i = 0; i < 2; i++) { writer.writeLong(0); if (readNullFields) { writer.writeInt(0); writer.writeBoolean(false); writer.writeUTF(""); writer.writeFloat(0.0f); writer.writeDouble(0.0); writer.writeLong(0L); writer.writeInt(0); // empty blob } } // Add a row with some missing fields writer.writeLong(0x15); writer.writeInt(42); if (readNullFields) writer.writeBoolean(false); writer.writeUTF("lolcat"); if (readNullFields) writer.writeFloat(0.0f); writer.writeDouble(2.72); if (readNullFields) writer.writeLong(0L); if (readNullFields) writer.writeInt(0); // empty blob writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(readNullFields); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); assertEquals(insertedValues.toString(), 3, insertedValues.size()); ContentValues value = insertedValues.get(0); assertEquals(value.toString(), 0, value.size()); value = insertedValues.get(1); assertEquals(value.toString(), 0, value.size()); // Verify the third row (only one with values) value = insertedValues.get(2); assertEquals(value.toString(), 3, value.size()); assertFalse(value.containsKey("col2")); assertFalse(value.containsKey("col4")); assertFalse(value.containsKey("col6")); assertValue(42, "col1", value); assertValue("lolcat", "col3", value); assertValue(2.72, "col5", value); } public void testImportAllRows_bulks() throws Exception { // Create a fake data stream to be read ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outputStream); // Add the header writer.writeInt(2); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); // Add lots of rows (so the insertions are split in multiple bulks) int numRows = TEST_BULK_SIZE * 5 / 2; writer.writeInt(numRows); for (int i = 0; i < numRows; i++) { writer.writeLong(3); writer.writeInt(i); writer.writeUTF(Integer.toString(i * 2)); } writer.flush(); // Do the importing DatabaseImporter importer = new TestableDatabaseImporter(false); byte[] dataBytes = outputStream.toByteArray(); importer.importAllRows(new DataInputStream(new ByteArrayInputStream(dataBytes))); // Verify the rows assertEquals(numRows, insertedValues.size()); for (int i = 0; i < numRows; i++) { ContentValues value = insertedValues.get(i); assertEquals(value.toString(), 2, value.size()); assertValue(i, "col1", value); assertValue(Integer.toString(i * 2), "col2", value); } } private void writeFullHeader(DataOutputStream writer) throws IOException { // Add the header writer.writeInt(7); writer.writeUTF("col1"); writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeUTF("col2"); writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID); writer.writeUTF("col3"); writer.writeByte(ContentTypeIds.STRING_TYPE_ID); writer.writeUTF("col4"); writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID); writer.writeUTF("col5"); writer.writeByte(ContentTypeIds.DOUBLE_TYPE_ID); writer.writeUTF("col6"); writer.writeByte(ContentTypeIds.LONG_TYPE_ID); writer.writeUTF("col7"); writer.writeByte(ContentTypeIds.BLOB_TYPE_ID); } private <T> void assertValue(T expectedValue, String name, ContentValues values) { @SuppressWarnings("unchecked") T value = (T) values.get(name); assertNotNull(value); assertEquals(expectedValue, value); } private void assertBlobValue(String expectedValue, String name, ContentValues values ){ byte[] blob = values.getAsByteArray(name); assertEquals(expectedValue, new String(blob)); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.TestCase; /** * Tests for {@link PreferenceBackupHelper}. * * @author Rodrigo Damazio */ public class PreferenceBackupHelperTest extends TestCase { private Map<String, ?> preferenceValues; private SharedPreferences preferences; private PreferenceBackupHelper preferenceBackupHelper; /** * Mock shared preferences editor which does not persist state. */ private class MockPreferenceEditor implements SharedPreferences.Editor { private Map<String, Object> newPreferences = new HashMap<String, Object>(preferenceValues); @Override public Editor clear() { newPreferences.clear(); return this; } @Override public boolean commit() { preferenceValues = newPreferences; return true; } @Override public void apply() { commit(); } @Override public Editor putBoolean(String key, boolean value) { return put(key, value); } @Override public Editor putFloat(String key, float value) { return put(key, value); } @Override public Editor putInt(String key, int value) { return put(key, value); } @Override public Editor putLong(String key, long value) { return put(key, value); } @Override public Editor putString(String key, String value) { return put(key, value); } @Override public Editor putStringSet(String key, Set<String> value) { return put(key, value); } private <T> Editor put(String key, T value) { newPreferences.put(key, value); return this; } @Override public Editor remove(String key) { newPreferences.remove(key); return this; } } /** * Mock shared preferences which does not persist state. */ private class MockPreferences implements SharedPreferences { @Override public boolean contains(String key) { return preferenceValues.containsKey(key); } @Override public Editor edit() { return new MockPreferenceEditor(); } @Override public Map<String, ?> getAll() { return preferenceValues; } @Override public boolean getBoolean(String key, boolean defValue) { return get(key, defValue); } @Override public float getFloat(String key, float defValue) { return get(key, defValue); } @Override public int getInt(String key, int defValue) { return get(key, defValue); } @Override public long getLong(String key, long defValue) { return get(key, defValue); } @Override public String getString(String key, String defValue) { return get(key, defValue); } @Override public Set<String> getStringSet(String key, Set<String> defValue) { return get(key, defValue); } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") private <T> T get(String key, T defValue) { Object value = preferenceValues.get(key); if (value == null) return defValue; return (T) value; } } @Override protected void setUp() throws Exception { super.setUp(); preferenceValues = new HashMap<String, Object>(); preferences = new MockPreferences(); preferenceBackupHelper = new PreferenceBackupHelper(); } public void testExportImportPreferences() throws Exception { // Populate with some initial values Editor editor = preferences.edit(); editor.clear(); editor.putBoolean("bool1", true); editor.putBoolean("bool2", false); editor.putFloat("flt1", 3.14f); editor.putInt("int1", 42); editor.putLong("long1", 123456789L); editor.putString("str1", "lolcat"); editor.commit(); // Export it byte[] exported = preferenceBackupHelper.exportPreferences(preferences); // Mess with the previous values editor = preferences.edit(); editor.clear(); editor.putString("str2", "Shouldn't be there after restore"); editor.putBoolean("bool2", true); editor.commit(); // Import it back preferenceBackupHelper.importPreferences(exported, preferences); assertFalse(preferences.contains("str2")); assertTrue(preferences.getBoolean("bool1", false)); assertFalse(preferences.getBoolean("bool2", true)); assertEquals(3.14f, preferences.getFloat("flt1", 0.0f)); assertEquals(42, preferences.getInt("int1", 0)); assertEquals(123456789L, preferences.getLong("long1", 0)); assertEquals("lolcat", preferences.getString("str1", "")); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.content.ContentTypeIds; import android.database.MatrixCursor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; /** * Tests for {@link DatabaseDumper}. * * @author Rodrigo Damazio */ public class DatabaseDumperTest extends TestCase { /** * This class is the same as {@link MatrixCursor}, except this class * implements {@link #getBlob} ({@link MatrixCursor} leaves it * unimplemented). */ private class BlobAwareMatrixCursor extends MatrixCursor { public BlobAwareMatrixCursor(String[] columnNames) { super(columnNames); } @Override public byte[] getBlob(int columnIndex) { return getString(columnIndex).getBytes(); } } private static final String[] COLUMN_NAMES = { "intCol", "longCol", "floatCol", "doubleCol", "stringCol", "boolCol", "blobCol" }; private static final byte[] COLUMN_TYPES = { ContentTypeIds.INT_TYPE_ID, ContentTypeIds.LONG_TYPE_ID, ContentTypeIds.FLOAT_TYPE_ID, ContentTypeIds.DOUBLE_TYPE_ID, ContentTypeIds.STRING_TYPE_ID, ContentTypeIds.BOOLEAN_TYPE_ID, ContentTypeIds.BLOB_TYPE_ID }; private static final String[][] FAKE_DATA = { { "42", "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { null, "123456789", "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", null, "3.1415", "2.72", "lolcat", "1", "blob" }, { "42", "123456789", null, "2.72", "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", null, "lolcat", "1", "blob" }, { "42", "123456789", "3.1415", "2.72", null, "1", "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", null, "blob" }, { "42", "123456789", "3.1415", "2.72", "lolcat", "1", null }, }; private static final long[] EXPECTED_FIELD_SETS = { 0x7F, 0x7E, 0x7D, 0x7B, 0x77, 0x6F, 0x5F, 0x3F }; private BlobAwareMatrixCursor cursor; @Override protected void setUp() throws Exception { super.setUp(); // Add fake data to the cursor cursor = new BlobAwareMatrixCursor(COLUMN_NAMES); for (String[] row : FAKE_DATA) { cursor.addRow(row); } } public void testWriteAllRows_noNulls() throws Exception { testWriteAllRows(false); } public void testWriteAllRows_withNulls() throws Exception { testWriteAllRows(true); } private void testWriteAllRows(boolean hasNullFields) throws Exception { // Dump it DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, hasNullFields); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream ); dumper.writeAllRows(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(FAKE_DATA.length, reader.readInt()); // Verify the row contents byte[] blob = new byte[4]; // Row 0 -- everything populated assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 -- no int assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); if (hasNullFields) reader.readInt(); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 2 -- no long assertEquals(EXPECTED_FIELD_SETS[2], reader.readLong()); assertEquals(42, reader.readInt()); if (hasNullFields) reader.readLong(); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 3 -- no float assertEquals(EXPECTED_FIELD_SETS[3], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); if (hasNullFields) reader.readFloat(); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 4 -- no double assertEquals(EXPECTED_FIELD_SETS[4], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); if (hasNullFields) reader.readDouble(); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 5 -- no string assertEquals(EXPECTED_FIELD_SETS[5], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); if (hasNullFields) reader.readUTF(); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 6 -- no boolean assertEquals(EXPECTED_FIELD_SETS[6], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); if (hasNullFields) reader.readBoolean(); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 7 -- no blob assertEquals(EXPECTED_FIELD_SETS[7], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); if (hasNullFields) { int length = reader.readInt(); readBlob(reader, length); } } public void testFewerRows() throws Exception { // Dump only the first two rows DatabaseDumper dumper = new DatabaseDumper(COLUMN_NAMES, COLUMN_TYPES, false); ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024); DataOutputStream writer = new DataOutputStream(outStream); dumper.writeHeaders(cursor, 2, writer); cursor.moveToFirst(); dumper.writeOneRow(cursor, writer); cursor.moveToNext(); dumper.writeOneRow(cursor, writer); // Read the results byte[] result = outStream.toByteArray(); ByteArrayInputStream inputStream = new ByteArrayInputStream(result); DataInputStream reader = new DataInputStream(inputStream); // Verify the header assertHeader(reader); // Verify the number of rows assertEquals(2, reader.readInt()); // Row 0 assertEquals(EXPECTED_FIELD_SETS[0], reader.readLong()); assertEquals(42, reader.readInt()); assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); // Row 1 assertEquals(EXPECTED_FIELD_SETS[1], reader.readLong()); // Null field not read assertEquals(123456789L, reader.readLong()); assertEquals(3.1415f, reader.readFloat()); assertEquals(2.72, reader.readDouble()); assertEquals("lolcat", reader.readUTF()); assertTrue(reader.readBoolean()); assertEquals(4, reader.readInt()); assertEquals("blob", readBlob(reader, 4)); } private void assertHeader(DataInputStream reader) throws IOException { assertEquals(COLUMN_NAMES.length, reader.readInt()); for (int i = 0; i < COLUMN_NAMES.length; i++) { assertEquals(COLUMN_NAMES[i], reader.readUTF()); assertEquals(COLUMN_TYPES[i], reader.readByte()); } } private String readBlob(InputStream reader, int length) throws Exception { if (length == 0) { return ""; } byte[] blob = new byte[length]; assertEquals(length, reader.read(blob)); return new String(blob); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.test.AndroidTestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * Base class for track format writer tests, which sets up a fake track and * gives auxiliary methods for verifying XML output. * * @author Rodrigo Damazio */ public abstract class TrackFormatWriterTest extends AndroidTestCase { // All the user-provided strings have "]]>" to ensure that proper escaping is // being done. protected static final String TRACK_NAME = "Home]]>"; protected static final String TRACK_DESCRIPTION = "The long ]]> journey home"; protected static final String WAYPOINT1_NAME = "point]]>1"; protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description"; protected static final String WAYPOINT2_NAME = "point]]>2"; protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description"; private static final int BUFFER_SIZE = 10240; protected static final long TRACK_ID = 12345L; protected Track track; protected MyTracksLocation location1, location2, location3, location4; protected Waypoint wp1, wp2; @Override protected void setUp() throws Exception { super.setUp(); track = new Track(); track.setId(TRACK_ID); track.setName(TRACK_NAME); track.setDescription(TRACK_DESCRIPTION); location1 = new MyTracksLocation("mock"); location2 = new MyTracksLocation("mock"); location3 = new MyTracksLocation("mock"); location4 = new MyTracksLocation("mock"); populateLocations(location1, location2, location3, location4); wp1 = new Waypoint(); wp2 = new Waypoint(); wp1.setLocation(location2); wp1.setName(WAYPOINT1_NAME); wp1.setDescription(WAYPOINT1_DESCRIPTION); wp2.setLocation(location3); wp2.setName(WAYPOINT2_NAME); wp2.setDescription(WAYPOINT2_DESCRIPTION); } /** * Populates the given locations with coordinates and time. */ protected void populateLocations(MyTracksLocation... locs) { for (int i = 0; i < locs.length; i++) { MyTracksLocation loc = locs[i]; loc.setAltitude(i * 5000000); loc.setLatitude(i); loc.setLongitude(-i); loc.setTime(10000000 + i * 1000); Sensor.SensorData.Builder hr = Sensor.SensorData.newBuilder() .setValue(100 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder() .setValue(400 + i) .setState(Sensor.SensorState.SENDING); Sensor.SensorDataSet sds = Sensor.SensorDataSet.newBuilder().setHeartRate(hr.build()) .setPower(power) .build(); loc.setSensorData(sds); } } /** * Makes the right sequence of calls to the writer in order to write the fake * track in {@link #track}. * * @param writer the writer to write to * @return the written contents */ protected String writeTrack(TrackFormatWriter writer) { OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE); writer.prepare(track, output); writer.writeHeader(); writer.writeBeginTrack(location1); writer.writeOpenSegment(); writer.writeLocation(location1); writer.writeLocation(location2); writer.writeCloseSegment(); writer.writeOpenSegment(); writer.writeLocation(location3); writer.writeLocation(location4); writer.writeCloseSegment(); writer.writeEndTrack(location4); writer.writeWaypoint(wp1); writer.writeWaypoint(wp2); writer.writeFooter(); writer.close(); return output.toString(); } /** * Gets the text data contained inside a tag. * * @param parent the parent of the tag containing the text * @param elementName the name of the tag containing the text * @return the text contents */ protected String getChildTextValue(Element parent, String elementName) { Element child = getChildElement(parent, elementName); assertTrue(child.hasChildNodes()); NodeList children = child.getChildNodes(); int length = children.getLength(); assertTrue(length > 0); // The children may be a sucession of text elements, just concatenate them String result = ""; for (int i = 0; i < length; i++) { Text textNode = (Text) children.item(i); result += textNode.getNodeValue(); } return result; } /** * Returns all child elements of a given parent which have the given name. * * @param parent the parent to get children from * @param elementName the element name to look for * @param expectedChildren the number of children we're expected to find * @return a list of the found elements */ protected List<Element> getChildElements(Node parent, String elementName, int expectedChildren) { assertTrue(parent.hasChildNodes()); NodeList children = parent.getChildNodes(); int length = children.getLength(); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < length; i++) { Node childNode = children.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.getNodeName().equalsIgnoreCase(elementName)) { result.add((Element) childNode); } } assertTrue(children.toString(), result.size() == expectedChildren); return result; } /** * Returns the single child element of the given parent with the given type. * * @param parent the parent to get a child from * @param elementName the name of the child to look for * @return the child element */ protected Element getChildElement(Node parent, String elementName) { return getChildElements(parent, elementName, 1).get(0); } /** * Parses the given XML contents and returns a DOM {@link Document} for it. */ protected Document parseXmlDocument(String contents) throws FactoryConfigurationError, ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setCoalescing(true); // TODO: Somehow do XML validation on Android // builderFactory.setValidating(true); builderFactory.setNamespaceAware(true); builderFactory.setIgnoringComments(true); builderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse( new InputSource(new StringReader(contents))); return doc; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.Date; import java.util.List; /** * Tests for the GPX track exporter. * * @author Sandor Dornbush */ public class TcxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new TcxTrackWriter(); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element root = getChildElement(doc, "TrainingCenterDatabase"); Element activitiesTag = getChildElement(root, "Activities"); Element activityTag = getChildElement(activitiesTag, "Activity"); Element lapTag = getChildElement(activityTag, "Lap"); List<Element> segmentTags = getChildElements(lapTag, "Track", 2); Element segment1Tag = segmentTags.get(0); Element segment2Tag = segmentTags.get(1); List<Element> seg1PointTags = getChildElements(segment1Tag, "Trackpoint", 2); List<Element> seg2PointTags = getChildElements(segment2Tag, "Trackpoint", 2); assertTagsMatchPoints(seg1PointTags, location1, location2); assertTagsMatchPoints(seg2PointTags, location3, location4); } /** * Asserts that the given tags describe the given points, in the same order. */ private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locs) { assertEquals(locs.length, tags.size()); for (int i = 0; i < locs.length; i++) { Element tag = tags.get(i); MyTracksLocation loc = locs[i]; assertTagMatchesLocation(tag, loc); } } /** * Asserts that the given tag describes the given location. */ private void assertTagMatchesLocation(Element tag, MyTracksLocation loc) { Element posTag = getChildElement(tag, "Position"); assertEquals(Double.toString(loc.getLatitude()), getChildTextValue(posTag, "LatitudeDegrees")); assertEquals(Double.toString(loc.getLongitude()), getChildTextValue(posTag, "LongitudeDegrees")); assertEquals( TcxTrackWriter.TIMESTAMP_FORMAT.format(new Date(loc.getTime())), getChildTextValue(tag, "Time")); assertEquals(Double.toString(loc.getAltitude()), getChildTextValue(tag, "AltitudeMeters")); assertTrue(loc.getSensorDataSet() != null); Sensor.SensorDataSet sds = loc.getSensorDataSet(); List<Element> bpm = getChildElements(tag, "HeartRateBpm", 1); assertEquals(Integer.toString(sds.getHeartRate().getValue()), getChildTextValue(bpm.get(0), "Value")); List<Element> ext = getChildElements(tag, "Extensions", 1); List<Element> tpx = getChildElements(ext.get(0), "TPX", 1); assertEquals(Integer.toString(sds.getPower().getValue()), getChildTextValue(tpx.get(0), "Watts")); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.List; /** * Tests for the GPX track exporter. * * @author Rodrigo Damazio */ public class GpxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new GpxTrackWriter(); String result = writeTrack(writer); Document doc = parseXmlDocument(result); Element gpxTag = getChildElement(doc, "gpx"); Element trackTag = getChildElement(gpxTag, "trk"); assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name")); assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc")); assertEquals(Long.toString(TRACK_ID), getChildTextValue(trackTag, "number")); List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2); List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "0", "0", "1970-01-01T02:46:40Z", "0"); assertTagMatchesLocation(segPointTags.get(1), "1", "-1", "1970-01-01T02:46:41Z", "5000000"); segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2); assertTagMatchesLocation(segPointTags.get(0), "2", "-2", "1970-01-01T02:46:42Z", "10000000"); assertTagMatchesLocation(segPointTags.get(1), "3", "-3", "1970-01-01T02:46:43Z", "15000000"); List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2); Element wptTag = waypointTags.get(0); assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "1", "-1", "1970-01-01T02:46:41Z", "5000000"); wptTag = waypointTags.get(1); assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name")); assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc")); assertTagMatchesLocation(wptTag, "2", "-2", "1970-01-01T02:46:42Z", "10000000"); } /** * Asserts that the given tag describes the location given by the * Strings lat, lon, time, and ele. */ private void assertTagMatchesLocation(Element tag, String lat, String lon, String time, String ele) { assertEquals(lat, tag.getAttribute("lat")); assertEquals(lon, tag.getAttribute("lon")); assertEquals(time, getChildTextValue(tag, "time")); assertEquals(ele, getChildTextValue(tag, "ele")); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; /** * Tests for the CSV track exporter. * * @author Rodrigo Damazio */ public class CsvTrackWriterTest extends TrackFormatWriterTest { }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.test.AndroidTestCase; import java.io.File; /** * @author Sandor Dornbush */ public class TempFileCleanerTest extends AndroidTestCase { @UsesMocks({ File.class, }) public void test_noDir() { File dir = AndroidMock.createMock(File.class, "/no_file"); TempFileCleaner cleaner = new TempFileCleaner(0); expect(dir.exists()).andStubReturn(false); AndroidMock.replay(dir); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir); } public void test_emptyDir() { File dir = AndroidMock.createMock(File.class, "/no_file"); TempFileCleaner cleaner = new TempFileCleaner(0); expect(dir.exists()).andStubReturn(true); expect(dir.listFiles()).andStubReturn(new File[0]); AndroidMock.replay(dir); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir); } public void test_newFile() { File dir = AndroidMock.createMock(File.class, "/no_file"); long now = 100000000; TempFileCleaner cleaner = new TempFileCleaner(now); expect(dir.exists()).andStubReturn(true); File file = AndroidMock.createMock(File.class, "/no_file/foo"); expect(file.lastModified()).andStubReturn(now); File[] list = { file }; expect(dir.listFiles()).andStubReturn(list); AndroidMock.replay(dir, file); assertEquals(0, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir, file); } public void test_oldFile() { File dir = AndroidMock.createMock(File.class, "/no_file"); long now = 100000000; TempFileCleaner cleaner = new TempFileCleaner(now); expect(dir.exists()).andStubReturn(true); File file = AndroidMock.createMock(File.class, "/no_file/foo"); expect(file.lastModified()).andStubReturn(now - 3600001); expect(file.delete()).andStubReturn(true); File[] list = { file }; expect(dir.listFiles()).andStubReturn(list); AndroidMock.replay(dir, file); assertEquals(1, cleaner.cleanTmpDirectory(dir)); AndroidMock.verify(dir, file); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io; import static org.easymock.EasyMock.expect; import com.google.android.apps.mytracks.content.MyTracksProvider; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import android.content.Context; import android.location.Location; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import android.test.mock.MockContentResolver; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.OutputStream; import org.easymock.EasyMock; import org.easymock.IArgumentMatcher; import org.easymock.IMocksControl; /** * Tests for the track writer. * * @author Rodrigo Damazio */ public class TrackWriterTest extends AndroidTestCase { /** * {@link TrackWriter} subclass which mocks out methods called from * {@link TrackWriter#openFile}. */ private static final class OpenFileTrackWriter extends TrackWriter { private final ByteArrayOutputStream stream; private final boolean canWrite; /** * Constructor. * * @param stream the stream to return from * {@link TrackWriter#newOutputStream}, or null to throw a * {@link FileNotFoundException} * @param canWrite the value that {@link TrackWriter#canWriteFile} will * return */ private OpenFileTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, ByteArrayOutputStream stream, boolean canWrite) { super(context, providerUtils, track, writer); this.stream = stream; this.canWrite = canWrite; } @Override protected boolean canWriteFile() { return canWrite; } @Override protected OutputStream newOutputStream(String fileName) throws FileNotFoundException { assertEquals(FULL_TRACK_NAME, fileName); if (stream == null) { throw new FileNotFoundException(); } return stream; } } /** * {@link TrackWriter} subclass which mocks out methods called from * {@link TrackWriter#writeTrack}. */ private final class WriteTracksTrackWriter extends TrackWriter { private final boolean openResult; /** * Constructor. * * @param openResult the return value for {@link TrackWriter#openFile} */ private WriteTracksTrackWriter(Context context, MyTracksProviderUtils providerUtils, Track track, TrackFormatWriter writer, boolean openResult) { super(context, providerUtils, track, writer); this.openResult = openResult; } @Override protected boolean openFile() { openFileCalls++; return openResult; } @Override void writeDocument() { writeDocumentCalls++; } @Override protected void runOnUiThread(Runnable runnable) { runnable.run(); } } private static final long TRACK_ID = 1234567L; private static final String EXTENSION = "ext"; private static final String TRACK_NAME = "Swimming across the pacific"; private static final String FULL_TRACK_NAME = "Swimming across the pacific.ext"; private Track track; private TrackFormatWriter formatWriter; private TrackWriter writer; private IMocksControl mocksControl; private MyTracksProviderUtils providerUtils; private Factory oldProviderUtilsFactory; // State used in specific tests private int writeDocumentCalls; private int openFileCalls; @Override protected void setUp() throws Exception { super.setUp(); MockContentResolver mockContentResolver = new MockContentResolver(); RenamingDelegatingContext targetContext = new RenamingDelegatingContext( getContext(), getContext(), "test."); Context context = new MockContext(mockContentResolver, targetContext); MyTracksProvider provider = new MyTracksProvider(); provider.attachInfo(context, null); mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider); setContext(context); providerUtils = MyTracksProviderUtils.Factory.get(context); oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(providerUtils); mocksControl = EasyMock.createStrictControl(); formatWriter = mocksControl.createMock(TrackFormatWriter.class); expect(formatWriter.getExtension()).andStubReturn(EXTENSION); track = new Track(); track.setName(TRACK_NAME); track.setId(TRACK_ID); } @Override protected void tearDown() throws Exception { TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory); super.tearDown(); } public void testWriteTrack() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, true); // Expect the completion callback to be run Runnable completionCallback = mocksControl.createMock(Runnable.class); completionCallback.run(); mocksControl.replay(); writer.setOnCompletion(completionCallback); writer.writeTrack(); assertEquals(1, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testWriteTrack_openFails() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, false); // Expect the completion callback to be run Runnable completionCallback = mocksControl.createMock(Runnable.class); completionCallback.run(); mocksControl.replay(); writer.setOnCompletion(completionCallback); writer.writeTrack(); assertEquals(0, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testOpenFile() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, true); formatWriter.prepare(track, stream); mocksControl.replay(); assertTrue(writer.openFile()); mocksControl.verify(); } public void testOpenFile_cantWrite() { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, false); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testOpenFile_streamError() { writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, null, true); mocksControl.replay(); assertFalse(writer.openFile()); mocksControl.verify(); } public void testWriteDocument_emptyTrack() { writer = new TrackWriter(getContext(), providerUtils, track, formatWriter); // Set expected mock behavior formatWriter.writeHeader(); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } public void testWriteDocument() { writer = new TrackWriter(getContext(), providerUtils, track, formatWriter); final Location[] locs = { new Location("fake0"), new Location("fake1"), new Location("fake2"), new Location("fake3"), new Location("fake4"), new Location("fake5") }; Waypoint[] wps = { new Waypoint(), new Waypoint(), new Waypoint() }; // Fill locations with valid values fillLocations(locs); // Make location 3 invalid locs[2].setLatitude(100); assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); for (int i = 0; i < wps.length; ++i) { Waypoint wpt = wps[i]; wpt.setTrackId(TRACK_ID); assertNotNull(providerUtils.insertWaypoint(wpt)); wpt.setId(i + 1); } formatWriter.writeHeader(); // Expect reading/writing of the waypoints (except the first) formatWriter.writeWaypoint(wptEq(wps[1])); formatWriter.writeWaypoint(wptEq(wps[2])); // Begin the track formatWriter.writeBeginTrack(locEq(locs[0])); // Write locations 1-2 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[0])); formatWriter.writeLocation(locEq(locs[1])); formatWriter.writeCloseSegment(); // Location 3 is not written - it's invalid // Write locations 4-6 formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[3])); formatWriter.writeLocation(locEq(locs[4])); formatWriter.writeLocation(locEq(locs[5])); formatWriter.writeCloseSegment(); // End the track formatWriter.writeEndTrack(locEq(locs[5])); formatWriter.writeFooter(); formatWriter.close(); mocksControl.replay(); writer.writeDocument(); assertTrue(writer.wasSuccess()); mocksControl.verify(); } private static Waypoint wptEq(final Waypoint wpt) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object wptObj2) { if (wptObj2 == null || wpt == null) return wpt == wptObj2; Waypoint wpt2 = (Waypoint) wptObj2; return wpt.getId() == wpt2.getId(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("wptEq("); buffer.append(wpt); buffer.append(")"); } }); return null; } private static Location locEq(final Location loc) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object locObj2) { if (locObj2 == null || loc == null) return loc == locObj2; Location loc2 = (Location) locObj2; return loc.hasAccuracy() == loc2.hasAccuracy() && (!loc.hasAccuracy() || loc.getAccuracy() == loc2.getAccuracy()) && loc.hasAltitude() == loc2.hasAltitude() && (!loc.hasAltitude() || loc.getAltitude() == loc2.getAltitude()) && loc.hasBearing() == loc2.hasBearing() && (!loc.hasBearing() || loc.getBearing() == loc2.getBearing()) && loc.hasSpeed() == loc2.hasSpeed() && (!loc.hasSpeed() || loc.getSpeed() == loc2.getSpeed()) && loc.getLatitude() == loc2.getLatitude() && loc.getLongitude() == loc2.getLongitude() && loc.getTime() == loc2.getTime(); } @Override public void appendTo(StringBuffer buffer) { buffer.append("locEq("); buffer.append(loc); buffer.append(")"); } }); return null; } private void fillLocations(Location... locs) { assertTrue(locs.length < 90); for (int i = 0; i < locs.length; i++) { Location location = locs[i]; location.setLatitude(i + 1); location.setLongitude(i + 1); location.setTime(i + 1000); } } }
Java
package com.dsi.ant.exception; public class AntInterfaceException extends Exception { /** * */ private static final long serialVersionUID = -7278855366167722274L; public AntInterfaceException() { this("Unknown ANT Interface error"); } public AntInterfaceException(String string) { super(string); } }
Java
package com.dsi.ant.exception; import android.os.RemoteException; public class AntRemoteException extends AntInterfaceException { /** * */ private static final long serialVersionUID = 8950974759973459561L; public AntRemoteException(RemoteException e) { this("ANT Interface error, ANT Radio Service remote error: "+e.toString(), e); } public AntRemoteException(String string, RemoteException e) { super(string); this.initCause(e); } }
Java
package com.dsi.ant.exception; public class AntServiceNotConnectedException extends AntInterfaceException { /** * */ private static final long serialVersionUID = -2085081032170129309L; public AntServiceNotConnectedException() { this("ANT Interface error, ANT Radio Service not connected."); } public AntServiceNotConnectedException(String string) { super(string); } }
Java
/* * Copyright 2011 Dynastream Innovations 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.dsi.ant; /** * Defines version numbers * * @hide */ public class Version { ////////////////////////////////////////////// // Library Version Information ////////////////////////////////////////////// public static final int ANT_LIBRARY_VERSION_CODE = 6; public static final int ANT_LIBRARY_VERSION_MAJOR = 2; public static final int ANT_LIBRARY_VERSION_MINOR = 0; public static final String ANT_LIBRARY_VERSION_NAME = String.valueOf(ANT_LIBRARY_VERSION_MAJOR) + "." + String.valueOf(ANT_LIBRARY_VERSION_MINOR); }
Java
/* * Copyright 2010 Dynastream Innovations 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.dsi.ant; /** * The Android Ant API is not finalized, and *will* change. Use at your * own risk. * * Public API for controlling the Ant Service. * AntDefines contains definitions commonly used in ANT messaging. * * @hide */ public class AntDefine { ////////////////////////////////////////////// // Valid Configuration Values ////////////////////////////////////////////// public static final byte MIN_BIN = 0; public static final byte MAX_BIN = 10; public static final short MIN_DEVICE_ID = 0; public static final short MAX_DEVICE_ID = (short)65535; public static final short MIN_BUFFER_THRESHOLD = 0; public static final short MAX_BUFFER_THRESHOLD = 996; ////////////////////////////////////////////// // ANT Message Payload Size ////////////////////////////////////////////// public static final byte ANT_STANDARD_DATA_PAYLOAD_SIZE =((byte)8); ////////////////////////////////////////////// // ANT LIBRARY Extended Data Message Fields // NOTE: You must check the extended message // bitfield first to find out which fields // are present before accessing them! ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE =((byte)4); //public static final byte ANT_EXT_STRING_SIZE =((byte)19); // this is the additional buffer space required required for setting USB Descriptor strings public static final byte ANT_EXT_STRING_SIZE =((byte)0); // changed to 0 as we will not be dealing with ANT USB parts. ////////////////////////////////////////////// // ANT Extended Data Message Bifield Definitions ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_BITFIELD_DEVICE_ID =((byte)0x80); // first field after bitfield public static final byte ANT_EXT_MESG_BITFIELD_RSSI =((byte)0x40); // next field after ID, if there is one public static final byte ANT_EXT_MESG_BITFIELD_TIME_STAMP =((byte)0x20); // next field after RSSI, if there is one // 4 bits free reserved set to 0 public static final byte ANT_EXT_MESG_BIFIELD_EXTENSION =((byte)0x01); // extended message input bitfield defines public static final byte ANT_EXT_MESG_BITFIELD_OVERWRITE_SHARED_ADR =((byte)0x10); public static final byte ANT_EXT_MESG_BITFIELD_TRANSMISSION_TYPE =((byte)0x08); ////////////////////////////////////////////// // ID Definitions ////////////////////////////////////////////// public static final byte ANT_ID_SIZE =((byte)4); public static final byte ANT_ID_TRANS_TYPE_OFFSET =((byte)3); public static final byte ANT_ID_DEVICE_TYPE_OFFSET =((byte)2); public static final byte ANT_ID_DEVICE_NUMBER_HIGH_OFFSET =((byte)1); public static final byte ANT_ID_DEVICE_NUMBER_LOW_OFFSET =((byte)0); public static final byte ANT_ID_DEVICE_TYPE_PAIRING_FLAG =((byte)0x80); public static final byte ANT_TRANS_TYPE_SHARED_ADDR_MASK =((byte)0x03); public static final byte ANT_TRANS_TYPE_1_BYTE_SHARED_ADDRESS =((byte)0x02); public static final byte ANT_TRANS_TYPE_2_BYTE_SHARED_ADDRESS =((byte)0x03); ////////////////////////////////////////////// // Assign Channel Parameters ////////////////////////////////////////////// public static final byte PARAMETER_RX_NOT_TX =((byte)0x00); public static final byte PARAMETER_TX_NOT_RX =((byte)0x10); public static final byte PARAMETER_SHARED_CHANNEL =((byte)0x20); public static final byte PARAMETER_NO_TX_GUARD_BAND =((byte)0x40); public static final byte PARAMETER_ALWAYS_RX_WILD_CARD_SEARCH_ID =((byte)0x40); //Pre-AP2 public static final byte PARAMETER_RX_ONLY =((byte)0x40); ////////////////////////////////////////////// // Ext. Assign Channel Parameters ////////////////////////////////////////////// public static final byte EXT_PARAM_ALWAYS_SEARCH =((byte)0x01); public static final byte EXT_PARAM_FREQUENCY_AGILITY =((byte)0x04); ////////////////////////////////////////////// // Radio TX Power Definitions ////////////////////////////////////////////// public static final byte RADIO_TX_POWER_LVL_MASK =((byte)0x03); public static final byte RADIO_TX_POWER_LVL_0 =((byte)0x00); //(formerly: RADIO_TX_POWER_MINUS20DB); lowest public static final byte RADIO_TX_POWER_LVL_1 =((byte)0x01); //(formerly: RADIO_TX_POWER_MINUS10DB); public static final byte RADIO_TX_POWER_LVL_2 =((byte)0x02); //(formerly: RADIO_TX_POWER_MINUS5DB); public static final byte RADIO_TX_POWER_LVL_3 =((byte)0x03); //(formerly: RADIO_TX_POWER_0DB); highest ////////////////////////////////////////////// // Channel Status ////////////////////////////////////////////// public static final byte STATUS_CHANNEL_STATE_MASK =((byte)0x03); public static final byte STATUS_UNASSIGNED_CHANNEL =((byte)0x00); public static final byte STATUS_ASSIGNED_CHANNEL =((byte)0x01); public static final byte STATUS_SEARCHING_CHANNEL =((byte)0x02); public static final byte STATUS_TRACKING_CHANNEL =((byte)0x03); ////////////////////////////////////////////// // Standard capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_NO_RX_CHANNELS =((byte)0x01); public static final byte CAPABILITIES_NO_TX_CHANNELS =((byte)0x02); public static final byte CAPABILITIES_NO_RX_MESSAGES =((byte)0x04); public static final byte CAPABILITIES_NO_TX_MESSAGES =((byte)0x08); public static final byte CAPABILITIES_NO_ACKD_MESSAGES =((byte)0x10); public static final byte CAPABILITIES_NO_BURST_TRANSFER =((byte)0x20); ////////////////////////////////////////////// // Advanced capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_OVERUN_UNDERRUN =((byte)0x01); // Support for this functionality has been dropped public static final byte CAPABILITIES_NETWORK_ENABLED =((byte)0x02); public static final byte CAPABILITIES_AP1_VERSION_2 =((byte)0x04); // This Version of the AP1 does not support transmit and only had a limited release public static final byte CAPABILITIES_SERIAL_NUMBER_ENABLED =((byte)0x08); public static final byte CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED =((byte)0x10); public static final byte CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED =((byte)0x20); public static final byte CAPABILITIES_SCRIPT_ENABLED =((byte)0x40); public static final byte CAPABILITIES_SEARCH_LIST_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 2 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_LED_ENABLED =((byte)0x01); public static final byte CAPABILITIES_EXT_MESSAGE_ENABLED =((byte)0x02); public static final byte CAPABILITIES_SCAN_MODE_ENABLED =((byte)0x04); public static final byte CAPABILITIES_RESERVED =((byte)0x08); public static final byte CAPABILITIES_PROX_SEARCH_ENABLED =((byte)0x10); public static final byte CAPABILITIES_EXT_ASSIGN_ENABLED =((byte)0x20); public static final byte CAPABILITIES_FREE_1 =((byte)0x40); public static final byte CAPABILITIES_FIT1_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 3 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_SENSRCORE_ENABLED =((byte)0x01); public static final byte CAPABILITIES_RESERVED_1 =((byte)0x02); public static final byte CAPABILITIES_RESERVED_2 =((byte)0x04); public static final byte CAPABILITIES_RESERVED_3 =((byte)0x08); ////////////////////////////////////////////// // Burst Message Sequence ////////////////////////////////////////////// public static final byte CHANNEL_NUMBER_MASK =((byte)0x1F); public static final byte SEQUENCE_NUMBER_MASK =((byte)0xE0); public static final byte SEQUENCE_NUMBER_ROLLOVER =((byte)0x60); public static final byte SEQUENCE_FIRST_MESSAGE =((byte)0x00); public static final byte SEQUENCE_LAST_MESSAGE =((byte)0x80); public static final byte SEQUENCE_NUMBER_INC =((byte)0x20); ////////////////////////////////////////////// // Control Message Flags ////////////////////////////////////////////// public static final byte BROADCAST_CONTROL_BYTE =((byte)0x00); public static final byte ACKNOWLEDGED_CONTROL_BYTE =((byte)0xA0); ////////////////////////////////////////////// // Response / Event Codes ////////////////////////////////////////////// public static final byte RESPONSE_NO_ERROR =((byte)0x00); public static final byte NO_EVENT =((byte)0x00); public static final byte EVENT_RX_SEARCH_TIMEOUT =((byte)0x01); public static final byte EVENT_RX_FAIL =((byte)0x02); public static final byte EVENT_TX =((byte)0x03); public static final byte EVENT_TRANSFER_RX_FAILED =((byte)0x04); public static final byte EVENT_TRANSFER_TX_COMPLETED =((byte)0x05); public static final byte EVENT_TRANSFER_TX_FAILED =((byte)0x06); public static final byte EVENT_CHANNEL_CLOSED =((byte)0x07); public static final byte EVENT_RX_FAIL_GO_TO_SEARCH =((byte)0x08); public static final byte EVENT_CHANNEL_COLLISION =((byte)0x09); public static final byte EVENT_TRANSFER_TX_START =((byte)0x0A); // a pending transmit transfer has begun public static final byte EVENT_CHANNEL_ACTIVE =((byte)0x0F); public static final byte EVENT_TRANSFER_TX_NEXT_MESSAGE =((byte)0x11); // only enabled in FIT1 public static final byte CHANNEL_IN_WRONG_STATE =((byte)0x15); // returned on attempt to perform an action from the wrong channel state public static final byte CHANNEL_NOT_OPENED =((byte)0x16); // returned on attempt to communicate on a channel that is not open public static final byte CHANNEL_ID_NOT_SET =((byte)0x18); // returned on attempt to open a channel without setting the channel ID public static final byte CLOSE_ALL_CHANNELS =((byte)0x19); // returned when attempting to start scanning mode, when channels are still open public static final byte TRANSFER_IN_PROGRESS =((byte)0x1F); // returned on attempt to communicate on a channel with a TX transfer in progress public static final byte TRANSFER_SEQUENCE_NUMBER_ERROR =((byte)0x20); // returned when sequence number is out of order on a Burst transfer public static final byte TRANSFER_IN_ERROR =((byte)0x21); public static final byte TRANSFER_BUSY =((byte)0x22); public static final byte INVALID_MESSAGE_CRC =((byte)0x26); // returned if there is a framing error on an incomming message public static final byte MESSAGE_SIZE_EXCEEDS_LIMIT =((byte)0x27); // returned if a data message is provided that is too large public static final byte INVALID_MESSAGE =((byte)0x28); // returned when the message has an invalid parameter public static final byte INVALID_NETWORK_NUMBER =((byte)0x29); // returned when an invalid network number is provided public static final byte INVALID_LIST_ID =((byte)0x30); // returned when the provided list ID or size exceeds the limit public static final byte INVALID_SCAN_TX_CHANNEL =((byte)0x31); // returned when attempting to transmit on channel 0 when in scan mode public static final byte INVALID_PARAMETER_PROVIDED =((byte)0x33); // returned when an invalid parameter is specified in a configuration message public static final byte EVENT_SERIAL_QUE_OVERFLOW =((byte)0x34); public static final byte EVENT_QUE_OVERFLOW =((byte)0x35); // ANT event que has overflowed and lost 1 or more events public static final byte EVENT_CLK_ERROR =((byte)0x36); // debug event for XOSC16M on LE1 public static final byte SCRIPT_FULL_ERROR =((byte)0x40); // error writing to script, memory is full public static final byte SCRIPT_WRITE_ERROR =((byte)0x41); // error writing to script, bytes not written correctly public static final byte SCRIPT_INVALID_PAGE_ERROR =((byte)0x42); // error accessing script page public static final byte SCRIPT_LOCKED_ERROR =((byte)0x43); // the scripts are locked and can't be dumped public static final byte NO_RESPONSE_MESSAGE =((byte)0x50); // returned to the Command_SerialMessageProcess function, so no reply message is generated public static final byte RETURN_TO_MFG =((byte)0x51); // default return to any mesg when the module determines that the mfg procedure has not been fully completed public static final byte FIT_ACTIVE_SEARCH_TIMEOUT =((byte)0x60); // Fit1 only event added for timeout of the pairing state after the Fit module becomes active public static final byte FIT_WATCH_PAIR =((byte)0x61); // Fit1 only public static final byte FIT_WATCH_UNPAIR =((byte)0x62); // Fit1 only public static final byte USB_STRING_WRITE_FAIL =((byte)0x70); // Internal only events below this point public static final byte INTERNAL_ONLY_EVENTS =((byte)0x80); public static final byte EVENT_RX =((byte)0x80); // INTERNAL: Event for a receive message public static final byte EVENT_NEW_CHANNEL =((byte)0x81); // INTERNAL: EVENT for a new active channel public static final byte EVENT_PASS_THRU =((byte)0x82); // INTERNAL: Event to allow an upper stack events to pass through lower stacks public static final byte EVENT_BLOCKED =((byte)0xFF); // INTERNAL: Event to replace any event we do not wish to go out, will also zero the size of the Tx message /////////////////////////////////////////////////////// // Script Command Codes /////////////////////////////////////////////////////// public static final byte SCRIPT_CMD_FORMAT =((byte)0x00); public static final byte SCRIPT_CMD_DUMP =((byte)0x01); public static final byte SCRIPT_CMD_SET_DEFAULT_SECTOR =((byte)0x02); public static final byte SCRIPT_CMD_END_SECTOR =((byte)0x03); public static final byte SCRIPT_CMD_END_DUMP =((byte)0x04); public static final byte SCRIPT_CMD_LOCK =((byte)0x05); /////////////////////////////////////////////////////// // Reset Mesg Codes /////////////////////////////////////////////////////// public static final byte RESET_FLAGS_MASK =((byte)0xE0); public static final byte RESET_SUSPEND =((byte)0x80); // this must follow bitfield def public static final byte RESET_SYNC =((byte)0x40); // this must follow bitfield def public static final byte RESET_CMD =((byte)0x20); // this must follow bitfield def public static final byte RESET_WDT =((byte)0x02); public static final byte RESET_RST =((byte)0x01); public static final byte RESET_POR =((byte)0x00); }
Java
/* * Copyright 2010 Dynastream Innovations 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.dsi.ant; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import com.dsi.ant.exception.*; /** * Public API for controlling the Ant Service. AntInterface is a proxy * object for controlling the Ant Service via IPC. Creating a AntInterface * object will create a binding with the Ant service. * * @hide */ public class AntInterface { /** The Log Tag. */ public static final String TAG = "ANTInterface"; /** Enable debug logging. */ public static boolean DEBUG = false; /** Search string to find ANT Radio Proxy Service in the Android Marketplace */ private static final String MARKET_SEARCH_TEXT_DEFAULT = "ANT Radio Service Dynastream Innovations Inc"; /** Name of the ANT Radio shared library */ private static final String ANT_LIBRARY_NAME = "com.dsi.ant.antradio_library"; /** Inter-process communication with the ANT Radio Proxy Service. */ private static IAnt_6 sAntReceiver = null; /** Singleton instance of this class. */ private static AntInterface INSTANCE; /** Used when obtaining a reference to the singleton instance. */ private static Object INSTANCE_LOCK = new Object(); /** The context to use. */ private static Context sContext = null; /** Listens to changes to service connection status. */ private static ServiceListener sServiceListener; /** Is the ANT Radio Proxy Service connected. */ private static boolean sServiceConnected = false; /** The version code (eg. 1) of ANTLib used by the ANT application service */ private static int mServiceLibraryVersionCode = 0; /** Has support for ANT already been checked */ private static boolean mCheckedAntSupported = false; /** Is ANT supported on this device */ private static boolean mAntSupported = false; /** * An interface for notifying AntInterface IPC clients when they have * been connected to the ANT service. * * @see ServiceEvent */ public interface ServiceListener { /** * Called to notify the client when this proxy object has been * connected to the ANT service. Clients must wait for * this callback before making IPC calls on the ANT * service. */ public void onServiceConnected(); /** * Called to notify the client that this proxy object has been * disconnected from the ANT service. Clients must not * make IPC calls on the ANT service after this callback. * This callback will currently only occur if the application hosting * the BluetoothAg service, but may be called more often in future. */ public void onServiceDisconnected(); } //Constructor /** * Instantiates a new ant interface. * * @param context the context * @param listener the listener * @since 1.0 */ private AntInterface(Context context, ServiceListener listener) { // This will be around as long as this process is sContext = context; sServiceListener = listener; } /** * Gets the single instance of AntInterface, creating it if it doesn't exist. * Only the initial request for an instance will have context and listener set to the requested objects. * * @param context the context used to bind to the remote service. * @param listener the listener to be notified of status changes. * @return the AntInterface instance. * @since 1.0 */ public static AntInterface getInstance(Context context,ServiceListener listener) { if(DEBUG) Log.d(TAG, "getInstance"); synchronized (INSTANCE_LOCK) { if(!hasAntSupport(context)) { if(DEBUG) Log.d(TAG, "getInstance: ANT not supported"); return null; } if (INSTANCE == null) { if(DEBUG) Log.d(TAG, "getInstance: Creating new instance"); INSTANCE = new AntInterface(context,listener); } else { if(DEBUG) Log.d(TAG, "getInstance: Using existing instance"); } if(!sServiceConnected) { if(DEBUG) Log.d(TAG, "getInstance: No connection to proxy service, attempting connection"); if(!INSTANCE.initService()) { Log.e(TAG, "getInstance: No connection to proxy service"); INSTANCE.destroy(); INSTANCE = null; } } return INSTANCE; } } /** * Go to market. * * @param pContext the context * @param pSearchText the search text * @since 1.2 */ public static void goToMarket(Context pContext, String pSearchText) { if(null == pSearchText) { goToMarket(pContext); } else { if(DEBUG) Log.i(TAG, "goToMarket: Search text = "+ pSearchText); Intent goToMarket = null; goToMarket = new Intent(Intent.ACTION_VIEW,Uri.parse("http://market.android.com/search?q=" + pSearchText)); goToMarket.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pContext.startActivity(goToMarket); } } /** * Go to market. * * @param pContext the context * @since 1.2 */ public static void goToMarket(Context pContext) { if(DEBUG) Log.d(TAG, "goToMarket"); goToMarket(pContext, MARKET_SEARCH_TEXT_DEFAULT); } /** * Class for interacting with the ANT interface. */ private static ServiceConnection sIAntConnection = new ServiceConnection() { public void onServiceConnected(ComponentName pClassName, IBinder pService) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. We are communicating with our // service through an IDL interface, so get a client-side // representation of that from the raw service object. if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected()"); sAntReceiver = IAnt_6.Stub.asInterface(pService); sServiceConnected = true; // Notify the attached application if it is registered if (sServiceListener != null) { sServiceListener.onServiceConnected(); } else { if(DEBUG) Log.d(TAG, "sIAntConnection onServiceConnected: No service listener registered"); } } public void onServiceDisconnected(ComponentName pClassName) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected()"); sAntReceiver = null; sServiceConnected = false; mServiceLibraryVersionCode = 0; // Notify the attached application if it is registered if (sServiceListener != null) { sServiceListener.onServiceDisconnected(); } else { if(DEBUG) Log.d(TAG, "sIAntConnection onServiceDisconnected: No service listener registered"); } // Try and rebind to the service INSTANCE.releaseService(); INSTANCE.initService(); } }; /** * Binds this activity to the ANT service. * * @return true, if successful */ private boolean initService() { if(DEBUG) Log.d(TAG, "initService() entered"); boolean ret = false; if(!sServiceConnected) { ret = sContext.bindService(new Intent(IAnt_6.class.getName()), sIAntConnection, Context.BIND_AUTO_CREATE); if(DEBUG) Log.i(TAG, "initService(): Bound with ANT service: " + ret); } else { if(DEBUG) Log.d(TAG, "initService: already initialised service"); ret = true; } return ret; } /** Unbinds this activity from the ANT service. */ private void releaseService() { if(DEBUG) Log.d(TAG, "releaseService() entered"); // TODO Make sure can handle multiple calls to onDestroy if(sServiceConnected) { sContext.unbindService(sIAntConnection); sServiceConnected = false; } if(DEBUG) Log.d(TAG, "releaseService() unbound."); } /** * True if this activity can communicate with the ANT service. * * @return true, if service is connected * @since 1.2 */ public boolean isServiceConnected() { return sServiceConnected; } /** * Destroy. * * @return true, if successful * @since 1.0 */ public boolean destroy() { if(DEBUG) Log.d(TAG, "destroy"); releaseService(); INSTANCE = null; return true; } ////------------------------------------------------- /** * Enable. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void enable() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.enable()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Disable. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void disable() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.disable()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Checks if is enabled. * * @return true, if is enabled. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public boolean isEnabled() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.isEnabled(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT tx message. * * @param message the message * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTTxMessage(byte[] message) throws AntInterfaceException { if(DEBUG) Log.d(TAG, "ANTTxMessage"); if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTTxMessage(message)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT reset system. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTResetSystem() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTResetSystem()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT unassign channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTUnassignChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTUnassignChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT assign channel. * * @param channelNumber the channel number * @param channelType the channel type * @param networkNumber the network number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTAssignChannel(channelNumber, channelType, networkNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel id. * * @param channelNumber the channel number * @param deviceNumber the device number * @param deviceType the device type * @param txType the tx type * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelId(channelNumber, deviceNumber, deviceType, txType)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel period. * * @param channelNumber the channel number * @param channelPeriod the channel period * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelPeriod(byte channelNumber, short channelPeriod) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelPeriod(channelNumber, channelPeriod)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel rf freq. * * @param channelNumber the channel number * @param radioFrequency the radio frequency * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelRFFreq(channelNumber, radioFrequency)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel search timeout. * * @param channelNumber the channel number * @param searchTimeout the search timeout * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelSearchTimeout(channelNumber, searchTimeout)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set low priority channel search timeout. * * @param channelNumber the channel number * @param searchTimeout the search timeout * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetLowPriorityChannelSearchTimeout(channelNumber, searchTimeout)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set proximity search. * * @param channelNumber the channel number * @param searchThreshold the search threshold * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetProximitySearch(byte channelNumber, byte searchThreshold) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetProximitySearch(channelNumber, searchThreshold)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT set channel transmit power * @param channelNumber the channel number * @param txPower the transmit power level * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSetChannelTxPower(byte channelNumber, byte txPower) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSetChannelTxPower(channelNumber, txPower)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT add channel id. * * @param channelNumber the channel number * @param deviceNumber the device number * @param deviceType the device type * @param txType the tx type * @param listIndex the list index * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTAddChannelId(byte channelNumber, short deviceNumber, byte deviceType, byte txType, byte listIndex) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTAddChannelId(channelNumber, deviceNumber, deviceType, txType, listIndex)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT config list. * * @param channelNumber the channel number * @param listSize the list size * @param exclude the exclude * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTConfigList(byte channelNumber, byte listSize, byte exclude) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTConfigList(channelNumber, listSize, exclude)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT config event buffering. * * @param screenOnFlushTimerInterval the screen on flush timer interval * @param screenOnFlushBufferThreshold the screen on flush buffer threshold * @param screenOffFlushTimerInterval the screen off flush timer interval * @param screenOffFlushBufferThreshold the screen off flush buffer threshold * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.3 */ public void ANTConfigEventBuffering(short screenOnFlushTimerInterval, short screenOnFlushBufferThreshold, short screenOffFlushTimerInterval, short screenOffFlushBufferThreshold) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTConfigEventBuffering((int)screenOnFlushTimerInterval, (int)screenOnFlushBufferThreshold, (int)screenOffFlushTimerInterval, (int)screenOffFlushBufferThreshold)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT disable event buffering. * * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.1 */ public void ANTDisableEventBuffering() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTDisableEventBuffering()) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT open channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTOpenChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTOpenChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT close channel. * * @param channelNumber the channel number * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTCloseChannel(byte channelNumber) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTCloseChannel(channelNumber)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT request message. * * @param channelNumber the channel number * @param messageID the message id * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTRequestMessage(byte channelNumber, byte messageID) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTRequestMessage(channelNumber, messageID)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send broadcast data. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendBroadcastData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendBroadcastData(channelNumber, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send acknowledged data. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendAcknowledgedData(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendAcknowledgedData(channelNumber, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send burst transfer packet. * * @param control the control * @param txBuffer the tx buffer * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public void ANTSendBurstTransferPacket(byte control, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { if(!sAntReceiver.ANTSendBurstTransferPacket(control, txBuffer)) { throw new AntInterfaceException(); } } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Transmits the given data on channelNumber as part of a burst message. * * @param channelNumber Which channel to transmit on. * @param txBuffer The data to send. * @param initialPacket Which packet in the burst sequence does the data begin in, 1 is the first. * @param containsEndOfBurst Is this the last of the data to be sent in burst. * @return The number of bytes still to be sent (approximately). 0 if success. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException */ public int ANTSendBurstTransfer(byte channelNumber, byte[] txBuffer) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.ANTSendBurstTransfer(channelNumber, txBuffer); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * ANT send partial burst. * * @param channelNumber the channel number * @param txBuffer the tx buffer * @param initialPacket the initial packet * @param containsEndOfBurst the contains end of burst * @return The number of bytes still to be sent (approximately). 0 if success. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.0 */ public int ANTSendPartialBurst(byte channelNumber, byte[] txBuffer, int initialPacket, boolean containsEndOfBurst) throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.ANTTransmitBurst(channelNumber, txBuffer, initialPacket, containsEndOfBurst); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Returns the version code (eg. 1) of ANTLib used by the ANT application service * * @return the service library version code, or 0 on error. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.2 */ public int getServiceLibraryVersionCode() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } if(mServiceLibraryVersionCode == 0) { try { mServiceLibraryVersionCode = sAntReceiver.getServiceLibraryVersionCode(); } catch(RemoteException e) { throw new AntRemoteException(e); } } return mServiceLibraryVersionCode; } /** * Returns the version name (eg "1.0") of ANTLib used by the ANT application service * * @return the service library version name, or null on error. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.2 */ public String getServiceLibraryVersionName() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.getServiceLibraryVersionName(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Take control of the ANT Radio. * * @return True if control has been granted, false if another application has control or the request failed. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean claimInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.claimInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Give up control of the ANT Radio. * * @return True if control has been given up, false if this application did not have control. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean releaseInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.releaseInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Claims the interface if it is available. If not the user will be prompted (on the notification bar) if a force claim should be done. * If the ANT Interface is claimed, an AntInterfaceIntent.ANT_INTERFACE_CLAIMED_ACTION intent will be sent, with the current applications pid. * * @param String appName The name if this application, to show to the user. * @returns false if a claim interface request notification already exists. * @throws IllegalArgumentException * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean requestForceClaimInterface(String appName) throws AntInterfaceException { if((null == appName) || ("" == appName)) { throw new IllegalArgumentException(); } if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.requestForceClaimInterface(appName); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Clears the notification asking the user if they would like to seize control of the ANT Radio. * * @returns false if this process is not requesting to claim the interface. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean stopRequestForceClaimInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.stopRequestForceClaimInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Check if the calling application has control of the ANT Radio. * * @return True if control is currently granted. * @throws AntInterfaceException * @throws AntServiceNotConnectedException * @throws AntRemoteException * @since 1.5 */ public boolean hasClaimedInterface() throws AntInterfaceException { if(!sServiceConnected) { throw new AntServiceNotConnectedException(); } try { return sAntReceiver.hasClaimedInterface(); } catch(RemoteException e) { throw new AntRemoteException(e); } } /** * Check if this device has support for ANT. * * @return True if the device supports ANT (may still require ANT Radio Service be installed). * @since 1.5 */ public static boolean hasAntSupport(Context pContext) { if(!mCheckedAntSupported) { mAntSupported = Arrays.asList(pContext.getPackageManager().getSystemSharedLibraryNames()).contains(ANT_LIBRARY_NAME); mCheckedAntSupported = true; } return mAntSupported; } }
Java
/* * Copyright 2010 Dynastream Innovations 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.dsi.ant; /** * Public API for controlling the Ant Service. * AntMesg contains definitions for ANT message IDs * * @hide */ public class AntMesg { ///////////////////////////////////////////////////////////////////////////// // HCI VS Message Format // Messages are in the format: // // Outgoing ANT messages (host -> ANT chip) // 01 D1 FD XX YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 01 is the 1 byte HCI packet Identifier (HCI Command packet) // D1 FD is the 2 byte HCI op code (0xFDD1 stored in little endian) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // // Incoming HCI Command Complete for ANT message command (host <- ANT chip) // 04 0E 04 01 D1 FD ZZ // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // 0E is the 1 byte HCI event (Command Complete) // 04 is the 1 byte Length of all parameters in bytes (there are 4 bytes) // 01 is the 1 byte Number of parameters in the packet (there is 1 parameter) // D1 FD is the 2 byte HCI Op code of the command (0xFDD1 stored in little endian) // ZZ is the 1 byte response to the command (0x00 - Command Successful // 0x1F - Returned if the receive message queue of the ANT chip is full, the command should be retried // Other - Any other non-zero response code indicates an error) // // Incoming ANT messages (host <- ANT chip) // 04 FF XX 00 05 YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // FF is the 1 byte HCI event code (0xFF Vendor Specific event) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // 00 05 is the 2 byte vendor specific event code for ANT messages (0x0500 stored in little endian) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // ///////////////////////////////////////////////////////////////////////////// public static final byte MESG_SYNC_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a sync byte public static final byte MESG_SIZE_SIZE =((byte)1); public static final byte MESG_ID_SIZE =((byte)1); public static final byte MESG_CHANNEL_NUM_SIZE =((byte)1); public static final byte MESG_EXT_MESG_BF_SIZE =((byte)1); // NOTE: this could increase in the future public static final byte MESG_CHECKSUM_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a checksum public static final byte MESG_DATA_SIZE =((byte)9); // The largest serial message is an ANT data message with all of the extended fields public static final byte MESG_ANT_MAX_PAYLOAD_SIZE =AntDefine.ANT_STANDARD_DATA_PAYLOAD_SIZE; public static final byte MESG_MAX_EXT_DATA_SIZE =(AntDefine.ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE + AntDefine.ANT_EXT_STRING_SIZE); // ANT device ID (4 bytes) + Padding for ANT EXT string size(19 bytes) public static final byte MESG_MAX_DATA_SIZE =(MESG_ANT_MAX_PAYLOAD_SIZE + MESG_EXT_MESG_BF_SIZE + MESG_MAX_EXT_DATA_SIZE); // ANT data payload (8 bytes) + extended bitfield (1 byte) + extended data (10 bytes) public static final byte MESG_MAX_SIZE_VALUE =(MESG_MAX_DATA_SIZE + MESG_CHANNEL_NUM_SIZE); // this is the maximum value that the serial message size value is allowed to be public static final byte MESG_BUFFER_SIZE =(MESG_SIZE_SIZE + MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_FRAMED_SIZE =(MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE); public static final byte MESG_HEADER_SIZE =(MESG_SYNC_SIZE + MESG_SIZE_SIZE + MESG_ID_SIZE); public static final byte MESG_FRAME_SIZE =(MESG_HEADER_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_MAX_SIZE =(MESG_MAX_DATA_SIZE + MESG_FRAME_SIZE); public static final byte MESG_SIZE_OFFSET =(MESG_SYNC_SIZE); public static final byte MESG_ID_OFFSET =(MESG_SYNC_SIZE + MESG_SIZE_SIZE); public static final byte MESG_DATA_OFFSET =(MESG_HEADER_SIZE); public static final byte MESG_RECOMMENDED_BUFFER_SIZE =((byte) 64); // This is the recommended size for serial message buffers if there are no RAM restrictions on the system ////////////////////////////////////////////// // Message ID's ////////////////////////////////////////////// public static final byte MESG_INVALID_ID =((byte)0x00); public static final byte MESG_EVENT_ID =((byte)0x01); public static final byte MESG_VERSION_ID =((byte)0x3E); public static final byte MESG_RESPONSE_EVENT_ID =((byte)0x40); public static final byte MESG_UNASSIGN_CHANNEL_ID =((byte)0x41); public static final byte MESG_ASSIGN_CHANNEL_ID =((byte)0x42); public static final byte MESG_CHANNEL_MESG_PERIOD_ID =((byte)0x43); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_ID =((byte)0x44); public static final byte MESG_CHANNEL_RADIO_FREQ_ID =((byte)0x45); public static final byte MESG_NETWORK_KEY_ID =((byte)0x46); public static final byte MESG_RADIO_TX_POWER_ID =((byte)0x47); public static final byte MESG_RADIO_CW_MODE_ID =((byte)0x48); public static final byte MESG_SYSTEM_RESET_ID =((byte)0x4A); public static final byte MESG_OPEN_CHANNEL_ID =((byte)0x4B); public static final byte MESG_CLOSE_CHANNEL_ID =((byte)0x4C); public static final byte MESG_REQUEST_ID =((byte)0x4D); public static final byte MESG_BROADCAST_DATA_ID =((byte)0x4E); public static final byte MESG_ACKNOWLEDGED_DATA_ID =((byte)0x4F); public static final byte MESG_BURST_DATA_ID =((byte)0x50); public static final byte MESG_CHANNEL_ID_ID =((byte)0x51); public static final byte MESG_CHANNEL_STATUS_ID =((byte)0x52); public static final byte MESG_RADIO_CW_INIT_ID =((byte)0x53); public static final byte MESG_CAPABILITIES_ID =((byte)0x54); public static final byte MESG_STACKLIMIT_ID =((byte)0x55); public static final byte MESG_SCRIPT_DATA_ID =((byte)0x56); public static final byte MESG_SCRIPT_CMD_ID =((byte)0x57); public static final byte MESG_ID_LIST_ADD_ID =((byte)0x59); public static final byte MESG_ID_LIST_CONFIG_ID =((byte)0x5A); public static final byte MESG_OPEN_RX_SCAN_ID =((byte)0x5B); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_ID =((byte)0x5C); // OBSOLETE: (for 905 radio) public static final byte MESG_EXT_BROADCAST_DATA_ID =((byte)0x5D); public static final byte MESG_EXT_ACKNOWLEDGED_DATA_ID =((byte)0x5E); public static final byte MESG_EXT_BURST_DATA_ID =((byte)0x5F); public static final byte MESG_CHANNEL_RADIO_TX_POWER_ID =((byte)0x60); public static final byte MESG_GET_SERIAL_NUM_ID =((byte)0x61); public static final byte MESG_GET_TEMP_CAL_ID =((byte)0x62); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_ID =((byte)0x63); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_ID =((byte)0x64); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_ID =((byte)0x65); public static final byte MESG_RX_EXT_MESGS_ENABLE_ID =((byte)0x66); public static final byte MESG_RADIO_CONFIG_ALWAYS_ID =((byte)0x67); public static final byte MESG_ENABLE_LED_FLASH_ID =((byte)0x68); public static final byte MESG_XTAL_ENABLE_ID =((byte)0x6D); public static final byte MESG_STARTUP_MESG_ID =((byte)0x6F); public static final byte MESG_AUTO_FREQ_CONFIG_ID =((byte)0x70); public static final byte MESG_PROX_SEARCH_CONFIG_ID =((byte)0x71); public static final byte MESG_EVENT_BUFFERING_CONFIG_ID =((byte)0x74); public static final byte MESG_CUBE_CMD_ID =((byte)0x80); public static final byte MESG_GET_PIN_DIODE_CONTROL_ID =((byte)0x8D); public static final byte MESG_PIN_DIODE_CONTROL_ID =((byte)0x8E); public static final byte MESG_FIT1_SET_AGC_ID =((byte)0x8F); public static final byte MESG_FIT1_SET_EQUIP_STATE_ID =((byte)0x91); // *** CONFLICT: w/ Sensrcore, Fit1 will never have sensrcore enabled // Sensrcore Messages public static final byte MESG_SET_CHANNEL_INPUT_MASK_ID =((byte)0x90); public static final byte MESG_SET_CHANNEL_DATA_TYPE_ID =((byte)0x91); public static final byte MESG_READ_PINS_FOR_SECT_ID =((byte)0x92); public static final byte MESG_TIMER_SELECT_ID =((byte)0x93); public static final byte MESG_ATOD_SETTINGS_ID =((byte)0x94); public static final byte MESG_SET_SHARED_ADDRESS_ID =((byte)0x95); public static final byte MESG_ATOD_EXTERNAL_ENABLE_ID =((byte)0x96); public static final byte MESG_ATOD_PIN_SETUP_ID =((byte)0x97); public static final byte MESG_SETUP_ALARM_ID =((byte)0x98); public static final byte MESG_ALARM_VARIABLE_MODIFY_TEST_ID =((byte)0x99); public static final byte MESG_PARTIAL_RESET_ID =((byte)0x9A); public static final byte MESG_OVERWRITE_TEMP_CAL_ID =((byte)0x9B); public static final byte MESG_SERIAL_PASSTHRU_SETTINGS_ID =((byte)0x9C); public static final byte MESG_BIST_ID =((byte)0xAA); public static final byte MESG_UNLOCK_INTERFACE_ID =((byte)0xAD); public static final byte MESG_SERIAL_ERROR_ID =((byte)0xAE); public static final byte MESG_SET_ID_STRING_ID =((byte)0xAF); public static final byte MESG_PORT_GET_IO_STATE_ID =((byte)0xB4); public static final byte MESG_PORT_SET_IO_STATE_ID =((byte)0xB5); public static final byte MESG_SLEEP_ID =((byte)0xC5); public static final byte MESG_GET_GRMN_ESN_ID =((byte)0xC6); public static final byte MESG_SET_USB_INFO_ID =((byte)0xC7); public static final byte MESG_COMMAND_COMPLETE_RESPONSE_ID =((byte)0xC8); ////////////////////////////////////////////// // Command complete results ////////////////////////////////////////////// public static final byte MESG_COMMAND_COMPLETE_SUCCESS =((byte)0x00); public static final byte MESG_COMMAND_COMPLETE_RETRY =((byte)0x1F); ////////////////////////////////////////////// // Message Sizes ////////////////////////////////////////////// public static final byte MESG_INVALID_SIZE =((byte)0); public static final byte MESG_VERSION_SIZE =((byte)13); public static final byte MESG_RESPONSE_EVENT_SIZE =((byte)3); public static final byte MESG_CHANNEL_STATUS_SIZE =((byte)2); public static final byte MESG_UNASSIGN_CHANNEL_SIZE =((byte)1); public static final byte MESG_ASSIGN_CHANNEL_SIZE =((byte)3); public static final byte MESG_CHANNEL_ID_SIZE =((byte)5); public static final byte MESG_CHANNEL_MESG_PERIOD_SIZE =((byte)3); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_FREQ_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_NETWORK_KEY_SIZE =((byte)9); public static final byte MESG_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_RADIO_CW_MODE_SIZE =((byte)3); public static final byte MESG_RADIO_CW_INIT_SIZE =((byte)1); public static final byte MESG_SYSTEM_RESET_SIZE =((byte)1); public static final byte MESG_OPEN_CHANNEL_SIZE =((byte)1); public static final byte MESG_CLOSE_CHANNEL_SIZE =((byte)1); public static final byte MESG_REQUEST_SIZE =((byte)2); public static final byte MESG_CAPABILITIES_SIZE =((byte)6); public static final byte MESG_STACKLIMIT_SIZE =((byte)2); public static final byte MESG_SCRIPT_DATA_SIZE =((byte)10); public static final byte MESG_SCRIPT_CMD_SIZE =((byte)3); public static final byte MESG_ID_LIST_ADD_SIZE =((byte)6); public static final byte MESG_ID_LIST_CONFIG_SIZE =((byte)3); public static final byte MESG_OPEN_RX_SCAN_SIZE =((byte)1); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_SIZE =((byte)3); public static final byte MESG_RADIO_CONFIG_ALWAYS_SIZE =((byte)2); public static final byte MESG_RX_EXT_MESGS_ENABLE_SIZE =((byte)2); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_SIZE =((byte)2); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_SIZE =((byte)3); public static final byte MESG_ENABLE_LED_FLASH_SIZE =((byte)2); public static final byte MESG_GET_SERIAL_NUM_SIZE =((byte)4); public static final byte MESG_GET_TEMP_CAL_SIZE =((byte)4); public static final byte MESG_XTAL_ENABLE_SIZE =((byte)1); public static final byte MESG_STARTUP_MESG_SIZE =((byte)1); public static final byte MESG_AUTO_FREQ_CONFIG_SIZE =((byte)4); public static final byte MESG_PROX_SEARCH_CONFIG_SIZE =((byte)2); public static final byte MESG_GET_PIN_DIODE_CONTROL_SIZE =((byte)1); public static final byte MESG_PIN_DIODE_CONTROL_ID_SIZE =((byte)2); public static final byte MESG_FIT1_SET_EQUIP_STATE_SIZE =((byte)2); public static final byte MESG_FIT1_SET_AGC_SIZE =((byte)3); public static final byte MESG_BIST_SIZE =((byte)6); public static final byte MESG_UNLOCK_INTERFACE_SIZE =((byte)1); public static final byte MESG_SET_SHARED_ADDRESS_SIZE =((byte)3); public static final byte MESG_GET_GRMN_ESN_SIZE =((byte)5); public static final byte MESG_PORT_SET_IO_STATE_SIZE =((byte)5); public static final byte MESG_EVENT_BUFFERING_CONFIG_SIZE =((byte)6); public static final byte MESG_SLEEP_SIZE =((byte)1); public static final byte MESG_EXT_DATA_SIZE =((byte)13); protected AntMesg() { } }
Java
/* * Copyright 2010 Dynastream Innovations 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.dsi.ant; /** * Manages the ANT Interface * * @hide */ public interface AntInterfaceIntent { public static final String STATUS = "com.dsi.ant.rx.intent.STATUS"; public static final String ANT_MESSAGE = "com.dsi.ant.intent.ANT_MESSAGE"; public static final String ANT_INTERFACE_CLAIMED_PID = "com.dsi.ant.intent.ANT_INTERFACE_CLAIMED_PID"; public static final String ANT_ENABLED_ACTION = "com.dsi.ant.intent.action.ANT_ENABLED"; public static final String ANT_DISABLED_ACTION = "com.dsi.ant.intent.action.ANT_DISABLED"; public static final String ANT_RESET_ACTION = "com.dsi.ant.intent.action.ANT_RESET"; public static final String ANT_INTERFACE_CLAIMED_ACTION = "com.dsi.ant.intent.action.ANT_INTERFACE_CLAIMED_ACTION"; public static final String ANT_RX_MESSAGE_ACTION = "com.dsi.ant.intent.action.ANT_RX_MESSAGE_ACTION"; }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * Activity which shows the list of waypoints in a track. * * @author Leif Hendrik Wilden */ public class MyTracksWaypointsList extends ListActivity implements View.OnClickListener { private int contextPosition = -1; private long trackId = -1; private long waypointId = -1; private ListView listView = null; private Button insertWaypointButton = null; private Button insertStatisticsButton = null; private long recordingTrackId = -1; private long selectedTrackId = -1; private MyTracksProviderUtils providerUtils; private Cursor waypointsCursor = null; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.waypointslist_this_waypoint); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; waypointId = MyTracksWaypointsList.this.listView.getAdapter() .getItemId(contextPosition); int type = providerUtils.getWaypoint(info.id).getType(); menu.add(0, MyTracksConstants.MENU_SHOW, 0, R.string.waypointslist_show_waypoint); menu.add(0, MyTracksConstants.MENU_EDIT, 0, R.string.waypointslist_edit_waypoint); menu.add(0, MyTracksConstants.MENU_DELETE, 0, R.string.waypointslist_delete_waypoint).setEnabled( recordingTrackId < 0 || type == Waypoint.TYPE_WAYPOINT || info.id != providerUtils.getLastWaypointId(recordingTrackId)); } }; @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent result = new Intent(); result.putExtra("trackid", trackId); result.putExtra(MyTracksWaypointDetails.WAYPOINT_ID_EXTRA, id); setResult(MyTracksConstants.EDIT_WAYPOINT, result); finish(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (!super.onMenuItemSelected(featureId, item)) { switch (item.getItemId()) { case MyTracksConstants.MENU_SHOW: { onListItemClick(null, null, 0, waypointId); return true; } case MyTracksConstants.MENU_EDIT: { Intent intent = new Intent(this, MyTracksWaypointDetails.class); intent.putExtra("trackid", trackId); intent.putExtra(MyTracksWaypointDetails.WAYPOINT_ID_EXTRA, waypointId); startActivity(intent); return true; } case MyTracksConstants.MENU_DELETE: { deleteWaypoint(waypointId); } } } return false; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_waypoints_list); listView = getListView(); listView.setOnCreateContextMenuListener(contextMenuListener); insertWaypointButton = (Button) findViewById(R.id.waypointslist_btn_insert_waypoint); insertWaypointButton.setOnClickListener(this); insertStatisticsButton = (Button) findViewById(R.id.waypointslist_btn_insert_statistics); insertStatisticsButton.setOnClickListener(this); SharedPreferences preferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (preferences != null) { recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); selectedTrackId = preferences.getLong(getString(R.string.selected_track_key), -1); } boolean selectedRecording = selectedTrackId > 0 && selectedTrackId == recordingTrackId; insertWaypointButton.setEnabled(selectedRecording); insertStatisticsButton.setEnabled(selectedRecording); if (getIntent() != null && getIntent().getExtras() != null) { trackId = getIntent().getExtras().getLong("trackid", -1); } else { trackId = -1; } final long firstWaypointId = providerUtils.getFirstWaypointId(trackId); waypointsCursor = getContentResolver().query( WaypointsColumns.CONTENT_URI, null, WaypointsColumns.TRACKID + "=" + trackId + " AND " + WaypointsColumns._ID + "!=" + firstWaypointId, null, null); startManagingCursor(waypointsCursor); setListAdapter(); } @Override public void onClick(View v) { WaypointCreationRequest request; switch (v.getId()) { case R.id.waypointslist_btn_insert_waypoint: request = WaypointCreationRequest.DEFAULT_MARKER; break; case R.id.waypointslist_btn_insert_statistics: request = WaypointCreationRequest.DEFAULT_STATISTICS; break; default: return; } long id; try { id = MyTracks.getInstance().insertWaypoint(request); } catch (RemoteException e) { Log.e(MyTracksConstants.TAG, "Cannot insert marker.", e); return; } catch (IllegalStateException e) { Log.e(MyTracksConstants.TAG, "Cannot insert marker.", e); return; } if (id < 0) { Log.e(MyTracksConstants.TAG, "Failed to insert marker."); return; } Intent intent = new Intent(this, MyTracksWaypointDetails.class); intent.putExtra(MyTracksWaypointDetails.WAYPOINT_ID_EXTRA, id); startActivity(intent); } private void setListAdapter() { // Get a cursor with all tracks SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.mytracks_marker_item, waypointsCursor, new String[] { WaypointsColumns.NAME, WaypointsColumns.TIME, WaypointsColumns.CATEGORY, WaypointsColumns.TYPE }, new int[] { R.id.waypointslist_item_name, R.id.waypointslist_item_time, R.id.waypointslist_item_category, R.id.waypointslist_item_icon }); final int timeIdx = waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TIME); final int typeIdx = waypointsCursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (columnIndex == timeIdx) { long time = cursor.getLong(timeIdx); TextView textView = (TextView) view; textView.setText(String.format("%tc", time)); textView.setVisibility( textView.getText().length() < 1 ? View.GONE : View.VISIBLE); } else if (columnIndex == typeIdx) { int type = cursor.getInt(typeIdx); ImageView imageView = (ImageView) view; imageView.setImageDrawable(getResources().getDrawable( type == Waypoint.TYPE_STATISTICS ? R.drawable.ylw_pushpin : R.drawable.blue_pushpin)); } else { TextView textView = (TextView) view; textView.setText(cursor.getString(columnIndex)); textView.setVisibility( textView.getText().length() < 1 ? View.GONE : View.VISIBLE); } return true; } }); setListAdapter(adapter); } /** * Deletes the way point with the given id. * Prompts the user if he want to really delete it. */ public void deleteWaypoint(final long waypointId) { AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.marker_will_be_permanently_deleted)); builder.setTitle(getString(R.string.are_you_sure_question)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); providerUtils.deleteWaypoint(waypointId, new StringUtils(MyTracksWaypointsList.this)); } }); builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.location.Location; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * A map overlay that displays a "MyLocation" arrow, an error circle, the * currently recording track and optionally a selected track. * * @author Leif Hendrik Wilden */ public class MyTracksOverlay extends Overlay { private final Drawable[] arrows; private final int arrowWidth, arrowHeight; private final Drawable statsMarker; private final Drawable waypointMarker; private final Drawable startMarker; private final Drawable endMarker; private final int markerWidth, markerHeight; private final Paint selectedTrackPaint; private final Paint errorCirclePaint; private final Context context; private final List<Waypoint> waypoints; private final List<CachedLocation> points; private final BlockingQueue<CachedLocation> pendingPoints; private boolean trackDrawingEnabled; private int lastHeading = 0; private Location myLocation; private boolean showEndMarker = true; // TODO: Remove it completely after completing performance tests. private boolean alwaysVisible = true; private GeoPoint lastReferencePoint; private Rect lastViewRect; private Path lastPath; /** * Represents a pre-processed {@code Location} to speed up drawing. * This class is more like a data object and doesn't provide accessors. */ private static class CachedLocation { public final boolean valid; public final GeoPoint geoPoint; public CachedLocation(Location location) { this.valid = MyTracksUtils.isValidLocation(location); this.geoPoint = valid ? MyTracksUtils.getGeoPoint(location) : null; } }; public MyTracksOverlay(Context context) { this.context = context; this.waypoints = new ArrayList<Waypoint>(); this.points = new ArrayList<CachedLocation>(1024); this.pendingPoints = new ArrayBlockingQueue<CachedLocation>( MyTracksConstants.MAX_DISPLAYED_TRACK_POINTS, true); // TODO: Can we use a FrameAnimation or similar here rather // than individual resources for each arrow direction? final Resources resources = context.getResources(); arrows = new Drawable[] { resources.getDrawable(R.drawable.arrow_0), resources.getDrawable(R.drawable.arrow_20), resources.getDrawable(R.drawable.arrow_40), resources.getDrawable(R.drawable.arrow_60), resources.getDrawable(R.drawable.arrow_80), resources.getDrawable(R.drawable.arrow_100), resources.getDrawable(R.drawable.arrow_120), resources.getDrawable(R.drawable.arrow_140), resources.getDrawable(R.drawable.arrow_160), resources.getDrawable(R.drawable.arrow_180), resources.getDrawable(R.drawable.arrow_200), resources.getDrawable(R.drawable.arrow_220), resources.getDrawable(R.drawable.arrow_240), resources.getDrawable(R.drawable.arrow_260), resources.getDrawable(R.drawable.arrow_280), resources.getDrawable(R.drawable.arrow_300), resources.getDrawable(R.drawable.arrow_320), resources.getDrawable(R.drawable.arrow_340) }; arrowWidth = arrows[lastHeading].getIntrinsicWidth(); arrowHeight = arrows[lastHeading].getIntrinsicHeight(); for (Drawable arrow : arrows) { arrow.setBounds(0, 0, arrowWidth, arrowHeight); } statsMarker = resources.getDrawable(R.drawable.ylw_pushpin); markerWidth = statsMarker.getIntrinsicWidth(); markerHeight = statsMarker.getIntrinsicHeight(); statsMarker.setBounds(0, 0, markerWidth, markerHeight); startMarker = resources.getDrawable(R.drawable.green_dot); startMarker.setBounds(0, 0, markerWidth, markerHeight); endMarker = resources.getDrawable(R.drawable.red_dot); endMarker.setBounds(0, 0, markerWidth, markerHeight); waypointMarker = resources.getDrawable(R.drawable.blue_pushpin); waypointMarker.setBounds(0, 0, markerWidth, markerHeight); selectedTrackPaint = new Paint(); selectedTrackPaint.setColor(resources.getColor(R.color.red)); selectedTrackPaint.setStrokeWidth(3); selectedTrackPaint.setStyle(Paint.Style.STROKE); selectedTrackPaint.setAntiAlias(true); errorCirclePaint = new Paint(); errorCirclePaint.setColor(resources.getColor(R.color.blue)); errorCirclePaint.setStyle(Paint.Style.STROKE); errorCirclePaint.setStrokeWidth(3); errorCirclePaint.setAlpha(127); errorCirclePaint.setAntiAlias(true); } /** * Add a location to the map overlay. * * NOTE: This method doesn't take ownership of the given location, so it is * safe to reuse the same location while calling this method. * * @param l the location to add. */ public void addLocation(Location l) { // Queue up in the pending queue until it's merged with {@code #points}. pendingPoints.offer(new CachedLocation(l)); } public void addWaypoint(Waypoint wpt) { // Note: We don't cache waypoints, because it's not worth the effort. if (wpt != null && wpt.getLocation() != null) { synchronized (waypoints) { waypoints.add(wpt); } } } public int getNumLocations() { synchronized (points) { return points.size() + pendingPoints.size(); } } // Visible for testing. int getNumWaypoints() { synchronized (waypoints) { return waypoints.size(); } } public void clearPoints() { synchronized (points) { points.clear(); pendingPoints.clear(); lastPath = null; lastViewRect = null; } } public void clearWaypoints() { synchronized (waypoints) { waypoints.clear(); } } public void setTrackDrawingEnabled(boolean trackDrawingEnabled) { this.trackDrawingEnabled = trackDrawingEnabled; } public void setShowEndMarker(boolean showEndMarker) { this.showEndMarker = showEndMarker; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) { return; } // It's safe to keep projection within a single draw operation. final Projection projection = getMapProjection(mapView); // Get the current viewing window. if (trackDrawingEnabled) { Rect viewRect = getMapViewRect(mapView); // Draw the selected track: drawTrack(canvas, projection, viewRect); // Draw the waypoints: drawWaypoints(canvas, projection); } // Draw the current location drawMyLocation(canvas, projection); } // Visible for testing. Projection getMapProjection(MapView mapView) { return mapView.getProjection(); } // Visible for testing. Rect getMapViewRect(MapView mapView) { int w = mapView.getLongitudeSpan(); int h = mapView.getLatitudeSpan(); int cx = mapView.getMapCenter().getLongitudeE6(); int cy = mapView.getMapCenter().getLatitudeE6(); return new Rect(cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2); } // Visible for testing. Path newPath() { return new Path(); } // Visible for testing. Path getLastPath() { return lastPath; } private void drawWaypoints(Canvas canvas, Projection projection) { synchronized (waypoints) {; for (Waypoint wpt : waypoints) { Location loc = wpt.getLocation(); drawElement(canvas, projection, MyTracksUtils.getGeoPoint(loc), wpt.getType() == Waypoint.TYPE_STATISTICS ? statsMarker : waypointMarker, -(markerWidth / 2) + 3, -markerHeight); } } } private void drawMyLocation(Canvas canvas, Projection projection) { // Draw the arrow icon. if (myLocation == null) { return; } Point pt = drawElement(canvas, projection, MyTracksUtils.getGeoPoint(myLocation), arrows[lastHeading], -(arrowWidth / 2) + 3, -(arrowHeight / 2)); // Draw the error circle. float radius = projection.metersToEquatorPixels(myLocation.getAccuracy()); canvas.drawCircle(pt.x, pt.y, radius, errorCirclePaint); } private void drawTrack(Canvas canvas, Projection projection, Rect viewRect) { Path path; synchronized (points) { // Merge the pending points with the list of cached locations. final GeoPoint referencePoint = projection.fromPixels(0, 0); int newPoints = pendingPoints.drainTo(points); boolean newProjection = !viewRect.equals(lastViewRect) || !referencePoint.equals(lastReferencePoint); if (newPoints == 0 && lastPath != null && !newProjection) { // No need to recreate path (same points and viewing area). path = lastPath; } else { int numPoints = points.size(); if (numPoints < 2) { // Not enough points to draw a path. path = null; } else if (lastPath != null && !newProjection) { // Incremental update of the path, without repositioning the view. path = lastPath; updatePath(projection, viewRect, path, numPoints - newPoints); } else { // The view has changed so we have to start from scratch. path = newPath(); path.incReserve(numPoints); updatePath(projection, viewRect, path, 0); } lastPath = path; } lastReferencePoint = referencePoint; lastViewRect = viewRect; } if (path != null) { canvas.drawPath(path, selectedTrackPaint); } // Draw the "End" marker. if (showEndMarker) { for (int i = points.size() - 1; i >= 0; --i) { if (points.get(i).valid) { drawElement(canvas, projection, points.get(i).geoPoint, endMarker, -markerWidth / 2, -markerHeight); break; } } } // Draw the "Start" marker. for (int i = 0; i < points.size(); ++i) { if (points.get(i).valid) { drawElement(canvas, projection, points.get(i).geoPoint, startMarker, -markerWidth / 2, -markerHeight); break; } } } private void updatePath(Projection projection, Rect viewRect, Path path, int startLocationIdx) { // Whether to start a new segment on new valid and visible point. boolean newSegment = startLocationIdx > 0 ? !points.get(startLocationIdx - 1).valid : true; boolean lastVisible = !newSegment; final Point pt = new Point(); // Loop over track points. for (int i = startLocationIdx; i < points.size(); ++i) { CachedLocation loc = points.get(i); // Check if valid, if not then indicate a new segment. if (!loc.valid) { newSegment = true; continue; } final GeoPoint geoPoint = loc.geoPoint; // Check if this breaks the existing segment. boolean visible = alwaysVisible || viewRect.contains( geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6()); if (!visible && !lastVisible) { // This is a point outside view not connected to a visible one. newSegment = true; } lastVisible = visible; // Either move to beginning of a new segment or continue the old one. projection.toPixels(geoPoint, pt); if (newSegment) { path.moveTo(pt.x, pt.y); newSegment = false; } else { path.lineTo(pt.x, pt.y); } } } // Visible for testing. Point drawElement(Canvas canvas, Projection projection, GeoPoint geoPoint, Drawable element, int offsetX, int offsetY) { Point pt = new Point(); projection.toPixels(geoPoint, pt); canvas.save(); canvas.translate(pt.x + offsetX, pt.y + offsetY); element.draw(canvas); canvas.restore(); return pt; } /** * Sets the pointer location (will be drawn on next invalidate). */ public void setMyLocation(Location myLocation) { this.myLocation = myLocation; } /** * Sets the pointer heading in degrees (will be drawn on next invalidate). * * @return true if the visible heading changed (i.e. a redraw of pointer is * potentially necessary) */ public boolean setHeading(float heading) { int newhdg = Math.round(-heading / 360 * 18 + 180); while (newhdg < 0) newhdg += 18; while (newhdg > 17) newhdg -= 18; if (newhdg != lastHeading) { lastHeading = newhdg; return true; } else { return false; } } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (p.equals(mapView.getMapCenter())) { // There is (unfortunately) no good way to determine whether the tap was // caused by an actual tap on the screen or the track ball. If the // location is equal to the map center,then it was a track ball press with // very high likelihood. return false; } final Location tapLocation = MyTracksUtils.getLocation(p); double dmin = Double.MAX_VALUE; Waypoint waypoint = null; synchronized (waypoints) { for (int i = 0; i < waypoints.size(); i++) { final Location waypointLocation = waypoints.get(i).getLocation(); if (waypointLocation == null) { continue; } final double d = waypointLocation.distanceTo(tapLocation); if (d < dmin) { dmin = d; waypoint = waypoints.get(i); } } } if (waypoint != null && dmin < 15000000 / Math.pow(2, mapView.getZoomLevel())) { Intent intent = new Intent(context, MyTracksWaypointDetails.class); intent.putExtra("waypointid", waypoint.getId()); context.startActivity(intent); return true; } return super.onTap(p, mapView); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.LinearLayout; import android.widget.ZoomControls; import java.util.ArrayList; /** * An activity that displays a chart from the track point provider. * * @author Sandor Dornbush */ public class ChartActivity extends Activity implements SharedPreferences.OnSharedPreferenceChangeListener { private final static int BUFFER_SIZE = 1024; private double profileLength = 0; private boolean metricUnits = true; private boolean reportSpeed = true; /** * The track id that is displayed. */ private long selectedTrackId = -1; /** * Id of the last location that was seen when reading tracks from the * provider. This is used to determine which locations are new compared to the * last time the chart was updated. */ private long lastSeenLocationId = -1; private long startTime = -1; private Location lastLocation; /** * The id of the track currently being recorded. */ private long recordingTrackId = -1; private final DoubleBuffer elevationBuffer = new DoubleBuffer(MyTracksConstants.ELEVATION_SMOOTHING_FACTOR); private final DoubleBuffer speedBuffer = new DoubleBuffer(MyTracksConstants.SPEED_SMOOTHING_FACTOR); private Mode mode = Mode.BY_DISTANCE; /** * Utilities to deal with the database. */ private MyTracksProviderUtils providerUtils; /* * UI elements: */ private ChartView chartView; private MenuItem chartSettingsMenuItem; private LinearLayout busyPane; private ZoomControls zoomControls; /** Handler for callbacks to the UI thread */ private final Handler uiHandler = new Handler(); /** * A runnable that can be posted to the UI thread. It will remove the spinner * (if any), enable/disable zoom controls and orange pointer as appropriate * and redraw. */ private final Runnable updateChart = new Runnable() { @Override public void run() { busyPane.setVisibility(View.GONE); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); chartView.setShowPointer(selectedTrackIsRecording()); chartView.invalidate(); } }; /** * A runnable that can be posted to the UI thread. It will show the spinner. */ private final Runnable showSpinner = new Runnable() { @Override public void run() { busyPane.setVisibility(View.VISIBLE); } }; /** * An observer for the tracks provider. Will listen to new track points being * added and update the chart if necessary. */ private ContentObserver observer; /** * An observer for the waypoints provider. Will listen to new way points being * added and update the chart if necessary. */ private ContentObserver waypointObserver; /** * A thread with a looper. Post to updateTrackHandler to execute Runnables on * this thread. */ private final HandlerThread updateTrackThread = new HandlerThread("updateTrackThread"); /** Handler for updateTrackThread */ private Handler updateTrackHandler; /** * A runnable that updates the profile from the provider. */ private final Runnable updateTrackRunnable = new Runnable() { @Override public void run() { readNewTrackPoints(); } }; @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key != null) { if (key.equals(getString(R.string.selected_track_key))) { selectedTrackId = sharedPreferences.getLong(getString(R.string.selected_track_key), -1); readProfileAsync(); } else if (key.equals(getString(R.string.metric_units_key))) { metricUnits = sharedPreferences.getBoolean(getString(R.string.metric_units_key), true); chartView.setMetricUnits(metricUnits); readProfileAsync(); } else if (key.equals(getString(R.string.report_speed_key))) { reportSpeed = sharedPreferences.getBoolean(getString(R.string.report_speed_key), true); chartView.setReportSpeed(reportSpeed, this); readProfileAsync(); } else if (key.equals(getString(R.string.recording_track_key))) { recordingTrackId = sharedPreferences.getLong(getString(R.string.recording_track_key), -1); runOnUiThread(updateChart); } } } @Override protected void onCreate(Bundle savedInstanceState) { Log.w(MyTracksConstants.TAG, "ChartActivity.onCreate"); super.onCreate(savedInstanceState); MyTracks.getInstance().setChartActivity(this); providerUtils = MyTracksProviderUtils.Factory.get(this); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_charts); ViewGroup layout = (ViewGroup) findViewById(R.id.elevation_chart); chartView = new ChartView(this); chartView.setMode(this.mode); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.addView(chartView, params); SharedPreferences preferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (preferences != null) { selectedTrackId = preferences.getLong(getString(R.string.selected_track_key), -1); recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true); chartView.setMetricUnits(metricUnits); reportSpeed = preferences.getBoolean(getString(R.string.report_speed_key), true); chartView.setReportSpeed(reportSpeed, this); preferences.registerOnSharedPreferenceChangeListener(this); } busyPane = (LinearLayout) findViewById(R.id.elevation_busypane); zoomControls = (ZoomControls) findViewById(R.id.elevation_zoom); zoomControls.setOnZoomInClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomIn(); } }); zoomControls.setOnZoomOutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { zoomOut(); } }); updateTrackThread.start(); updateTrackHandler = new Handler(updateTrackThread.getLooper()); // Register observer for the track point provider: Handler contentHandler = new Handler(); observer = new ContentObserver(contentHandler) { @Override public void onChange(boolean selfChange) { Log.d(MyTracksConstants.TAG, "ChartActivity: ContentObserver.onChange"); // Check for any new locations and append them to the currently // recording track. if (recordingTrackId < 0) { // No track is being recorded. We should not be here. return; } if (selectedTrackId != recordingTrackId) { // No track, or one other than the recording track is selected, don't // bother. return; } // Update can potentially be lengthy, put it in its own thread: updateTrackHandler.post(updateTrackRunnable); super.onChange(selfChange); } }; waypointObserver = new ContentObserver(contentHandler) { @Override public void onChange(boolean selfChange) { Log.d(MyTracksConstants.TAG, "MyTracksMap: ContentObserver.onChange waypoints"); if (selectedTrackId < 0) { return; } Thread t = new Thread() { @Override public void run() { readWaypoints(); ChartActivity.this.runOnUiThread(new Runnable() { @Override public void run() { chartView.invalidate(); } }); } }; t.start(); super.onChange(selfChange); } }; readProfileAsync(); } @Override protected void onPause() { super.onPause(); unregisterContentObservers(); } @Override protected void onResume() { super.onResume(); // Make sure any updates that might have happened are propagated to this // activity: observer.onChange(false); waypointObserver.onChange(false); registerContentObservers(); } /** * Register the content observer for the map overlay. */ private void registerContentObservers() { getContentResolver().registerContentObserver(TrackPointsColumns.CONTENT_URI, false/* notifyForDescendents */, observer); getContentResolver().registerContentObserver(WaypointsColumns.CONTENT_URI, false/* notifyForDescendents */, waypointObserver); } /** * Unregister the content observer for the map overlay. */ private void unregisterContentObservers() { getContentResolver().unregisterContentObserver(observer); getContentResolver().unregisterContentObserver(waypointObserver); } private boolean selectedTrackIsRecording() { return selectedTrackId == recordingTrackId; } private void zoomIn() { chartView.zoomIn(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } private void zoomOut() { chartView.zoomOut(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } public void setMode(Mode newMode) { if (this.mode != newMode) { this.mode = newMode; chartView.setMode(this.mode); readProfileAsync(); } } public Mode getMode() { return mode; } public void setSeriesEnabled(int index, boolean enabled) { chartView.getChartValueSeries(index).setEnabled(enabled); runOnUiThread(updateChart); } public boolean isSeriesEnabled(int index) { return chartView.getChartValueSeries(index).isEnabled(); } private void readWaypoints() { if (selectedTrackId < 0) { return; } Cursor cursor = null; chartView.clearWaypoints(); try { // We will silently drop extra waypoints to make the app responsive. cursor = providerUtils.getWaypointsCursor(selectedTrackId, 0, MyTracksConstants.MAX_DISPLAYED_TRACK_POINTS); if (cursor != null) { if (cursor.moveToFirst()) { do { Waypoint wpt = providerUtils.createWaypoint(cursor); chartView.addWaypoint(wpt); } while (cursor.moveToNext()); } } } catch (RuntimeException e) { Log.w(MyTracksConstants.TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); chartSettingsMenuItem = menu.add(0, MyTracksConstants.MENU_CHART_SETTINGS, 0, R.string.chart_settings); chartSettingsMenuItem.setIcon(R.drawable.chart_settings); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MyTracksConstants.MENU_CHART_SETTINGS: MyTracks.getInstance().getDialogManager().showDialogSafely( DialogManager.DIALOG_CHART_SETTINGS); return true; } return super.onOptionsItemSelected(item); } /** * Given a location, creates a new data point for the chart. A data point is * an array double[3 or 6], where: * data[0] = the time or distance * data[1] = the elevation * data[2] = the speed * and possibly: * data[3] = power * data[4] = cadence * data[5] = heart rate * * This must be called in order for each point. * * @param location the location to get data for (this method takes ownership of that location) * @param track the track to get data from * @param result the resulting point to fill out * @return the previous location, now available for reuse */ private Location getDataPoint(Location location, Track track, double[] result) { if (location instanceof MyTracksLocation && ((MyTracksLocation) location).getSensorDataSet() != null) { SensorDataSet sensorData = ((MyTracksLocation) location).getSensorDataSet(); if (sensorData.hasPower() && sensorData.getPower().getState() == Sensor.SensorState.SENDING && sensorData.getPower().hasValue()) { result[3] = sensorData.getPower().getValue(); } else { result[3] = Double.NaN; } if (sensorData.hasCadence() && sensorData.getCadence().getState() == Sensor.SensorState.SENDING && sensorData.getCadence().hasValue()) { result[4] = sensorData.getCadence().getValue(); } else { result[4] = Double.NaN; } if (sensorData.hasHeartRate() && sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorData.getHeartRate().hasValue()) { result[5] = sensorData.getHeartRate().getValue(); } else { result[5] = Double.NaN; } } else { result[3] = Double.NaN; result[4] = Double.NaN; result[5] = Double.NaN; } switch (mode) { case BY_DISTANCE: result[0] = profileLength; if (lastLocation != null) { double d = lastLocation.distanceTo(location); if (metricUnits) { profileLength += d / 1000.0; } else { profileLength += d * UnitConversions.KM_TO_MI / 1000.0; } } break; case BY_TIME: if (startTime == -1) { // Base case startTime = location.getTime(); } result[0] = (location.getTime() - startTime); break; default: Log.w(MyTracksConstants.TAG, "ChartActivity unknown mode: " + mode); } elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); result[1] = elevationBuffer.getAverage(); if (lastLocation == null) { if (Math.abs(location.getSpeed() - 128) > 1) { speedBuffer.setNext(location.getSpeed()); } } else if (TripStatisticsBuilder.isValidSpeed( location.getTime(), location.getSpeed(), lastLocation.getTime(), lastLocation.getSpeed(), speedBuffer) && (location.getSpeed() <= track.getStatistics().getMaxSpeed())) { speedBuffer.setNext(location.getSpeed()); } result[2] = speedBuffer.getAverage() * 3.6; if (!metricUnits) { result[2] *= UnitConversions.KM_TO_MI; } if (!reportSpeed && (result[2] != 0)) { // Format as hours per unit result[2] = (60.0 / result[2]); } Location oldLastLocation = lastLocation; lastLocation = location; if (oldLastLocation == null) { // No previous location, but return a blank one for reuse return new MyTracksLocation(""); } return oldLastLocation; } /** * Sets the chart data points reading from the provider. This is non-blocking. */ private void readProfileAsync() { chartView.reset(); updateTrackHandler.post(new Runnable() { public void run() { runOnUiThread(showSpinner); readProfile(); readWaypoints(); runOnUiThread(updateChart); } }); } /** * Reads the track profile from the provider. This is a blocking function and * should not be run from the UI thread. */ private void readProfile() { profileLength = 0; lastLocation = null; startTime = -1; if (selectedTrackId < 0) { return; } Track track = providerUtils.getTrack(selectedTrackId); if (track == null) { return; } lastSeenLocationId = track.getStartId(); final ArrayList<double[]> theData = readPointsToList(track); runOnUiThread(new Runnable() { public void run() { chartView.setDataPoints(theData); } }); } /** * Read all new track points. */ private void readNewTrackPoints() { Log.i(MyTracksConstants.TAG, "MyTracks: Updating chart last seen: " + lastSeenLocationId); Track track = providerUtils.getTrack(recordingTrackId); if (track == null) { Log.w(MyTracksConstants.TAG, "MyTracks: track not found"); return; } chartView.addDataPoints(readPointsToList(track)); uiHandler.post(new Runnable() { public void run() { chartView.invalidate(); } }); Log.i(MyTracksConstants.TAG, "MyTracks: Updated chart last seen: " + lastSeenLocationId); } /** * Get the frequency at which points should be displayed. * Limit the number of chart readings. Ideally we would want around 1024. * @param track The track which will be displayed. * @return The inverse of the frequency of points to be displayed. */ private int getSamplingFrequency(Track track) { long totalLocations = track.getStopId() - track.getStartId(); return Math.max(1, (int) (totalLocations / 1024.0)); } private Cursor getLocationsCursor(long lastLocationRead) { return providerUtils.getLocationsCursor(selectedTrackId, lastLocationRead, BUFFER_SIZE, false); } /** * Read all of the points to a list. * @param track The track which will be displayed. * @return */ private ArrayList<double[]> readPointsToList(Track track) { Cursor cursor = null; long lastLocationRead = lastSeenLocationId; int points = 0; int chartSamplingFrequency = getSamplingFrequency(track); ArrayList<double[]> result = new ArrayList<double[]>(); // Need two locations so we can keep track of the last location. Location location = new MyTracksLocation(""); try { while (lastSeenLocationId < track.getStopId()) { cursor = getLocationsCursor(lastLocationRead); if (cursor != null) { elevationBuffer.reset(); speedBuffer.reset(); if (cursor.moveToFirst()) { final int idColumnIdx = cursor.getColumnIndexOrThrow(TrackPointsColumns._ID); while (cursor.moveToNext()) { points++; providerUtils.fillLocation(cursor, location); if (MyTracksUtils.isValidLocation(location)) { lastLocationRead = lastSeenLocationId = cursor.getLong(idColumnIdx); // TODO Can we be smarter about choosing 3 or 6 entries? double[] point = new double[6]; location = getDataPoint(location, track, point); if (points % chartSamplingFrequency == 0) { result.add(point); } } } } else { lastLocationRead += BUFFER_SIZE; } } else { lastLocationRead += BUFFER_SIZE; } cursor.close(); cursor = null; } return result; } finally { if (cursor != null) { cursor.close(); } } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.MenuItem; /** * Manage the application menus. * * @author Sandor Dornbush */ class MenuManager { private final MyTracks activity; public MenuManager(MyTracks activity) { this.activity = activity; } public boolean onCreateOptionsMenu(Menu menu) { activity.getMenuInflater().inflate(R.menu.main, menu); return true; } public void onPrepareOptionsMenu(Menu menu, boolean hasRecorded, boolean isRecording, boolean hasSelectedTrack) { menu.findItem(R.id.menu_list_tracks); menu.findItem(R.id.menu_list_markers) .setEnabled(hasRecorded && hasSelectedTrack); menu.findItem(R.id.menu_start_recording) .setEnabled(!isRecording) .setVisible(!isRecording); menu.findItem(R.id.menu_stop_recording) .setEnabled(isRecording) .setVisible(isRecording); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_start_recording: { activity.startRecording(); return true; } case R.id.menu_stop_recording: { activity.stopRecording(); return true; } case R.id.menu_list_tracks: { activity.startActivityForResult(new Intent(activity, MyTracksList.class), MyTracksConstants.SHOW_TRACK); return true; } case R.id.menu_list_markers: { Intent startIntent = new Intent(activity, MyTracksWaypointsList.class); startIntent.putExtra("trackid", activity.getSelectedTrackId()); activity.startActivityForResult(startIntent, MyTracksConstants.SHOW_WAYPOINT); return true; } case R.id.menu_sensor_state: { return startActivity(SensorStateActivity.class); } case R.id.menu_settings: { return startActivity(MyTracksSettings.class); } case R.id.menu_aggregated_stats: { return startActivity(AggregatedStatsActivity.class); } case R.id.menu_help: { return startActivity(WelcomeActivity.class); } case MyTracksConstants.MENU_CLEAR_MAP: { activity.setSelectedTrackId(-1); return true; } } return false; } private boolean startActivity(Class<? extends Activity> activityClass) { activity.startActivity(new Intent(activity, activityClass)); return true; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; /** * Interface that allows to set a progress dialog message and progress value * in percent. * * @author Leif Hendrik Wilden */ public interface ProgressIndicator { public void setProgressMessage(int resId); public void clearProgressMessage(); public void setProgressValue(int percent); }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksConstants; import android.util.Log; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * This class will periodically announce the user's trip statistics. * * @author Sandor Dornbush */ public class PeriodicTaskExecuter { private final PeriodicTask task; private final TrackRecordingService service; /** * A timer to schedule the announcements. * This is non-null if the task is in started (scheduled) state. */ private Timer timer; public PeriodicTaskExecuter(PeriodicTask task, TrackRecordingService service) { this.task = task; this.service = service; } /** * Schedules the task at the given interval. * * @param interval The interval in milliseconds */ public void scheduleTask(long interval) { // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (timer != null) { timer.cancel(); timer.purge(); } else { // First start, or we were previously shut down. task.start(); } timer = new Timer(); if (interval <= 0) { return; } long now = System.currentTimeMillis(); long next = service.getTripStatistics().getStartTime(); if (next < now) { next = now + interval - ((now - next) % interval); } Date start = new Date(next); Log.i(MyTracksConstants.TAG, task.getClass().getSimpleName() + " scheduled to start at " + start + " every " + interval + " milliseconds."); timer.scheduleAtFixedRate(new PeriodicTimerTask(), start, interval); } /** * Cleans up this object. */ public void shutdown() { Log.i(MyTracksConstants.TAG, task.getClass().getSimpleName() + " shutting down."); if (timer != null) { timer.cancel(); timer.purge(); timer = null; task.shutdown(); } } /** * The timer task to announce the trip status. */ private class PeriodicTimerTask extends TimerTask { @Override public void run() { task.run(service); } } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; /** * This is a simple location listener policy that will always dictate the same * polling interval. * * @author Sandor Dornbush */ public class AbsoluteLocationListenerPolicy implements LocationListenerPolicy { /** * The interval to request for gps signal. */ private final long interval; /** * @param interval The interval to request for gps signal */ public AbsoluteLocationListenerPolicy(final long interval) { this.interval = interval; } /** * @return The interval given in the constructor */ public long getDesiredPollingInterval() { return interval; } /** * Discards the idle time. */ public void updateIdleTime(long idleTime) { } /** * Returns the minimum distance between updates. * Get all updates to properly measure moving time. */ public int getMinDistance() { return 0; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.content.WaypointCreationRequest; /** * A simple task to insert statistics markers every n minutes. * @author Sandor Dornbush */ public class TimeSplitTask implements PeriodicTask { @Override public void run(TrackRecordingService service) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } @Override public void shutdown() { } @Override public void start() { } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.util.UnitConversions; import android.util.Log; /** * This class manages inserting time or distance splits. * * @author Sandor Dornbush */ public class SplitManager { /** * The frequency of splits. */ private int splitFrequency = 0; /** * The next distance when a split should be taken. */ private double nextSplitDistance = 0; /** * Splits executer. */ private PeriodicTaskExecuter splitExecuter = null; private boolean metricUnits; private final TrackRecordingService service; public SplitManager(TrackRecordingService service) { this.service = service; } /** * Restores the manager. */ public void restore() { if ((splitFrequency > 0) && (splitExecuter != null)) { splitExecuter.scheduleTask(splitFrequency * 60000); } calculateNextSplit(); } /** * Shuts down the manager. */ public void shutdown() { if (splitExecuter != null) { splitExecuter.shutdown(); } } /** * Calculates the next distance that a split should be inserted at. */ public void calculateNextSplit() { // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (splitFrequency >= 0) { nextSplitDistance = Double.MAX_VALUE; Log.d(MyTracksConstants.TAG, "SplitManager: Distance splits disabled."); return; } double dist = service.getTripStatistics().getTotalDistance() / 1000; if (!metricUnits) { dist *= UnitConversions.KM_TO_MI; } // The index will be negative since the frequency is negative. int index = (int) (dist / splitFrequency); index -= 1; nextSplitDistance = splitFrequency * index; Log.d(MyTracksConstants.TAG, "SplitManager: Next split distance: " + nextSplitDistance); } /** * Updates split manager with new trip statistics. */ public void updateSplits() { if (this.splitFrequency >= 0) { return; } // Convert the distance in meters to km or mi. double distance = service.getTripStatistics().getTotalDistance() / 1000.0; if (!metricUnits) { distance *= UnitConversions.KM_TO_MI; } if (distance > this.nextSplitDistance) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); calculateNextSplit(); } } /** * Sets the split frequency. * &lt; 0 Use the absolute value as a distance in the current measurement km * or mi * 0 Turn off splits * &gt; 0 Use the value as a time in minutes * @param splitFrequency The frequency in time or distance */ public void setSplitFrequency(int splitFrequency) { Log.d(MyTracksConstants.TAG, "setSplitFrequency: splitFrequency = " + splitFrequency); this.splitFrequency = splitFrequency; // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (splitFrequency < 1) { if (splitExecuter != null) { splitExecuter.shutdown(); splitExecuter = null; } } if (splitFrequency > 0) { if (splitExecuter == null) { TimeSplitTask splitter = new TimeSplitTask(); splitExecuter = new PeriodicTaskExecuter(splitter, service); } splitExecuter.scheduleTask(splitFrequency * 60000); } else { // For distance based splits. calculateNextSplit(); } } public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; calculateNextSplit(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import android.content.Context; import android.media.AudioManager; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.util.Log; import java.util.HashMap; /** * This class will periodically announce the user's trip statistics for Froyo and future handsets. * This class will request and release audio focus. * * @author Sandor Dornbush */ public class FroyoStatusAnnouncerTask extends StatusAnnouncerTask { private final static HashMap<String, String> SPEECH_PARAMS = new HashMap<String, String>(); static { SPEECH_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "not_used"); } private final AudioManager audioManager; private final OnUtteranceCompletedListener utteranceListener = new OnUtteranceCompletedListener() { @Override public void onUtteranceCompleted(String utteranceId) { if (audioManager != null) { Log.d(TAG, "FroyoStatusAnnouncerTask: Abandoning audio focus."); audioManager.abandonAudioFocus(null); } } }; public FroyoStatusAnnouncerTask(Context context) { super(context); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } @Override protected void onTtsInit(int status) { super.onTtsInit(status); if (status == TextToSpeech.SUCCESS) { tts.setOnUtteranceCompletedListener(utteranceListener); } } @Override protected void speakAnnouncment(String announcement) { int result = audioManager.requestAudioFocus(null, TextToSpeech.Engine.DEFAULT_STREAM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK); if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) { Log.w(TAG, "FroyoStatusAnnouncerTask: Request audio focus failed."); } // We don't care about the utterance id. // It is supplied here to force onUtteranceCompleted to be called. tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, SPEECH_PARAMS); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.maps.mytracks.R; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A class that manages reading the shared preferences for the service. * * @author Sandor Dornbush */ public class PreferenceManager implements OnSharedPreferenceChangeListener { private TrackRecordingService service; private SharedPreferences sharedPreferences; private final String announcementFrequencyKey; private final String autoResumeTrackCurrentRetryKey; private final String autoResumeTrackTimeoutKey; private final String maxRecordingDistanceKey; private final String metricUnitsKey; private final String minRecordingDistanceKey; private final String minRecordingIntervalKey; private final String minRequiredAccuracyKey; private final String recordingTrackKey; private final String splitFrequencyKey; public PreferenceManager(TrackRecordingService 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 = service.getString(R.string.announcement_frequency_key); autoResumeTrackCurrentRetryKey = service.getString(R.string.auto_resume_track_current_retry_key); autoResumeTrackTimeoutKey = service.getString(R.string.auto_resume_track_timeout_key); maxRecordingDistanceKey = service.getString(R.string.max_recording_distance_key); metricUnitsKey = service.getString(R.string.metric_units_key); minRecordingDistanceKey = service.getString(R.string.min_recording_distance_key); minRecordingIntervalKey = service.getString(R.string.min_recording_interval_key); minRequiredAccuracyKey = service.getString(R.string.min_required_accuracy_key); recordingTrackKey = service.getString(R.string.recording_track_key); splitFrequencyKey = service.getString(R.string.split_frequency_key); // Refresh all properties. onSharedPreferenceChanged(sharedPreferences, null); } /** * Notifies that preferences have changed. * Call this with key == null to update all preferences in one call. * * @param key the key that changed (may be null to update all preferences) */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (service == null) { Log.w(MyTracksConstants.TAG, "onSharedPreferenceChanged: a preference change (key = " + key + ") after a call to shutdown()"); return; } if (key == null || key.equals(minRecordingDistanceKey)) { service.setMinRecordingDistance( sharedPreferences.getInt( minRecordingDistanceKey, MyTracksSettings.DEFAULT_MIN_RECORDING_DISTANCE)); Log.d(MyTracksConstants.TAG, "TrackRecordingService: minRecordingDistance = " + service.getMinRecordingDistance()); } if (key == null || key.equals(maxRecordingDistanceKey)) { service.setMaxRecordingDistance(sharedPreferences.getInt( maxRecordingDistanceKey, MyTracksSettings.DEFAULT_MAX_RECORDING_DISTANCE)); } if (key == null || key.equals(minRecordingIntervalKey)) { int minRecordingInterval = sharedPreferences.getInt( minRecordingIntervalKey, MyTracksSettings.DEFAULT_MIN_RECORDING_INTERVAL); switch (minRecordingInterval) { case -2: // Battery Miser // min: 30 seconds // max: 5 minutes // minDist: 5 meters Choose battery life over moving time accuracy. service.setLocationListenerPolicy( new AdaptiveLocationListenerPolicy(30000, 300000, 5)); break; case -1: // High Accuracy // min: 1 second // max: 30 seconds // minDist: 0 meters get all updates to properly measure moving time. service.setLocationListenerPolicy( new AdaptiveLocationListenerPolicy(1000, 30000, 0)); break; default: service.setLocationListenerPolicy( new AbsoluteLocationListenerPolicy(minRecordingInterval * 1000)); } } if (key == null || key.equals(minRequiredAccuracyKey)) { service.setMinRequiredAccuracy(sharedPreferences.getInt( minRequiredAccuracyKey, MyTracksSettings.DEFAULT_MIN_REQUIRED_ACCURACY)); } if (key == null || key.equals(announcementFrequencyKey)) { service.setAnnouncementFrequency( sharedPreferences.getInt(announcementFrequencyKey, -1)); } if (key == null || key.equals(autoResumeTrackTimeoutKey)) { service.setAutoResumeTrackTimeout(sharedPreferences.getInt( autoResumeTrackTimeoutKey, MyTracksSettings.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT)); } if (key == null || key.equals(recordingTrackKey)) { long recordingTrackId = sharedPreferences.getLong(recordingTrackKey, -1); // Only read the id if it is valid. // Setting it to -1 should only happen in // TrackRecordingService.endCurrentTrack() if (recordingTrackId > 0) { service.setRecordingTrackId(recordingTrackId); } } if (key == null || key.equals(splitFrequencyKey)) { service.getSplitManager().setSplitFrequency( sharedPreferences.getInt(splitFrequencyKey, 0)); } if (key == null || key.equals(metricUnitsKey)) { service.getSplitManager().setMetricUnits( sharedPreferences.getBoolean(metricUnitsKey, true)); } } public void setAutoResumeTrackCurrentRetry(int retryAttempts) { sharedPreferences .edit() .putInt(autoResumeTrackCurrentRetryKey, retryAttempts) .commit(); } public void setRecordingTrack(long id) { sharedPreferences .edit() .putLong(recordingTrackKey, id) .commit(); } public void shutdown() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); service = null; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; /** * A LocationListenerPolicy that will change based on how long the user has been * stationary. * * This policy will dictate a policy based on a min, max and idle time. * The policy will dictate an interval bounded by min and max whic is half of * the idle time. * * @author Sandor Dornbush */ public class AdaptiveLocationListenerPolicy implements LocationListenerPolicy { /** * Smallest interval this policy will dictate, in milliseconds. */ private final long minInterval; /** * Largest interval this policy will dictate, in milliseconds. */ private final long maxInterval; private final int minDistance; /** * The time the user has been at the current location, in milliseconds. */ private long idleTime; /** * Creates a policy that will be bounded by the given min and max. * * @param min Smallest interval this policy will dictate, in milliseconds * @param max Largest interval this policy will dictate, in milliseconds */ public AdaptiveLocationListenerPolicy(long min, long max, int minDistance) { this.minInterval = min; this.maxInterval = max; this.minDistance = minDistance; } /** * @return An interval bounded by min and max which is half of the idle time */ public long getDesiredPollingInterval() { long desiredInterval = idleTime / 2; // Round to avoid setting the interval too often. desiredInterval = (desiredInterval / 1000) * 1000; return Math.max(Math.min(maxInterval, desiredInterval), minInterval); } public void updateIdleTime(long newIdleTime) { this.idleTime = newIdleTime; } /** * Returns the minimum distance between updates. */ public int getMinDistance() { return minDistance; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.util.ApiFeatures; import android.content.Context; import android.media.AudioManager; /** * Factory which wraps construction and setup of text-to-speech announcements in * an API-level-safe way. * * @author Rodrigo Damazio */ public class StatusAnnouncerFactory { private final boolean hasTts; public StatusAnnouncerFactory(ApiFeatures apiFeatures) { this.hasTts = apiFeatures.hasTextToSpeech(); } /** * Creates a periodic task which does voice announcements. * * @return the task, or null if announcements are not supported */ public PeriodicTask create(Context context) { if (hasTts) { if (ApiFeatures.getInstance().isAudioFocusSupported()) { return new FroyoStatusAnnouncerTask(context); } else { return new StatusAnnouncerTask(context); } } else { return null; } } /** * Returns the appropriate volume stream for controlling announcement * volume. */ public int getVolumeStream() { if (hasTts) { return StatusAnnouncerTask.getVolumeStream(); } else { return AudioManager.USE_DEFAULT_STREAM_TYPE; } } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; /** * This is an interface for classes that will manage the location listener policy. * Different policy options are: * Absolute * Addaptive * * @author Sandor Dornbush */ public interface LocationListenerPolicy { /** * Returns the polling time this policy would like at this time. * * @return The polling that this policy dictates */ public long getDesiredPollingInterval(); /** * Returns the minimum distance between updates. */ public int getMinDistance(); /** * Notifies the amount of time the user has been idle at their current * location. * * @param idleTime The time that the user has been idle at this spot */ public void updateIdleTime(long idleTime); }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import static com.google.android.apps.mytracks.MyTracksConstants.RESUME_TRACK_EXTRA_NAME; import com.google.android.apps.mytracks.MyTracks; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.services.sensors.SensorManager; import com.google.android.apps.mytracks.services.sensors.SensorManagerFactory; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.ApiPlatformAdapter; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A background service that registers a location listener and records track * points. Track points are saved to the MyTracksProvider. * * @author Leif Hendrik Wilden */ public class TrackRecordingService extends Service implements LocationListener { static final int MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS = 3; private NotificationManager notificationManager; private LocationManager locationManager; private WakeLock wakeLock; private int minRecordingDistance = MyTracksSettings.DEFAULT_MIN_RECORDING_DISTANCE; private int maxRecordingDistance = MyTracksSettings.DEFAULT_MAX_RECORDING_DISTANCE; private int minRequiredAccuracy = MyTracksSettings.DEFAULT_MIN_REQUIRED_ACCURACY; private int autoResumeTrackTimeout = MyTracksSettings.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT; private long recordingTrackId = -1; private long currentWaypointId = -1; /** The timer posts a runnable to the main thread via this handler. */ private final Handler handler = new Handler(); /** * Utilities to deal with the database. */ private MyTracksProviderUtils providerUtils; private TripStatisticsBuilder statsBuilder; private TripStatisticsBuilder waypointStatsBuilder; /** * Current length of the recorded track. This length is calculated from the * recorded points (as compared to each location fix). It's used to overlay * waypoints precisely in the elevation profile chart. */ private double length; /** * Status announcer executer. */ private PeriodicTaskExecuter announcementExecuter; private SplitManager splitManager; private SensorManager sensorManager; private PreferenceManager prefManager; /** * The interval in milliseconds that we have requested to be notified of gps * readings. */ private long currentRecordingInterval; /** * The policy used to decide how often we should request gps updates. */ private LocationListenerPolicy locationListenerPolicy = new AbsoluteLocationListenerPolicy(0); /** * Task invoked by a timer periodically to make sure the location listener is * still registered. */ private TimerTask checkLocationListener = new TimerTask() { @Override public void run() { // It's always safe to assume that if isRecording() is true, it implies // that onCreate() has finished. if (isRecording()) { handler.post(new Runnable() { public void run() { Log.d(MyTracksConstants.TAG, "Re-registering location listener with TrackRecordingService."); unregisterLocationListener(); registerLocationListener(); } }); } } }; /** * This timer invokes periodically the checkLocationListener timer task. */ private final Timer timer = new Timer(); /** * Is the phone currently moving? */ private boolean isMoving = true; /** * The most recent recording track. */ private Track recordingTrack; /** * Is the service currently recording a track? */ private boolean isRecording; /** * Last good location the service has received from the location listener */ private Location lastLocation; /** * Last valid location (i.e. not a marker) that was recorded. */ private Location lastValidLocation; /** * The frequency of status announcements. */ private int announcementFrequency = -1; private ExecutorService executerServce; /* * Utility functions */ /** * Inserts a new location in the track points db and updates the corresponding * track in the track db. * * @param recordingTrack the track that is currently being recorded * @param location the location to be inserted * @param lastRecordedLocation the last recorded location before this one (or * null if none) * @param lastRecordedLocationId the id of the last recorded location (or -1 * if none) * @param trackId the id of the track * @return true if successful. False if SQLite3 threw an exception. */ private boolean insertLocation(Track recordingTrack, Location location, Location lastRecordedLocation, long lastRecordedLocationId, long trackId) { // Keep track of length along recorded track (needed when a waypoint is // inserted): if (MyTracksUtils.isValidLocation(location)) { if (lastValidLocation != null) { length += location.distanceTo(lastValidLocation); } lastValidLocation = location; } // Insert the new location: try { Location locationToInsert = location; if (sensorManager != null && sensorManager.isEnabled()) { SensorDataSet sd = sensorManager.getSensorDataSet(); if (sd != null && sensorManager.isDataValid()) { locationToInsert = new MyTracksLocation(location, sd); } } Uri pointUri = providerUtils.insertTrackPoint(locationToInsert, trackId); int pointId = Integer.parseInt(pointUri.getLastPathSegment()); // Update the current track: if (lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90) { ContentValues values = new ContentValues(); TripStatistics stats = statsBuilder.getStatistics(); if (recordingTrack.getStartId() < 0) { values.put(TracksColumns.STARTID, pointId); recordingTrack.setStartId(pointId); } values.put(TracksColumns.STOPID, pointId); values.put(TracksColumns.STOPTIME, System.currentTimeMillis()); values.put(TracksColumns.NUMPOINTS, recordingTrack.getNumberOfPoints() + 1); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); getContentResolver().update(TracksColumns.CONTENT_URI, values, "_id=" + recordingTrack.getId(), null); updateCurrentWaypoint(); } } catch (SQLiteException e) { // Insert failed, most likely because of SqlLite error code 5 // (SQLite_BUSY). This is expected to happen extremely rarely (if our // listener gets invoked twice at about the same time). Log.w(MyTracksConstants.TAG, "Caught SQLiteException: " + e.getMessage(), e); return false; } splitManager.updateSplits(); return true; } private void updateCurrentWaypoint() { if (currentWaypointId >= 0) { ContentValues values = new ContentValues(); TripStatistics waypointStats = waypointStatsBuilder.getStatistics(); values.put(WaypointsColumns.STARTTIME, waypointStats.getStartTime()); values.put(WaypointsColumns.LENGTH, length); values.put(WaypointsColumns.DURATION, System.currentTimeMillis() - statsBuilder.getStatistics().getStartTime()); values.put(WaypointsColumns.TOTALDISTANCE, waypointStats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, waypointStats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, waypointStats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, waypointStats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, waypointStats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, waypointStats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, waypointStats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, waypointStats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, waypointStats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, waypointStats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, waypointStats.getMaxGrade()); getContentResolver().update(WaypointsColumns.CONTENT_URI, values, "_id=" + currentWaypointId, null); } } /** * 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. */ private void acquireWakeLock() { try { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if (pm == null) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Power manager not found!"); return; } if (wakeLock == null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MyTracksConstants.TAG); if (wakeLock == null) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Could not create wake lock (null)."); return; } } if (!wakeLock.isHeld()) { wakeLock.acquire(); if (!wakeLock.isHeld()) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Could not acquire wake lock."); } } } catch (RuntimeException e) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Caught unexpected exception: " + e.getMessage(), e); } } /** * 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. */ public void showNotification() { final ApiPlatformAdapter apiPlatformAdapter = ApiFeatures.getInstance().getApiPlatformAdapter(); if (isRecording) { Notification notification = new Notification( R.drawable.arrow_320, null /* tickerText */, System.currentTimeMillis()); PendingIntent contentIntent = PendingIntent.getActivity( this, 0 /* requestCode */, new Intent(this, MyTracks.class), 0 /* flags */); notification.setLatestEventInfo(this, getString(R.string.app_name), getString(R.string.recording_your_track), contentIntent); notification.flags += Notification.FLAG_NO_CLEAR; apiPlatformAdapter.startForeground(this, notificationManager, 1, notification); } else { apiPlatformAdapter.stopForeground(this, notificationManager, 1); } } public void registerLocationListener() { if (locationManager == null) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Do not have any location manager."); return; } Log.d(MyTracksConstants.TAG, "Preparing to register location listener w/ TrackRecordingService..."); try { long desiredInterval = locationListenerPolicy.getDesiredPollingInterval(); locationManager.requestLocationUpdates( MyTracksConstants.GPS_PROVIDER, desiredInterval, locationListenerPolicy.getMinDistance(), // , 0 /* minDistance, get all updates to properly time pauses */ TrackRecordingService.this); currentRecordingInterval = desiredInterval; Log.d(MyTracksConstants.TAG, "...location listener now registered w/ TrackRecordingService @ " + currentRecordingInterval); } catch (RuntimeException e) { Log.e(MyTracksConstants.TAG, "Could not register location listener: " + e.getMessage(), e); } } public void unregisterLocationListener() { if (locationManager == null) { Log.e(MyTracksConstants.TAG, "TrackRecordingService: Do not have any location manager."); return; } locationManager.removeUpdates(this); Log.d(MyTracksConstants.TAG, "Location listener now unregistered w/ TrackRecordingService."); } private Track getRecordingTrack() { if (recordingTrackId < 0) { return null; } return providerUtils.getTrack(recordingTrackId); } private void restoreStats(Track track) { Log.d(MyTracksConstants.TAG, "Restoring stats of track with ID: " + track.getId()); TripStatistics stats = track.getStatistics(); statsBuilder = new TripStatisticsBuilder(stats.getStartTime()); statsBuilder.setMinRecordingDistance(minRecordingDistance); setUpAnnouncer(); splitManager.restore(); length = 0; lastValidLocation = null; Waypoint waypoint = providerUtils.getFirstWaypoint(recordingTrackId); if (waypoint != null && waypoint.getStatistics() != null) { currentWaypointId = waypoint.getId(); waypointStatsBuilder = new TripStatisticsBuilder( waypoint.getStatistics()); } else { // This should never happen, but we got to do something so life goes on: waypointStatsBuilder = new TripStatisticsBuilder(stats.getStartTime()); currentWaypointId = -1; } waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); Cursor cursor = null; try { cursor = providerUtils.getLocationsCursor( recordingTrackId, -1, MyTracksConstants.MAX_LOADED_TRACK_POINTS, true); if (cursor != null) { if (cursor.moveToLast()) { do { Location location = providerUtils.createLocation(cursor); if (MyTracksUtils.isValidLocation(location)) { statsBuilder.addLocation(location, location.getTime()); if (lastValidLocation != null) { length += location.distanceTo(lastValidLocation); } lastValidLocation = location; } } while (cursor.moveToPrevious()); } statsBuilder.getStatistics().setMovingTime(stats.getMovingTime()); statsBuilder.pauseAt(stats.getStopTime()); statsBuilder.resumeAt(System.currentTimeMillis()); } else { Log.e(MyTracksConstants.TAG, "Could not get track points cursor."); } } catch (RuntimeException e) { Log.e(MyTracksConstants.TAG, "Error while restoring track.", e); } finally { if (cursor != null) { cursor.close(); } } splitManager.calculateNextSplit(); } /* * Location listener implementation: ================================= */ @Override public void onLocationChanged(final Location location) { this.executerServce.submit( new Runnable() { @Override public void run() { onLocationChangedAsync(location); } }); } private void onLocationChangedAsync(Location location) { Log.d(MyTracksConstants.TAG, "TrackRecordingService.onLocationChanged"); try { // Don't record if the service has been asked to pause recording: if (!isRecording) { Log.w(MyTracksConstants.TAG, "Not recording because recording has been paused."); return; } // This should never happen, but just in case (we really don't want the // service to crash): if (location == null) { Log.w(MyTracksConstants.TAG, "Location changed, but location is null."); return; } // Don't record if the accuracy is too bad: if (location.getAccuracy() > minRequiredAccuracy) { Log.d(MyTracksConstants.TAG, "Not recording. Bad accuracy."); return; } // At least one track must be available for appending points: recordingTrack = getRecordingTrack(); if (recordingTrack == null) { Log.d(MyTracksConstants.TAG, "Not recording. No track to append to available."); return; } // Update the idle time if needed. locationListenerPolicy.updateIdleTime(statsBuilder.getIdleTime()); addLocationToStats(location); if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) { registerLocationListener(); } Location lastRecordedLocation = providerUtils.getLastLocation(); long lastRecordedLocationId = providerUtils.getLastLocationId(recordingTrackId); double distanceToLastRecorded = Double.POSITIVE_INFINITY; if (lastRecordedLocation != null) { distanceToLastRecorded = location.distanceTo(lastRecordedLocation); } double distanceToLast = Double.POSITIVE_INFINITY; if (lastLocation != null) { distanceToLast = location.distanceTo(lastLocation); } boolean hasSensorData = sensorManager != null && sensorManager.isEnabled() && sensorManager.getSensorDataSet() != null && sensorManager.isDataValid(); // If the user has been stationary for two recording just record the first // two and ignore the rest. This code will only have an effect if the // maxRecordingDistance = 0 if (distanceToLast == 0 && !hasSensorData) { if (isMoving) { Log.d(MyTracksConstants.TAG, "Found two identical locations."); isMoving = false; if (lastLocation != null && lastRecordedLocation != null && !lastRecordedLocation.equals(lastLocation)) { // Need to write the last location. This will happen when // lastRecordedLocation.distance(lastLocation) < // minRecordingDistance if (!insertLocation(recordingTrack, lastLocation, lastRecordedLocation, lastRecordedLocationId, recordingTrackId)) { return; } lastRecordedLocationId++; } } else { Log.d(MyTracksConstants.TAG, "Not recording. More than two identical locations."); } } else if (distanceToLastRecorded > minRecordingDistance || hasSensorData) { if (lastLocation != null && !isMoving) { // Last location was the last stationary location. Need to go back and // add it. if (!insertLocation(recordingTrack, lastLocation, lastRecordedLocation, lastRecordedLocationId, recordingTrackId)) { return; } lastRecordedLocationId++; isMoving = true; } // If separation from last recorded point is too large insert a // separator to indicate end of a segment: boolean startNewSegment = lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90 && distanceToLastRecorded > maxRecordingDistance && recordingTrack.getStartId() >= 0; if (startNewSegment) { // Insert a separator point to indicate start of new track: Log.d(MyTracksConstants.TAG, "Inserting a separator."); Location separator = new Location(MyTracksConstants.GPS_PROVIDER); separator.setLongitude(0); separator.setLatitude(100); separator.setTime(lastRecordedLocation.getTime()); providerUtils.insertTrackPoint(separator, recordingTrackId); } if (!insertLocation(recordingTrack, location, lastRecordedLocation, lastRecordedLocationId, recordingTrackId)) { return; } } else { Log.d(MyTracksConstants.TAG, String.format( "Not recording. Distance to last recorded point (%f m) is less than" + " %d m.", distanceToLastRecorded, minRecordingDistance)); // Return here so that the location is NOT recorded as the last location. return; } } catch (Error e) { // Probably important enough to rethrow. Log.e(MyTracksConstants.TAG, "Error in onLocationChanged", e); throw e; } catch (RuntimeException e) { // Safe usually to trap exceptions. Log.e(MyTracksConstants.TAG, "Trapping exception in onLocationChanged", e); throw e; } lastLocation = location; } private void addLocationToStats(Location location) { if (MyTracksUtils.isValidLocation(location)) { long now = System.currentTimeMillis(); statsBuilder.addLocation(location, now); waypointStatsBuilder.addLocation(location, now); } } @Override public void onProviderDisabled(String provider) { // Do nothing } @Override public void onProviderEnabled(String provider) { // Do nothing } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing } /* * Application lifetime events: ============================ */ @Override public void onCreate() { super.onCreate(); Log.d(MyTracksConstants.TAG, "TrackRecordingService.onCreate"); providerUtils = MyTracksProviderUtils.Factory.get(this); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); splitManager = new SplitManager(this); prefManager = new PreferenceManager(this); registerLocationListener(); /* * After 5 min, check every minute that location listener still is * registered and spit out additional debugging info to the logs: */ timer.schedule(checkLocationListener, 1000 * 60 * 5, 1000 * 60); // Try to restore previous recording state in case this service has been // restarted by the system, which can sometimes happen. recordingTrack = getRecordingTrack(); if (recordingTrack != null) { restoreStats(recordingTrack); isRecording = true; } else { if (recordingTrackId != -1) { // Make sure we have consistent state in shared preferences. Log.w(MyTracksConstants.TAG, "TrackRecordingService.onCreate: " + "Resetting an orphaned recording track = " + recordingTrackId); } prefManager.setRecordingTrack(recordingTrackId = -1); } showNotification(); executerServce = Executors.newSingleThreadExecutor(); } /** * Creates an {@link Executer} and schedules {@class SafeStatusAnnouncerTask}. * The announcer requires a TTS service and user should have enabled * the announcements, otherwise this method is no-op. */ private void setUpAnnouncer() { Log.d(MyTracksConstants.TAG, "TrackRecordingService.setUpAnnouncer: " + announcementExecuter); if (announcementFrequency != -1 && recordingTrackId != -1) { handler.post(new Runnable() { @Override public void run() { if (announcementExecuter == null) { StatusAnnouncerFactory statusAnnouncerFactory = new StatusAnnouncerFactory(ApiFeatures.getInstance()); PeriodicTask announcer = statusAnnouncerFactory.create( TrackRecordingService.this); if (announcer == null) { return; } // TODO: Either use TaskExecuterManager everywhere, or get rid of it announcementExecuter = new PeriodicTaskExecuter(announcer, TrackRecordingService.this); } announcementExecuter.scheduleTask(announcementFrequency * 60000); } }); } } private void shutdownAnnouncer() { Log.d(MyTracksConstants.TAG, "TrackRecordingService.shutdownAnnouncer: " + announcementExecuter); if (announcementExecuter != null) { try { announcementExecuter.shutdown(); } finally { announcementExecuter = null; } } } @Override public void onDestroy() { Log.d(MyTracksConstants.TAG, "TrackRecordingService.onDestroy"); isRecording = false; showNotification(); prefManager.shutdown(); prefManager = null; checkLocationListener.cancel(); checkLocationListener = null; timer.cancel(); timer.purge(); unregisterLocationListener(); shutdownAnnouncer(); splitManager.shutdown(); splitManager = null; if (sensorManager != null) { sensorManager.shutdown(); sensorManager = null; } // Make sure we have no indirect references to this service. locationManager = null; notificationManager = null; providerUtils = null; binder.detachFromService(); binder = null; // This should be the last operation. releaseWakeLock(); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { Log.d(MyTracksConstants.TAG, "TrackRecordingService.onBind"); return binder; } @Override public boolean onUnbind(Intent intent) { Log.d(MyTracksConstants.TAG, "TrackRecordingService.onUnbind"); return super.onUnbind(intent); } @Override public boolean stopService(Intent name) { Log.d(MyTracksConstants.TAG, "TrackRecordingService.stopService"); unregisterLocationListener(); return super.stopService(name); } @Override public void onStart(Intent intent, int startId) { handleStartCommand(intent, startId); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleStartCommand(intent, startId); return START_STICKY; } private void handleStartCommand(Intent intent, int startId) { Log.d(MyTracksConstants.TAG, "TrackRecordingService.handleStartCommand: " + startId); // Check if called on phone reboot with resume intent. if (intent != null && intent.getBooleanExtra(RESUME_TRACK_EXTRA_NAME, false)) { Log.d(MyTracksConstants.TAG, "TrackRecordingService: requested resume"); // Make sure that the current track exists and is fresh enough. if (recordingTrack == null || !shouldResumeTrack(recordingTrack)) { Log.i(MyTracksConstants.TAG, "TrackRecordingService: Not resuming, because the previous track (" + recordingTrack + ") doesn't exist or is too old"); isRecording = false; prefManager.setRecordingTrack(recordingTrackId = -1); stopSelfResult(startId); return; } Log.i(MyTracksConstants.TAG, "TrackRecordingService: resuming"); } } private void setAutoResumeTrackRetries( SharedPreferences sharedPreferences, int retryAttempts) { Log.d(MyTracksConstants.TAG, "Updating auto-resume retry attempts to: " + retryAttempts); prefManager.setAutoResumeTrackCurrentRetry(retryAttempts); } private boolean shouldResumeTrack(Track track) { Log.d(MyTracksConstants.TAG, "shouldResumeTrack: autoResumeTrackTimeout = " + autoResumeTrackTimeout); // Check if we haven't exceeded the maximum number of retry attempts. SharedPreferences sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); int retries = sharedPreferences.getInt( getString(R.string.auto_resume_track_current_retry_key), 0); Log.d(MyTracksConstants.TAG, "shouldResumeTrack: Attempting to auto-resume the track (" + (retries + 1) + "/" + MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS + ")"); if (retries >= MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS) { Log.i(MyTracksConstants.TAG, "shouldResumeTrack: Not resuming because exceeded the maximum " + "number of auto-resume retries"); return false; } // Increase number of retry attempts. setAutoResumeTrackRetries(sharedPreferences, retries + 1); // Check for special cases. if (autoResumeTrackTimeout == 0) { // Never resume. Log.d(MyTracksConstants.TAG, "shouldResumeTrack: Auto-resume disabled (never resume)"); return false; } else if (autoResumeTrackTimeout == -1) { // Always resume. Log.d(MyTracksConstants.TAG, "shouldResumeTrack: Auto-resume forced (always resume)"); return true; } // Check if the last modified time is within the acceptable range. long lastModified = track.getStatistics() != null ? track.getStatistics().getStopTime() : 0; Log.d(MyTracksConstants.TAG, "shouldResumeTrack: lastModified = " + lastModified + ", autoResumeTrackTimeout: " + autoResumeTrackTimeout); return lastModified > 0 && System.currentTimeMillis() - lastModified <= autoResumeTrackTimeout * 60 * 1000; } public boolean isRecording() { return isRecording; } public long insertWaypoint(WaypointCreationRequest request) { if (!isRecording()) { throw new IllegalStateException( "Unable to insert waypoint marker while not recording!"); } if (request == null) { request = WaypointCreationRequest.DEFAULT_MARKER; } Waypoint wpt = new Waypoint(); switch (request.getType()) { case MARKER: buildMarker(wpt, request); break; case STATISTICS: buildStatisticsMarker(wpt); break; } wpt.setTrackId(recordingTrackId); wpt.setLength(length); if (lastValidLocation == null) { // A null location is ok, and expected on track start. // Make it an impossible location. Location l = new Location(""); l.setLatitude(100); l.setLongitude(200); wpt.setLocation(l); } else { // A null location is ok, and expected on track start. wpt.setLocation(lastLocation); if (lastLocation != null) { wpt.setDuration(lastLocation.getTime() - statsBuilder.getStatistics().getStartTime()); } } Uri uri = providerUtils.insertWaypoint(wpt); return Long.parseLong(uri.getLastPathSegment()); } private void buildMarker(Waypoint wpt, WaypointCreationRequest request) { wpt.setType(Waypoint.TYPE_WAYPOINT); if (request.getIconUrl() == null) { wpt.setIcon(getString(R.string.waypoint_icon_url)); } else { wpt.setIcon(request.getIconUrl()); } if (request.getName() == null) { wpt.setName(getString(R.string.waypoint)); } else { wpt.setName(request.getName()); } if (request.getDescription() != null) { wpt.setDescription(request.getDescription()); } } /** * Build a statistics marker. * A statistics marker holds the stats for the* last segment up to this marker. * * @param Waypoint The waypoint which will be populated with stats data. * @return the unique id of the inserted marker */ private void buildStatisticsMarker(Waypoint waypoint) { StringUtils utils = new StringUtils(TrackRecordingService.this); // Set stop and total time in the stats data final long time = System.currentTimeMillis(); waypointStatsBuilder.pauseAt(time); // Override the duration - it's not the duration from the last waypoint, but // the duration from the beginning of the whole track waypoint.setDuration(time - statsBuilder.getStatistics().getStartTime()); // Set the rest of the waypoint data waypoint.setType(Waypoint.TYPE_STATISTICS); waypoint.setName(getString(R.string.statistics)); waypoint.setStatistics(waypointStatsBuilder.getStatistics()); waypoint.setDescription(utils.generateWaypointDescription(waypoint)); waypoint.setIcon(getString(R.string.stats_icon_url)); waypoint.setStartId(providerUtils.getLastLocationId(recordingTrackId)); // Create a new stats keeper for the next marker. waypointStatsBuilder = new TripStatisticsBuilder(time); } private ServiceBinder binder = new ServiceBinder(this); /** * TODO: There is a bug in Android that leaks Binder instances. This bug is * especially visible if we have a non-static class, as there is no way to * nullify reference to the outer class (the service). * A workaround is to use a static class and explicitly clear service * and detach it from the underlying Binder. With this approach, we minimize * the leak to 24 bytes per each service instance. * * For more details, see the following bug: * http://code.google.com/p/android/issues/detail?id=6426. */ private static class ServiceBinder extends ITrackRecordingService.Stub { private TrackRecordingService service; public ServiceBinder(TrackRecordingService service) { this.service = service; } /** * Clears the reference to the outer class to minimize the leak. */ public void detachFromService() { this.service = null; attachInterface(null, null); } @Override public boolean isRecording() { checkService(); return service.isRecording(); } private void checkService() { if (service == null) { throw new IllegalStateException("The service has been already detached!"); } } @Override public long getRecordingTrackId() { checkService(); return service.recordingTrackId; } @Override public boolean hasRecorded() { checkService(); return service.providerUtils.getLastTrackId() >= 0; } @Override public long startNewTrack() { checkService(); return service.startNewTrack(); } /** * Inserts a waypoint marker in the track being recorded. * * @param request Details of the waypoint to insert * @return the unique ID of the inserted marker */ public long insertWaypoint(WaypointCreationRequest request) { checkService(); return service.insertWaypoint(request); } @Override public void endCurrentTrack() { checkService(); service.endCurrentTrack(); } @Override public void deleteAllTracks() { checkService(); if (isRecording()) { throw new IllegalStateException("Cannot delete all tracks while recording!"); } service.providerUtils.deleteAllTracks(); } @Override public void recordLocation(Location loc) { checkService(); service.onLocationChanged(loc); } @Override public byte[] getSensorData() { checkService(); if (service.sensorManager == null) { Log.d(MyTracksConstants.TAG, "No sensor manager for data."); return null; } if (service.sensorManager.getSensorDataSet() == null) { Log.d(MyTracksConstants.TAG, "Sensor data set is null."); return null; } return service.sensorManager.getSensorDataSet().toByteArray(); } @Override public int getSensorState() { checkService(); if (service.sensorManager == null) { Log.d(MyTracksConstants.TAG, "No sensor manager for data."); return Sensor.SensorState.NONE.getNumber(); } return service.sensorManager.getSensorState().getNumber(); } } public long startNewTrack() { Log.d(MyTracksConstants.TAG, "TrackRecordingService.startNewTrack"); if (recordingTrackId != -1 || isRecording) { throw new IllegalStateException("A track is already in progress!"); } long startTime = System.currentTimeMillis(); acquireWakeLock(); Track track = new Track(); TripStatistics trackStats = track.getStatistics(); trackStats.setStartTime(startTime); track.setStartId(-1); Uri trackUri = providerUtils.insertTrack(track); recordingTrackId = Long.parseLong(trackUri.getLastPathSegment()); track.setId(recordingTrackId); track.setName(new DefaultTrackNameFactory(this).newTrackName( recordingTrackId, startTime)); isRecording = true; isMoving = true; providerUtils.updateTrack(track); statsBuilder = new TripStatisticsBuilder(startTime); statsBuilder.setMinRecordingDistance(minRecordingDistance); waypointStatsBuilder = new TripStatisticsBuilder(startTime); waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); currentWaypointId = insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); setUpAnnouncer(); length = 0; showNotification(); registerLocationListener(); splitManager.restore(); sensorManager = SensorManagerFactory.getSensorManager(this); if (sensorManager != null) { sensorManager.onStartTrack(); } // Reset the number of auto-resume retries. setAutoResumeTrackRetries( getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0), 0); // Persist the current recording track. prefManager.setRecordingTrack(recordingTrackId); // Notify the world that we're now recording. sendTrackBroadcast( R.string.track_started_broadcast_action, 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(); long recordedTrackId = recordingTrackId; prefManager.setRecordingTrack(recordingTrackId = -1); if (sensorManager != null) { sensorManager.shutdown(); sensorManager = null; } releaseWakeLock(); // Notify the world that we're no longer recording. sendTrackBroadcast( R.string.track_stopped_broadcast_action, recordedTrackId); } private void sendTrackBroadcast(int actionResId, long trackId) { Intent broadcastIntent = new Intent() .setAction(getString(actionResId)) .putExtra(getString(R.string.track_id_broadcast_extra), trackId); sendBroadcast(broadcastIntent, getString(R.string.broadcast_notifications_permission)); } public TripStatistics getTripStatistics() { return statsBuilder.getStatistics(); } Location getLastLocation() { return lastLocation; } long getRecordingTrackId() { return recordingTrackId; } public void setRecordingTrackId(long recordingTrackId) { this.recordingTrackId = recordingTrackId; } public int getAnnouncementFrequency() { return announcementFrequency; } public void setAnnouncementFrequency(int announcementFrequency) { this.announcementFrequency = announcementFrequency; if (announcementFrequency == -1) { shutdownAnnouncer(); } else { setUpAnnouncer(); } } public int getMaxRecordingDistance() { return maxRecordingDistance; } public void setMaxRecordingDistance(int maxRecordingDistance) { this.maxRecordingDistance = maxRecordingDistance; } public int getMinRecordingDistance() { return minRecordingDistance; } public void setMinRecordingDistance(int minRecordingDistance) { this.minRecordingDistance = minRecordingDistance; if (statsBuilder != null && waypointStatsBuilder != null) { statsBuilder.setMinRecordingDistance(minRecordingDistance); waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); } } public int getMinRequiredAccuracy() { return minRequiredAccuracy; } public void setMinRequiredAccuracy(int minRequiredAccuracy) { this.minRequiredAccuracy = minRequiredAccuracy; } public LocationListenerPolicy getLocationListenerPolicy() { return locationListenerPolicy; } public void setLocationListenerPolicy( LocationListenerPolicy locationListenerPolicy) { this.locationListenerPolicy = locationListenerPolicy; } public int getAutoResumeTrackTimeout() { return autoResumeTrackTimeout; } public void setAutoResumeTrackTimeout(int autoResumeTrackTimeout) { this.autoResumeTrackTimeout = autoResumeTrackTimeout; } public SplitManager getSplitManager() { return splitManager; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; /** * This is interface for a task that will be executed on some schedule. * * @author Sandor Dornbush */ public interface PeriodicTask { /** * Sets up this task for subsequent calls to the run method. */ public void start(); /** * This method will be called periodically. */ public void run(TrackRecordingService service); /** * Shuts down this task and clean up resources. */ public void shutdown(); }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import java.text.SimpleDateFormat; import java.util.Date; /** * Creates a default track name based on the current default track name policy. * * @author Matthew Simmons */ class DefaultTrackNameFactory { private static final String TIMESTAMP_DATE_FORMAT = "yyyy-MM-dd HH:mm"; private final Context context; DefaultTrackNameFactory(Context context) { this.context = context; } /** * Creates a new track name. * * @param trackId The ID for the current track. * @param startTime The start time, in milliseconds since the epoch, of the * current track. * @return The new track name. */ String newTrackName(long trackId, long startTime) { if (useTimestampTrackName()) { SimpleDateFormat formatter = new SimpleDateFormat(TIMESTAMP_DATE_FORMAT); return formatter.format(new Date(startTime)); } else { return String.format(context.getString(R.string.new_track), trackId); } } /** Determines whether the preferences allow a timestamp-based track name */ protected boolean useTimestampTrackName() { SharedPreferences prefs = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); return prefs.getBoolean( context.getString(R.string.timestamp_track_name_key), true); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; /** * Manage the connection to a bluetooth sensor. * * @author Sandor Dornbush */ public class BluetoothSensorManager extends SensorManager { // Local Bluetooth adapter private BluetoothAdapter bluetoothAdapter = null; // Member object for the sensor threads and connections. private BluetoothConnectionManager connectionManager = null; // Name of the connected device private String connectedDeviceName = null; private Context context = null; private Sensor.SensorDataSet sensorDataSet = null; private MessageParser parser; public BluetoothSensorManager( Context context, MessageParser parser) { this.context = context; this.parser = parser; // Get local Bluetooth adapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If BT is not available or not enabled quit. if (!isEnabled()) { return; } setupSensor(); } private void setupSensor() { Log.d(TAG, "setupSensor()"); // Initialize the BluetoothSensorAdapter to perform bluetooth connections. connectionManager = new BluetoothConnectionManager(messageHandler, parser); } public boolean isEnabled() { return bluetoothAdapter != null && bluetoothAdapter.isEnabled(); } public void setupChannel() { if (!isEnabled() || connectionManager == null) { Log.w(TAG, "Disabled manager onStartTrack"); return; } SharedPreferences prefs = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); String address = prefs.getString(context.getString(R.string.bluetooth_sensor_key), null); if (address == null) { return; } Log.w(TAG, "Connecting to bluetooth sensor: " + address); // Get the BluetoothDevice object BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address); // Attempt to connect to the device connectionManager.connect(device); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if (connectionManager != null) { // Only if the state is STATE_NONE, do we know that we haven't started // already if (connectionManager.getState() == Sensor.SensorState.NONE) { // Start the Bluetooth sensor services Log.w(TAG, "Disabled manager onStartTrack"); connectionManager.start(); } } } public void onDestroy() { // Stop the Bluetooth sensor services if (connectionManager != null) { connectionManager.stop(); } } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public Sensor.SensorState getSensorState() { return (connectionManager == null) ? Sensor.SensorState.NONE : connectionManager.getState(); } // The Handler that gets information back from the BluetoothSensorService private final Handler messageHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case BluetoothConnectionManager.MESSAGE_STATE_CHANGE: // TODO should we update the SensorManager state var? Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1); break; case BluetoothConnectionManager.MESSAGE_WRITE: break; case BluetoothConnectionManager.MESSAGE_READ: byte[] readBuf = null; try { readBuf = (byte[]) msg.obj; sensorDataSet = parser.parseBuffer(readBuf); Log.d(TAG, "MESSAGE_READ: " + sensorDataSet.toString()); } catch (IllegalArgumentException iae) { sensorDataSet = null; Log.i(TAG, "Got bad sensor data: " + new String(readBuf, 0, readBuf.length), iae); } catch (RuntimeException re) { sensorDataSet = null; Log.i(TAG, "Unexpected exception on read.", re); } break; case BluetoothConnectionManager.MESSAGE_DEVICE_NAME: // save the connected device's name connectedDeviceName = msg.getData().getString(BluetoothConnectionManager.DEVICE_NAME); Toast.makeText(context.getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT) .show(); break; } } }; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import android.content.Context; public class ZephyrSensorManager extends BluetoothSensorManager { public ZephyrSensorManager(Context context) { super(context, new ZephyrMessageParser()); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A sensor manager that can connect to an SRM Power Control 7 head unit. * * @author Sandor Dornbush */ public class AntSRMSensorManager extends AntSensorManager { /* * These constants are defined by the SRM Headunit spec. */ public static final byte NETWORK_NUMBER = (byte) 0; public static final byte DEVICE_TYPE = (byte) 12; public static final byte MANUFACTURER_ID = (byte) 1; public static final short CHANNEL_PERIOD = (short) 8192; public static final byte RF_FREQUENCY = (byte) 50; public static final int MESSAGE_TYPE_INDEX = 3; public static final int INITIALS_MESSAGE_TYPE = 5; public static final int SENSOR_DATA_MESSAGE_TYPE = 6; public static final int MESSAGE_ID_INDEX = 4; /** * This can be any value between 0..8 */ private byte channel = (byte) 5; /** * This is the id of this device. * The head unit must be programmed to expect this number. */ private byte deviceId; /** * The id of the last message received from the SRM head unit. */ private int lastMessageId; public AntSRMSensorManager(Context context) { super(context); // First read the the device id that we will be announcing. SharedPreferences prefs = context.getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); if (prefs != null) { deviceId = (byte) prefs.getInt( context.getString(R.string.ant_srm_bridge_sensor_id_key), WILDCARD); } } @Override public void handleMessage(byte[] antMessage) { // Parse channel number byte receivedChannel = (byte) (antMessage[AntMesg.MESG_DATA_OFFSET] & AntDefine.CHANNEL_NUMBER_MASK); if (receivedChannel != channel) { Log.d(TAG, "Unexpected channel: " + receivedChannel); return; } switch (antMessage[AntMesg.MESG_ID_OFFSET]) { case AntMesg.MESG_BROADCAST_DATA_ID: handleBroadcastData(antMessage); break; case AntMesg.MESG_RESPONSE_EVENT_ID: handleMessageResponse(antMessage); break; case AntMesg.MESG_CHANNEL_ID_ID: handleChannelId(antMessage); break; default: Log.e(TAG, "Unexpected message id: " + antMessage[3]); } } private void handleBroadcastData(byte[] antMessage) { if (deviceId == WILDCARD) { try { Log.d(TAG, "Requesting channel id id."); getAntReceiver().ANTRequestMessage(channel, AntMesg.MESG_CHANNEL_ID_ID); } catch (AntInterfaceException e) { Log.e(TAG, "Failed to request channel id id", e); } } setSensorState(Sensor.SensorState.CONNECTED); switch(antMessage[MESSAGE_TYPE_INDEX]) { case INITIALS_MESSAGE_TYPE: // TODO handle initials message. break; case SENSOR_DATA_MESSAGE_TYPE: parseSensorData(antMessage); break; default: Log.e(TAG, "Unexpected message type: " + antMessage[MESSAGE_TYPE_INDEX]); } } private void handleChannelId(byte[] antMessage) { // Store the device id. deviceId = antMessage[3]; Log.i(TAG, "Found device id: " + deviceId); SharedPreferences prefs = context.getSharedPreferences( MyTracksSettings.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_srm_bridge_sensor_id_key), deviceId); editor.commit(); } private void handleMessageResponse(byte[] antMessage) { if (antMessage[3] == AntMesg.MESG_EVENT_ID && antMessage[4] == AntDefine.EVENT_RX_SEARCH_TIMEOUT) { // Search timeout Log.w(TAG, "Search timed out. Unassigning channel."); try { getAntReceiver().ANTUnassignChannel(channel); } catch (AntInterfaceException e) { Log.e(TAG, "Failed to unassign ANT channel", e); } setSensorState(Sensor.SensorState.DISCONNECTED); } else if (antMessage[3] == AntMesg.MESG_UNASSIGN_CHANNEL_ID) { setSensorState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Disconnected from the sensor: " + getSensorState()); } } private void parseSensorData(byte[] antMessage) { if (antMessage.length != 11) { Log.e(TAG, "Unexpected ant message length: " + antMessage.length); return; } int newMessageId = antMessage[MESSAGE_ID_INDEX] & 0xFF; if (lastMessageId == newMessageId) { // Repeated message. Log.i(TAG, String.format("SRM ignoring repeat: 0x%X", newMessageId)); return; } if (newMessageId < lastMessageId) { if (!(newMessageId < 20 && lastMessageId > 200)) { Log.i(TAG, String.format("SRM ignoring repeat: 0x%X", newMessageId)); return; } // else assume the byte overflowed to 0. } lastMessageId = newMessageId; Sensor.SensorDataSet.Builder builder = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()); int power = SensorUtils.unsignedShortToInt(antMessage, 5); if (power >= 0) { Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(power) .setState(Sensor.SensorState.SENDING); builder.setPower(b); } int speed = SensorUtils.unsignedShortToInt(antMessage, 7); if (speed >= 0) { // The speed from srm is in 1/10 km/hr. // Sensor data expects the speed as m/s. // TODO finish this. //sensorData.setWheelSpeed(UnitConversions.TENTH_KMH_TO_MPS * speed); } int cadence = antMessage[9] & 0xFF; if (cadence >= 0) { Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(cadence) .setState(Sensor.SensorState.SENDING); builder.setCadence(b); } int bpm = antMessage[10] & 0xFF; if (bpm > 0) { Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(bpm) .setState(Sensor.SensorState.SENDING); builder.setHeartRate(b); } sensorData = builder.build(); } @Override protected void setupAntSensorChannels() { lastMessageId = 0; setupAntSensorChannel(NETWORK_NUMBER, channel, deviceId, DEVICE_TYPE, MANUFACTURER_ID, CHANNEL_PERIOD, RF_FREQUENCY, (byte) 0); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import android.content.Context; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; /** * A collection of methods for message parsers. * * @author Sandor Dornbush */ public class SensorUtils { private SensorUtils() { } /** * Extract one unsigned short from a big endian byte array. * @param buffer the buffer to extract the short from * @param index the first byte to be interpreted as part of the short * @return The unsigned short at the given index in the buffer */ public static int unsignedShortToInt(byte[] buffer, int index) { int r = (buffer[index] & 0xFF) << 8; r |= buffer[index + 1] & 0xFF; return r; } public static String getStateAsString(Sensor.SensorState state, Context c) { switch (state) { case NONE: return c.getString(R.string.none); case CONNECTING: return c.getString(R.string.connecting); case CONNECTED: return c.getString(R.string.connected); case DISCONNECTED: return c.getString(R.string.disconnected); case SENDING: return c.getString(R.string.sending); default: return ""; } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import android.util.Log; import java.util.Timer; import java.util.TimerTask; /** * Manage the connection to a sensor. * * @author Sandor Dornbush */ public abstract class SensorManager { /** * The maximum age where the data is considered valid. */ public static final long MAX_AGE = 5000; /** * Time to wait after a time out to retry. */ public static final int RETRY_PERIOD = 30000; private Sensor.SensorState sensorState = Sensor.SensorState.NONE; private long sensorStateTimestamp = 0; /** * A task to run periodically to check to see if connection was lost. */ private TimerTask checkSensorManager = new TimerTask() { @Override public void run() { Log.i(TAG, "SensorManager state: " + getSensorState()); switch (getSensorState()) { case CONNECTING: long age = System.currentTimeMillis() - getSensorStateTimestamp(); if (age > 2 * RETRY_PERIOD) { Log.i(TAG, "Retrying connecting SensorManager."); setupChannel(); } break; case DISCONNECTED: Log.i(TAG, "Re-registering disconnected SensorManager."); setupChannel(); break; } } }; /** * This timer invokes periodically the checkLocationListener timer task. */ private final Timer timer = new Timer(); /** * Is the sensor that this manages enabled. * @return true if the sensor is enabled */ public abstract boolean isEnabled(); /** * This is called when my tracks starts recording a new track. * This is the place to open connections to the sensor. */ public void onStartTrack() { setupChannel(); timer.schedule(checkSensorManager, RETRY_PERIOD, RETRY_PERIOD); } /** * This method is used to set up any necessary connections to underlying * sensor hardware. */ protected abstract void setupChannel(); public void shutdown() { timer.cancel(); onDestroy(); } /** * This is called when my tracks stops recording. * This is the place to shutdown any open connections. */ public abstract void onDestroy(); /** * Return the last sensor reading. * @return The last reading from the sensor. */ public abstract Sensor.SensorDataSet getSensorDataSet(); public void setSensorState(Sensor.SensorState sensorState) { this.sensorState = sensorState; } /** * Return the current sensor state. * @return The current sensor state. */ public Sensor.SensorState getSensorState() { return sensorState; } public long getSensorStateTimestamp() { return sensorStateTimestamp; } /** * @return True if the data is recent enough to be considered valid. */ public boolean isDataValid() { return (System.currentTimeMillis() - getSensorDataSet().getCreationTime()) < MAX_AGE; } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import com.google.android.apps.mytracks.content.Sensor; /** * An interface for parsing a byte array to a SensorData object. * * @author Sandor Dornbush */ public interface MessageParser { public int getFrameSize(); public Sensor.SensorDataSet parseBuffer(byte[] readBuff); public boolean isValid(byte[] buffer); public int findNextAlignment(byte[] buffer); }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; import com.dsi.ant.AntInterface; import android.content.Context; /** * Utility methods for ANT functionality. * * Prefer use of this class to importing DSI ANT classes into code outside of * the sensors package. */ public class AntUtils { private AntUtils() {} /** Returns true if this device supports ANT sensors. */ public static boolean hasAntSupport(Context context) { return AntInterface.hasAntSupport(context); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Channel ID message. * (ANT Message ID 0x51, Protocol & Usage guide v4.2 section 9.5.7.2) * * @author Matthew Simmons */ public class AntChannelIdMessage extends AntMessage { private byte channelNumber; private short deviceNumber; private byte deviceTypeId; private byte transmissionType; public AntChannelIdMessage(byte[] messageData) { channelNumber = messageData[0]; deviceNumber = decodeShort(messageData[1], messageData[2]); deviceTypeId = messageData[3]; transmissionType = messageData[4]; } /** Returns the channel number */ public byte getChannelNumber() { return channelNumber; } /** Returns the device number */ public short getDeviceNumber() { return deviceNumber; } /** Returns the device type */ public byte getDeviceTypeId() { return deviceTypeId; } /** Returns the transmission type */ public byte getTransmissionType() { return transmissionType; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; /** * This is a common superclass for ANT message subclasses. * * @author Matthew Simmons */ public class AntMessage { protected AntMessage() {} /** Build a short value from its constituent bytes */ protected static short decodeShort(byte b0, byte b1) { short value = b0; value |= ((short) b1) << 8; return value; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Channel Response / Event message. * (ANT Message ID 0x40, Protocol & Usage guide v4.2 section 9.5.6.1) * * @author Matthew Simmons */ public class AntChannelResponseMessage extends AntMessage { private byte channelNumber; private byte messageId; private byte messageCode; public AntChannelResponseMessage(byte[] messageData) { channelNumber = messageData[0]; messageId = messageData[1]; messageCode = messageData[2]; } /** Returns the channel number */ public byte getChannelNumber() { return channelNumber; } /** Returns the ID of the message being responded to */ public byte getMessageId() { return messageId; } /** Returns the code for a specific response or event */ public byte getMessageCode() { return messageCode; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors.ant; /** * This class decodes and encapsulates an ANT Startup message. * (ANT Message ID 0x6f, Protocol & Usage guide v4.2 section 9.5.3.1) * * @author Matthew Simmons */ public class AntStartupMessage extends AntMessage { private byte message; public AntStartupMessage(byte[] messageData) { message = messageData[0]; } /** Returns the cause of the startup */ public byte getMessage() { return message; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.services.sensors.ant.AntChannelIdMessage; import com.google.android.apps.mytracks.services.sensors.ant.AntChannelResponseMessage; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A sensor manager to connect ANT+ sensors. * This can include heart rate monitors. * * @author Sandor Dornbush */ public class AntDirectSensorManager extends AntSensorManager { /* * These constants are defined by the ANT+ heart rate monitor spec. */ public static final byte HRM_CHANNEL = 0; public static final byte NETWORK_NUMBER = 1; public static final byte HEART_RATE_DEVICE_TYPE = 120; public static final byte POWER_DEVICE_TYPE = 11; public static final byte MANUFACTURER_ID = 1; public static final short CHANNEL_PERIOD = 8070; public static final byte RF_FREQUENCY = 57; private short deviceNumberHRM; public AntDirectSensorManager(Context context) { super(context); deviceNumberHRM = WILDCARD; // First read the the device id that we will be pairing with. SharedPreferences prefs = context.getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); if (prefs != null) { deviceNumberHRM = (short) prefs.getInt(context.getString(R.string.ant_heart_rate_sensor_id_key), 0); } Log.i(TAG, "Will pair with heart rate monitor: " + deviceNumberHRM); } @Override protected boolean handleMessage(byte messageId, byte[] messageData) { if (super.handleMessage(messageId, messageData)) { return true; } int channel = messageData[0] & AntDefine.CHANNEL_NUMBER_MASK; switch (channel) { case HRM_CHANNEL: antDecodeHRM(messageId, messageData); break; default: Log.d(TAG, "Unhandled message: " + channel); } return true; } /** * Decode an ant heart rate monitor message. * @param messageData The byte array received from the heart rate monitor. */ private void antDecodeHRM(int messageId, byte[] messageData) { switch (messageId) { case AntMesg.MESG_BROADCAST_DATA_ID: handleBroadcastData(messageData); break; case AntMesg.MESG_RESPONSE_EVENT_ID: handleMessageResponse(messageData); break; case AntMesg.MESG_CHANNEL_ID_ID: handleChannelId(messageData); break; default: Log.e(TAG, "Unexpected message id: " + messageId); } } private void handleBroadcastData(byte[] antMessage) { if (deviceNumberHRM == WILDCARD) { try { getAntReceiver().ANTRequestMessage(HRM_CHANNEL, AntMesg.MESG_CHANNEL_ID_ID); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error handling broadcast data", e); } Log.d(TAG, "Requesting channel id id."); } setSensorState(Sensor.SensorState.CONNECTED); int bpm = (int) antMessage[8] & 0xFF; Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(bpm) .setState(Sensor.SensorState.SENDING); sensorData = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()) .setHeartRate(b) .build(); } void handleChannelId(byte[] rawMessage) { AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); deviceNumberHRM = message.getDeviceNumber(); Log.i(TAG, "Found device id: " + deviceNumberHRM); SharedPreferences prefs = context.getSharedPreferences( MyTracksSettings.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_heart_rate_sensor_id_key), deviceNumberHRM); editor.commit(); } private void handleMessageResponse(byte[] rawMessage) { AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); switch (message.getMessageId()) { case AntMesg.MESG_EVENT_ID: if (message.getMessageCode() == AntDefine.EVENT_RX_SEARCH_TIMEOUT) { // Search timeout Log.w(TAG, "Search timed out. Unassigning channel."); try { getAntReceiver().ANTUnassignChannel((byte) 0); } catch (AntInterfaceException e) { Log.e(TAG, "ANT error unassigning channel", e); } setSensorState(Sensor.SensorState.DISCONNECTED); } break; case AntMesg.MESG_UNASSIGN_CHANNEL_ID: setSensorState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Disconnected from the sensor: " + getSensorState()); break; } } @Override protected void setupAntSensorChannels() { setupAntSensorChannel(NETWORK_NUMBER, HRM_CHANNEL, deviceNumberHRM, HEART_RATE_DEVICE_TYPE, (byte) 0x01, CHANNEL_PERIOD, RF_FREQUENCY, (byte) 0); } public short getDeviceNumberHRM() { return deviceNumberHRM; } void setDeviceNumberHRM(short deviceNumberHRM) { this.deviceNumberHRM = deviceNumberHRM; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntInterface; import com.dsi.ant.AntInterfaceIntent; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.content.Sensor.SensorDataSet; import com.google.android.apps.mytracks.services.sensors.ant.AntStartupMessage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; /** * This is the common superclass for ANT-based sensors. It handles tasks which * apply to the ANT framework as a whole, such as framework initialization and * destruction. Subclasses are expected to handle the initialization and * management of individual sensors. * * Implementation: * * The initialization process is somewhat complicated. This is due in part to * the asynchronous nature of ANT Radio Service initialization, and in part due * to an apparent bug in that service. The following is an overview of the * initialization process. * * Initialization begins in {@link #setupChannel}, which is invoked by the * {@link SensorManager} when track recording begins. {@link #setupChannel} * asks the ANT Radio Service (via {@link AntInterface}) to start, using a * {@link AntInterface.ServiceListener} to indicate when the service has * connected. {@link #serviceConnected} claims and enables the Radio Service, * and then resets it to a known state for our use. Completion of reset is * indicated by receipt of a startup message (see {@link AntStartupMessage}). * Once we've received that message, the ANT service is ready for use, and we * can start sensor-specific initialization using * {@link #setupAntSensorChannels}. The initialization of each sensor will * usually result in a call to {@link #setupAntSensorChannel}. * * @author Sandor Dornbush */ public abstract class AntSensorManager extends SensorManager { // Pairing protected static final short WILDCARD = 0; private AntInterface antReceiver; // Flag to know if the ANT App was interrupted // TODO: This code path is not used but probably should be. private boolean antInterrupted; /** * The data from the sensors. */ protected SensorDataSet sensorData; protected Context context; private static final boolean DEBUGGING = false; /** Receives and logs all status ANT intents. */ private final BroadcastReceiver statusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String antAction = intent.getAction(); Log.i(TAG, "enter status onReceive" + antAction); } }; /** Receives all data ANT intents. */ private final BroadcastReceiver dataReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String antAction = intent.getAction(); Log.i(TAG, "enter data onReceive" + antAction); if (antAction.equals(AntInterfaceIntent.ANT_RX_MESSAGE_ACTION)) { byte[] antMessage = intent.getByteArrayExtra(AntInterfaceIntent.ANT_MESSAGE); if (DEBUGGING) { Log.d(TAG, "Received RX message " + messageToString(antMessage)); } handleMessage(antMessage); } } }; /** * ANT uses this listener to tell us when it has bound to the ANT Radio * Service. We can't start sending ANT commands until we've been notified * (via this listener) that the Radio Service has connected. */ private AntInterface.ServiceListener antServiceListener = new AntInterface.ServiceListener() { @Override public void onServiceConnected() { serviceConnected(); } @Override public void onServiceDisconnected() { Log.d(TAG, "ANT interface reports disconnection"); } }; public AntSensorManager(Context context) { this.context = context; } @Override public void onDestroy() { Log.i(TAG, "destroying AntSensorManager"); context.unregisterReceiver(statusReceiver); context.unregisterReceiver(dataReceiver); try { antReceiver.releaseInterface(); } catch (AntInterfaceException e) { Log.e(TAG, "failed to release ANT interface", e); } antReceiver.destroy(); } @Override public SensorDataSet getSensorDataSet() { return sensorData; } @Override public boolean isEnabled() { return true; } public AntInterface getAntReceiver() { return antReceiver; } /** * This is the interface used by the {@link SensorManager} to tell this * class when to start. It handles initialization of the ANT framework, * eventually resulting in sensor-specific initialization via * {@link #setupAntSensorChannels}. */ @Override protected final void setupChannel() { // We handle this unpleasantly because the UI should've checked for ANT // support before it even instantiated this class. if (!AntInterface.hasAntSupport(context)) { throw new IllegalStateException("device does not have ANT support"); } // We register for ANT intents early because we want to have a record of // the status intents in the log as we start up. registerForAntIntents(); antReceiver = AntInterface.getInstance(context, antServiceListener); if (antReceiver == null) { Log.e(TAG, "Failed to get ANT Receiver"); return; } setSensorState(Sensor.SensorState.CONNECTING); } /** * This method is invoked via the ServiceListener when we're connected to * the ANT service. If we're just starting up, this is our first opportunity * to initiate any ANT commands. */ private synchronized void serviceConnected() { Log.d(TAG, "ANT service connected"); try { if (!antReceiver.claimInterface()) { Log.e(TAG, "failed to claim ANT interface"); return; } if (!antReceiver.isEnabled()) { // Make sure not to call AntInterface.enable() again, if it has been // already called before if (antInterrupted == false) { Log.i(TAG, "Powering on Radio"); antReceiver.enable(); } } else { Log.i(TAG, "Radio already enabled"); } } catch (AntInterfaceException e) { Log.e(TAG, "failed to enable ANT", e); } try { // We expect this call to throw an exception due to a bug in the ANT // Radio Service. It won't actually fail, though, as we'll get the // startup message (see {@link AntStartupMessage}) one normally expects // after a reset. Channel initialization can proceed once we receive // that message. antReceiver.ANTResetSystem(); } catch (AntInterfaceException e) { Log.e(TAG, "failed to reset ANT (expected exception)", e); } } /** * Process a raw ANT message. * @param antMessage the ANT message, including the size and message ID bytes * @deprecated Use {@link #handleMessage(int, byte[])} instead. */ protected void handleMessage(byte[] antMessage) { int len = antMessage[0]; if (len != antMessage.length - 2 || antMessage.length <= 2) { Log.e(TAG, "Invalid message: " + messageToString(antMessage)); return; } byte messageId = antMessage[1]; // Arrays#copyOfRange doesn't exist?? byte[] messageData = new byte[antMessage.length - 2]; System.arraycopy(antMessage, 2, messageData, 0, antMessage.length - 2); handleMessage(messageId, messageData); } /** * Process a raw ANT message. * @param messageId the message ID. See the ANT Message Protocol and Usage * guide, section 9.3. * @param messageData the ANT message, without the size and message ID bytes. * @return true if this method has taken responsibility for the passed * message; false otherwise. */ protected boolean handleMessage(byte messageId, byte[] messageData) { if (messageId == AntMesg.MESG_STARTUP_MESG_ID) { Log.d(TAG, String.format("Received startup message (reason %02x); initializing channel", new AntStartupMessage(messageData).getMessage())); setupAntSensorChannels(); return true; } return false; } /** * Subclasses define this method to perform sensor-specific initialization. * When this method is called, the ANT framework has been enabled, and is * ready for use. */ protected abstract void setupAntSensorChannels(); /** * Used by subclasses to set up an ANT channel for a single sensor. A given * subclass may invoke this method multiple times if the subclass is * responsible for more than one sensor. * * @return true on success */ protected boolean setupAntSensorChannel(byte networkNumber, byte channelNumber, short deviceNumber, byte deviceType, byte txType, short channelPeriod, byte radioFreq, byte proxSearch) { try { // Assign as slave channel on selected network (0 = public, 1 = ANT+, 2 = // ANTFS) antReceiver.ANTAssignChannel(channelNumber, AntDefine.PARAMETER_RX_NOT_TX, networkNumber); antReceiver.ANTSetChannelId(channelNumber, deviceNumber, deviceType, txType); antReceiver.ANTSetChannelPeriod(channelNumber, channelPeriod); antReceiver.ANTSetChannelRFFreq(channelNumber, radioFreq); // Disable high priority search antReceiver.ANTSetChannelSearchTimeout(channelNumber, (byte) 0); // Set search timeout to 30 seconds (low priority search)) antReceiver.ANTSetLowPriorityChannelSearchTimeout(channelNumber, (byte) 12); if (deviceNumber == WILDCARD) { // Configure proximity search, if using wild card search antReceiver.ANTSetProximitySearch(channelNumber, proxSearch); } antReceiver.ANTOpenChannel(channelNumber); return true; } catch (AntInterfaceException e) { Log.e(TAG, "failed to setup ANT channel", e); return false; } } private void registerForAntIntents() { Log.i(TAG, "Registering for ant intents."); // Register for ANT intent broadcasts. IntentFilter statusIntentFilter = new IntentFilter(); statusIntentFilter.addAction(AntInterfaceIntent.ANT_ENABLED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_DISABLED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_INTERFACE_CLAIMED_ACTION); statusIntentFilter.addAction(AntInterfaceIntent.ANT_RESET_ACTION); context.registerReceiver(statusReceiver, statusIntentFilter); IntentFilter dataIntentFilter = new IntentFilter(); dataIntentFilter.addAction(AntInterfaceIntent.ANT_RX_MESSAGE_ACTION); context.registerReceiver(dataReceiver, dataIntentFilter); } private String messageToString(byte[] message) { StringBuilder out = new StringBuilder(); for (byte b : message) { out.append(String.format("%s%02x", (out.length() == 0 ? "" : " "), b)); } return out.toString(); } }
Java
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.UUID; /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for incoming * connections, a thread for connecting with a device, and a thread for * performing data transmissions when connected. * * @author Sandor Dornbush */ public class BluetoothConnectionManager { // Unique UUID for this application private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private MessageParser parser; // Member fields private final BluetoothAdapter adapter; private final Handler handler; private ConnectThread connectThread; private ConnectedThread connectedThread; private Sensor.SensorState state; // Message types sent from the BluetoothSenorService Handler public static final int MESSAGE_STATE_CHANGE = 1; public static final int MESSAGE_READ = 2; public static final int MESSAGE_WRITE = 3; public static final int MESSAGE_DEVICE_NAME = 4; // Key names received from the BluetoothSenorService Handler public static final String DEVICE_NAME = "device_name"; /** * Constructor. Prepares a new BluetoothSensor session. * * @param context The UI Activity Context * @param handler A Handler to send messages back to the UI Activity */ public BluetoothConnectionManager(Handler handler, MessageParser parser) { this.adapter = BluetoothAdapter.getDefaultAdapter(); this.state = Sensor.SensorState.NONE; this.handler = handler; this.parser = parser; } /** * Set the current state of the sensor connection * * @param state An integer defining the current connection state */ private synchronized void setState(Sensor.SensorState state) { // TODO pretty print this. Log.d(TAG, "setState(" + state + ")"); this.state = state; // Give the new state to the Handler so the UI Activity can update handler.obtainMessage(MESSAGE_STATE_CHANGE, state.getNumber(), -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized Sensor.SensorState getState() { return state; } /** * Start the sensor service. Specifically start AcceptThread to begin a session * in listening (server) mode. Called by the Activity onResume() */ public synchronized void start() { Log.d(TAG, "BluetoothConnectionManager.start()"); // Cancel any thread attempting to make a connection if (connectThread != null) { connectThread.cancel(); connectThread = null; } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } setState(Sensor.SensorState.NONE); } /** * Start the ConnectThread to initiate a connection to a remote device. * * @param device The BluetoothDevice to connect */ public synchronized void connect(BluetoothDevice device) { Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (state == Sensor.SensorState.CONNECTING) { if (connectThread != null) { connectThread.cancel(); connectThread = null; } } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } // Start the thread to connect with the given device connectThread = new ConnectThread(device); connectThread.start(); setState(Sensor.SensorState.CONNECTING); } /** * Start the ConnectedThread to begin managing a Bluetooth connection * * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) { Log.d(TAG, "connected"); // Cancel the thread that completed the connection if (connectThread != null) { connectThread.cancel(); connectThread = null; } // Cancel any thread currently running a connection if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } // Start the thread to manage the connection and perform transmissions connectedThread = new ConnectedThread(socket); connectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = handler.obtainMessage(MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(DEVICE_NAME, device.getName()); msg.setData(bundle); handler.sendMessage(msg); setState(Sensor.SensorState.CONNECTED); } /** * Stop all threads */ public synchronized void stop() { Log.d(TAG, "stop()"); if (connectThread != null) { connectThread.cancel(); connectThread = null; } if (connectedThread != null) { connectedThread.cancel(); connectedThread = null; } setState(Sensor.SensorState.NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (state != Sensor.SensorState.CONNECTED) { return; } r = connectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { setState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Bluetooth connection failed."); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { setState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Bluetooth connection lost."); } /** * This thread runs while attempting to make an outgoing connection with a * device. It runs straight through; the connection either succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket socket; private final BluetoothDevice device; public ConnectThread(BluetoothDevice device) { setName("ConnectThread-" + device.getName()); this.device = device; BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { tmp = getSocket(); } catch (IOException e) { Log.e(TAG, "create() failed", e); } socket = tmp; } private BluetoothSocket getSocket() throws IOException { try { Class<? extends BluetoothDevice> c = device.getClass(); Method insecure = c.getMethod("createInsecureRfcommSocket", Integer.class); insecure.setAccessible(true); return (BluetoothSocket) insecure.invoke(device, 1); } catch (SecurityException e) { Log.e(TAG, "Unable to get insecure connect.", e); } catch (NoSuchMethodException e) { Log.e(TAG, "Unable to get insecure connect.", e); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to get insecure connect.", e); } catch (IllegalAccessException e) { Log.e(TAG, "Unable to get insecure connect.", e); } catch (InvocationTargetException e) { Log.e(TAG, "Unable to get insecure connect.", e); } return device.createRfcommSocketToServiceRecord(SPP_UUID); } @Override public void run() { Log.d(TAG, "BEGIN mConnectThread"); // Always cancel discovery because it will slow down a connection adapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception socket.connect(); } catch (IOException e) { connectionFailed(); // Close the socket try { socket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() socket during connection failure", e2); } // Start the service over to restart listening mode BluetoothConnectionManager.this.start(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothConnectionManager.this) { connectThread = null; } // Start the connected thread connected(socket, device); } public void cancel() { try { socket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } /** * This thread runs during a connection with a remote device. It handles all * incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket btSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "create ConnectedThread"); btSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } @Override public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[parser.getFrameSize()]; int bytes; int offset = 0; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer, offset, parser.getFrameSize() - offset); if (bytes < 0) { throw new IOException("EOF reached"); } offset += bytes; if (offset != parser.getFrameSize()) { // partial frame received, call read() again to receive the rest continue; } // check if its a valid frame if (!parser.isValid(buffer)) { int index = parser.findNextAlignment(buffer); if (index > 0) { // re-align offset = parser.getFrameSize() - index; System.arraycopy(buffer, index, buffer, 0, offset); Log.w(TAG, "Misaligned data, found new message at " + index + " recovering..."); continue; } Log.w(TAG, "Could not find valid data, dropping data"); offset = 0; continue; } offset = 0; // Send the obtained bytes to the UI Activity handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } /** * Write to the connected OutStream. * * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity handler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { btSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import android.util.Log; /** * An implementation of a SensorData parser for Zephyr HRM. * * @author Sandor Dornbush */ public class ZephyrMessageParser implements MessageParser { @Override public Sensor.SensorDataSet parseBuffer(byte[] buffer) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buffer.length; i++) { sb.append(String.format("%02X", buffer[i])); } Log.w(TAG, "Got zephyr data: " + sb); // The provided units are 1/16 strides per minute. // TODO: Fix the cadence calculation. // int cadence = SensorUtils.unsignedShortToInt(buffer, 56); // Heart Rate Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(buffer[12] & 0xFF) .setState(Sensor.SensorState.SENDING); // Cadence //.setCadence(cadence / 16) //.build(); Sensor.SensorDataSet sds = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()) .setHeartRate(b) .build(); return sds; } @Override public boolean isValid(byte[] buffer) { // TODO crc etc. return buffer[0] == 0x02 && buffer[59] == 0x03; } @Override public int getFrameSize() { return 60; } @Override public int findNextAlignment(byte[] buffer) { // TODO test or understand this code. for (int i = 0; i < buffer.length - 1; i++) { if (buffer[i] == 0x03 && buffer[i+1] == 0x02) { return i; } } return -1; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services.sensors; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A factory of SensorManagers. * * @author Sandor Dornbush */ public class SensorManagerFactory { private SensorManagerFactory() {} /** * Get a new sensor manager. * @param context Context to fetch system preferences. * @return The sensor manager that corresponds to the sensor type setting. */ public static SensorManager getSensorManager(Context context) { SharedPreferences prefs = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (prefs == null) { return null; } String sensor = prefs.getString(context.getString(R.string.sensor_type_key), null); Log.i(TAG, "Creating sensor of type: " + sensor); if (sensor == null) { return null; } else if (sensor.equals(context.getString(R.string.ant_sensor_type))) { return new AntDirectSensorManager(context); } else if (sensor.equals(context.getString(R.string.srm_ant_bridge_sensor_type))) { return new AntSRMSensorManager(context); } else if (sensor.equals(context.getString(R.string.zephyr_sensor_type))) { return new ZephyrSensorManager(context); } else { Log.w(TAG, "Unable to find sensor type: " + sensor); return null; } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksConstants; import android.util.Log; /** * This class manages a period task executer. * * @author Sandor Dornbush */ public class TaskExecuterManager { private int frequency; private final PeriodicTask task; private PeriodicTaskExecuter executer; public TaskExecuterManager(int frequency, PeriodicTask task, TrackRecordingService service) { this.task = task; setFrequency(frequency, service); } public int getFrequency() { return frequency; } /** * Sets the frequency that the task should be run at. * If needed the task will be scheduled. * * @param frequency The frequency in minutes for the task to run * @param service The service to run the task on */ public void setFrequency(int frequency, TrackRecordingService service) { this.frequency = frequency; Log.i(MyTracksConstants.TAG, "Frequency set to " + frequency + " for task " + task.getClass().getSimpleName()); if (frequency == -1) { if (executer != null) { executer.shutdown(); executer = null; Log.i(MyTracksConstants.TAG, "Shut down service: " + task.getClass().getSimpleName()); } } else { if (executer == null) { executer = new PeriodicTaskExecuter(task, service); } executer.scheduleTask(frequency * 60000); } } /** * Restores the task at the current frequency. */ public void restore() { if (frequency > 0) { executer.scheduleTask(frequency * 60000); } } /** * Shuts down this executer. */ public void shutdown() { if (executer != null) { executer.shutdown(); } } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.services; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksSettings; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.Locale; /** * This class will periodically announce the user's trip statistics. * * @author Sandor Dornbush */ public class StatusAnnouncerTask implements PeriodicTask { /** * The rate at which announcements are spoken. */ // @VisibleForTesting static final float TTS_SPEECH_RATE = 0.9f; /** * A pointer to the service context. */ private final Context context; /** * String utilities. */ private final StringUtils stringUtils; /** * The interface to the text to speech engine. */ protected TextToSpeech tts; /** * The response received from the TTS engine after initialization. */ private boolean ready = false; /** * Whether we're allowed to speak right now. */ private boolean speechAllowed; /** * Listener which updates {@link #speechAllowed} when the phone state changes. */ private final PhoneStateListener phoneListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { speechAllowed = state == TelephonyManager.CALL_STATE_IDLE; if (!speechAllowed && tts.isSpeaking()) { // If we're already speaking, stop it. tts.stop(); } } }; public StatusAnnouncerTask(Context context) { this(context, new StringUtils(context)); } public StatusAnnouncerTask(Context context, StringUtils stringUtils) { this.context = context; this.stringUtils = stringUtils; } /** * Called when the TTS engine is initialized. */ protected void onTtsInit(int status) { Log.i(MyTracksConstants.TAG, "TrackRecordingService.TTS init: " + status); this.ready = status == TextToSpeech.SUCCESS; if (ready) { // Force the language to be the same as the string we will be speaking, // if that's available. Locale speechLanguage = Locale.getDefault(); int languageAvailability = tts.isLanguageAvailable(speechLanguage); if (languageAvailability == TextToSpeech.LANG_MISSING_DATA || languageAvailability == TextToSpeech.LANG_NOT_SUPPORTED) { // English is probably supported. // TODO: Somehow use announcement strings from English too. Log.w(MyTracksConstants.TAG, "Default language not available, using English."); speechLanguage = Locale.ENGLISH; } tts.setLanguage(speechLanguage); // Slow down the speed just a bit as it is hard to hear when exercising. tts.setSpeechRate(TTS_SPEECH_RATE); } } /** * {@inheritDoc} * * Announces the trip status. */ @Override public void run(TrackRecordingService service) { if (!ready || tts == null) { Log.e(MyTracksConstants.TAG, "StatusAnnouncer Tts not ready."); return; } if (!speechAllowed) { Log.i(MyTracksConstants.TAG, "Not making announcement - not allowed at this time"); return; } if (service == null || service.getTripStatistics() == null) { Log.e(MyTracksConstants.TAG, "StatusAnnouncer stats not initialized."); return; } String announcement = getAnnouncement(service.getTripStatistics()); Log.d(MyTracksConstants.TAG, "Announcement: " + announcement); speakAnnouncment(announcement); } protected void speakAnnouncment(String announcement) { tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null); } /** * Builds the announcement string. * * @return The string that will be read to the user */ // @VisibleForTesting protected String getAnnouncement(TripStatistics stats) { SharedPreferences preferences = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); boolean metricUnits = true; boolean reportSpeed = true; if (preferences != null) { metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true); reportSpeed = preferences.getBoolean(context.getString(R.string.report_speed_key), true); } double d = stats.getTotalDistance() / 1000; double s = stats.getAverageMovingSpeed() * 3.6; if (d == 0) { return context.getString(R.string.announce_no_distance); } int speedLabel; if (metricUnits) { if (reportSpeed) { speedLabel = R.string.kilometer_per_hour_long; } else { speedLabel = R.string.per_kilometer; } } else { s *= UnitConversions.KMH_TO_MPH; d *= UnitConversions.KM_TO_MI; if (reportSpeed) { speedLabel = R.string.mile_per_hour_long; } else { speedLabel = R.string.per_mile; } } String speed = null; if ((s == 0) || Double.isNaN(s)) { speed = context.getString(R.string.unknown); } else { if (reportSpeed) { speed = String.format("%.1f", s); } else { double pace = 3600000.0 / s; Log.w(MyTracksConstants.TAG, "Converted speed: " + s + " to pace: " + pace); speed = stringUtils.formatTimeLong((long) pace); } } return context.getString(R.string.announce_template, context.getString(R.string.total_distance_label), d, context.getString(metricUnits ? R.string.kilometers_long : R.string.miles_long), stringUtils.formatTimeLong(stats.getMovingTime()), speed, context.getString(speedLabel)); } @Override public void start() { Log.i(MyTracksConstants.TAG, "Starting TTS"); if (tts == null) { // We can't have this class also be the listener, otherwise it's unsafe to // reference it in Cupcake (even if we don't instantiate it). tts = newTextToSpeech(context, new OnInitListener() { @Override public void onInit(int status) { onTtsInit(status); } }); } speechAllowed = true; // Register ourselves as a listener so we won't speak during a call. listenToPhoneState(phoneListener, PhoneStateListener.LISTEN_CALL_STATE); } @Override public void shutdown() { // Stop listening to phone state. listenToPhoneState(phoneListener, PhoneStateListener.LISTEN_NONE); if (tts != null) { tts.shutdown(); tts = null; } Log.i(MyTracksConstants.TAG, "TTS shut down"); } /** * Wrapper for instantiating a {@link TextToSpeech} object, which causes * several issues during testing. */ // @VisibleForTesting protected TextToSpeech newTextToSpeech(Context ctx, OnInitListener onInitListener) { return new TextToSpeech(ctx, onInitListener); } /** * Wrapper for calls to the 100%-unmockable {@link TelephonyManager#listen}. */ // @VisibleForTesting protected void listenToPhoneState(PhoneStateListener listener, int events) { TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephony != null) { telephony.listen(listener, events); } } /** * Returns the volume stream to use for controlling announcement volume. */ public static int getVolumeStream() { return TextToSpeech.Engine.DEFAULT_STREAM; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.util.ApiFeatures; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; /** * A provider that handles recorded (GPS) tracks and their track points. * * @author Leif Hendrik Wilden */ public class MyTracksProvider extends ContentProvider { private static final String DATABASE_NAME = "mytracks.db"; private static final int DATABASE_VERSION = 19; private static final int TRACKPOINTS = 1; private static final int TRACKPOINTS_ID = 2; private static final int TRACKS = 3; private static final int TRACKS_ID = 4; private static final int WAYPOINTS = 5; private static final int WAYPOINTS_ID = 6; private static final String TRACKPOINTS_TABLE = "trackpoints"; private static final String TRACKS_TABLE = "tracks"; private static final String WAYPOINTS_TABLE = "waypoints"; public static final String TAG = "MyTracksProvider"; /** * Helper which creates or upgrades the database if necessary. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TRACKPOINTS_TABLE + " (" + TrackPointsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TrackPointsColumns.TRACKID + " INTEGER, " + TrackPointsColumns.LONGITUDE + " INTEGER, " + TrackPointsColumns.LATITUDE + " INTEGER, " + TrackPointsColumns.TIME + " INTEGER, " + TrackPointsColumns.ALTITUDE + " FLOAT, " + TrackPointsColumns.ACCURACY + " FLOAT, " + TrackPointsColumns.SPEED + " FLOAT, " + TrackPointsColumns.BEARING + " FLOAT, " + TrackPointsColumns.SENSOR + " BLOB);"); db.execSQL("CREATE TABLE " + TRACKS_TABLE + " (" + TracksColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TracksColumns.NAME + " STRING, " + TracksColumns.DESCRIPTION + " STRING, " + TracksColumns.CATEGORY + " STRING, " + TracksColumns.STARTID + " INTEGER, " + TracksColumns.STOPID + " INTEGER, " + TracksColumns.STARTTIME + " INTEGER, " + TracksColumns.STOPTIME + " INTEGER, " + TracksColumns.NUMPOINTS + " INTEGER, " + TracksColumns.TOTALDISTANCE + " FLOAT, " + TracksColumns.TOTALTIME + " INTEGER, " + TracksColumns.MOVINGTIME + " INTEGER, " + TracksColumns.MINLAT + " INTEGER, " + TracksColumns.MAXLAT + " INTEGER, " + TracksColumns.MINLON + " INTEGER, " + TracksColumns.MAXLON + " INTEGER, " + TracksColumns.AVGSPEED + " FLOAT, " + TracksColumns.AVGMOVINGSPEED + " FLOAT, " + TracksColumns.MAXSPEED + " FLOAT, " + TracksColumns.MINELEVATION + " FLOAT, " + TracksColumns.MAXELEVATION + " FLOAT, " + TracksColumns.ELEVATIONGAIN + " FLOAT, " + TracksColumns.MINGRADE + " FLOAT, " + TracksColumns.MAXGRADE + " FLOAT, " + TracksColumns.MAPID + " STRING, " + TracksColumns.TABLEID + " STRING);"); db.execSQL("CREATE TABLE " + WAYPOINTS_TABLE + " (" + WaypointsColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + WaypointsColumns.NAME + " STRING, " + WaypointsColumns.DESCRIPTION + " STRING, " + WaypointsColumns.CATEGORY + " STRING, " + WaypointsColumns.ICON + " STRING, " + WaypointsColumns.TRACKID + " INTEGER, " + WaypointsColumns.TYPE + " INTEGER, " + WaypointsColumns.LENGTH + " FLOAT, " + WaypointsColumns.DURATION + " INTEGER, " + WaypointsColumns.STARTTIME + " INTEGER, " + WaypointsColumns.STARTID + " INTEGER, " + WaypointsColumns.STOPID + " INTEGER, " + WaypointsColumns.LONGITUDE + " INTEGER, " + WaypointsColumns.LATITUDE + " INTEGER, " + WaypointsColumns.TIME + " INTEGER, " + WaypointsColumns.ALTITUDE + " FLOAT, " + WaypointsColumns.ACCURACY + " FLOAT, " + WaypointsColumns.SPEED + " FLOAT, " + WaypointsColumns.BEARING + " FLOAT, " + WaypointsColumns.TOTALDISTANCE + " FLOAT, " + WaypointsColumns.TOTALTIME + " INTEGER, " + WaypointsColumns.MOVINGTIME + " INTEGER, " + WaypointsColumns.AVGSPEED + " FLOAT, " + WaypointsColumns.AVGMOVINGSPEED + " FLOAT, " + WaypointsColumns.MAXSPEED + " FLOAT, " + WaypointsColumns.MINELEVATION + " FLOAT, " + WaypointsColumns.MAXELEVATION + " FLOAT, " + WaypointsColumns.ELEVATIONGAIN + " FLOAT, " + WaypointsColumns.MINGRADE + " FLOAT, " + WaypointsColumns.MAXGRADE + " FLOAT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 17) { // Wipe the old data. Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TRACKPOINTS_TABLE); db.execSQL("DROP TABLE IF EXISTS " + TRACKS_TABLE); db.execSQL("DROP TABLE IF EXISTS " + WAYPOINTS_TABLE); onCreate(db); } else { // Incremental updates go here. // Each time you increase the DB version, add a corresponding if clause. Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion); // Sensor data. if (oldVersion <= 17) { Log.w(TAG, "Upgrade DB: Adding sensor column."); db.execSQL("ALTER TABLE " + TRACKPOINTS_TABLE + " ADD " + TrackPointsColumns.SENSOR + " BLOB"); } if (oldVersion <= 18) { Log.w(TAG, "Upgrade DB: Adding tableid column."); db.execSQL("ALTER TABLE " + TRACKS_TABLE + " ADD " + TracksColumns.TABLEID + " STRING"); } } } } private final UriMatcher urlMatcher; private SQLiteDatabase db; public MyTracksProvider() { urlMatcher = new UriMatcher(UriMatcher.NO_MATCH); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "trackpoints", TRACKPOINTS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "trackpoints/#", TRACKPOINTS_ID); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "tracks", TRACKS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "tracks/#", TRACKS_ID); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "waypoints", WAYPOINTS); urlMatcher.addURI(MyTracksProviderUtils.AUTHORITY, "waypoints/#", WAYPOINTS_ID); } @Override public boolean onCreate() { DatabaseHelper dbHelper = new DatabaseHelper(getContext()); db = dbHelper.getWritableDatabase(); return db != null; } @Override public int delete(Uri url, String where, String[] selectionArgs) { String table; switch (urlMatcher.match(url)) { case TRACKPOINTS: table = TRACKPOINTS_TABLE; break; case TRACKS: table = TRACKS_TABLE; break; case WAYPOINTS: table = WAYPOINTS_TABLE; break; default: throw new IllegalArgumentException("Unknown URL " + url); } Log.w(MyTracksProvider.TAG, "provider delete in " + table + "!"); int count = db.delete(table, where, selectionArgs); getContext().getContentResolver().notifyChange(url, null, true); return count; } @Override public String getType(Uri url) { switch (urlMatcher.match(url)) { case TRACKPOINTS: return TrackPointsColumns.CONTENT_TYPE; case TRACKPOINTS_ID: return TrackPointsColumns.CONTENT_ITEMTYPE; case TRACKS: return TracksColumns.CONTENT_TYPE; case TRACKS_ID: return TracksColumns.CONTENT_ITEMTYPE; case WAYPOINTS: return WaypointsColumns.CONTENT_TYPE; case WAYPOINTS_ID: return WaypointsColumns.CONTENT_ITEMTYPE; default: throw new IllegalArgumentException("Unknown URL " + url); } } @Override public Uri insert(Uri url, ContentValues initialValues) { Log.d(MyTracksProvider.TAG, "MyTracksProvider.insert"); ContentValues values; if (initialValues != null) { values = initialValues; } else { values = new ContentValues(); } int urlMatchType = urlMatcher.match(url); return insertType(url, urlMatchType, values); } private Uri insertType(Uri url, int urlMatchType, ContentValues values) { switch (urlMatchType) { case TRACKPOINTS: return insertTrackPoint(url, values); case TRACKS: return insertTrack(url, values); case WAYPOINTS: return insertWaypoint(url, values); default: throw new IllegalArgumentException("Unknown URL " + url); } } @Override public int bulkInsert(Uri url, ContentValues[] valuesBulk) { Log.d(MyTracksProvider.TAG, "MyTracksProvider.bulkInsert"); int numInserted = 0; try { // Use a transaction in order to make the insertions run as a single batch db.beginTransaction(); int urlMatch = urlMatcher.match(url); for (numInserted = 0; numInserted < valuesBulk.length; numInserted++) { ContentValues values = valuesBulk[numInserted]; if (values == null) { values = new ContentValues(); } insertType(url, urlMatch, values); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return numInserted; } private Uri insertTrackPoint(Uri url, ContentValues values) { boolean hasLat = values.containsKey(TrackPointsColumns.LATITUDE); boolean hasLong = values.containsKey(TrackPointsColumns.LONGITUDE); boolean hasTime = values.containsKey(TrackPointsColumns.TIME); if (!hasLat || !hasLong || !hasTime) { throw new IllegalArgumentException( "Latitude, longitude, and time values are required."); } long rowId = db.insert(TRACKPOINTS_TABLE, TrackPointsColumns._ID, values); if (rowId >= 0) { Uri uri = ContentUris.appendId( TrackPointsColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLiteException("Failed to insert row into " + url); } private Uri insertTrack(Uri url, ContentValues values) { boolean hasStartTime = values.containsKey(TracksColumns.STARTTIME); boolean hasStartId = values.containsKey(TracksColumns.STARTID); if (!hasStartTime || !hasStartId) { throw new IllegalArgumentException( "Both start time and start id values are required."); } long rowId = db.insert(TRACKS_TABLE, TracksColumns._ID, values); if (rowId > 0) { Uri uri = ContentUris.appendId( TracksColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLException("Failed to insert row into " + url); } private Uri insertWaypoint(Uri url, ContentValues values) { long rowId = db.insert(WAYPOINTS_TABLE, WaypointsColumns._ID, values); if (rowId > 0) { Uri uri = ContentUris.appendId( WaypointsColumns.CONTENT_URI.buildUpon(), rowId).build(); getContext().getContentResolver().notifyChange(url, null, true); return uri; } throw new SQLException("Failed to insert row into " + url); } @Override public Cursor query( Uri url, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); int match = urlMatcher.match(url); String sortOrder = null; if (match == TRACKPOINTS) { qb.setTables(TRACKPOINTS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = TrackPointsColumns.DEFAULT_SORT_ORDER; } } else if (match == TRACKPOINTS_ID) { qb.setTables(TRACKPOINTS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else if (match == TRACKS) { qb.setTables(TRACKS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = TracksColumns.DEFAULT_SORT_ORDER; } } else if (match == TRACKS_ID) { qb.setTables(TRACKS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else if (match == WAYPOINTS) { qb.setTables(WAYPOINTS_TABLE); if (sort != null) { sortOrder = sort; } else { sortOrder = WaypointsColumns.DEFAULT_SORT_ORDER; } } else if (match == WAYPOINTS_ID) { qb.setTables(WAYPOINTS_TABLE); qb.appendWhere("_id=" + url.getPathSegments().get(1)); } else { throw new IllegalArgumentException("Unknown URL " + url); } if (ApiFeatures.getInstance().canReuseSQLiteQueryBuilder()) { Log.i(MyTracksConstants.TAG, "Build query: " + qb.buildQuery(projection, selection, selectionArgs, null, null, sortOrder, null)); } Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), url); return c; } @Override public int update(Uri url, ContentValues values, String where, String[] selectionArgs) { int count; int match = urlMatcher.match(url); if (match == TRACKPOINTS) { count = db.update(TRACKPOINTS_TABLE, values, where, selectionArgs); } else if (match == TRACKPOINTS_ID) { String segment = url.getPathSegments().get(1); count = db.update(TRACKPOINTS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else if (match == TRACKS) { count = db.update(TRACKS_TABLE, values, where, selectionArgs); } else if (match == TRACKS_ID) { String segment = url.getPathSegments().get(1); count = db.update(TRACKS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else if (match == WAYPOINTS) { count = db.update(WAYPOINTS_TABLE, values, where, selectionArgs); } else if (match == WAYPOINTS_ID) { String segment = url.getPathSegments().get(1); count = db.update(WAYPOINTS_TABLE, values, "_id=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), selectionArgs); } else { throw new IllegalArgumentException("Unknown URL " + url); } getContext().getContentResolver().notifyChange(url, null, true); return count; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; /** * Utilities for serializing primitive types. * * @author Rodrigo Damazio */ public class ContentTypeIds { public static final byte BOOLEAN_TYPE_ID = 0; public static final byte LONG_TYPE_ID = 1; public static final byte INT_TYPE_ID = 2; public static final byte FLOAT_TYPE_ID = 3; public static final byte DOUBLE_TYPE_ID = 4; public static final byte STRING_TYPE_ID = 5; public static final byte BLOB_TYPE_ID = 6; private ContentTypeIds() { /* Not instantiable */ } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import java.text.DecimalFormat; import java.text.NumberFormat; import android.app.Activity; import android.util.Log; import android.widget.TextView; /** * Various utility functions for views that display statistics information. * * @author Sandor Dornbush */ public class StatsUtilities { private final Activity activity; private static final NumberFormat LAT_LONG_FORMAT = new DecimalFormat("##,###.00000"); private static final NumberFormat ALTITUDE_FORMAT = new DecimalFormat("###,###"); private static final NumberFormat SPEED_FORMAT = new DecimalFormat("#,###,###.00"); private static final NumberFormat GRADE_FORMAT = new DecimalFormat("##.0%"); /** * True if distances should be displayed in metric units (from shared * preferences). */ private boolean metricUnits = true; /** * True - report speed * False - report pace */ private boolean reportSpeed = true; public StatsUtilities(Activity a) { this.activity = a; } public boolean isMetricUnits() { return metricUnits; } public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; } public boolean isReportSpeed() { return reportSpeed; } public void setReportSpeed(boolean reportSpeed) { this.reportSpeed = reportSpeed; } public void setUnknown(int id) { ((TextView) activity.findViewById(id)).setText(R.string.unknown); } public void setText(int id, double d, NumberFormat format) { if (!Double.isNaN(d) && !Double.isInfinite(d)) { setText(id, format.format(d)); } } public void setText(int id, String s) { int lengthLimit = 8; String displayString = s.length() > lengthLimit ? s.substring(0, lengthLimit - 3) + "..." : s; ((TextView) activity.findViewById(id)).setText(displayString); } public void setLatLong(int id, double d) { TextView msgTextView = (TextView) activity.findViewById(id); msgTextView.setText(LAT_LONG_FORMAT.format(d)); } public void setAltitude(int id, double d) { setText(id, (metricUnits ? d : (d * UnitConversions.M_TO_FT)), ALTITUDE_FORMAT); } public void setDistance(int id, double d) { setText(id, (metricUnits ? d : (d * UnitConversions.KM_TO_MI)), SPEED_FORMAT); } public void setSpeed(int id, double d) { if (d == 0) { setUnknown(id); return; } double speed = metricUnits ? d : d * UnitConversions.KM_TO_MI; if (reportSpeed) { setText(id, speed, SPEED_FORMAT); } else { // Format as milliseconds per unit long pace = (long) (3600000.0 / speed); setTime(id, pace); } } public void setAltitudeUnits(int unitLabelId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(metricUnits ? R.string.meter : R.string.feet); } public void setDistanceUnits(int unitLabelId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(metricUnits ? R.string.kilometer : R.string.mile); } public void setSpeedUnits(int unitLabelId, int unitLabelBottomId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(reportSpeed ? (metricUnits ? R.string.kilometer : R.string.mile) : R.string.min); unitTextView = (TextView) activity.findViewById(unitLabelBottomId); unitTextView.setText(reportSpeed ? R.string.hr : (metricUnits ? R.string.kilometer : R.string.mile)); } public void setTime(int id, long l) { setText(id, StringUtils.formatTime(l)); } public void setGrade(int id, double d) { setText(id, d, GRADE_FORMAT); } /** * Updates the unit fields. */ public void updateUnits() { setSpeedUnits(R.id.speed_unit_label_top, R.id.speed_unit_label_bottom); updateWaypointUnits(); } /** * Updates the units fields used by waypoints. */ public void updateWaypointUnits() { setSpeedUnits(R.id.average_moving_speed_unit_label_top, R.id.average_moving_speed_unit_label_bottom); setSpeedUnits(R.id.average_speed_unit_label_top, R.id.average_speed_unit_label_bottom); setDistanceUnits(R.id.total_distance_unit_label); setSpeedUnits(R.id.max_speed_unit_label_top, R.id.max_speed_unit_label_bottom); setAltitudeUnits(R.id.elevation_unit_label); setAltitudeUnits(R.id.elevation_gain_unit_label); setAltitudeUnits(R.id.min_elevation_unit_label); setAltitudeUnits(R.id.max_elevation_unit_label); } /** * Sets all fields to "-" (unknown). */ public void setAllToUnknown() { // "Instant" values: setUnknown(R.id.elevation_register); setUnknown(R.id.latitude_register); setUnknown(R.id.longitude_register); setUnknown(R.id.speed_register); // Values from provider: setUnknown(R.id.total_time_register); setUnknown(R.id.moving_time_register); setUnknown(R.id.total_distance_register); setUnknown(R.id.average_speed_register); setUnknown(R.id.average_moving_speed_register); setUnknown(R.id.max_speed_register); setUnknown(R.id.min_elevation_register); setUnknown(R.id.max_elevation_register); setUnknown(R.id.elevation_gain_register); setUnknown(R.id.min_grade_register); setUnknown(R.id.max_grade_register); } public void setAllStats(long movingTime, double totalDistance, double averageSpeed, double averageMovingSpeed, double maxSpeed, double minElevation, double maxElevation, double elevationGain, double minGrade, double maxGrade) { setTime(R.id.moving_time_register, movingTime); setDistance(R.id.total_distance_register, totalDistance / 1000); setSpeed(R.id.average_speed_register, averageSpeed * 3.6); setSpeed(R.id.average_moving_speed_register, averageMovingSpeed * 3.6); setSpeed(R.id.max_speed_register, maxSpeed * 3.6); setAltitude(R.id.min_elevation_register, minElevation); setAltitude(R.id.max_elevation_register, maxElevation); setAltitude(R.id.elevation_gain_register, elevationGain); setGrade(R.id.min_grade_register, minGrade); setGrade(R.id.max_grade_register, maxGrade); } public void setAllStats(TripStatistics stats) { setTime(R.id.moving_time_register, stats.getMovingTime()); setDistance(R.id.total_distance_register, stats.getTotalDistance() / 1000); setSpeed(R.id.average_speed_register, stats.getAverageSpeed() * 3.6); setSpeed(R.id.average_moving_speed_register, stats.getAverageMovingSpeed() * 3.6); setSpeed(R.id.max_speed_register, stats.getMaxSpeed() * 3.6); setAltitude(R.id.min_elevation_register, stats.getMinElevation()); setAltitude(R.id.max_elevation_register, stats.getMaxElevation()); setAltitude(R.id.elevation_gain_register, stats.getTotalElevationGain()); setGrade(R.id.min_grade_register, stats.getMinGrade()); setGrade(R.id.max_grade_register, stats.getMaxGrade()); setTime(R.id.total_time_register, stats.getTotalTime()); } public void setSpeedLabel(int id, int speedString, int paceString) { Log.w(MyTracksConstants.TAG, "Setting view " + id + " to " + reportSpeed + " speed: " + speedString + " pace: " + paceString); TextView tv = ((TextView) activity.findViewById(id)); if (tv != null) { tv.setText(reportSpeed ? speedString : paceString); } else { Log.w(MyTracksConstants.TAG, "Could not find id: " + id); } } public void setSpeedLabels() { setSpeedLabel(R.id.average_speed_label, R.string.average_speed_label, R.string.average_pace_label); setSpeedLabel(R.id.average_moving_speed_label, R.string.average_moving_speed_label, R.string.average_moving_pace_label); setSpeedLabel(R.id.max_speed_label, R.string.max_speed_label, R.string.min_pace_label); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.RadioGroup; /** * An activity that allows the user to set the chart settings. * * @author Sandor Dornbush */ public class ChartSettingsDialog extends Dialog { private RadioButton distance; private CheckBox[] series; public ChartSettingsDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.chart_settings); Button cancel = (Button) findViewById(R.id.chart_settings_cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dismiss(); } }); Button ok = (Button) findViewById(R.id.chart_settings_ok); ok.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { handleOk(); } }); distance = (RadioButton) findViewById(R.id.chart_settings_by_distance); series = new CheckBox[ChartView.NUM_SERIES]; series[ChartView.ELEVATION_SERIES] = (CheckBox) findViewById(R.id.chart_settings_elevation); series[ChartView.SPEED_SERIES] = (CheckBox) findViewById(R.id.chart_settings_speed); series[ChartView.POWER_SERIES] = (CheckBox) findViewById(R.id.chart_settings_power); series[ChartView.CADENCE_SERIES] = (CheckBox) findViewById(R.id.chart_settings_cadence); series[ChartView.HEART_RATE_SERIES] = (CheckBox) findViewById(R.id.chart_settings_heart_rate); } public void setup(ChartActivity chart) { if (chart == null) { return; } RadioGroup rd = (RadioGroup) findViewById(R.id.chart_settings_x); rd.check(chart.getMode() == Mode.BY_DISTANCE ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); for (int i = 0; i < ChartView.NUM_SERIES; i++) { series[i].setChecked(chart.isSeriesEnabled(i)); } } private void handleOk() { ChartActivity chart = MyTracks.getInstance().getChartActivity(); chart.setMode(distance.isChecked() ? Mode.BY_DISTANCE : Mode.BY_TIME); // TODO: check that something is visible. for (int i = 0; i < ChartView.NUM_SERIES; i++) { chart.setSeriesEnabled(i, series[i].isChecked()); } dismiss(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import static android.content.Intent.ACTION_BOOT_COMPLETED; import static com.google.android.apps.mytracks.MyTracksConstants.RESUME_TRACK_EXTRA_NAME; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.services.TrackRecordingService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class handles MyTracks related broadcast messages. * * One example of a broadcast message that this class is interested in, * is notification about the phone boot. We may want to resume a previously * started tracking session if the phone crashed (hopefully not), or the user * decided to swap the battery or some external event occurred which forced * a phone reboot. * * This class simply delegates to {@link TrackRecordingService} to make a * decision whether to continue with the previous track (if any), or just * abandon it. * * @author Bartlomiej Niechwiej */ public class MyTracksReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "MyTracksReceiver.onReceive: " + intent.getAction()); if (ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Intent startIntent = new Intent(context, TrackRecordingService.class); startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true); context.startService(startIntent); } else { Log.w(TAG, "MyTracksReceiver: unsupported action"); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; /** * A list preference which persists its values as integers instead of strings. * Code reading the values should use * {@link android.content.SharedPreferences#getInt}. * When using XML-declared arrays for entry values, the arrays should be regular * string arrays containing valid integer values. * * @author Rodrigo Damazio */ public class IntegerListPreference extends ListPreference { public IntegerListPreference(Context context) { super(context); verifyEntryValues(null); } public IntegerListPreference(Context context, AttributeSet attrs) { super(context, attrs); verifyEntryValues(null); } @Override public void setEntryValues(CharSequence[] entryValues) { CharSequence[] oldValues = getEntryValues(); super.setEntryValues(entryValues); verifyEntryValues(oldValues); } @Override public void setEntryValues(int entryValuesResId) { CharSequence[] oldValues = getEntryValues(); super.setEntryValues(entryValuesResId); verifyEntryValues(oldValues); } @Override protected String getPersistedString(String defaultReturnValue) { // During initial load, there's no known default value int defaultIntegerValue = Integer.MIN_VALUE; if (defaultReturnValue != null) { defaultIntegerValue = Integer.parseInt(defaultReturnValue); } // When the list preference asks us to read a string, instead read an // integer. int value = getPersistedInt(defaultIntegerValue); return Integer.toString(value); } @Override protected boolean persistString(String value) { // When asked to save a string, instead save an integer return persistInt(Integer.parseInt(value)); } private void verifyEntryValues(CharSequence[] oldValues) { CharSequence[] entryValues = getEntryValues(); if (entryValues == null) { return; } for (CharSequence entryValue : entryValues) { try { Integer.parseInt(entryValue.toString()); } catch (NumberFormatException nfe) { super.setEntryValues(oldValues); throw nfe; } } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; /** * A preference for an ANT device pairing. * Currently this shows the ID and lets the user clear that ID for future pairing. * TODO: Support pairing from this preference. * * @author Sandor Dornbush */ public class AntPreference extends Preference { public AntPreference(Context context) { super(context); init(); } public AntPreference(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { int sensorId = getPersistedInt(0); if (sensorId == 0) { setSummary(R.string.settings_ant_not_paired); } else { setSummary(String.format(getContext().getString(R.string.settings_ant_paired), sensorId)); } // Add actions to allow repairing. setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AntPreference.this.persistInt(0); setSummary(R.string.settings_ant_not_paired); return true; } }); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.ResourceUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; /** * This class handles display of EULAs ("End User License Agreements") to the * user. */ class Eula { private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; private static final String PREFERENCES_EULA = "eula"; private Eula() {} /** * Displays the EULA if necessary. This method should be called from the * onCreate() method of your main Activity. If the user accepts, the EULA * will never be displayed again. If the user refuses, the activity will * finish (exit). * * @param activity The Activity to finish if the user rejects the EULA */ static void showEulaRequireAcceptance(final Activity activity) { final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA, Activity.MODE_PRIVATE); if (preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) { return; } final AlertDialog.Builder builder = initDialog(activity); builder.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { accept(activity, preferences); } }); builder.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { refuse(activity); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { refuse(activity); } }); builder.show(); } /** * Display the EULA to the user in an informational context. They won't be * given the choice of accepting or declining the EULA -- we're simply * displaying it for them to read. */ static void showEula(Context context) { AlertDialog.Builder builder = initDialog(context); builder.setPositiveButton(R.string.ok, null); builder.show(); } private static AlertDialog.Builder initDialog(Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setTitle(R.string.eula_title); builder.setMessage(ResourceUtils.readFile(context, R.raw.eula)); return builder; } private static void accept(Activity activity, SharedPreferences preferences) { ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges( preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true)); Intent startIntent = new Intent(activity, WelcomeActivity.class); activity.startActivityForResult(startIntent, MyTracksConstants.WELCOME); } private static void refuse(Activity activity) { activity.finish(); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; /** * Constants used by the MyTracks application. * * @author Leif Hendrik Wilden */ public abstract class MyTracksConstants { /** * Should be used by all log statements */ public static final String TAG = "MyTracks"; /** * Name of the gps location provider: */ public static final String GPS_PROVIDER = "gps"; /** * Name of the top-level directory inside the SD card where our files will * be read from/written to. */ public static final String SDCARD_TOP_DIR = "MyTracks"; /* * onActivityResult request codes: */ public static final int GET_LOGIN = 0; public static final int GET_MAP = 1; public static final int CREATE_MAP = 2; public static final int SHOW_TRACK = 3; public static final int ADD_LIST = 4; public static final int FEATURE_DETAILS = 5; public static final int START_RECORDING = 6; public static final int STOP_RECORDING = 7; public static final int AUTHENTICATE_TO_MY_MAPS = 8; public static final int AUTHENTICATE_TO_FUSION_TABLES = 9; public static final int AUTHENTICATE_TO_DOCLIST = 10; public static final int AUTHENTICATE_TO_TRIX = 11; public static final int DELETE_TRACK = 13; public static final int SEND_TO_GOOGLE_DIALOG = 14; public static final int SHARE_LINK = 15; public static final int SHARE_GPX_FILE = 16; public static final int SHARE_KML_FILE = 17; public static final int SHARE_CSV_FILE = 18; public static final int SHARE_TCX_FILE = 19; public static final int EDIT_DETAILS = 20; public static final int SAVE_GPX_FILE = 21; public static final int SAVE_KML_FILE = 22; public static final int SAVE_CSV_FILE = 23; public static final int SAVE_TCX_FILE = 24; public static final int CLEAR_MAP = 25; public static final int SHOW_WAYPOINT = 26; public static final int EDIT_WAYPOINT = 27; public static final int WELCOME = 28; /* * Menu ids: */ public static final int MENU_MY_LOCATION = 1; public static final int MENU_TOGGLE_LAYERS = 2; public static final int MENU_CHART_SETTINGS = 3; public static final int MENU_CURRENT_SEGMENT = 4; /* * Context menu ids: */ public static final int MENU_EDIT = 100; public static final int MENU_DELETE = 101; public static final int MENU_SEND_TO_GOOGLE = 102; public static final int MENU_SHARE = 103; public static final int MENU_SHOW = 104; public static final int MENU_SHARE_LINK = 200; public static final int MENU_SHARE_GPX_FILE = 201; public static final int MENU_SHARE_KML_FILE = 202; public static final int MENU_SHARE_CSV_FILE = 203; public static final int MENU_SHARE_TCX_FILE = 204; public static final int MENU_WRITE_TO_SD_CARD = 205; public static final int MENU_SAVE_GPX_FILE = 206; public static final int MENU_SAVE_KML_FILE = 207; public static final int MENU_SAVE_CSV_FILE = 208; public static final int MENU_SAVE_TCX_FILE = 209; public static final int MENU_CLEAR_MAP = 210; /** * The number of distance readings to smooth to get a stable signal. */ public static final int DISTANCE_SMOOTHING_FACTOR = 25; /** * The number of elevation readings to smooth to get a somewhat accurate * signal. */ public static final int ELEVATION_SMOOTHING_FACTOR = 25; /** * The number of grade readings to smooth to get a somewhat accurate signal. */ public static final int GRADE_SMOOTHING_FACTOR = 5; /** * The number of speed reading to smooth to get a somewhat accurate signal. */ public static final int SPEED_SMOOTHING_FACTOR = 25; /** * Maximum number of track points displayed by the map overlay. */ public static final int MAX_DISPLAYED_TRACK_POINTS = 10000; /** * Target number of track points displayed by the map overlay. * We may display more than this number of points. */ public static final int TARGET_DISPLAYED_TRACK_POINTS = 5000; /** * Maximum number of track points ever loaded at once from the provider into * memory. * With a recording frequency of 2 seconds, 15000 corresponds to 8.3 hours. */ public static final int MAX_LOADED_TRACK_POINTS = 20000; /** * Maximum number of way points displayed by the map overlay. */ public static final int MAX_DISPLAYED_WAYPOINTS_POINTS = 128; /** * Maximum number of way points that will be loaded at one time. */ public static final int MAX_LOADED_WAYPOINTS_POINTS = 10000; /** * Any time segment where the distance traveled is less than this value will * not be considered moving. */ public static final double MAX_NO_MOVEMENT_DISTANCE = 2; /** * Anything faster than that (in meters per second) will be considered moving. */ public static final double MAX_NO_MOVEMENT_SPEED = 0.224; /** * Ignore any acceleration faster than this. * Will ignore any speeds that imply accelaration greater than 2g's * 2g = 19.6 m/s^2 = 0.0002 m/ms^2 = 0.02 m/(m*ms) */ public static final double MAX_ACCELERATION = 0.02; /** * The type of account that we can use for gdata uploads. */ public static final String ACCOUNT_TYPE = "com.google"; /** * The name of extra intent property to indicate whether we want to resume * a previously recorded track. */ public static final String RESUME_TRACK_EXTRA_NAME = "com.google.android.apps.mytracks.RESUME_TRACK"; public static int getActionFromMenuId(int menuId) { switch (menuId) { case MyTracksConstants.MENU_SEND_TO_GOOGLE: return MyTracksConstants.SEND_TO_GOOGLE_DIALOG; case MyTracksConstants.MENU_EDIT: return MyTracksConstants.EDIT_DETAILS; case MyTracksConstants.MENU_DELETE: return MyTracksConstants.DELETE_TRACK; case MyTracksConstants.MENU_SHARE_LINK: return MyTracksConstants.SHARE_LINK; case MyTracksConstants.MENU_SHARE_KML_FILE: return MyTracksConstants.SHARE_KML_FILE; case MyTracksConstants.MENU_SHARE_GPX_FILE: return MyTracksConstants.SHARE_GPX_FILE; case MyTracksConstants.MENU_SHARE_CSV_FILE: return MyTracksConstants.SHARE_CSV_FILE; case MyTracksConstants.MENU_SHARE_TCX_FILE: return MyTracksConstants.SHARE_TCX_FILE; case MyTracksConstants.MENU_SAVE_GPX_FILE: return MyTracksConstants.SAVE_GPX_FILE; case MyTracksConstants.MENU_SAVE_KML_FILE: return MyTracksConstants.SAVE_KML_FILE; case MyTracksConstants.MENU_SAVE_CSV_FILE: return MyTracksConstants.SAVE_CSV_FILE; case MyTracksConstants.MENU_SAVE_TCX_FILE: return MyTracksConstants.SAVE_TCX_FILE; case MyTracksConstants.MENU_CLEAR_MAP: return MyTracksConstants.CLEAR_MAP; default: return -1; } } public static final String MAPSHOP_BASE_URL = "http://maps.google.com/maps/ms"; /** * This is an abstract utility class. */ protected MyTracksConstants() { } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import com.google.android.apps.mytracks.MyTracksConstants; import com.google.android.apps.mytracks.MyTracksSettings; import android.location.Location; import android.util.Log; /** * Statistics keeper for a trip. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class TripStatisticsBuilder { /** * Statistical data about the trip, which can be displayed to the user. */ private final TripStatistics data; /** * The last location that the gps reported. */ private Location lastLocation; /** * The last location that contributed to the stats. It is also the last * location the user was found to be moving. */ private Location lastMovingLocation; /** * The current speed in meters/second as reported by the gps. */ private double currentSpeed; /** * The current grade. This value is very noisy and not reported to the user. */ private double currentGrade; /** * Is the trip currently paused? * All trips start paused. */ private boolean paused = true; /** * A buffer of the last speed readings in meters/second. */ private final DoubleBuffer speedBuffer = new DoubleBuffer(MyTracksConstants.SPEED_SMOOTHING_FACTOR); /** * A buffer of the recent elevation readings in meters. */ private final DoubleBuffer elevationBuffer = new DoubleBuffer(MyTracksConstants.ELEVATION_SMOOTHING_FACTOR); /** * A buffer of the distance between recent gps readings in meters. */ private final DoubleBuffer distanceBuffer = new DoubleBuffer(MyTracksConstants.DISTANCE_SMOOTHING_FACTOR); /** * A buffer of the recent grade calculations. */ private final DoubleBuffer gradeBuffer = new DoubleBuffer(MyTracksConstants.GRADE_SMOOTHING_FACTOR); /** * The total number of locations in this trip. */ private long totalLocations = 0; private int minRecordingDistance = MyTracksSettings.DEFAULT_MIN_RECORDING_DISTANCE; /** * Creates a new trip starting at the given time. * * @param startTime the start time. */ public TripStatisticsBuilder(long startTime) { data = new TripStatistics(); resumeAt(startTime); } /** * Creates a new trip, starting with existing statistics data. * * @param statsData the statistics data to copy and start from */ public TripStatisticsBuilder(TripStatistics statsData) { data = new TripStatistics(statsData); if (data.getStartTime() > 0) { resumeAt(data.getStartTime()); } } /** * Adds a location to the current trip. This will update all of the internal * variables with this new location. * * @param currentLocation the current gps location * @param systemTime the time used for calculation of totalTime. This should * be the phone's time (not GPS time) * @return true if the person is moving */ public boolean addLocation(Location currentLocation, long systemTime) { if (paused) { Log.w(MyTracksConstants.TAG, "Tried to account for location while track is paused"); return false; } totalLocations++; double elevationDifference = updateElevation(currentLocation.getAltitude()); // Update the "instant" values: data.setTotalTime(systemTime - data.getStartTime()); currentSpeed = currentLocation.getSpeed(); // This was the 1st location added, remember it and do nothing else: if (lastLocation == null) { lastLocation = currentLocation; lastMovingLocation = currentLocation; return false; } updateBounds(currentLocation); // Don't do anything if we didn't move since last fix: double distance = lastLocation.distanceTo(currentLocation); if (distance < minRecordingDistance && currentSpeed < MyTracksConstants.MAX_NO_MOVEMENT_SPEED) { lastLocation = currentLocation; return false; } data.addTotalDistance(lastMovingLocation.distanceTo(currentLocation)); updateSpeed(currentLocation.getTime(), currentSpeed, lastLocation.getTime(), lastLocation.getSpeed()); updateGrade(distance, elevationDifference); lastLocation = currentLocation; lastMovingLocation = currentLocation; return true; } /** * Updates the track's bounding box to include the given location. */ private void updateBounds(Location location) { data.updateLatitudeExtremities(location.getLatitude()); data.updateLongitudeExtremities(location.getLongitude()); } /** * Updates the elevation measurements. * * @param elevation the current elevation */ // @VisibleForTesting double updateElevation(double elevation) { double oldSmoothedElevation = getSmoothedElevation(); elevationBuffer.setNext(elevation); double smoothedElevation = getSmoothedElevation(); data.updateElevationExtremities(smoothedElevation); double elevationDifference = elevationBuffer.isFull() ? smoothedElevation - oldSmoothedElevation : 0.0; if (elevationDifference > 0) { data.addTotalElevationGain(elevationDifference); } return elevationDifference; } /** * Updates the speed measurements. * * @param updateTime the time of the speed update * @param speed the current speed * @param lastLocationTime the time of the last speed update * @param lastLocationSpeed the speed of the last update */ // @VisibleForTesting void updateSpeed(long updateTime, double speed, long lastLocationTime, double lastLocationSpeed) { // We are now sure the user is moving. long timeDifference = updateTime - lastLocationTime; if (timeDifference < 0) { Log.e(MyTracksConstants.TAG, "Found negative time change: " + timeDifference); } data.addMovingTime(timeDifference); if (isValidSpeed(updateTime, speed, lastLocationTime, lastLocationSpeed, speedBuffer)) { speedBuffer.setNext(speed); if (speed > data.getMaxSpeed()) { data.setMaxSpeed(speed); } double movingSpeed = data.getAverageMovingSpeed(); if (speedBuffer.isFull() && (movingSpeed > data.getMaxSpeed())) { data.setMaxSpeed(movingSpeed); } } else { Log.d(MyTracksConstants.TAG, "TripStatistics ignoring big change: Raw Speed: " + speed + " old: " + lastLocationSpeed + " [" + toString() + "]"); } } /** * Checks to see if this is a valid speed. * * @param updateTime The time at the current reading * @param speed The current speed * @param lastLocationTime The time at the last location * @param lastLocationSpeed Speed at the last location * @param speedBuffer A buffer of recent readings * @return True if this is likely a valid speed */ public static boolean isValidSpeed(long updateTime, double speed, long lastLocationTime, double lastLocationSpeed, DoubleBuffer speedBuffer) { // We don't want to count 0 towards the speed. if (speed == 0) { return false; } // We are now sure the user is moving. long timeDifference = updateTime - lastLocationTime; // There are a lot of noisy speed readings. // Do the cheapest checks first, most expensive last. // The following code will ignore unlikely to be real readings. // - 128 m/s seems to be an internal android error code. if (Math.abs(speed - 128) < 1) { return false; } // Another check for a spurious reading. See if the path seems physically // likely. Ignore any speeds that imply accelaration greater than 2g's // Really who can accelerate faster? double speedDifference = Math.abs(lastLocationSpeed - speed); if (speedDifference > MyTracksConstants.MAX_ACCELERATION * timeDifference) { return false; } // There are three additional checks if the reading gets this far: // - Only use the speed if the buffer is full // - Check that the current speed is less than 10x the recent smoothed speed // - Double check that the current speed does not imply crazy acceleration double smoothedSpeed = speedBuffer.getAverage(); double smoothedDiff = Math.abs(smoothedSpeed - speed); return !speedBuffer.isFull() || (speed < smoothedSpeed * 10 && smoothedDiff < MyTracksConstants.MAX_ACCELERATION * timeDifference); } /** * Updates the grade measurements. * * @param distance the distance the user just traveled * @param elevationDifference the elevation difference between the current * reading and the previous reading */ // @VisibleForTesting void updateGrade(double distance, double elevationDifference) { distanceBuffer.setNext(distance); double smoothedDistance = distanceBuffer.getAverage(); // With the error in the altitude measurement it is dangerous to divide // by anything less than 5. if (!elevationBuffer.isFull() || !distanceBuffer.isFull() || smoothedDistance < 5.0) { return; } currentGrade = elevationDifference / smoothedDistance; gradeBuffer.setNext(currentGrade); data.updateGradeExtremities(gradeBuffer.getAverage()); } /** * Pauses the track at the given time. * * @param time the time to pause at */ public void pauseAt(long time) { if (paused) { return; } data.setStopTime(time); data.setTotalTime(time - data.getStartTime()); lastLocation = null; // Make sure the counter restarts. paused = true; } /** * Resumes the current track at the given time. * * @param time the time to resume at */ public void resumeAt(long time) { if (!paused) { return; } // TODO: The times are bogus if the track is paused then resumed again data.setStartTime(time); data.setStopTime(-1); paused = false; } @Override public String toString() { return "TripStatistics { Data: " + data.toString() + "; Total Locations: " + totalLocations + "; Paused: " + paused + "; Current speed: " + currentSpeed + "; Current grade: " + currentGrade + "}"; } /** * Returns the amount of time the user has been idle or 0 if they are moving. */ public long getIdleTime() { if (lastLocation == null || lastMovingLocation == null) return 0; return lastLocation.getTime() - lastMovingLocation.getTime(); } /** * Gets the current elevation smoothed over several readings. The elevation * data is very noisy so it is better to use the smoothed elevation than the * raw elevation for many tasks. * * @return The elevation smoothed over several readings */ public double getSmoothedElevation() { return elevationBuffer.getAverage(); } public TripStatistics getStatistics() { // Take a snapshot - we don't want anyone messing with our internals return new TripStatistics(data); } public void setMinRecordingDistance(int minRecordingDistance) { this.minRecordingDistance = minRecordingDistance; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; /** * This class maintains a buffer of doubles. This buffer is a convenient class * for storing a series of doubles and calculating information about them. This * is a FIFO buffer. * * @author Sandor Dornbush */ public class DoubleBuffer { /** * The location that the next write will occur at. */ private int index; /** * The sliding buffer of doubles. */ private final double[] buffer; /** * Have all of the slots in the buffer been filled? */ private boolean isFull; /** * Creates a buffer with size elements. * * @param size the number of elements in the buffer * @throws IllegalArgumentException if the size is not a positive value */ public DoubleBuffer(int size) { if (size < 1) { throw new IllegalArgumentException("The buffer size must be positive."); } buffer = new double[size]; reset(); } /** * Adds a double to the buffer. If the buffer is full the oldest element is * overwritten. * * @param d the double to add */ public void setNext(double d) { if (index == buffer.length) { index = 0; } buffer[index] = d; index++; if (index == buffer.length) { isFull = true; } } /** * Are all of the entries in the buffer used? */ public boolean isFull() { return isFull; } /** * Resets the buffer to the initial state. */ public void reset() { index = 0; isFull = false; } /** * Gets the average of values from the buffer. * * @return The average of the buffer */ public double getAverage() { int numberOfEntries = isFull ? buffer.length : index; if (numberOfEntries == 0) { return 0; } double sum = 0; for (int i = 0; i < numberOfEntries; i++) { sum += buffer[i]; } return sum / numberOfEntries; } /** * Gets the average and standard deviation of the buffer. * * @return An array of two elements - the first is the average, and the second * is the variance */ public double[] getAverageAndVariance() { int numberOfEntries = isFull ? buffer.length : index; if (numberOfEntries == 0) { return new double[]{0, 0}; } double sum = 0; double sumSquares = 0; for (int i = 0; i < numberOfEntries; i++) { sum += buffer[i]; sumSquares += Math.pow(buffer[i], 2); } double average = sum / numberOfEntries; return new double[]{average, sumSquares / numberOfEntries - Math.pow(average, 2)}; } @Override public String toString() { StringBuffer stringBuffer = new StringBuffer("Full: "); stringBuffer.append(isFull); stringBuffer.append("\n"); for (int i = 0; i < buffer.length; i++) { stringBuffer.append((i == index) ? "<<" : "["); stringBuffer.append(buffer[i]); stringBuffer.append((i == index) ? ">> " : "] "); } return stringBuffer.toString(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.io.GpxImporter; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.SharedPreferences; import android.os.Handler; import android.os.HandlerThread; import android.os.PowerManager.WakeLock; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * A class that will import all GPX tracks in /sdcard/MyTracks/gpx/ * * @author David Piggott */ public class ImportAllTracks { private final Activity activity; private WakeLock wakeLock; private ProgressDialog progress; private FileUtils fileUtils; private String gpxPath; private int gpxFileCount; private int importSuccessCount; public ImportAllTracks(Activity activity) { this.activity = activity; Log.i(MyTracksConstants.TAG, "ImportAllTracks: Starting"); fileUtils = new FileUtils(); gpxPath = fileUtils.buildExternalDirectoryPath("gpx"); HandlerThread handlerThread; Handler handler; handlerThread = new HandlerThread("ImportAllTracks"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); handler.post(runner); } private final Runnable runner = new Runnable() { public void run() { aquireLocksAndImport(); } }; /** * Makes sure that we keep the phone from sleeping. See if there is a current * track. Acquire a wake lock if there is no current track. */ private void aquireLocksAndImport() { SharedPreferences prefs = activity.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId != -1) { wakeLock = MyTracksUtils.acquireWakeLock(activity, wakeLock); } // Now we can safely import everything. importAll(); // Release the wake lock if we acquired one. // TODO check what happens if we started recording after getting this lock. if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.i(MyTracksConstants.TAG, "ImportAllTracks: Releasing wake lock."); } Log.i(MyTracksConstants.TAG, "ImportAllTracks: Done"); AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (gpxFileCount == 0) { builder.setMessage(activity.getString(R.string.import_empty, gpxPath + "/")); } else { builder.setMessage(activity.getString(R.string.import_done, importSuccessCount, gpxFileCount, gpxPath + "/")); } builder.setPositiveButton(R.string.ok, null); builder.show(); } private void makeProgressDialog(final int trackCount) { String importMsg = activity.getString(R.string.tracklist_btn_import_all); progress = new ProgressDialog(activity); progress.setIcon(android.R.drawable.ic_dialog_info); progress.setTitle(importMsg); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setMax(trackCount); progress.setProgress(0); progress.show(); } /** * Actually import the tracks. This should be called after the wake locks have * been acquired. */ private void importAll() { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(activity); if (!fileUtils.isSdCardAvailable()) { return; } List<File> gpxFiles = getGpxFiles(); gpxFileCount = gpxFiles.size(); if (gpxFileCount == 0) { return; } Log.i(MyTracksConstants.TAG, "ImportAllTracks: Importing: " + gpxFileCount + " tracks."); activity.runOnUiThread(new Runnable() { public void run() { makeProgressDialog(gpxFileCount); } }); Iterator<File> gpxFilesIterator = gpxFiles.iterator(); for (int currentFileNumber = 0; gpxFilesIterator.hasNext(); currentFileNumber++) { File currentFile = gpxFilesIterator.next(); final int status = currentFileNumber; activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progress == null) { return; } progress.setProgress(status); } } }); if (importFile(currentFile, providerUtils)) { importSuccessCount++; } } if (progress != null) { synchronized (this) { progress.dismiss(); progress = null; } } } /** * Attempts to import a GPX file. Returns true on success, issues error * notifications and returns false on failure. */ private boolean importFile(File gpxFile, MyTracksProviderUtils providerUtils) { Log.i(MyTracksConstants.TAG, "ImportAllTracks: importing: " + gpxFile.getName()); try { GpxImporter.importGPXFile(new FileInputStream(gpxFile), providerUtils); return true; } catch (FileNotFoundException e) { Log.w(MyTracksConstants.TAG, "GPX file wasn't found/went missing: " + gpxFile.getAbsolutePath(), e); } catch (ParserConfigurationException e) { Log.w(MyTracksConstants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (SAXException e) { Log.w(MyTracksConstants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (IOException e) { Log.w(MyTracksConstants.TAG, "Error reading file: " + gpxFile.getAbsolutePath(), e); } Toast.makeText(activity, activity.getString(R.string.import_error, gpxFile.getName()), Toast.LENGTH_LONG).show(); return false; } /** * Returns a list of the GPX Files found in the GPX directory. */ private List<File> getGpxFiles() { List<File> gpxFiles = new LinkedList<File>(); File[] gpxFileCandidates = new File(gpxPath).listFiles(); if (gpxFileCandidates != null) { for (File file : gpxFileCandidates) { if (!file.isDirectory() && file.getName().endsWith(".gpx")) { gpxFiles.add(file); } } } return gpxFiles; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.stats.ExtremityMonitor; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Paint.Style; import java.text.DecimalFormat; /** * This class encapsulates meta data about one series of values for a chart. * * @author Sandor Dornbush */ public class ChartValueSeries { private final ExtremityMonitor monitor = new ExtremityMonitor(); private final DecimalFormat format; private final Path path = new Path(); private final Paint fillPaint; private final Paint strokePaint; private final Paint labelPaint; private final ZoomSettings zoomSettings; private String title; private double min; private double max = 1.0; private int effectiveMax; private int effectiveMin; private double spread; private int interval; private boolean enabled = true; /** * This class controls how effective min/max values of a {@link ChartValueSeries} are calculated. */ public static class ZoomSettings { private int intervals; private final int absoluteMin; private final int absoluteMax; private final int[] zoomLevels; public ZoomSettings(int intervals, int[] zoomLevels) { this.intervals = intervals; this.absoluteMin = Integer.MAX_VALUE; this.absoluteMax = Integer.MIN_VALUE; this.zoomLevels = zoomLevels; checkArgs(); } public ZoomSettings(int intervals, int absoluteMin, int absoluteMax, int[] zoomLevels) { this.intervals = intervals; this.absoluteMin = absoluteMin; this.absoluteMax = absoluteMax; this.zoomLevels = zoomLevels; checkArgs(); } private void checkArgs() { if (intervals <= 0 || zoomLevels == null || zoomLevels.length == 0) { throw new IllegalArgumentException("Expecing positive intervals and non-empty zoom levels"); } for (int i = 1; i < zoomLevels.length; ++i) { if (zoomLevels[i] <= zoomLevels[i - 1]) { throw new IllegalArgumentException("Expecting zoom levels in ascending order"); } } } public int getIntervals() { return intervals; } public int getAbsoluteMin() { return absoluteMin; } public int getAbsoluteMax() { return absoluteMax; } public int[] getZoomLevels() { return zoomLevels; } /** * Calculates the interval between markings given the min and max values. * This function attempts to find the smallest zoom level that fits [min,max] after rounding * it to the current zoom level. * * @param min the minimum value in the series * @param max the maximum value in the series * @return the calculated interval for the given range */ public int calculateInterval(double min, double max) { min = Math.min(min, absoluteMin); max = Math.max(max, absoluteMax); for (int i = 0; i < zoomLevels.length; ++i) { int zoomLevel = zoomLevels[i]; int roundedMin = (int)(min / zoomLevel) * zoomLevel; if (roundedMin > min) { roundedMin -= zoomLevel; } double interval = (max - roundedMin) / intervals; if (zoomLevel >= interval) { return zoomLevel; } } return zoomLevels[zoomLevels.length - 1]; } } /** * Constructs a new chart value series. * * @param context The context for the chart * @param formatString The format of the decimal format for this series * @param fill The paint for filling the chart * @param stroke The paint for stroking the outside the chart, optional * @param zoomSettings The settings related to zooming * * TODO: Get rid of Context and inject appropriate values instead. */ public ChartValueSeries(Context context, String formatString, int fillColor, int strokeColor, ZoomSettings zoomSettings, int titleId) { this.format = new DecimalFormat(formatString); fillPaint = new Paint(); fillPaint.setStyle(Style.FILL); fillPaint.setColor(context.getResources().getColor(fillColor)); fillPaint.setAntiAlias(true); if (strokeColor != -1) { strokePaint = new Paint(); strokePaint.setStyle(Style.STROKE); strokePaint.setColor(context.getResources().getColor(strokeColor)); strokePaint.setAntiAlias(true); // Make a copy of the stroke paint with the default thickness. labelPaint = new Paint(strokePaint); strokePaint.setStrokeWidth(2f); } else { strokePaint = null; labelPaint = fillPaint; } this.zoomSettings = zoomSettings; this.title = context.getString(titleId); } /** * Draws the path of the chart */ public void drawPath(Canvas c) { c.drawPath(path, fillPaint); if (strokePaint != null) { c.drawPath(path, strokePaint); } } /** * Resets this series */ public void reset() { monitor.reset(); } /** * Updates this series with a new value */ public void update(double d) { monitor.update(d); } /** * @return The interval between markers */ public int getInterval() { return interval; } /** * Determines what the min and max of the chart will be. * This will round down and up the min and max respectively. */ public void updateDimension() { if (monitor.getMax() == Double.NEGATIVE_INFINITY) { min = 0; max = 1; } else { min = monitor.getMin(); max = monitor.getMax(); } min = Math.min(min, zoomSettings.getAbsoluteMin()); max = Math.max(max, zoomSettings.getAbsoluteMax()); this.interval = zoomSettings.calculateInterval(min, max); // Round it up. effectiveMax = ((int) (max / interval)) * interval + interval; // Round it down. effectiveMin = ((int) (min / interval)) * interval; if (min < 0) { effectiveMin -= interval; } spread = effectiveMax - effectiveMin; } /** * @return The length of the longest string from the series */ public int getMaxLabelLength() { String minS = format.format(effectiveMin); String maxS = format.format(getMax()); return Math.max(minS.length(), maxS.length()); } /** * @return The rounded down minimum value */ public int getMin() { return effectiveMin; } /** * @return The rounded up maximum value */ public int getMax() { return effectiveMax; } /** * @return The difference between the min and max values in the series */ public double getSpread() { return spread; } /** * @return The format for the decimal format for this series */ DecimalFormat getFormat() { return format; } /** * @return The path for this series */ Path getPath() { return path; } /** * @return The paint for this series */ Paint getPaint() { return strokePaint == null ? fillPaint : strokePaint; } public Paint getLabelPaint() { return labelPaint; } /** * @return The title of the series */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * @return is this series enabled */ public boolean isEnabled() { return enabled; } /** * Sets the series enabled flag. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean hasData() { return monitor.hasData(); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.io.TrackWriter; import com.google.android.apps.mytracks.io.TrackWriterFactory; import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Handler; import android.os.HandlerThread; import android.os.PowerManager.WakeLock; import android.util.Log; import android.widget.Toast; /** * A class that will export all tracks to the sd card. * * @author Sandor Dornbush */ public class ExportAllTracks { // These must line up with the index in the array. public static final int GPX_OPTION_INDEX = 0; public static final int KML_OPTION_INDEX = 1; public static final int CSV_OPTION_INDEX = 2; public static final int TCX_OPTION_INDEX = 3; private final Activity activity; private WakeLock wakeLock; private ProgressDialog progress; private TrackFileFormat format = TrackFileFormat.GPX; private final DialogInterface.OnClickListener itemClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case GPX_OPTION_INDEX: format = TrackFileFormat.GPX; break; case KML_OPTION_INDEX: format = TrackFileFormat.KML; break; case CSV_OPTION_INDEX: format = TrackFileFormat.CSV; break; case TCX_OPTION_INDEX: format = TrackFileFormat.TCX; break; default: Log.w(MyTracksConstants.TAG, "Unknown export format: " + which); } } }; public ExportAllTracks(Activity activity) { this.activity = activity; Log.i(MyTracksConstants.TAG, "ExportAllTracks: Starting"); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setSingleChoiceItems(R.array.export_formats, 0, itemClick); builder.setPositiveButton(R.string.ok, positiveClick); builder.setNegativeButton(R.string.cancel, null); builder.show(); } private final DialogInterface.OnClickListener positiveClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { HandlerThread handlerThread; Handler handler; handlerThread = new HandlerThread("SendToMyMaps"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); handler.post(runner); } }; private final Runnable runner = new Runnable() { public void run() { aquireLocksAndExport(); } }; /** * Makes sure that we keep the phone from sleeping. * See if there is a current track. Aquire a wake lock if there is no * current track. */ private void aquireLocksAndExport() { SharedPreferences prefs = activity.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId != -1) { wakeLock = MyTracksUtils.acquireWakeLock(activity, wakeLock); } // Now we can safely export everything. exportAll(); // Release the wake lock if we recorded one. // TODO check what happens if we started recording after getting this lock. if (wakeLock != null && wakeLock.isHeld()) { wakeLock.release(); Log.i(MyTracksConstants.TAG, "ExportAllTracks: Releasing wake lock."); } Log.i(MyTracksConstants.TAG, "ExportAllTracks: Done"); Toast.makeText(activity, R.string.export_done, Toast.LENGTH_SHORT).show(); } private void makeProgressDialog(final int trackCount) { String exportMsg = activity.getString(R.string.tracklist_btn_export_all); progress = new ProgressDialog(activity); progress.setIcon(android.R.drawable.ic_dialog_info); progress.setTitle(exportMsg); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setMax(trackCount); progress.setProgress(0); progress.show(); } /** * Actually export the tracks. * This should be called after the wake locks have been aquired. */ private void exportAll() { // Get a cursor over all tracks. Cursor cursor = null; try { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(activity); cursor = providerUtils.getTracksCursor(""); if (cursor == null) { return; } final int trackCount = cursor.getCount(); Log.i(MyTracksConstants.TAG, "ExportAllTracks: Exporting: " + cursor.getCount() + " tracks."); int idxTrackId = cursor.getColumnIndexOrThrow(TracksColumns._ID); activity.runOnUiThread(new Runnable() { public void run() { makeProgressDialog(trackCount); } }); for (int i = 0; cursor.moveToNext(); i++) { final int status = i; activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progress == null) { return; } progress.setProgress(status); } } }); long id = cursor.getLong(idxTrackId); Log.i(MyTracksConstants.TAG, "ExportAllTracks: exporting: " + id); TrackWriter writer = TrackWriterFactory.newWriter(activity, providerUtils, id, format); writer.writeTrack(); if (!writer.wasSuccess()) { // Abort the whole export on the first error. int error = writer.getErrorMessage(); Toast.makeText(activity, error, Toast.LENGTH_LONG).show(); return; } } } finally { if (cursor != null) { cursor.close(); } if (progress != null) { synchronized (this) { progress.dismiss(); progress = null; } } } } }
Java
package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Window; import android.widget.ScrollView; import android.widget.TextView; import java.util.List; /** * Activity for viewing the combined statistics for all the recorded tracks. * * Other features to add - menu items to change setings. * * @author Fergus Nelson */ public class AggregatedStatsActivity extends Activity implements OnSharedPreferenceChangeListener { private final StatsUtilities utils; private MyTracksProviderUtils tracksProvider; private boolean metricUnits = true; public AggregatedStatsActivity() { this.utils = new StatsUtilities(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(MyTracksConstants.TAG, "StatsActivity: onSharedPreferences changed " + key); if (key != null) { if (key.equals(R.string.metric_units_key)) { metricUnits = sharedPreferences.getBoolean( getString(R.string.metric_units_key), true); utils.setMetricUnits(metricUnits); utils.updateUnits(); loadAggregatedStats(); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.tracksProvider = MyTracksProviderUtils.Factory.get(this); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.stats); ScrollView sv = ((ScrollView) findViewById(R.id.scrolly)); sv.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); SharedPreferences preferences = getSharedPreferences( MyTracksSettings.SETTINGS_NAME, 0); if (preferences != null) { metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true); preferences.registerOnSharedPreferenceChangeListener(this); } utils.setMetricUnits(metricUnits); utils.updateUnits(); utils.setSpeedLabel(R.id.speed_label, R.string.speed, R.string.pace_label); utils.setSpeedLabels(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (metrics.heightPixels > 600) { ((TextView) findViewById(R.id.speed_register)).setTextSize(80.0f); } loadAggregatedStats(); } /** * 1. Reads tracks from the db * 2. Merges the trip stats from the tracks * 3. Updates the view */ private void loadAggregatedStats() { List<Track> tracks = retrieveTracks(); TripStatistics rollingStats = null; if (!tracks.isEmpty()) { rollingStats = new TripStatistics(tracks.iterator().next() .getStatistics()); for (int i = 1; i < tracks.size(); i++) { rollingStats.merge(tracks.get(i).getStatistics()); } } updateView(rollingStats); } private List<Track> retrieveTracks() { return tracksProvider.getAllTracks(); } private void updateView(TripStatistics aggStats) { if (aggStats != null) { utils.setAllStats(aggStats); } } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import static com.google.android.apps.mytracks.DialogManager.DIALOG_IMPORT_PROGRESS; import static com.google.android.apps.mytracks.DialogManager.DIALOG_PROGRESS; import static com.google.android.apps.mytracks.DialogManager.DIALOG_SEND_TO_GOOGLE; import static com.google.android.apps.mytracks.DialogManager.DIALOG_WRITE_PROGRESS; import com.google.android.accounts.Account; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManagerFactory; import com.google.android.apps.mytracks.io.GpxImporter; import com.google.android.apps.mytracks.io.SendToDocs; import com.google.android.apps.mytracks.io.SendToFusionTables; import com.google.android.apps.mytracks.io.SendToFusionTables.OnSendCompletedListener; import com.google.android.apps.mytracks.io.SendToMyMaps; import com.google.android.apps.mytracks.io.TempFileCleaner; import com.google.android.apps.mytracks.io.TrackWriter; import com.google.android.apps.mytracks.io.TrackWriterFactory; import com.google.android.apps.mytracks.io.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.io.mymaps.MapsService; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.services.TrackRecordingService; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.TabActivity; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Resources; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TabHost; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * The super activity that embeds our sub activities. * * @author Leif Hendrik Wilden */ public class MyTracks extends TabActivity implements OnTouchListener, OnSharedPreferenceChangeListener, ProgressIndicator { /** * Singleton instance */ private static MyTracks instance; private ChartActivity chartActivity; /* * Authentication */ private AuthManager auth; private final HashMap<String, AuthManager> authMap = new HashMap<String, AuthManager>(); private final AccountChooser accountChooser = new AccountChooser(); /* * Dialogs manager. */ private DialogManager dialogManager; /* * Menu manager. */ private MenuManager menuManager; /* * Information on upload success to MyMaps/Docs. * Used by SendToGoogleResultDialog. */ public long sendToTrackId = -1; public boolean sendToMyMapsSuccess = false; public boolean sendToFusionTablesSuccess = false; public boolean sendToDocsSuccess = false; public String sendToMyMapsMapId; public String sendToMyMapsMessage = ""; public String sendToFusionTablesTableId; public String sendToFusionTablesMessage = ""; public String sendToDocsMessage = ""; /** * True if a new track should be created after the track recording service * binds. */ private boolean startNewTrackRequested = false; private ITrackRecordingService trackRecordingService; /** * The id of the currently recording track. */ private long recordingTrackId = -1; /** * The id of the currently selected track. */ private long selectedTrackId = -1; /** * Does the user want to share the current track. */ private boolean shareRequested = false; /** * Utilities to deal with the database. */ private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; /** * The connection to the track recording service. */ private final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.d(MyTracksConstants.TAG, "MyTracks: Service now connected."); // Delay setting the service until we are done with initialization. ITrackRecordingService trackRecordingService = ITrackRecordingService.Stub.asInterface(service); try { // TODO: Send a start service intent and broadcast service started // message to avoid the hack below and a race condition. if (startNewTrackRequested) { startNewTrackRequested = false; startRecordingNewTrack(trackRecordingService); } } finally { MyTracks.this.trackRecordingService = trackRecordingService; } } @Override public void onServiceDisconnected(ComponentName className) { Log.d(MyTracksConstants.TAG, "MyTracks: Service now disconnected."); trackRecordingService = null; } }; /** * Whether {@link #serviceConnection} is bound or not. */ private boolean isBound = false; /* * Tabs/View navigation: */ private NavControls navControls; private final Runnable changeTab = new Runnable() { public void run() { getTabHost().setCurrentTab(navControls.getCurrentIcons()); } }; public static MyTracks getInstance() { return instance; } /** * Checks whether we have a track recording session in progress. * In some cases, when the service has crashed or has been restarted * by the system, we fall back to the shared preferences. * * @return true if the activity is bound to the track recording service and * the service is recording a track or in case the service is down, * based on settings from the shared preferences. */ public boolean isRecording() { if (trackRecordingService == null) { // Fall back to alternative check method. return isRecordingBasedOnSharedPreferences(); } try { return trackRecordingService.isRecording(); // TODO: We catch Exception, because after eliminating the service process // all exceptions it may throw are no longer wrapped in a RemoteException. } catch (Exception e) { Log.e(MyTracksConstants.TAG, "MyTracks: Remote exception.", e); // Fall back to alternative check method. return isRecordingBasedOnSharedPreferences(); } } private boolean isRecordingBasedOnSharedPreferences() { // TrackRecordingService guarantees that recordingTrackId is set to // -1 if the track has been stopped. return recordingTrackId >= 0; } /* * Application lifetime events: * ============================ */ @Override protected void onCreate(Bundle savedInstanceState) { Log.d(MyTracksConstants.TAG, "MyTracks.onCreate"); super.onCreate(savedInstanceState); instance = this; ApiFeatures apiFeatures = ApiFeatures.getInstance(); if (!MyTracksUtils.isRelease(this)) { apiFeatures.getApiPlatformAdapter().enableStrictMode(); } providerUtils = MyTracksProviderUtils.Factory.get(this); menuManager = new MenuManager(this); sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); dialogManager = new DialogManager(this); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(apiFeatures).getVolumeStream(); setVolumeControlStream(volumeStream); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); final Resources res = getResources(); final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("Map", res.getDrawable( android.R.drawable.ic_menu_mapmode)) .setContent(new Intent(this, MyTracksMap.class))); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("Stats", res.getDrawable(R.drawable.menu_stats)) .setContent(new Intent(this, StatsActivity.class))); tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("Chart", res.getDrawable(R.drawable.menu_elevation)) .setContent(new Intent(this, ChartActivity.class))); // Hide the tab widget itself. We'll use overlayed prev/next buttons to // switch between the tabs: tabHost.getTabWidget().setVisibility(View.GONE); RelativeLayout layout = new RelativeLayout(this); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.setLayoutParams(params); navControls = new NavControls(this, layout, getResources().obtainTypedArray(R.array.left_icons), getResources().obtainTypedArray(R.array.right_icons), changeTab); navControls.show(); tabHost.addView(layout); layout.setOnTouchListener(this); if (sharedPreferences != null) { selectedTrackId = sharedPreferences.getLong(getString(R.string.selected_track_key), -1); recordingTrackId = sharedPreferences.getLong( getString(R.string.recording_track_key), -1); sharedPreferences.registerOnSharedPreferenceChangeListener(this); Log.d(MyTracksConstants.TAG, "recordingTrackId: " + recordingTrackId + ", selectedTrackId: " + selectedTrackId); if (recordingTrackId > 0) { Intent startIntent = new Intent(this, TrackRecordingService.class); startService(startIntent); } } // This will show the eula until the user accepts or quits the app. Eula.showEulaRequireAcceptance(this); // Check if we got invoked via the VIEW intent: Intent intent = getIntent(); String action; if (intent != null && (action = intent.getAction()) != null) { if (action.equals(Intent.ACTION_MAIN)) { // Do nothing. } else if (action.equals(Intent.ACTION_VIEW)) { if (intent.getScheme() != null && intent.getScheme().equals("file")) { Log.w(MyTracksConstants.TAG, "Received a VIEW intent with file scheme. Importing."); importGpxFile(intent.getData().getPath()); } else { Log.w(MyTracksConstants.TAG, "Received a VIEW intent with unsupported scheme " + intent.getScheme()); } } else { Log.w(MyTracksConstants.TAG, "Received an intent with unsupported action " + action); } } else { Log.d(MyTracksConstants.TAG, "Received an intent with no action."); } } @Override protected void onDestroy() { Log.d(MyTracksConstants.TAG, "MyTracks.onDestroy"); tryUnbindTrackRecordingService(); super.onDestroy(); } @Override protected void onPause() { // Called when activity is going into the background, but has not (yet) been // killed. Shouldn't block longer than approx. 2 seconds. Log.d(MyTracksConstants.TAG, "MyTracks.onPause"); tryUnbindTrackRecordingService(); super.onPause(); } @Override protected void onResume() { // Called when the current activity is being displayed or re-displayed // to the user. Log.d(MyTracksConstants.TAG, "MyTracks.onResume"); tryBindTrackRecordingService(); super.onResume(); } @Override protected void onStop() { Log.d(MyTracksConstants.TAG, "MyTracks.onStop"); // Clean up any temporary track files. TempFileCleaner.clean(); super.onStop(); } /* * Menu events: * ============ */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return menuManager.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menuManager.onPrepareOptionsMenu(menu, providerUtils.getLastTrack() != null, isRecording(), selectedTrackId >= 0); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return menuManager.onOptionsItemSelected(item) ? true : super.onOptionsItemSelected(item); } /* * Dialog events: * ============== */ @Override protected Dialog onCreateDialog(int id, Bundle args) { return dialogManager.onCreateDialog(id, args); } @Override protected Dialog onCreateDialog(int id) { return dialogManager.onCreateDialog(id, null); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); dialogManager.onPrepareDialog(id, dialog); } /* * Key events: * =========== */ @Override public boolean onTrackballEvent(MotionEvent event) { if (isRecording()) { if (event.getAction() == MotionEvent.ACTION_DOWN) { try { insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } catch (RemoteException e) { Log.e(MyTracksConstants.TAG, "Cannot insert statistics marker.", e); } catch (IllegalStateException e) { Log.e(MyTracksConstants.TAG, "Cannot insert statistics marker.", e); } return true; } } return super.onTrackballEvent(event); } @Override public void onActivityResult(int requestCode, int resultCode, final Intent results) { TrackFileFormat exportFormat = null; switch (requestCode) { case MyTracksConstants.GET_LOGIN: { if (resultCode != RESULT_OK || auth == null || !auth.authResult(resultCode, results)) { dialogManager.dismissDialogSafely(DIALOG_PROGRESS); } break; } case MyTracksConstants.SHOW_TRACK: { if (results != null) { final long trackId = results.getLongExtra("trackid", -1); if (trackId >= 0) { setSelectedTrackId(trackId); // The track list passed the requested action as result code. Hand // it off to the onAcitivtyResult for further processing: if (resultCode != MyTracksConstants.SHOW_TRACK) { onActivityResult(resultCode, Activity.RESULT_OK, results); } } } break; } case MyTracksConstants.SHOW_WAYPOINT: { if (results != null) { final long waypointId = results.getLongExtra("waypointid", -1); if (waypointId >= 0) { MyTracksMap map = (MyTracksMap) getLocalActivityManager().getActivity("tab1"); if (map != null) { getTabHost().setCurrentTab(0); map.showWaypoint(waypointId); } } } break; } case MyTracksConstants.DELETE_TRACK: { if (results != null && resultCode == RESULT_OK) { final long trackId = results.getLongExtra("trackid", selectedTrackId); deleteTrack(trackId); } break; } case MyTracksConstants.EDIT_DETAILS: { if (results != null && resultCode == RESULT_OK) { final long trackId = results.getLongExtra("trackid", selectedTrackId); Intent intent = new Intent(this, MyTracksDetails.class); intent.putExtra("trackid", trackId); startActivity(intent); } break; } case MyTracksConstants.SEND_TO_GOOGLE_DIALOG: { shareRequested = false; dialogManager.showDialogSafely(DIALOG_SEND_TO_GOOGLE); break; } case MyTracksConstants.GET_MAP: { // User picked a map to upload to if (resultCode == RESULT_OK) { results.putExtra("trackid", selectedTrackId); if (results.hasExtra("mapid")) { sendToMyMapsMapId = results.getStringExtra("mapid"); } authenticateToGoogleMaps(results); } else { onSendToGoogleDone(); } break; } case MyTracksConstants.AUTHENTICATE_TO_MY_MAPS: { // Authenticated with Google My Maps if (results != null && resultCode == RESULT_OK) { final String mapId; final long trackId; if (results.hasExtra("mapid")) { mapId = results.getStringExtra("mapid"); } else { mapId = "new"; } if (results.hasExtra("trackid")) { trackId = results.getLongExtra("trackid", -1); } else { trackId = selectedTrackId; } sendToGoogleMaps(trackId, mapId); } else { onSendToGoogleDone(); } break; } case MyTracksConstants.AUTHENTICATE_TO_FUSION_TABLES: { // Authenticated with Google Fusion Tables if (results != null && resultCode == RESULT_OK) { final long trackId; if (results.hasExtra("trackid")) { trackId = results.getLongExtra("trackid", -1); } else { trackId = selectedTrackId; } sendToFusionTables(trackId); } else { onSendToGoogleDone(); } break; } case MyTracksConstants.AUTHENTICATE_TO_DOCLIST: { // Authenticated with Google Docs if (resultCode == RESULT_OK) { authenticateToGoogleTrix(); } else { onSendToGoogleDone(); } break; } case MyTracksConstants.AUTHENTICATE_TO_TRIX: { // Authenticated with Trix if (resultCode == RESULT_OK) { final long trackId = results.getLongExtra("trackid", selectedTrackId); sendToGoogleDocs(trackId); } else { onSendToGoogleDone(); } break; } case MyTracksConstants.SAVE_GPX_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.GPX; } //$FALL-THROUGH$ case MyTracksConstants.SAVE_KML_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.KML; } //$FALL-THROUGH$ case MyTracksConstants.SAVE_CSV_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.CSV; } //$FALL-THROUGH$ case MyTracksConstants.SAVE_TCX_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.TCX; } if (results != null && resultCode == Activity.RESULT_OK) { final long trackId = results.getLongExtra("trackid", selectedTrackId); if (trackId >= 0) { saveTrack(trackId, exportFormat); } } break; case MyTracksConstants.SHARE_LINK: { Track selectedTrack = providerUtils.getTrack(selectedTrackId); if (selectedTrack != null) { if (!TextUtils.isEmpty(selectedTrack.getMapId())) { shareLinkToMap(MapsService.buildMapUrl(selectedTrack.getMapId())); } else if (!TextUtils.isEmpty(selectedTrack.getTableId())) { shareLinkToMap(getFusionTablesUrl(selectedTrackId)); } else { shareRequested = true; dialogManager.showDialogSafely(DIALOG_SEND_TO_GOOGLE); } } break; } case MyTracksConstants.SHARE_GPX_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.GPX; } //$FALL-THROUGH$ case MyTracksConstants.SHARE_KML_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.KML; } //$FALL-THROUGH$ case MyTracksConstants.SHARE_CSV_FILE: if (exportFormat == null) { exportFormat = TrackFileFormat.CSV; } //$FALL-THROUGH$ case MyTracksConstants.SHARE_TCX_FILE: { if (exportFormat == null) { exportFormat = TrackFileFormat.TCX; } if (results != null && resultCode == Activity.RESULT_OK) { final long trackId = results.getLongExtra("trackid", selectedTrackId); if (trackId >= 0) { sendTrack(trackId, exportFormat); } } break; } case MyTracksConstants.CLEAR_MAP: { setSelectedTrackId(-1); break; } case MyTracksConstants.WELCOME: { CheckUnits.check(this); break; } default: { Log.w(MyTracksConstants.TAG, "Warning unhandled request code: " + requestCode); } } } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { navControls.show(); } return false; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key != null && key.equals(getString(R.string.selected_track_key))) { selectedTrackId = sharedPreferences.getLong( 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); } } /** * Resets status information for sending to MyMaps/Docs. */ public void resetSendToGoogleStatus() { sendToMyMapsMapId = null; sendToMyMapsMessage = ""; sendToMyMapsSuccess = true; sendToFusionTablesMessage = ""; sendToFusionTablesSuccess = true; sendToDocsMessage = ""; sendToDocsSuccess = true; sendToFusionTablesTableId = null; } private void importGpxFile(final String fileName) { dialogManager.showDialogSafely(DIALOG_IMPORT_PROGRESS); Thread t = new Thread() { @Override public void run() { int message = R.string.success; long[] trackIdsImported = null; try { try { InputStream is = new FileInputStream(fileName); trackIdsImported = GpxImporter.importGPXFile(is, providerUtils); } catch (SAXException e) { Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); message = R.string.error_generic; } catch (ParserConfigurationException e) { Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); message = R.string.error_generic; } catch (IOException e) { Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); message = R.string.error_unable_to_read_file; } catch (NullPointerException e) { Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); message = R.string.error_invalid_gpx_format; } catch (OutOfMemoryError e) { Log.e(MyTracksConstants.TAG, "Caught an unexpected exception.", e); message = R.string.error_out_of_memory; } if (trackIdsImported != null && trackIdsImported.length > 0) { // select last track from import file setSelectedTrackId(trackIdsImported[trackIdsImported.length - 1]); } else { dialogManager.showMessageDialog(message, false/* success */); } } finally { runOnUiThread(new Runnable() { public void run() { dismissDialog(DIALOG_IMPORT_PROGRESS); } }); } } }; t.start(); } // ProgressIndicator implementation @Override public void setProgressMessage(int resId) { dialogManager.setProgressMessage(getString(resId)); } @Override public void clearProgressMessage() { dialogManager.setProgressMessage(""); } @Override public void setProgressValue(final int percent) { dialogManager.setProgressValue(percent); } /** * Shares a link to a My Map or Fusion Table via external app (email, gmail, ...) * A chooser with apps that support text/plain will be shown to the user. */ public void shareLinkToMap(String url) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getText(R.string.share_map_subject).toString()); boolean shareUrlOnly = true; if (sharedPreferences != null) { shareUrlOnly = sharedPreferences.getBoolean( getString(R.string.share_url_only_key), false); } String msg = shareUrlOnly ? url : String.format( getResources().getText(R.string.share_map_body_format).toString(), url); shareIntent.putExtra(Intent.EXTRA_TEXT, msg); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_map).toString())); } /** * Deletes the track with the given id. * Prompts the user if he want to really delete the track first. * If the selected track is deleted, the selection will be removed. */ public void deleteTrack(final long trackId) { AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.track_will_be_permanently_deleted)); builder.setTitle(getString(R.string.are_you_sure_question)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); providerUtils.deleteTrack(trackId); if (trackId == selectedTrackId) { setSelectedTrackId(-1); } }}); builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } public Location getCurrentLocation() { // TODO: Let's look at more advanced algorithms to determine the best // current location. LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager == null) { return null; } final long maxAgeMilliSeconds = 1000 * 60 * 1; // 1 minute final long maxAgeNetworkMilliSeconds = 1000 * 60 * 10; // 10 minutes final long now = System.currentTimeMillis(); Location loc = locationManager.getLastKnownLocation( MyTracksConstants.GPS_PROVIDER); if (loc == null || loc.getTime() < now - maxAgeMilliSeconds) { // We don't have a recent GPS fix, just use cell towers if available loc = locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER); if (loc == null || loc.getTime() < now - maxAgeNetworkMilliSeconds) { // We don't have a recent cell tower location, let the user know: Toast.makeText(this, getString(R.string.status_no_location), Toast.LENGTH_LONG).show(); return null; } else { // Let the user know we have only an approximate location: Toast.makeText(this, getString(R.string.status_approximate_location), Toast.LENGTH_LONG).show(); } } return loc; } public Location getLastLocation() { if (providerUtils.getLastLocationId(recordingTrackId) < 0) { return null; } LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.getLastKnownLocation(MyTracksConstants.GPS_PROVIDER); } /** * Inserts a waypoint marker. * * @return Id of the inserted statistics marker. * @throws RemoteException If the call on the service failed. */ public long insertWaypoint(WaypointCreationRequest request) throws RemoteException { if (trackRecordingService == null) { throw new IllegalStateException("The recording service is not bound."); } try { long waypointId = trackRecordingService.insertWaypoint(request); if (waypointId >= 0) { Toast.makeText(this, R.string.status_statistics_inserted, Toast.LENGTH_LONG).show(); } return waypointId; } catch (RemoteException e) { Toast.makeText(this, R.string.error_unable_to_insert_marker, Toast.LENGTH_LONG).show(); throw e; } } /** * Initializes the authentication manager which obtains an authentication * token, prompting the user for a login and password if needed. */ private void authenticate(final Intent results, final int requestCode, final String service) { auth = authMap.get(service); if (auth == null) { Log.i(MyTracksConstants.TAG, "Creating a new authentication for service: " + service); auth = AuthManagerFactory.getAuthManager(this, MyTracksConstants.GET_LOGIN, null, true, service); authMap.put(service, auth); } Log.d(MyTracksConstants.TAG, "Logging in to " + service + "..."); if (AuthManagerFactory.useModernAuthManager()) { runOnUiThread(new Runnable() { @Override public void run() { accountChooser.chooseAccount(MyTracks.this, new AccountChooser.AccountHandler() { @Override public void handleAccountSelected(Account account) { if (account == null) { dialogManager.dismissDialogSafely(DIALOG_PROGRESS); return; } doLogin(results, requestCode, service, account); } }); } }); } else { doLogin(results, requestCode, service, null); } } private void doLogin(final Intent results, final int requestCode, final String service, final Account account) { auth.doLogin(new Runnable() { public void run() { Log.d(MyTracksConstants.TAG, "Loggin success for " + service + "!"); onActivityResult(requestCode, RESULT_OK, results); } }, account); } private void startRecordingNewTrack( ITrackRecordingService trackRecordingService) { try { recordingTrackId = trackRecordingService.startNewTrack(); // Select the recording track. setSelectedTrackId(recordingTrackId); Toast.makeText(this, getString(R.string.status_now_recording), Toast.LENGTH_SHORT).show(); // TODO: We catch Exception, because after eliminating the service process // all exceptions it may throw are no longer wrapped in a RemoteException. } catch (Exception e) { Toast.makeText(this, getString(R.string.error_unable_to_start_recording), Toast.LENGTH_SHORT).show(); Log.w(MyTracksConstants.TAG, "Unable to start recording.", e); } } /** * Starts the track recording service (if not already running) and binds to * it. Starts recording a new track. */ public void startRecording() { if (trackRecordingService == null) { startNewTrackRequested = true; Intent startIntent = new Intent(this, TrackRecordingService.class); startService(startIntent); tryBindTrackRecordingService(); } else { startRecordingNewTrack(trackRecordingService); } } /** * Stops the track recording service and unbinds from it. Will display a toast * "Stopped recording" and pop up the Track Details activity. */ public void stopRecording() { if (trackRecordingService != null) { // Save the track id as the shared preference will overwrite the recording track id. long currentTrackId = recordingTrackId; try { trackRecordingService.endCurrentTrack(); // TODO: We catch Exception, because after eliminating the service process // all exceptions it may throw are no longer wrapped in a RemoteException. } catch (Exception e) { Log.e(MyTracksConstants.TAG, "Unable to stop recording.", e); } Intent intent = new Intent(MyTracks.this, MyTracksDetails.class); intent.putExtra("trackid", currentTrackId); intent.putExtra("hasCancelButton", false); startActivity(intent); } tryUnbindTrackRecordingService(); try { stopService(new Intent(MyTracks.this, TrackRecordingService.class)); } catch (SecurityException e) { Log.e(MyTracksConstants.TAG, "Encountered a security exception when trying to stop service.", e); } trackRecordingService = null; } /** * Initiates the process to send tracks to google. * This is called once the user has selected sending options via the * SendToGoogleDialog. * * TODO: Change this whole flow to an actual state machine. */ public void sendToGoogle() { SendToGoogleDialog sendToGoogleDialog = dialogManager.getSendToGoogleDialog(); if (sendToGoogleDialog == null) { return; } setProgressValue(0); clearProgressMessage(); dialogManager.showDialogSafely(DIALOG_PROGRESS); if (sendToGoogleDialog.getSendToMyMaps()) { sendToGoogleMapsOrPickMap(sendToGoogleDialog); } else if (sendToGoogleDialog.getSendToFusionTables()) { authenticateToFusionTables(null); } else if (sendToGoogleDialog.getSendToDocs()) { authenticateToGoogleDocs(); } else { Log.w(MyTracksConstants.TAG, "Nowhere to upload to"); onSendToGoogleDone(); } } private void sendToGoogleMapsOrPickMap(SendToGoogleDialog sendToGoogleDialog) { if (!sendToGoogleDialog.getCreateNewMap()) { // Ask the user to choose a map to upload into Intent listIntent = new Intent(this, MyMapsList.class); startActivityForResult(listIntent, MyTracksConstants.GET_MAP); // The callback for GET_MAP calls authenticateToGoogleMaps } else { authenticateToGoogleMaps(null); } } private void authenticateToGoogleMaps(Intent results) { if (results == null) { results = new Intent(); } setProgressValue(0); setProgressMessage( R.string.progress_message_authenticating_mymaps); authenticate(results, MyTracksConstants.AUTHENTICATE_TO_MY_MAPS, MapsService.getServiceName()); // AUTHENTICATE_TO_MY_MAPS callback calls sendToGoogleMaps } private void sendToGoogleMaps(final long trackId, String mapId) { SendToMyMaps.OnSendCompletedListener onCompletion = new SendToMyMaps.OnSendCompletedListener() { @Override public void onSendCompleted(String mapId, boolean success, int statusMessage) { sendToMyMapsMessage = getString(statusMessage); sendToMyMapsSuccess = success; if (sendToMyMapsSuccess) { sendToMyMapsMapId = mapId; // Update the map id for this track: try { Track track = providerUtils.getTrack(trackId); track.setMapId(mapId); providerUtils.updateTrack(track); } catch (RuntimeException e) { // If that fails whatever reasons we'll just log an error, but // continue. Log.w(MyTracksConstants.TAG, "Updating map id failed.", e); } } onSendToGoogleMapsDone(); } }; final SendToMyMaps sender = new SendToMyMaps(this, mapId, auth, trackId, this /*progressIndicator*/, onCompletion); HandlerThread handlerThread = new HandlerThread("SendToMyMaps"); handlerThread.start(); Handler handler = new Handler(handlerThread.getLooper()); handler.post(sender); } private void onSendToGoogleMapsDone() { SendToGoogleDialog sendToGoogleDialog = dialogManager.getSendToGoogleDialog(); if (sendToGoogleDialog.getSendToFusionTables()) { authenticateToFusionTables(null); } else if (sendToGoogleDialog.getSendToDocs()) { authenticateToGoogleDocs(); } else { onSendToGoogleDone(); } } private void authenticateToFusionTables(Intent results) { if (results == null) { results = new Intent(); } setProgressValue(0); setProgressMessage(R.string.progress_message_authenticating_fusiontables); authenticate(results, MyTracksConstants.AUTHENTICATE_TO_FUSION_TABLES, SendToFusionTables.SERVICE_ID); // AUTHENTICATE_TO_FUSION_TABLES callback calls sendToFusionTables } private void sendToFusionTables(final long trackId) { OnSendCompletedListener onCompletion = new OnSendCompletedListener() { @Override public void onSendCompleted(String tableId, boolean success, int statusMessage) { sendToFusionTablesMessage = getString(statusMessage); sendToFusionTablesSuccess = success; if (sendToFusionTablesSuccess) { sendToFusionTablesTableId = tableId; // Update the table id for this track: try { Track track = providerUtils.getTrack(trackId); track.setTableId(tableId); providerUtils.updateTrack(track); } catch (RuntimeException e) { // If that fails whatever reasons we'll just log an error, but // continue. Log.w(MyTracksConstants.TAG, "Updating table id failed.", e); } } onSendToFusionTablesDone(); } }; sendToTrackId = trackId; final SendToFusionTables sender = new SendToFusionTables(this, auth, trackId, this/*progressIndicator*/, onCompletion); HandlerThread handlerThread = new HandlerThread("SendToFusionTables"); handlerThread.start(); Handler handler = new Handler(handlerThread.getLooper()); handler.post(sender); } private void onSendToFusionTablesDone() { SendToGoogleDialog sendToGoogleDialog = dialogManager.getSendToGoogleDialog(); if (sendToGoogleDialog.getSendToDocs()) { authenticateToGoogleDocs(); } else { onSendToGoogleDone(); } } private void authenticateToGoogleDocs() { setProgressValue(0); setProgressMessage( R.string.progress_message_authenticating_docs); authenticate(new Intent(), MyTracksConstants.AUTHENTICATE_TO_DOCLIST, SendToDocs.GDATA_SERVICE_NAME_DOCLIST); // AUTHENTICATE_TO_DOCLIST callback calls authenticateToGoogleTrix } private void authenticateToGoogleTrix() { setProgressValue(30); setProgressMessage( R.string.progress_message_authenticating_docs); authenticate(new Intent(), MyTracksConstants.AUTHENTICATE_TO_TRIX, SendToDocs.GDATA_SERVICE_NAME_TRIX); // AUTHENTICATE_TO_TRIX callback calls sendToGoogleDocs } private void sendToGoogleDocs(final long trackId) { Log.d(MyTracksConstants.TAG, "Sending to Docs...."); setProgressValue(50); setProgressMessage(R.string.progress_message_sending_docs); final SendToDocs sender = new SendToDocs(this, authMap.get(SendToDocs.GDATA_SERVICE_NAME_TRIX), authMap.get(SendToDocs.GDATA_SERVICE_NAME_DOCLIST), trackId); sendToTrackId = trackId; Runnable onCompletion = new Runnable() { public void run() { setProgressValue(100); dialogManager.dismissDialogSafely(DIALOG_PROGRESS); sendToDocsMessage = sender.getStatusMessage(); sendToDocsSuccess = sender.wasSuccess(); onSendToGoogleDocsDone(); } }; sender.setOnCompletion(onCompletion); sender.run(); } private void onSendToGoogleDocsDone() { onSendToGoogleDone(); } private void onSendToGoogleDone() { SendToGoogleDialog sendToGoogleDialog = dialogManager.getSendToGoogleDialog(); final boolean sentToMyMaps = sendToGoogleDialog.getSendToMyMaps(); final boolean sentToFusionTables = sendToGoogleDialog.getSendToFusionTables(); dialogManager.dismissDialogSafely(DIALOG_PROGRESS); runOnUiThread(new Runnable() { public void run() { if (shareRequested) { Toast.makeText(MyTracks.this, getSendToGoogleResultMessage(), Toast.LENGTH_LONG) .show(); if (shareLinkToMap(sentToMyMaps, sentToFusionTables)) { return; } } // If anything failed or sharing was not requested, show the dialog dialogManager.showDialogSafely( DialogManager.DIALOG_SEND_TO_GOOGLE_RESULT); } }); } boolean shareLinkToMap(boolean sentToMyMaps, boolean sentToFusionTables) { String url = null; if (sentToMyMaps && sendToMyMapsSuccess) { // Prefer a link to My Maps url = MapsService.buildMapUrl(sendToMyMapsMapId); } else if (sentToFusionTables && sendToFusionTablesSuccess) { // Otherwise try using the link to fusion tables url = getFusionTablesUrl(sendToTrackId); } if (url != null) { shareLinkToMap(url); return true; } return false; } protected String getFusionTablesUrl(long sendToTrackId2) { Track track = providerUtils.getTrack(sendToTrackId); return SendToFusionTables.getMapVisualizationUrl(track); } String getSendToGoogleResultMessage() { StringBuilder message = new StringBuilder(); SendToGoogleDialog sendToGoogleDialog = dialogManager.getSendToGoogleDialog(); if (sendToGoogleDialog.getSendToMyMaps()) { message.append(sendToMyMapsMessage); } if (sendToGoogleDialog.getSendToFusionTables()) { message.append(sendToFusionTablesMessage); } if (sendToGoogleDialog.getSendToDocs()) { if (message.length() > 0) { message.append(' '); } message.append(sendToDocsMessage); } if (sendToMyMapsSuccess && sendToFusionTablesSuccess && sendToDocsSuccess) { message.append(' '); message.append(getString(R.string.status_mymap_info)); } return message.toString(); } /** * Writes the selected track id to the shared preferences. * Executed on the UI thread. * * @param trackId the id of the track */ public void setSelectedTrackId(final long trackId) { ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges( sharedPreferences .edit() .putLong(getString(R.string.selected_track_key), trackId)); } long getSelectedTrackId() { return selectedTrackId; } /** * Binds to track recording service if it is running. */ private void tryBindTrackRecordingService() { Log.d(MyTracksConstants.TAG, "MyTracks: Trying to bind to track recording service..."); bindService(new Intent(this, TrackRecordingService.class), serviceConnection, 0); Log.d(MyTracksConstants.TAG, "MyTracks: ...bind finished!"); isBound = true; } /** * Tries to unbind the track recording service. Catches exception silently in * case service is not registered anymore. */ private void tryUnbindTrackRecordingService() { if (isBound) { Log.d(MyTracksConstants.TAG, "MyTracks: Trying to unbind from track recording service..."); try { unbindService(serviceConnection); Log.d(MyTracksConstants.TAG, "MyTracks: ...unbind finished!"); } catch (IllegalArgumentException e) { Log.d(MyTracksConstants.TAG, "MyTracks: Tried unbinding, but service was not registered.", e); } isBound = false; } } /** * Saves the track with the given id to the SD card. * * @param trackId The id of the track to be sent */ public void saveTrack(long trackId, TrackFileFormat format) { dialogManager.showDialogSafely(DIALOG_WRITE_PROGRESS); final TrackWriter writer = TrackWriterFactory.newWriter(this, providerUtils, trackId, format); writer.setOnCompletion(new Runnable() { public void run() { dialogManager.dismissDialogSafely(DIALOG_WRITE_PROGRESS); dialogManager.showMessageDialog(writer.getErrorMessage(), writer.wasSuccess()); } }); writer.writeTrackAsync(); } /** * Sends the requested track as an email attachment. * This will leave the gpx file on the SD card for at least one hour. * Temporary gpx files will be deleted in onStop. * * @param trackId The id of the track to be sent */ public void sendTrack(long trackId, final TrackFileFormat format) { dialogManager.showDialogSafely(DIALOG_WRITE_PROGRESS); final TrackWriter writer = TrackWriterFactory.newWriter(this, providerUtils, trackId, format); FileUtils fileUtils = new FileUtils(); String extension = format.getExtension(); String dirName = fileUtils.buildExternalDirectoryPath(extension, "tmp"); File dir = new File(dirName); writer.setDirectory(dir); writer.setOnCompletion(new Runnable() { public void run() { dialogManager.dismissDialogSafely(DIALOG_WRITE_PROGRESS); if (!writer.wasSuccess()) { dialogManager.showMessageDialog(writer.getErrorMessage(), writer.wasSuccess()); } else { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getText(R.string.send_track_subject).toString()); shareIntent.putExtra(Intent.EXTRA_TEXT, getResources().getText(R.string.send_track_body_format) .toString()); shareIntent.setType(format.getMimeType()); Uri u = Uri.fromFile(new File(writer.getAbsolutePath())); shareIntent.putExtra(Intent.EXTRA_STREAM, u); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share_track).toString())); } } }); writer.writeTrackAsync(); } public AccountChooser getAccountChooser() { return accountChooser; } public ChartActivity getChartActivity() { return chartActivity; } public void setChartActivity(ChartActivity chartActivity) { this.chartActivity = chartActivity; } public DialogManager getDialogManager() { return dialogManager; } public String getSendToMyMapsMapId() { return sendToMyMapsMapId; } public String getSendToFusionTablesTableId() { return sendToFusionTablesTableId; } public boolean getSendToGoogleSuccess() { return sendToFusionTablesSuccess && sendToDocsSuccess; } // @VisibleForTesting long getRecordingTrackId() { return recordingTrackId; } // @VisibleForTesting SharedPreferences getSharedPreferences() { return sharedPreferences; } // @VisibleForTesting static void clearInstance() { instance = null; } // @VisibleForTesting ITrackRecordingService getTrackRecordingService() { return trackRecordingService; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.GeoRect; import com.google.android.apps.mytracks.util.MyTracksUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.hardware.GeomagneticField; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.provider.Settings; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.view.View; import android.view.Window; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * The map view activity of the MyTracks application. * * @author Leif Hendrik Wilden */ public class MyTracksMap extends MapActivity implements View.OnTouchListener, View.OnClickListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final int TRACKPOINT_BUFFER_SIZE = 1024; // Saved instance state keys: // --------------------------- public static final String KEY_CURRENT_LOCATION = "currentLocation"; public static final String KEY_KEEP_MY_LOCATION_VISIBLE = "keepMyLocationVisible"; public static final String KEY_HAVE_GOOD_FIX = "haveGoodFix"; /** * The ID of the currently selected track (or -1 if nothing selected). */ private long selectedTrackId = -1; /** * The id of the currently recording track. */ private long recordingTrackId = -1; /** * True if the map should be scrolled so that the pointer is always in the * visible area. */ private boolean keepMyLocationVisible; /** * Id of the first location that was seen when reading tracks from the * provider. */ private long firstSeenLocationId = -1; /** * Id of the last location that was seen when reading tracks from the * provider. This is used to determine which locations are new compared to the * last time the mapOverlay was updated. */ private long lastSeenLocationId = -1; /** * Magnetic variation. */ private double variation; /** * From the shared preferences. */ private int minRequiredAccuracy = MyTracksSettings.DEFAULT_MIN_REQUIRED_ACCURACY; /** * True, if the application thinks it has a good fix, i.e. accuracy is better * than the required accuracy. */ private boolean haveGoodFix; /** * The current pointer location. */ private Location currentLocation; /** * A thread with a looper. Post to updateTrackHandler to execute * {@link Runnable}s on this thread. */ private HandlerThread updateTrackThread; /** * Handler for updateTrackThread. */ private Handler updateTrackHandler; private MyTracksProviderUtils providerUtils; private SharedPreferences sharedPreferences; /** * A runnable that updates the track from the provider (looking for points * added after "lastSeenLocationId"). */ private final Runnable updateTrackRunnable = new Runnable() { @Override public void run() { if (!isATrackSelected()) { return; } readAllNewTrackPoints(); } }; /** * A runnable that restores all track points from the provider. */ private Runnable restoreTrackRunnable = new Runnable() { @Override public void run() { if (!isATrackSelected()) { return; } mapOverlay.clearPoints(); firstSeenLocationId = -1; lastSeenLocationId = -1; readAllNewTrackPoints(); } }; /** * A runnable that restores all waypoints from the provider. */ private final Runnable restoreWaypointsRunnable = new Runnable() { @Override public void run() { if (!isATrackSelected()) { return; } Cursor cursor = null; mapOverlay.clearWaypoints(); try { // We will silently drop extra waypoints to make the app responsive. // TODO: Try to only load the waypoints in the view port. cursor = providerUtils.getWaypointsCursor( selectedTrackId, 0, MyTracksConstants.MAX_DISPLAYED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { do { Waypoint waypoint = providerUtils.createWaypoint(cursor); if (MyTracksUtils.isValidLocation(waypoint.getLocation())) { mapOverlay.addWaypoint(waypoint); } } while (cursor.moveToNext()); } } catch (RuntimeException e) { Log.w(MyTracksConstants.TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } mapView.postInvalidate(); } }; /** * A runnable intended to be posted to the {@code #updateTrackThread} after * the selected track changes. It will post to the UI thread to update * the screen elements and move the map to show the selected track. */ private final Runnable setSelectedTrackRunnable = new Runnable() { @Override public void run() { uiHandler.post(new Runnable() { public void run() { showTrack(selectedTrackId); mapOverlay.setTrackDrawingEnabled(isATrackSelected()); mapOverlay.setShowEndMarker(!isRecordingSelected()); mapView.invalidate(); busyPane.setVisibility(View.GONE); updateOptionsButton(); } }); } }; // UI elements: // ------------- private RelativeLayout screen; private MapView mapView; private MyTracksOverlay mapOverlay; private LinearLayout messagePane; private TextView messageText; private LinearLayout busyPane; private ImageButton optionsBtn; private MenuItem myLocation; private MenuItem toggleLayers; private SensorManager sensorManager; private LocationManager locationManager; private ContentObserver observer; private ContentObserver waypointObserver; /** Handler for callbacks to the UI thread */ private final Handler uiHandler = new Handler(); /** * We are not displaying driving directions. Just an arbitrary track that is * not associated to any licensed mapping data. Therefore it should be okay to * return false here and still comply with the terms of service. */ @Override protected boolean isRouteDisplayed() { return false; } /** * We are displaying a location. This needs to return true in order to comply * with the terms of service. */ @Override protected boolean isLocationDisplayed() { return true; } // Application life cycle: // ------------------------ @Override public void onCreate(Bundle bundle) { Log.d(MyTracksConstants.TAG, "MyTracksMap.onCreate"); super.onCreate(bundle); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); providerUtils = MyTracksProviderUtils.Factory.get(this); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); // Inflate the layout: setContentView(R.layout.mytracks_layout); // Remove the window's background because the MapView will obscure it getWindow().setBackgroundDrawable(null); // Set up a map overlay: screen = (RelativeLayout) findViewById(R.id.screen); mapView = (MapView) findViewById(R.id.map); mapView.requestFocus(); mapOverlay = new MyTracksOverlay(this); mapView.getOverlays().add(mapOverlay); mapView.setOnTouchListener(this); messagePane = (LinearLayout) findViewById(R.id.messagepane); messageText = (TextView) findViewById(R.id.messagetext); busyPane = (LinearLayout) findViewById(R.id.busypane); optionsBtn = (ImageButton) findViewById(R.id.showOptions); optionsBtn.setOnCreateContextMenuListener(contextMenuListener); optionsBtn.setOnClickListener(this); setupZoomControls(); // Get the sensor and location managers: sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); updateTrackThread = new HandlerThread("updateTrackThread"); updateTrackThread.start(); updateTrackHandler = new Handler(updateTrackThread.getLooper()); // Register observer for the track point provider: Handler contentHandler = new Handler(); observer = new ContentObserver(contentHandler) { @Override public void onChange(boolean selfChange) { Log.d(MyTracksConstants.TAG, "MyTracksMap: ContentObserver.onChange"); if (!isRecordingSelected()) { // No track, or one other than the recording track is selected, // don't bother. return; } // Update can potentially be lengthy, put it in its own thread: updateTrackHandler.post(updateTrackRunnable); super.onChange(selfChange); } }; waypointObserver = new ContentObserver(contentHandler) { @Override public void onChange(boolean selfChange) { Log.d(MyTracksConstants.TAG, "MyTracksMap: ContentObserver.onChange waypoints"); if (!isATrackSelected()) { return; } updateTrackHandler.post(restoreWaypointsRunnable); super.onChange(selfChange); } }; // Read shared preferences and register change listener. sharedPreferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (sharedPreferences != null) { reloadSharedPreferences(sharedPreferences, null); updateOptionsButton(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } } @Override protected void onDestroy() { Log.d(MyTracksConstants.TAG, "MyTracksMap.onDestroy"); if (updateTrackThread != null) { ApiFeatures.getInstance().getApiPlatformAdapter().stopHandlerThread( updateTrackThread); } if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } super.onDestroy(); } /** * Returns whether there's a track currently selected for display. */ private boolean isATrackSelected() { return selectedTrackId >= 0; } /** * Returns whether we're currently recording the same track that's selected * for display. */ private boolean isRecordingSelected() { return isATrackSelected() && selectedTrackId == recordingTrackId; } protected void setupZoomControls() { mapView.setBuiltInZoomControls(true); } @Override protected void onStart() { // Called after onCreate or onStop. // Will be followed by onRestart. Log.d(MyTracksConstants.TAG, "MyTracksMap.onStart"); super.onStart(); } @Override protected void onStop() { // Called when activity is no longer visible to user. // Next either onStart, onDestroy or nothing will be called. // This method may never be called in low memory situations. Log.d(MyTracksConstants.TAG, "MyTracksMap.onStop"); super.onStop(); } @Override protected void onRestart() { // Called when the current activity is being re-displayed. // Will be followed by onResume. Log.d(MyTracksConstants.TAG, "MyTracksMap.onRestart"); super.onRestart(); } @Override protected void onPause() { // Called when activity is going into the background, but has not (yet) been // killed. Shouldn't block longer than approx. 2 seconds. Log.d(MyTracksConstants.TAG, "MyTracksMap.onPause"); unregisterLocationAndSensorListeners(); unregisterContentObservers(); super.onPause(); } @Override protected void onResume() { // Called when the current activity is being displayed or re-displayed // to the user. Log.d(MyTracksConstants.TAG, "MyTracksMap.onResume"); super.onResume(); // Reload all preferences as they might have changed since last run. reloadSharedPreferences(sharedPreferences, null); // Make sure any updates that might have happened are propagated to the // Map overlay: observer.onChange(false); waypointObserver.onChange(false); registerContentObservers(); registerLocationAndSensorListeners(); if (locationManager.isProviderEnabled(MyTracksConstants.GPS_PROVIDER)) { messageText.setText(R.string.wait_for_fix); messagePane.setOnClickListener(null); } else { messageText.setText(R.string.status_enable_gps); messagePane.setVisibility(View.VISIBLE); messagePane.setOnClickListener(this); screen.requestLayout(); } // While this activity was paused the user may have deleted the selected // track. In that case the map overlay needs to be cleared: if (isATrackSelected() && !providerUtils.trackExists(selectedTrackId)) { // The recording track must have been deleted meanwhile. mapOverlay.setTrackDrawingEnabled(false); mapView.invalidate(); } } @Override protected void onSaveInstanceState(Bundle outState) { Log.d(MyTracksConstants.TAG, "MyTracksMap.onSaveInstanceState"); outState.putBoolean(KEY_HAVE_GOOD_FIX, haveGoodFix); outState.putBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, keepMyLocationVisible); if (currentLocation != null) { outState.putParcelable(KEY_CURRENT_LOCATION, currentLocation); } super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle bundle) { Log.d(MyTracksConstants.TAG, "MyTracksMap.onRestoreInstanceState"); if (bundle != null) { super.onRestoreInstanceState(bundle); haveGoodFix = bundle.getBoolean(KEY_HAVE_GOOD_FIX, false); keepMyLocationVisible = bundle.getBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, false); if (bundle.containsKey(KEY_CURRENT_LOCATION)) { currentLocation = (Location) bundle.getParcelable(KEY_CURRENT_LOCATION); if (currentLocation != null) { setVariation(currentLocation); showCurrentLocation(); } } else { currentLocation = null; } } } // Utility functions: // ------------------- /** * Toggles between satellite and map view. */ public void toggleLayer() { mapView.setSatellite(!mapView.isSatellite()); } /** * Registers to receive location updates from the GPS location provider and * sensor updated from the compass. */ void registerLocationAndSensorListeners() { if (locationManager != null) { LocationProvider gpsProvider = locationManager.getProvider(MyTracksConstants.GPS_PROVIDER); if (gpsProvider == null) { alert(getString(R.string.error_no_gps_location_provider)); return; } else { Log.d(MyTracksConstants.TAG, "MyTracksMap: Using location provider " + gpsProvider.getName()); } locationManager.requestLocationUpdates(gpsProvider.getName(), 0 /*minTime*/, 0 /*minDist*/, locationListener); try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60 * 5 /*minTime*/, 0 /*minDist*/, locationListener); } catch (RuntimeException e) { // If anything at all goes wrong with getting a cell location do not // abort. Cell location is not essential to this app. Log.w(MyTracksConstants.TAG, "Could not register network location listener."); } } if (sensorManager == null) { return; } Sensor compass = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); if (compass == null) { return; } Log.d(MyTracksConstants.TAG, "MyTracksMap: Now registering sensor listeners."); sensorManager.registerListener( sensorListener, compass, SensorManager.SENSOR_DELAY_UI); } /** * Unregisters all location and sensor listeners */ void unregisterLocationAndSensorListeners() { if (locationManager != null) { Log.d(MyTracksConstants.TAG, "MyTracksMap: Now unregistering location listeners."); locationManager.removeUpdates(locationListener); } if (sensorManager != null) { Log.d(MyTracksConstants.TAG, "MyTracksMap: Now unregistering sensor listeners."); sensorManager.unregisterListener(sensorListener); } } /** * Registers the content observer for the map overlay. */ private void registerContentObservers() { getContentResolver().registerContentObserver( TrackPointsColumns.CONTENT_URI, false /* notifyForDescendents */, observer); getContentResolver().registerContentObserver( WaypointsColumns.CONTENT_URI, false /* notifyForDescendents */, waypointObserver); } /** * Unregisters the content observer for the map overlay. */ private void unregisterContentObservers() { getContentResolver().unregisterContentObserver(observer); getContentResolver().unregisterContentObserver(waypointObserver); } /** * Shows the options button if a track is selected, or hide it if not. */ private void updateOptionsButton() { optionsBtn.setVisibility( isATrackSelected() ? View.VISIBLE : View.INVISIBLE); } /** * Tests if a location is visible. * * @param location a given location * @return true if the given location is within the visible map area */ private boolean locationIsVisible(Location location) { if (location == null || mapView == null) { return false; } GeoPoint center = mapView.getMapCenter(); int latSpan = mapView.getLatitudeSpan(); int lonSpan = mapView.getLongitudeSpan(); // Bottom of map view is obscured by zoom controls/buttons. // Subtract a margin from the visible area: GeoPoint marginBottom = mapView.getProjection().fromPixels( 0, mapView.getHeight()); GeoPoint marginTop = mapView.getProjection().fromPixels(0, mapView.getHeight() - mapView.getZoomButtonsController().getZoomControls().getHeight()); int margin = Math.abs(marginTop.getLatitudeE6() - marginBottom.getLatitudeE6()); GeoRect r = new GeoRect(center, latSpan, lonSpan); r.top += margin; GeoPoint geoPoint = MyTracksUtils.getGeoPoint(location); return r.contains(geoPoint); } /** * Moves the location pointer to the current location and center the map if * the current location is outside the visible area. */ private void showCurrentLocation() { if (currentLocation == null || mapOverlay == null || mapView == null) { return; } mapOverlay.setMyLocation(currentLocation); mapView.invalidate(); if (keepMyLocationVisible && !locationIsVisible(currentLocation)) { MapController controller = mapView.getController(); GeoPoint geoPoint = MyTracksUtils.getGeoPoint(currentLocation); controller.animateTo(geoPoint); } } /** * Zooms and pans the map so that the given track is visible. * * @param trackId a given track ID */ public void showTrack(long trackId) { if (mapView == null) { return; } Track track = providerUtils.getTrack(trackId); if (track == null || track.getNumberOfPoints() < 2) { return; } TripStatistics stats = track.getStatistics(); int bottom = stats.getBottom(); int left = stats.getLeft(); int latSpanE6 = stats.getTop() - bottom; int lonSpanE6 = stats.getRight() - left; if (latSpanE6 > 0 && latSpanE6 < 180E6 && lonSpanE6 > 0 && lonSpanE6 < 360E6) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint( bottom + latSpanE6 / 2, left + lonSpanE6 / 2); if (MyTracksUtils.isValidGeoPoint(center)) { mapView.getController().setCenter(center); mapView.getController().zoomToSpan(latSpanE6, lonSpanE6); } } } /** * Zooms and pans the map so that the given waypoint is visible. */ public void showWaypoint(long waypointId) { Waypoint wpt = providerUtils.getWaypoint(waypointId); if (wpt != null && wpt.getLocation() != null) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint( (int) (wpt.getLocation().getLatitude() * 1E6), (int) (wpt.getLocation().getLongitude() * 1E6)); mapView.getController().setCenter(center); mapView.getController().setZoom(20); mapView.invalidate(); } } /** * Sets the selected track and zoom and pan the map so that it is visible. * * @param trackId a given track id */ public void setSelectedTrack(final long trackId) { Log.d(MyTracksConstants.TAG, "MyTracksMap.setSelectedTrack: " + "selectedTrackId = " + selectedTrackId + ", trackId = " + trackId); if (selectedTrackId == trackId) { // Selected track did not change, nothing to do. mapOverlay.setTrackDrawingEnabled(isATrackSelected()); updateOptionsButton(); mapView.invalidate(); return; } if (trackId < 0) { // Remove selection. selectedTrackId = -1; mapOverlay.setTrackDrawingEnabled(false); mapOverlay.clearWaypoints(); updateOptionsButton(); mapView.invalidate(); return; } busyPane.setVisibility(View.VISIBLE); selectedTrackId = trackId; loadSelectedTrack(); } private void loadSelectedTrack() { updateTrackHandler.post(restoreTrackRunnable); updateTrackHandler.post(restoreWaypointsRunnable); updateTrackHandler.post(setSelectedTrackRunnable); } /** * Displays an alert for a few seconds. * * @param txt The text to be displayed */ public void alert(String txt) { Toast.makeText(this, txt, Toast.LENGTH_LONG).show(); } public void launchMyLocationSettings() { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } public void setVariation(Location location) { long timestamp = location.getTime(); if (timestamp == 0) { // Hack for Samsung phones which don't populate the time field timestamp = System.currentTimeMillis(); } GeomagneticField field = new GeomagneticField( (float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), timestamp); variation = field.getDeclination(); Log.d(MyTracksConstants.TAG, "MyTracksMap: Variation reset to " + variation + " degrees."); } public MyTracksOverlay getMapOverlay() { return mapOverlay; } public MapView getMapView() { return mapView; } // Event listeners: // ----------------- private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.tracklist_this_track); menu.add(0, MyTracksConstants.MENU_EDIT, 0, R.string.tracklist_edit_track); if (!isRecordingSelected()) { menu.add(0, MyTracksConstants.MENU_SEND_TO_GOOGLE, 0, R.string.tracklist_send_to_google); SubMenu share = menu.addSubMenu(0, MyTracksConstants.MENU_SHARE, 0, R.string.tracklist_share_track); share.add(0, MyTracksConstants.MENU_SHARE_LINK, 0, R.string.tracklist_share_link); share.add(0, MyTracksConstants.MENU_SHARE_GPX_FILE, 0, R.string.tracklist_share_gpx_file); share.add(0, MyTracksConstants.MENU_SHARE_KML_FILE, 0, R.string.tracklist_share_kml_file); share.add(0, MyTracksConstants.MENU_SHARE_CSV_FILE, 0, R.string.tracklist_share_csv_file); share.add(0, MyTracksConstants.MENU_SHARE_TCX_FILE, 0, R.string.tracklist_share_tcx_file); SubMenu save = menu.addSubMenu(0, MyTracksConstants.MENU_WRITE_TO_SD_CARD, 0, R.string.tracklist_write_to_sd); save.add(0, MyTracksConstants.MENU_SAVE_GPX_FILE, 0, R.string.tracklist_save_as_gpx); save.add(0, MyTracksConstants.MENU_SAVE_KML_FILE, 0, R.string.tracklist_save_as_kml); save.add(0, MyTracksConstants.MENU_SAVE_CSV_FILE, 0, R.string.tracklist_save_as_csv); save.add(0, MyTracksConstants.MENU_SAVE_TCX_FILE, 0, R.string.tracklist_save_as_tcx); menu.add(0, MyTracksConstants.MENU_CLEAR_MAP, 0, R.string.tracklist_clear_map); menu.add(0, MyTracksConstants.MENU_DELETE, 0, R.string.tracklist_delete_track); } } }; @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (!super.onMenuItemSelected(featureId, item)) { if (isATrackSelected()) { MyTracks.getInstance().onActivityResult( MyTracksConstants.getActionFromMenuId(item.getItemId()), RESULT_OK, new Intent()); return true; } } return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); myLocation = menu.add(0, MyTracksConstants.MENU_MY_LOCATION, 0, R.string.mylocation); myLocation.setIcon(android.R.drawable.ic_menu_mylocation); toggleLayers = menu.add(0, MyTracksConstants.MENU_TOGGLE_LAYERS, 0, R.string.switch_to_sat); toggleLayers.setIcon(android.R.drawable.ic_menu_mapmode); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { toggleLayers.setTitle(mapView.isSatellite() ? R.string.switch_to_map : R.string.switch_to_sat); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MyTracksConstants.MENU_MY_LOCATION: { Location loc = MyTracks.getInstance().getCurrentLocation(); if (loc != null) { currentLocation = loc; setVariation(currentLocation); mapOverlay.setMyLocation(loc); mapView.invalidate(); GeoPoint geoPoint = MyTracksUtils.getGeoPoint(loc); MapController controller = mapView.getController(); controller.animateTo(geoPoint); if (mapView.getZoomLevel() < 18) { controller.setZoom(18); } keepMyLocationVisible = true; } return true; } case MyTracksConstants.MENU_TOGGLE_LAYERS: { toggleLayer(); return true; } } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { if (v == messagePane) { launchMyLocationSettings(); } else if (v == optionsBtn) { optionsBtn.performLongClick(); } } /** * We want the pointer to become visible again in case of the next location * update: */ @Override public boolean onTouch(View view, MotionEvent event) { if (keepMyLocationVisible && event.getAction() == MotionEvent.ACTION_MOVE) { if (!locationIsVisible(currentLocation)) { keepMyLocationVisible = false; } } return false; } @Override public void onSharedPreferenceChanged( final SharedPreferences sharedPreferences, final String key) { Log.d(MyTracksConstants.TAG, "MyTracksMap.onSharedPreferenceChanged: " + key); if (key != null) { uiHandler.post(new Runnable() { @Override public void run() { reloadSharedPreferences(sharedPreferences, key); } }); } } private final LocationListener locationListener = new LocationListener() { @Override public void onProviderEnabled(String provider) { if (provider.equals(MyTracksConstants.GPS_PROVIDER)) { messageText.setText(R.string.wait_for_fix); } } @Override public void onProviderDisabled(String provider) { if (provider.equals(MyTracksConstants.GPS_PROVIDER)) { messageText.setText(R.string.status_enable_gps); messagePane.setVisibility(View.VISIBLE); messagePane.setOnClickListener(MyTracksMap.this); screen.requestLayout(); } } @Override public void onLocationChanged(Location location) { if (location.getProvider().equals(MyTracksConstants.GPS_PROVIDER)) { // Recalculate the variation if there was a jump in location > 1km: if (currentLocation == null || location.distanceTo(currentLocation) > 1000) { setVariation(location); } currentLocation = location; boolean haveGoodFixNow = currentLocation.getAccuracy() < minRequiredAccuracy; if (haveGoodFixNow != haveGoodFix) { haveGoodFix = haveGoodFixNow; messagePane.setVisibility(haveGoodFix ? View.GONE : View.VISIBLE); screen.requestLayout(); } showCurrentLocation(); } else { Log.d(MyTracksConstants.TAG, "MyTracksMap: Network location update received."); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (provider.equals(MyTracksConstants.GPS_PROVIDER)) { switch (status) { case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: haveGoodFix = false; messagePane.setVisibility(View.VISIBLE); screen.requestLayout(); break; } } } }; private final SensorEventListener sensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent se) { synchronized (this) { float magneticHeading = se.values[0]; double heading = magneticHeading + variation; if (mapOverlay.setHeading((float) heading)) { mapView.invalidate(); } } } @Override public void onAccuracyChanged(Sensor s, int accuracy) { // do nothing } }; private void reloadSharedPreferences(SharedPreferences sharedPreferences, String key) { if (key == null || key.equals(getString(R.string.min_required_accuracy_key))) { minRequiredAccuracy = sharedPreferences.getInt( getString(R.string.min_required_accuracy_key), MyTracksSettings.DEFAULT_MIN_REQUIRED_ACCURACY); } if (key == null || key.equals(getString(R.string.recording_track_key))) { recordingTrackId = sharedPreferences.getLong( getString(R.string.recording_track_key), -1); } if (key == null || key.equals(getString(R.string.selected_track_key))) { setSelectedTrack(sharedPreferences.getLong( getString(R.string.selected_track_key), -1)); } // Show end marker if the track has been selected and is not recording. // Note: This check must be *after* a call to setSelectedTrack(...) above. if (isATrackSelected()) { mapOverlay.setShowEndMarker(!isRecordingSelected()); mapView.postInvalidate(); } } private void readAllNewTrackPoints() { int numPoints = mapOverlay.getNumLocations(); if (numPoints >= MyTracksConstants.MAX_DISPLAYED_TRACK_POINTS) { // We're about to exceed the maximum allowed number of points, so reload // the whole track with fewer points (the sampling frequency will be // lower). loadSelectedTrack(); return; } // Keep a copy of selectedTrackId, because it can change asynchronously. long currentSelectedTrackId = selectedTrackId; long lastStoredLocationId = providerUtils.getLastLocationId(currentSelectedTrackId); int samplingFrequency = -1; Location location = new Location(""); while (currentSelectedTrackId == selectedTrackId) { Cursor cursor = null; try { cursor = providerUtils.getLocationsCursor(currentSelectedTrackId, lastSeenLocationId + 1, TRACKPOINT_BUFFER_SIZE, false); if (cursor == null || !cursor.moveToFirst()) { // No (more) data break; } final int idColumnIdx = cursor.getColumnIndexOrThrow( TrackPointsColumns._ID); do { long locationId = cursor.getLong(idColumnIdx); lastSeenLocationId = locationId; if (firstSeenLocationId == -1) { // This was our first point, keep its ID firstSeenLocationId = locationId; } if (samplingFrequency == -1) { // Now we already have at least one point, calculate the sampling // frequency long numTotalPoints = lastStoredLocationId - firstSeenLocationId; samplingFrequency = (int) (1 + numTotalPoints / MyTracksConstants.TARGET_DISPLAYED_TRACK_POINTS); // TODO: This shouldn't happen after adding currentSelectedTrackId, // but just to be safe until we have 100% confidence. if (samplingFrequency <= 0) { Log.w(MyTracksConstants.TAG, "readAllNewTrackPoints: samplingFreq <= 0, numTotalPoints = " + numTotalPoints + ", trackId = " + currentSelectedTrackId); samplingFrequency = 1; } } providerUtils.fillLocation(cursor, location); // Include a point if it fits one of the following criteria: // - Has the mod for the sampling frequency (includes first point). // - Is the last point and we are not recording this track. // - The point is a segment split if (numPoints % samplingFrequency == 0 || (!isRecordingSelected() && locationId == lastStoredLocationId) || !MyTracksUtils.isValidLocation(location)) { // No need to allocate a new location (we can safely reuse the existing). mapOverlay.addLocation(location); } numPoints++; } while (cursor.moveToNext() && currentSelectedTrackId == selectedTrackId); } finally { if (cursor != null) { cursor.close(); } } } mapView.postInvalidate(); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import java.util.Locale; /** * Check to see if the units are the default for the locale. * This comes down to warning Americans that the default is metric. * * @author Sandor Dornbush */ class CheckUnits { private static final String PREFERENCE_UNITS_CHECKED = "checkunits.checked"; private static final String PREFERENCES_CHECK_UNITS = "checkunits"; static void check(final Context context) { final SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_CHECK_UNITS, Activity.MODE_PRIVATE); // Has the user already warned about the default units? if (preferences.getBoolean(PREFERENCE_UNITS_CHECKED, false)) { return; } // Is the user in the US? Locale current = Locale.getDefault(); Locale enUs = new Locale(Locale.ENGLISH.getLanguage(), Locale.US.getCountry()); if (!current.equals(enUs)) { return; } final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.check_units_title); builder.setCancelable(true); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { accept(context, preferences); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { recordCheckPerformed(preferences); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { recordCheckPerformed(preferences); } }); builder.setMessage(R.string.check_units_message); builder.show(); } private static void accept(Context context, SharedPreferences preferences) { recordCheckPerformed(preferences); Intent startIntent = new Intent(context, MyTracksSettings.class); context.startActivity(startIntent); } private static void recordCheckPerformed(SharedPreferences preferences) { ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges( preferences.edit().putBoolean(PREFERENCE_UNITS_CHECKED, true)); } private CheckUnits() { } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.ContentValues; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; /** * An activity that let's the user see and edit the user editable track meta * data such as name, activity type and description. * * @author Leif Hendrik Wilden */ public class MyTracksDetails extends Activity implements OnClickListener { /** * The id of the track being edited (taken from bundle, "trackid") */ private Long trackId; private EditText name; private EditText description; private AutoCompleteTextView category; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.mytracks_detail); // Required extra when launching this intent: trackId = getIntent().getLongExtra("trackid", -1); if (trackId < 0) { Log.d(MyTracksConstants.TAG, "MyTracksDetails intent was launched w/o track id."); finish(); return; } // Optional extra that can be used to suppress the cancel button: boolean hasCancelButton = getIntent().getBooleanExtra("hasCancelButton", true); name = (EditText) findViewById(R.id.trackdetails_name); description = (EditText) findViewById(R.id.trackdetails_description); category = (AutoCompleteTextView) findViewById(R.id.trackdetails_category); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.activity_types, android.R.layout.simple_dropdown_item_1line); category.setAdapter(adapter); Button cancel = (Button) findViewById(R.id.trackdetails_cancel); if (hasCancelButton) { cancel.setOnClickListener(this); cancel.setVisibility(View.VISIBLE); } else { cancel.setVisibility(View.GONE); } Button save = (Button) findViewById(R.id.trackdetails_save); save.setOnClickListener(this); fillDialog(); } private void fillDialog() { Track track = MyTracksProviderUtils.Factory.get(this).getTrack(trackId); if (track != null) { name.setText(track.getName()); description.setText(track.getDescription()); category.setText(track.getCategory()); } } private void saveDialog() { ContentValues values = new ContentValues(); values.put(TracksColumns.NAME, name.getText().toString()); values.put(TracksColumns.DESCRIPTION, description.getText().toString()); values.put(TracksColumns.CATEGORY, category.getText().toString()); getContentResolver().update( TracksColumns.CONTENT_URI, values, "_id = " + trackId, null/*selectionArgs*/); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.trackdetails_cancel: finish(); break; case R.id.trackdetails_save: saveDialog(); finish(); break; } } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.google.android.apps.mytracks.io.backup.BackupActivityHelper; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.services.sensors.ant.AntUtils; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.BluetoothDeviceUtils; import com.google.android.maps.mytracks.R; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceScreen; import android.provider.Settings; /** * An activity that let's the user see and edit the settings. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class MyTracksSettings extends PreferenceActivity { public static final String SETTINGS_NAME = "MyTracksSettings"; /* * Default values - keep in sync with those in preferences.xml. */ public static final int DEFAULT_AUTO_RESUME_TRACK_TIMEOUT = 10; // In min. public static final int DEFAULT_ANNOUNCEMENT_FREQUENCY = -1; public static final int DEFAULT_MAX_RECORDING_DISTANCE = 200; public static final int DEFAULT_MIN_RECORDING_DISTANCE = 5; public static final int DEFAULT_MIN_RECORDING_INTERVAL = 0; public static final int DEFAULT_MIN_REQUIRED_ACCURACY = 200; public static final int DEFAULT_SPLIT_FREQUENCY = 0; private BackupPreferencesListener backupListener; private SharedPreferences preferences; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // The volume we want to control is the Text-To-Speech volume ApiFeatures apiFeatures = ApiFeatures.getInstance(); int volumeStream = new StatusAnnouncerFactory(apiFeatures).getVolumeStream(); setVolumeControlStream(volumeStream); // Tell it where to read/write preferences PreferenceManager preferenceManager = getPreferenceManager(); preferenceManager.setSharedPreferencesName(SETTINGS_NAME); preferenceManager.setSharedPreferencesMode(0); // Set up automatic preferences backup backupListener = BackupPreferencesListener.create(this, apiFeatures); preferences = preferenceManager.getSharedPreferences(); preferences.registerOnSharedPreferenceChangeListener(backupListener); // Load the preferences to be displayed addPreferencesFromResource(R.xml.preferences); // Hook up switching of displayed list entries between metric and imperial // units CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); metricUnitsPreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { boolean isMetric = (Boolean) newValue; updatePreferenceUnits(isMetric); return true; } }); updatePreferenceUnits(metricUnitsPreference.isChecked()); customizeSensorOptionsPreferences(); // Disable TTS announcement preference if not available if (!apiFeatures.hasTextToSpeech()) { IntegerListPreference announcementFrequency = (IntegerListPreference) findPreference( getString(R.string.announcement_frequency_key)); announcementFrequency.setEnabled(false); announcementFrequency.setValue("-1"); announcementFrequency.setSummary( R.string.settings_not_available_summary); } } private void customizeSensorOptionsPreferences() { ListPreference sensorTypePreference = (ListPreference) findPreference(getString(R.string.sensor_type_key)); sensorTypePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { updateSensorSettings((String) newValue); return true; } }); updateSensorSettings(sensorTypePreference.getValue()); if (!AntUtils.hasAntSupport(this)) { // The sensor options screen has a few ANT-specific options which we // need to remove. First, we need to remove the ANT sensor types. // Second, we need to remove the ANT unpairing options. Set<Integer> toRemove = new HashSet<Integer>(); String[] antValues = getResources().getStringArray(R.array.ant_sensor_type_values); for (String antValue : antValues) { toRemove.add(sensorTypePreference.findIndexOfValue(antValue)); } CharSequence[] entries = sensorTypePreference.getEntries(); CharSequence[] entryValues = sensorTypePreference.getEntryValues(); CharSequence[] filteredEntries = new CharSequence[entries.length - toRemove.size()]; CharSequence[] filteredEntryValues = new CharSequence[filteredEntries.length]; for (int i = 0, last = 0; i < entries.length; i++) { if (!toRemove.contains(i)) { filteredEntries[last] = entries[i]; filteredEntryValues[last++] = entryValues[i]; } } sensorTypePreference.setEntries(filteredEntries); sensorTypePreference.setEntryValues(filteredEntryValues); PreferenceScreen sensorOptionsScreen = (PreferenceScreen) findPreference(getString(R.string.sensor_options_key)); sensorOptionsScreen.removePreference(findPreference(getString(R.string.ant_options_key))); } } @Override protected void onResume() { super.onResume(); configureBluetoothPreferences(); Preference backupNowPreference = findPreference(getString(R.string.backup_to_sd_key)); Preference restoreNowPreference = findPreference(getString(R.string.restore_from_sd_key)); // If recording, disable backup/restore // (we don't want to get to inconsistent states) boolean recording = preferences.getLong(getString(R.string.recording_track_key), -1) != -1; backupNowPreference.setEnabled(!recording); restoreNowPreference.setEnabled(!recording); backupNowPreference.setSummary( recording ? R.string.settings_no_backup_while_recording : R.string.settings_backup_to_sd_summary); restoreNowPreference.setSummary( recording ? R.string.settings_no_backup_while_recording : R.string.settings_restore_from_sd_summary); // Add actions to the backup preferences backupNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(MyTracksSettings.this); backupHelper.writeBackup(); return true; } }); restoreNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(MyTracksSettings.this); backupHelper.restoreBackup(); return true; } }); } @Override protected void onDestroy() { getPreferenceManager().getSharedPreferences() .unregisterOnSharedPreferenceChangeListener(backupListener); super.onPause(); } private void updateSensorSettings(String sensorType) { boolean usesBluetooth = getString(R.string.zephyr_sensor_type).equals(sensorType); findPreference( getString(R.string.bluetooth_sensor_key)).setEnabled(usesBluetooth); findPreference( getString(R.string.bluetooth_pairing_key)).setEnabled(usesBluetooth); // Update the ANT+ sensors. // TODO: Only enable on phones that have ANT+. findPreference(getString(R.string.ant_heart_rate_sensor_id_key)) .setEnabled(getString(R.string.ant_sensor_type).equals(sensorType)); findPreference(getString(R.string.ant_srm_bridge_sensor_id_key)) .setEnabled(getString(R.string.srm_ant_bridge_sensor_type).equals(sensorType)); } /** * Updates all the preferences which give options with distance units to use * the proper unit the user has selected. * * @param isMetric true to use metric units, false to use imperial */ private void updatePreferenceUnits(boolean isMetric) { final ListPreference minRecordingDistance = (ListPreference) findPreference( getString(R.string.min_recording_distance_key)); final ListPreference maxRecordingDistance = (ListPreference) findPreference( getString(R.string.max_recording_distance_key)); final ListPreference minRequiredAccuracy = (ListPreference) findPreference( getString(R.string.min_required_accuracy_key)); final ListPreference splitFrequency = (ListPreference) findPreference( getString(R.string.split_frequency_key)); minRecordingDistance.setEntries(isMetric ? R.array.min_recording_distance_options : R.array.min_recording_distance_options_ft); maxRecordingDistance.setEntries(isMetric ? R.array.max_recording_distance_options : R.array.max_recording_distance_options_ft); minRequiredAccuracy.setEntries(isMetric ? R.array.min_required_accuracy_options : R.array.min_required_accuracy_options_ft); splitFrequency.setEntries(isMetric ? R.array.split_frequency_options : R.array.split_frequency_options_ft); } /** * Configures preference actions related to bluetooth. */ private void configureBluetoothPreferences() { if (BluetoothDeviceUtils.isBluetoothMethodSupported()) { // Populate the list of bluetooth devices populateBluetoothDeviceList(); // Make the pair devices preference go to the system preferences findPreference(getString(R.string.bluetooth_pairing_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Intent settingsIntent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); startActivity(settingsIntent); return false; } }); } } /** * Populates the list preference with all available bluetooth devices. */ private void populateBluetoothDeviceList() { // Build the list of entries and their values List<String> entries = new ArrayList<String>(); List<String> entryValues = new ArrayList<String>(); // The actual devices BluetoothDeviceUtils.getInstance().populateDeviceLists(entries, entryValues); CharSequence[] entriesArray = entries.toArray(new CharSequence[entries.size()]); CharSequence[] entryValuesArray = entryValues.toArray(new CharSequence[entryValues.size()]); ListPreference devicesPreference = (ListPreference) findPreference(getString(R.string.bluetooth_sensor_key)); devicesPreference.setEntryValues(entryValuesArray); devicesPreference.setEntries(entriesArray); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.ListActivity; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * A list activity displaying all the recorded tracks. There's a context * menu (via long press) displaying various options such as showing, editing, * deleting, sending to MyMaps, or writing to SD card. * * @author Leif Hendrik Wilden */ public class MyTracksList extends ListActivity implements SharedPreferences.OnSharedPreferenceChangeListener, View.OnClickListener { private int contextPosition = -1; private long trackId = -1; private ListView listView = null; private boolean metricUnits = true; private Cursor tracksCursor = null; /** * The id of the currently recording track. */ private long recordingTrackId = -1; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.tracklist_this_track); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; trackId = MyTracksList.this.listView.getAdapter().getItemId( contextPosition); menu.add(0, MyTracksConstants.MENU_SHOW, 0, R.string.tracklist_show_track); menu.add(0, MyTracksConstants.MENU_EDIT, 0, R.string.tracklist_edit_track); if (!MyTracks.getInstance().isRecording() || trackId != recordingTrackId) { menu.add(0, MyTracksConstants.MENU_SEND_TO_GOOGLE, 0, R.string.tracklist_send_to_google); SubMenu share = menu.addSubMenu(0, MyTracksConstants.MENU_SHARE, 0, R.string.tracklist_share_track); share.add(0, MyTracksConstants.MENU_SHARE_LINK, 0, R.string.tracklist_share_link); share.add(0, MyTracksConstants.MENU_SHARE_GPX_FILE, 0, R.string.tracklist_share_gpx_file); share.add(0, MyTracksConstants.MENU_SHARE_KML_FILE, 0, R.string.tracklist_share_kml_file); share.add(0, MyTracksConstants.MENU_SHARE_CSV_FILE, 0, R.string.tracklist_share_csv_file); share.add(0, MyTracksConstants.MENU_SHARE_TCX_FILE, 0, R.string.tracklist_share_tcx_file); SubMenu save = menu.addSubMenu(0, MyTracksConstants.MENU_WRITE_TO_SD_CARD, 0, R.string.tracklist_write_to_sd); save.add(0, MyTracksConstants.MENU_SAVE_GPX_FILE, 0, R.string.tracklist_save_as_gpx); save.add(0, MyTracksConstants.MENU_SAVE_KML_FILE, 0, R.string.tracklist_save_as_kml); save.add(0, MyTracksConstants.MENU_SAVE_CSV_FILE, 0, R.string.tracklist_save_as_csv); save.add(0, MyTracksConstants.MENU_SAVE_TCX_FILE, 0, R.string.tracklist_save_as_tcx); menu.add(0, MyTracksConstants.MENU_DELETE, 0, R.string.tracklist_delete_track); } } }; @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (key == null) { return; } if (key.equals(getString(R.string.metric_units_key))) { metricUnits = sharedPreferences.getBoolean( getString(R.string.metric_units_key), true); if (tracksCursor != null && !tracksCursor.isClosed()) { tracksCursor.requery(); } } if (key.equals(getString(R.string.recording_track_key))) { recordingTrackId = sharedPreferences.getLong( getString(R.string.recording_track_key), -1); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent result = new Intent(); result.putExtra("trackid", id); setResult(MyTracksConstants.SHOW_TRACK, result); finish(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (!super.onMenuItemSelected(featureId, item)) { switch (item.getItemId()) { case MyTracksConstants.MENU_SHOW: { onListItemClick(null, null, 0, trackId); return true; } case MyTracksConstants.MENU_EDIT: { Intent intent = new Intent(this, MyTracksDetails.class); intent.putExtra("trackid", trackId); startActivity(intent); return true; } case MyTracksConstants.MENU_SHARE: case MyTracksConstants.MENU_WRITE_TO_SD_CARD: return false; default: { Intent result = new Intent(); result.putExtra("trackid", trackId); setResult( MyTracksConstants.getActionFromMenuId(item.getItemId()), result); finish(); return true; } } } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tracklist_btn_delete_all: { Handler h = new MyTracksDeleteAllTracks(this, null); h.handleMessage(null); break; } case R.id.tracklist_btn_export_all: { new ExportAllTracks(this); break; } case R.id.tracklist_btn_import_all: { new ImportAllTracks(this); break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_list); listView = getListView(); listView.setOnCreateContextMenuListener(contextMenuListener); findViewById(R.id.tracklist_btn_delete_all).setOnClickListener(this); findViewById(R.id.tracklist_btn_export_all).setOnClickListener(this); findViewById(R.id.tracklist_btn_import_all).setOnClickListener(this); SharedPreferences preferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); preferences.registerOnSharedPreferenceChangeListener(this); metricUnits = preferences.getBoolean(getString(R.string.metric_units_key), true); recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); tracksCursor = getContentResolver().query( TracksColumns.CONTENT_URI, null, null, null, "_id DESC"); startManagingCursor(tracksCursor); setListAdapter(); } private void setListAdapter() { // Get a cursor with all tracks SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.mytracks_list_item, tracksCursor, new String[] { TracksColumns.NAME, TracksColumns.STARTTIME, TracksColumns.TOTALDISTANCE, TracksColumns.DESCRIPTION, TracksColumns.CATEGORY }, new int[] { R.id.trackdetails_item_name, R.id.trackdetails_item_time, R.id.trackdetails_item_stats, R.id.trackdetails_item_description, R.id.trackdetails_item_category }); final int startTimeIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); final int totalTimeIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); final int totalDistanceIdx = tracksCursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { TextView textView = (TextView) view; if (columnIndex == startTimeIdx) { long time = cursor.getLong(startTimeIdx); textView.setText(String.format("%tc", time)); } else if (columnIndex == totalDistanceIdx) { double length = cursor.getDouble(totalDistanceIdx); String lengthUnit = null; if (metricUnits) { if (length > 1000) { length /= 1000; lengthUnit = getString(R.string.kilometer); } else { lengthUnit = getString(R.string.meter); } } else { if (length > UnitConversions.MI_TO_M) { length /= UnitConversions.MI_TO_M; lengthUnit = getString(R.string.mile); } else { length *= UnitConversions.M_TO_FT; lengthUnit = getString(R.string.feet); } } textView.setText(String.format("%s %.2f %s", StringUtils.formatTime(cursor.getLong(totalTimeIdx)), length, lengthUnit)); } else { textView.setText(cursor.getString(columnIndex)); if (textView.getText().length() < 1) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); } } return true; } }); setListAdapter(adapter); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.MyTracksProviderUtilsImpl; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.services.StatusAnnouncerFactory; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; /** * An activity that displays track statistics to the user. * * @author Sandor Dornbush */ public class StatsActivity extends Activity implements OnSharedPreferenceChangeListener { private StatsUtilities utils; private UIUpdateThread thread; private ContentObserver observer; /** * The id of the currently selected track. */ private long selectedTrackId = -1; /** * The id of the currently recording track. */ private long recordingTrackId = -1; /** * The start time of the selected track. */ private long startTime = -1; /** * True if distances should be displayed in metric units (from shared * preferences). */ private boolean metricUnits = true; /** * True if pace should be displayed as dist/time (from shared preferences). */ private boolean displaySpeed = true; /** * true if activity has resumed and is on top */ private boolean activityOnTop = false; /** * If true, the statistics for the current segment are shown, otherwise * for the full track. */ private boolean showCurrentSegment = false; private MyTracksProviderUtils providerUtils; /** * A runnable for posting to the UI thread. Will update the total time field. */ private final Runnable updateResults = new Runnable() { public void run() { updateTotalTime(); } }; /** * A thread that updates the total time field every second. */ private class UIUpdateThread extends Thread { public UIUpdateThread() { super(); Log.i(MyTracksConstants.TAG, "Created UI update thread"); } @Override public void run() { Log.i(MyTracksConstants.TAG, "Started UI update thread"); while (MyTracks.getInstance().isRecording()) { long sleeptime = 1000; runOnUiThread(updateResults); try { Thread.sleep(sleeptime); } catch (InterruptedException e) { Log.w(MyTracksConstants.TAG, "StatsActivity: Caught exception on sleep.", e); break; } } Log.w(MyTracksConstants.TAG, "UIUpdateThread finished."); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); utils = new StatsUtilities(this); providerUtils = new MyTracksProviderUtilsImpl(getContentResolver()); // The volume we want to control is the Text-To-Speech volume int volumeStream = new StatusAnnouncerFactory(ApiFeatures.getInstance()).getVolumeStream(); setVolumeControlStream(volumeStream); // We don't need a window title bar: requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.stats); Handler contentHandler = new Handler(); observer = new ContentObserver(contentHandler) { @Override public void onChange(boolean selfChange) { Log.d(MyTracksConstants.TAG, "StatsActivity: ContentObserver.onChange"); restoreStats(); super.onChange(selfChange); } }; ScrollView sv = ((ScrollView) findViewById(R.id.scrolly)); sv.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); SharedPreferences preferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (preferences != null) { selectedTrackId = preferences.getLong( getString(R.string.selected_track_key), -1); recordingTrackId = preferences.getLong( getString(R.string.recording_track_key), -1); metricUnits = preferences.getBoolean( getString(R.string.metric_units_key), true); displaySpeed = preferences.getBoolean(getString(R.string.report_speed_key), true); checkLiveTrack(); restoreStats(); showUnknownLocation(); preferences.registerOnSharedPreferenceChangeListener(this); } utils.setMetricUnits(metricUnits); utils.setReportSpeed(displaySpeed); utils.updateUnits(); utils.setSpeedLabel(R.id.speed_label, R.string.speed, R.string.pace_label); utils.setSpeedLabels(); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); if (metrics.heightPixels > 600) { ((TextView) findViewById(R.id.speed_register)).setTextSize(80.0f); } } @Override protected void onPause() { unregisterLocationListener(); if (thread != null) { thread.interrupt(); thread = null; } getContentResolver().unregisterContentObserver(observer); activityOnTop = false; super.onPause(); } @Override protected void onResume() { activityOnTop = true; checkLiveTrack(); restoreStats(); showUnknownLocation(); super.onResume(); } @Override public void onSharedPreferenceChanged( final SharedPreferences sharedPreferences, final String key) { Log.d(MyTracksConstants.TAG, "StatsActivity: onSharedPreferences changed " + key); if (key != null) { runOnUiThread(new Runnable() { @Override public void run() { if (key.equals(getString(R.string.selected_track_key))) { selectedTrackId = sharedPreferences.getLong( getString(R.string.selected_track_key), -1); checkLiveTrack(); restoreStats(); showUnknownLocation(); } else if (key.equals(getString(R.string.recording_track_key))) { recordingTrackId = sharedPreferences.getLong( getString(R.string.recording_track_key), -1); checkLiveTrack(); restoreStats(); showUnknownLocation(); } else if (key.equals(getString(R.string.metric_units_key))) { metricUnits = sharedPreferences.getBoolean( getString(R.string.metric_units_key), true); utils.setMetricUnits(metricUnits); utils.updateUnits(); restoreStats(); } else if (key.equals(getString(R.string.report_speed_key))) { displaySpeed = sharedPreferences.getBoolean( getString(R.string.report_speed_key), true); utils.setReportSpeed(displaySpeed); utils.updateUnits(); utils.setSpeedLabel( R.id.speed_label, R.string.speed, R.string.pace_label); Log.w(MyTracksConstants.TAG, "Setting speed labels"); utils.setSpeedLabels(); restoreStats(); } } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem currentSegment = menu.add(0, MyTracksConstants.MENU_CURRENT_SEGMENT, 0, R.string.current_segment); currentSegment.setIcon(R.drawable.ic_menu_lastsegment); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(MyTracksConstants.MENU_CURRENT_SEGMENT); if (item != null) { item.setTitle(showCurrentSegment ? getString(R.string.current_track) : getString(R.string.current_segment)); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MyTracksConstants.MENU_CURRENT_SEGMENT: showCurrentSegment = !showCurrentSegment; restoreStats(); return true; } return super.onOptionsItemSelected(item); } private final LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location l) { if (selectedTrackIsRecording()) { showLocation(l); } } @Override public void onProviderDisabled(String provider) { // Do nothing } @Override public void onProviderEnabled(String provider) { // Do nothing } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing } }; /** * Registers to receive location updates from the GPS location provider. */ private void registerLocationListener() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager != null) { LocationProvider gpsProvider = locationManager.getProvider(MyTracksConstants.GPS_PROVIDER); if (gpsProvider == null) { Toast.makeText(this, getString(R.string.error_no_gps_location_provider), Toast.LENGTH_LONG).show(); return; } else { Log.d(MyTracksConstants.TAG, "StatsActivity: Using location provider " + gpsProvider.getName()); } locationManager.requestLocationUpdates(gpsProvider.getName(), 0/*minTime*/, 0/*minDist*/, locationListener); } } /** * Unregisters all location listener. */ private void unregisterLocationListener() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (locationManager != null) { locationManager.removeUpdates(locationListener); } } /** * @return true if the selected track is the currently recording track */ private boolean selectedTrackIsRecording() { return MyTracks.getInstance().isRecording() && selectedTrackId == recordingTrackId; } /** * Reads values for selected tracks from provider and update the UI. */ private void restoreStats() { if (selectedTrackId < 0) { utils.setAllToUnknown(); return; } Track track = providerUtils.getTrack(selectedTrackId); if (track == null || track.getStatistics() == null) { utils.setAllToUnknown(); return; } startTime = track.getStatistics().getStartTime(); if (!selectedTrackIsRecording()) { utils.setTime(R.id.total_time_register, track.getStatistics().getTotalTime()); } utils.setAllStats(track.getStatistics()); } /** * Checks if this activity needs to update live track data or not. * If so, make sure that: * a) a thread keeps updating the total time * b) a location listener is registered * c) a content observer is registered * Otherwise unregister listeners, observers, and kill update thread. */ private void checkLiveTrack() { final boolean isRecording = selectedTrackIsRecording(); final boolean startThread = (thread == null) && isRecording && activityOnTop; final boolean killThread = (thread != null) && (!isRecording || !activityOnTop); if (startThread) { thread = new UIUpdateThread(); thread.start(); getContentResolver().registerContentObserver( TracksColumns.CONTENT_URI, false, observer); getContentResolver().registerContentObserver( WaypointsColumns.CONTENT_URI, false, observer); registerLocationListener(); } else if (killThread) { thread.interrupt(); thread = null; getContentResolver().unregisterContentObserver(observer); unregisterLocationListener(); } } public void updateTotalTime() { if (selectedTrackIsRecording()) { utils.setTime(R.id.total_time_register, System.currentTimeMillis() - startTime); } } /** * Updates the given location fields (latitude, longitude, altitude) and all * other fields. * * @param l may be null (will set location fields to unknown) */ private void showLocation(Location l) { utils.setAltitude(R.id.elevation_register, l.getAltitude()); utils.setLatLong(R.id.latitude_register, l.getLatitude()); utils.setLatLong(R.id.longitude_register, l.getLongitude()); utils.setSpeed(R.id.speed_register, l.getSpeed() * 3.6); } private void showUnknownLocation() { utils.setUnknown(R.id.elevation_register); utils.setUnknown(R.id.latitude_register); utils.setUnknown(R.id.longitude_register); utils.setUnknown(R.id.speed_register); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import static com.google.android.apps.mytracks.MyTracksConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.sensors.SensorUtils; import com.google.android.maps.mytracks.R; import com.google.protobuf.InvalidProtocolBufferException; import android.app.Activity; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * An activity that displays information about sensors. * * @author Sandor Dornbush */ public class SensorStateActivity extends Activity { private static final SimpleDateFormat TIMESTAMP_FORMAT = new SimpleDateFormat("HH:mm:ss"); private static final long REFRESH_PERIOD_MS = 250; private final StatsUtilities utils; /** * This timer periodically invokes the refresh timer task. */ private Timer timer; private final Runnable stateUpdater = new Runnable() { public void run() { updateState(); } }; /** * A task which will update the U/I. */ private class RefreshTask extends TimerTask { @Override public void run() { runOnUiThread(stateUpdater); } }; public SensorStateActivity() { utils = new StatsUtilities(this); Log.w(TAG, "SensorStateActivity()"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.w(TAG, "SensorStateActivity.onCreate"); setContentView(R.layout.sensor_state); updateState(); } @Override protected void onResume() { super.onResume(); timer = new Timer(); timer.schedule(new RefreshTask(), REFRESH_PERIOD_MS, REFRESH_PERIOD_MS); } @Override protected void onPause() { super.onPause(); timer.cancel(); timer.purge(); timer = null; } protected void updateState() { MyTracks mt = MyTracks.getInstance(); ITrackRecordingService service = mt == null ? null : mt.getTrackRecordingService(); if (service == null) { Log.d(MyTracksConstants.TAG, "Could not get track recording service."); updateSensorState(Sensor.SensorState.NONE); updateSensorData(null); return; } Sensor.SensorDataSet sds = null; try { byte[] buff = service.getSensorData(); if (buff != null) { sds = Sensor.SensorDataSet.parseFrom(buff); updateSensorData(sds); } } catch (RemoteException e) { Log.e(MyTracksConstants.TAG, "Could not read sensor data.", e); } catch (InvalidProtocolBufferException e) { Log.e(MyTracksConstants.TAG, "Could not read sensor data.", e); } updateSensorData(sds); try { int i = service.getSensorState(); updateSensorState(Sensor.SensorState.valueOf(i)); } catch (RemoteException e) { Log.e(MyTracksConstants.TAG, "Could not read sensor state.", e); updateSensorState(Sensor.SensorState.NONE); } } private void updateSensorState(Sensor.SensorState state) { TextView sensorTime = ((TextView) findViewById(R.id.sensor_state_register)); sensorTime.setText(SensorUtils.getStateAsString(state, this)); } protected void updateSensorData(Sensor.SensorDataSet sds) { if (sds == null) { utils.setUnknown(R.id.sensor_data_time_register); utils.setUnknown(R.id.cadence_state_register); utils.setUnknown(R.id.power_state_register); utils.setUnknown(R.id.heart_rate_register); return; } TextView sensorTime = ((TextView) findViewById(R.id.sensor_data_time_register)); sensorTime.setText( TIMESTAMP_FORMAT.format(new Date(sds.getCreationTime()))); if (sds.hasPower() && sds.getPower().hasValue() && sds.getPower().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.power_state_register, Integer.toString(sds.getPower().getValue())); } else { utils.setText(R.id.power_state_register, SensorUtils.getStateAsString( sds.hasPower() ? sds.getPower().getState() : Sensor.SensorState.NONE, this)); } if (sds.hasCadence() && sds.getCadence().hasValue() && sds.getCadence().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.cadence_state_register, Integer.toString(sds.getCadence().getValue())); } else { utils.setText(R.id.cadence_state_register, SensorUtils.getStateAsString( sds.hasCadence() ? sds.getCadence().getState() : Sensor.SensorState.NONE, this)); } if (sds.hasHeartRate() && sds.getHeartRate().hasValue() && sds.getHeartRate().getState() == Sensor.SensorState.SENDING) { utils.setText(R.id.heart_rate_register, Integer.toString(sds.getHeartRate().getValue())); } else { utils.setText(R.id.heart_rate_register, SensorUtils.getStateAsString( sds.hasHeartRate() ? sds.getHeartRate().getState() : Sensor.SensorState.NONE, this)); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.accounts.Account; import com.google.android.accounts.AccountManager; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.util.Log; /** * Choose which account to upload track information to. * @author Sandor Dornbush */ public class AccountChooser { /** * The last selected account. */ private int selectedAccountIndex = -1; private Account selectedAccount = null; /** * An interface for receiving updates once the user has selected the account. */ public interface AccountHandler { /** * Handle the account being selected. * @param account The selected account or null if none could be found */ public void handleAccountSelected(Account account); } /** * Chooses the best account to upload to. * If no account is found the user will be alerted. * If only one account is found that will be used. * If multiple accounts are found the user will be allowed to choose. * * @param activity The parent activity * @param handler The handler to be notified when an account has been selected */ public void chooseAccount(final Activity activity, final AccountHandler handler) { final Account[] accounts = AccountManager.get(activity) .getAccountsByType(MyTracksConstants.ACCOUNT_TYPE); if (accounts.length < 1) { alertNoAccounts(activity, handler); return; } if (accounts.length == 1) { handler.handleAccountSelected(accounts[0]); return; } // TODO This should be read out of a preference. if (selectedAccount != null) { handler.handleAccountSelected(selectedAccount); return; } // Let the user choose. Log.e(MyTracksConstants.TAG, "Multiple matching accounts found."); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.choose_account_title); builder.setCancelable(false); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectedAccount = accounts[selectedAccountIndex]; handler.handleAccountSelected(selectedAccount); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { handler.handleAccountSelected(null); } }); String[] choices = new String[accounts.length]; for (int i = 0; i < accounts.length; i++) { choices[i] = accounts[i].name; } builder.setSingleChoiceItems(choices, selectedAccountIndex, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { selectedAccountIndex = which; } }); builder.show(); } /** * Puts up a dialog alerting the user that no suitable account was found. */ private void alertNoAccounts(final Activity activity, final AccountHandler handler) { Log.e(MyTracksConstants.TAG, "No matching accounts found."); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.no_account_found_title); builder.setMessage(R.string.no_account_found); builder.setCancelable(true); builder.setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { handler.handleAccountSelected(null); } }); builder.show(); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.ChartValueSeries.ZoomSettings; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.ExtremityMonitor; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.widget.Scroller; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; /** * Visualization of the chart. * * @author Sandor Dornbush * @author Leif Hendrik Wilden */ public class ChartView extends View { /* * Scrolling logic: */ private final Scroller scroller; private VelocityTracker velocityTracker = null; /** Position of the last motion event */ private float lastMotionX; /* * Zoom logic: */ private int zoomLevel = 1; private final int minZoomLevel = 1; private int maxZoomLevel = 10; private static final int MAX_INTERVALS = 5; /* * Borders, margins, dimensions (in pixels): */ private int leftBorder = -1; /** * Unscaled top border of the chart. */ private static final int TOP_BORDER = 15; /** * Device scaled top border of the chart. */ private int topBorder; /** * Unscaled bottom border of the chart. */ private static final float BOTTOM_BORDER = 40; /** * Device scaled bottom border of the chart. */ private int bottomBorder; private static final int RIGHT_BORDER = 17; /** Space to leave for drawing the unit labels */ private static final int UNIT_BORDER = 15; private static final int FONT_HEIGHT = 10; private int w = 0; private int h = 0; private int effectiveWidth = 0; private int effectiveHeight = 0; /* * Ranges (in data units): */ private double maxX = 1; /** * The various series. */ public static final int ELEVATION_SERIES = 0; public static final int SPEED_SERIES = 1; public static final int POWER_SERIES = 2; public static final int CADENCE_SERIES = 3; public static final int HEART_RATE_SERIES = 4; public static final int NUM_SERIES = 5; private ChartValueSeries[] series; private final ExtremityMonitor xMonitor = new ExtremityMonitor(); private final NumberFormat xFormat = new DecimalFormat("###,###"); private final NumberFormat xShortFormat = new DecimalFormat("#.0"); /* * Paints etc. used when drawing the histogram: */ private final Paint borderPaint = new Paint(); private final Paint labelPaint = new Paint(); private final Paint gridPaint = new Paint(); private final Paint gridBarPaint = new Paint(); private final Paint clearPaint = new Paint(); private final Drawable pointer; private final Drawable statsMarker; private final Drawable waypointMarker; private final int markerWidth, markerHeight; /** * The chart data stored as an array of double arrays. Each one dimensional * array is composed of [x, y]. */ private final ArrayList<double[]> data = new ArrayList<double[]>(); /** * List of way points to be displayed. */ private final ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>(); private boolean metricUnits = true; private boolean showPointer = false; /** Display chart versus distance or time */ public enum Mode { BY_DISTANCE, BY_TIME } private Mode mode = Mode.BY_DISTANCE; public ChartView(Context context) { super(context); setUpChartValueSeries(context); labelPaint.setStyle(Style.STROKE); labelPaint.setColor(context.getResources().getColor(R.color.black)); labelPaint.setAntiAlias(true); borderPaint.setStyle(Style.STROKE); borderPaint.setColor(context.getResources().getColor(R.color.black)); borderPaint.setAntiAlias(true); gridPaint.setStyle(Style.STROKE); gridPaint.setColor(context.getResources().getColor(R.color.gray)); gridPaint.setAntiAlias(false); gridBarPaint.set(gridPaint); gridBarPaint.setPathEffect(new DashPathEffect(new float[] {3, 2}, 0)); clearPaint.setStyle(Style.FILL); clearPaint.setColor(context.getResources().getColor(R.color.white)); clearPaint.setAntiAlias(false); pointer = context.getResources().getDrawable(R.drawable.arrow_180); pointer.setBounds(0, 0, pointer.getIntrinsicWidth(), pointer.getIntrinsicHeight()); statsMarker = getResources().getDrawable(R.drawable.ylw_pushpin); markerWidth = statsMarker.getIntrinsicWidth(); markerHeight = statsMarker.getIntrinsicHeight(); statsMarker.setBounds(0, 0, markerWidth, markerHeight); waypointMarker = getResources().getDrawable(R.drawable.blue_pushpin); waypointMarker.setBounds(0, 0, markerWidth, markerHeight); scroller = new Scroller(context); setFocusable(true); setClickable(true); updateDimensions(); } public void setUpChartValueSeries(Context context) { series = new ChartValueSeries[NUM_SERIES]; // Create the value series. series[ELEVATION_SERIES] = new ChartValueSeries(context, "###,###", R.color.elevation_fill, R.color.elevation_border, new ZoomSettings(MAX_INTERVALS, new int[] {5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000}), R.string.elevation); series[SPEED_SERIES] = new ChartValueSeries(context, "###,###", R.color.speed_fill, R.color.speed_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {1, 5, 10, 20, 50}), R.string.speed); series[POWER_SERIES] = new ChartValueSeries(context, "###,###", R.color.power_fill, R.color.power_border, new ZoomSettings(MAX_INTERVALS, 0, 1000, new int[] {5, 50, 100, 200}), R.string.power); series[CADENCE_SERIES] = new ChartValueSeries(context, "###,###", R.color.cadence_fill, R.color.cadence_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {5, 10, 25, 50}), R.string.cadence); series[HEART_RATE_SERIES] = new ChartValueSeries(context, "###,###", R.color.heartrate_fill, R.color.heartrate_border, new ZoomSettings(MAX_INTERVALS, 0, Integer.MIN_VALUE, new int[] {25, 50}), R.string.heart_rate); } public void clearWaypoints() { waypoints.clear(); } public void addWaypoint(Waypoint waypoint) { waypoints.add(waypoint); } /** * Determines whether the pointer icon is shown on the last data point. */ public void setShowPointer(boolean showPointer) { this.showPointer = showPointer; } /** * Sets whether metric units are used or not. */ public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; } public void setReportSpeed(boolean reportSpeed, Context c) { series[SPEED_SERIES].setTitle(c.getString(reportSpeed ? R.string.speed : R.string.pace_label)); } /** * Gets the data that is displayed by the chart. * * @return an array list with data points */ public ArrayList<double[]> getData() { return data; } /** * Sets the data that is to be displayed by the chart. * * @param theData an array list of data points */ public synchronized void setDataPoints(ArrayList<double[]> theData) { scrollTo(0, 0); zoomLevel = 1; data.clear(); xMonitor.reset(); for (ChartValueSeries cvs : series) { cvs.reset(); } addDataPoints(theData); } /** * Adds a new data point to the chart. * * @param theData a data point */ public synchronized void addDataPoint(double[] theData) { data.add(theData); addDataPointInternal(theData); updateDimensions(); setUpPath(); } private void addDataPointInternal(double[] theData) { xMonitor.update(theData[0]); int min = Math.min(series.length, theData.length - 1); for (int i = 0; i < min; i++) { if (!Double.isNaN(theData[i + 1])) { series[i].update(theData[i + 1]); } } // Fill in the extra's if needed. for (int i = theData.length; i < series.length; i++) { if (series[i].hasData()) { series[i].update(0); } } } /** * Adds multiple data points to the chart. * * @param theData an array list of data points to be added */ public synchronized void addDataPoints(ArrayList<double[]> theData) { data.addAll(theData); for (int i = 0; i < theData.size(); i++) { double d[] = theData.get(i); addDataPointInternal(d); } updateDimensions(); setUpPath(); } /** * Clears all data. * Call this only from the UI thread! */ public synchronized void reset() { data.clear(); zoomLevel = 1; scrollTo(0, 0); updateDimensions(); } /** * @return true if the chart can be zoomed into. */ public boolean canZoomIn() { return zoomLevel < maxZoomLevel; } /** * @return true if the chart can be zoomed out */ public boolean canZoomOut() { return zoomLevel > minZoomLevel; } /** * Zooms in one level (factor 2). */ public void zoomIn() { if (canZoomIn()) { zoomLevel++; setUpPath(); invalidate(); } } /** * Zooms out one level (factor 2). */ public void zoomOut() { if (canZoomOut()) { zoomLevel--; scroller.abortAnimation(); int scrollX = getScrollX(); if (scrollX > effectiveWidth * (zoomLevel - 1)) { scrollX = effectiveWidth * (zoomLevel - 1); scrollTo(scrollX, 0); } setUpPath(); invalidate(); } } /** * @return the current zoom level (1 equals to showing all data points) */ public int getZoomLevel() { return zoomLevel; } /** * Initiates flinging. * * @param velocityX start velocity (pixels per second) */ public void fling(int velocityX) { scroller.fling(getScrollX(), 0, velocityX, 0, 0, effectiveWidth * (zoomLevel - 1), 0, 0); invalidate(); } /** * Scrolls the view horizontally by the given amount. * * @param deltaX number of pixels to scroll */ public void scrollBy(int deltaX) { int scrollX = getScrollX() + deltaX; if (scrollX < 0) { scrollX = 0; } int available = effectiveWidth * (zoomLevel - 1); if (scrollX > available) { scrollX = available; } scrollTo(scrollX, 0); } /** * Sets the scroll position of the chart. This will trigger a redraw. */ @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); } /** * @return the current display mode (by distance, by time) */ public Mode getMode() { return mode; } /** * Sets the display mode (by distance, by time). */ public void setMode(Mode mode) { this.mode = mode; } private int getWaypointX(Waypoint waypoint) { return (mode == Mode.BY_DISTANCE) ? getX(metricUnits ? waypoint.getLength() / 1000.0 : waypoint.getLength() * UnitConversions.KM_TO_MI / 1000.0) : getX(waypoint.getDuration()); } /** * Called by the parent to indicate that the mScrollX/Y values need to be * updated. Triggers a redraw during flinging. */ @Override public void computeScroll() { if (scroller.computeScrollOffset()) { int oldX = getScrollX(); int x = scroller.getCurrX(); scrollTo(x, 0); if (oldX != x) { onScrollChanged(x, 0, oldX, 0); postInvalidate(); } } } @Override public boolean onTouchEvent(MotionEvent event) { if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain(); } velocityTracker.addMovement(event); final int action = event.getAction(); final float x = event.getX(); switch (action) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished will be * false if being flinged. */ if (!scroller.isFinished()) { scroller.abortAnimation(); } // Remember where the motion event started lastMotionX = x; break; case MotionEvent.ACTION_MOVE: // Scroll to follow the motion event final int deltaX = (int) (lastMotionX - x); lastMotionX = x; if (deltaX < 0) { if (getScrollX() > 0) { scrollBy(deltaX); } } else if (deltaX > 0) { final int availableToScroll = effectiveWidth * (zoomLevel - 1) - getScrollX(); if (availableToScroll > 0) { scrollBy(Math.min(availableToScroll, deltaX)); } } break; case MotionEvent.ACTION_UP: // Check if top area with waypoint markers was touched and find the // touched marker if any: if (event.getY() < 100) { int dmin = Integer.MAX_VALUE; Waypoint nearestWaypoint = null; for (int i = 0; i < waypoints.size(); i++) { final Waypoint waypoint = waypoints.get(i); final int d = Math.abs(getWaypointX(waypoint) - (int) event.getX() - getScrollX()); if (d < dmin) { dmin = d; nearestWaypoint = waypoint; } } if (nearestWaypoint != null && dmin < 100) { Intent intent = new Intent(getContext(), MyTracksWaypointDetails.class); intent.putExtra("waypointid", nearestWaypoint.getId()); getContext().startActivity(intent); return true; } } VelocityTracker myVelocityTracker = velocityTracker; myVelocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int) myVelocityTracker.getXVelocity(); if (Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) { fling(-initialVelocity); } if (velocityTracker != null) { velocityTracker.recycle(); velocityTracker = null; } break; } return true; } @Override protected synchronized void onDraw(Canvas c) { if (w != c.getWidth() || h != c.getHeight()) { // Dimensions have changed (for example due to orientation change). w = c.getWidth(); h = c.getHeight(); effectiveWidth = Math.max(0, w - leftBorder - RIGHT_BORDER); effectiveHeight = Math.max(0, h - topBorder - bottomBorder); setUpPath(); } c.save(); c.drawColor(Color.WHITE); if (data.size() < 1) { drawXAxis(c); drawYAxis(c); c.restore(); return; } c.save(); c.clipRect(leftBorder + 1 + getScrollX(), topBorder + 1, w - RIGHT_BORDER + getScrollX() - 1, h - bottomBorder - 1); drawGrid(c); // Draw the data series. for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { cvs.drawPath(c); } } // Draw the waypoints. for (int i = 1; i < waypoints.size(); i++) { final Waypoint waypoint = waypoints.get(i); if (waypoint.getLocation() == null) { continue; } c.save(); final float x = getWaypointX(waypoint); c.drawLine(x, h - bottomBorder, x, topBorder, gridPaint); c.translate(x - markerWidth / 2, markerHeight); if (waypoints.get(i).getType() == Waypoint.TYPE_STATISTICS) { statsMarker.draw(c); } else { waypointMarker.draw(c); } c.restore(); } c.restore(); // Draw the axis and labels. drawXLabels(c); drawXAxis(c); drawSeriesTitles(c); c.translate(getScrollX(), 0); drawYAxis(c); float density = getContext().getResources().getDisplayMetrics().density; final int spacer = (int) (5 * density); int x = leftBorder - spacer; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { x -= drawYLabels(cvs, c, x) + spacer; } } c.restore(); if (showPointer && !data.isEmpty()) { c.translate(getX(maxX) - pointer.getIntrinsicWidth() / 2, getY(series[0], data.get(data.size() - 1)[1]) - pointer.getIntrinsicHeight() / 2 - 12); pointer.draw(c); } } private void drawSeriesTitles(Canvas c) { int sections = 1; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { sections++; } } int j = 0; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { int x = (int) (w * (double) ++j / sections) + getScrollX(); c.drawText(cvs.getTitle(), x, topBorder, cvs.getLabelPaint()); } } } /** * Sets up the path that is used to draw the histogram in onDraw(). The path * needs to be updated any time after the data or histogram dimensions change. */ private synchronized void setUpPath() { for (ChartValueSeries cvs : series) { cvs.getPath().reset(); } if (data.isEmpty()) { return; } // All of the data points to the respective series. // TODO: Come up with a better sampling than Math.max(1, (maxZoomLevel - zoomLevel + 1) / 2); int sampling = 1; for (int i = 0; i < data.size(); i += sampling) { double[] d = data.get(i); int min = Math.min(series.length, d.length - 1); for (int j = 0; j < min; ++j) { ChartValueSeries cvs = series[j]; Path path = cvs.getPath(); int x = getX(d[0]); int y = getY(cvs, d[j + 1]); if (i == 0) { path.moveTo(x, y); } else { path.lineTo(x, y); } } } // Close the path. int yCorner = topBorder + effectiveHeight; int xCorner = getX(data.get(0)[0]); int min = series.length; for (int j = 0; j < min; j++) { ChartValueSeries cvs = series[j]; Path path = cvs.getPath(); int first = getFirstPointPopulatedIndex(j + 1); if (first != -1) { // Bottom right corner path.lineTo(getX(data.get(data.size() - 1)[0]), yCorner); // Bottom left corner path.lineTo(xCorner, yCorner); // Top right corner path.lineTo(xCorner, getY(cvs, data.get(first)[j + 1])); } } } /** * Find the index of the first point which has a series populated. * @param seriesIndex The index of the value series to search for. * @return The index in the first data for the point in the series that has series * index value populated or -1 if none is found. */ private int getFirstPointPopulatedIndex(int seriesIndex) { for (int i = 0; i < data.size(); i++) { if (data.get(i).length > seriesIndex) { return i; } } return -1; } /** * Update the histogram dimensions. */ private void updateDimensions() { maxX = xMonitor.getMax(); if (data.size() <= 1) { maxX = 1; } for (ChartValueSeries cvs : series) { cvs.updateDimension(); } // TODO: This is totally broken. Make sure that we calculate based on measureText for each // grid line, as the labels may vary across intervals. int maxLength = 0; for (ChartValueSeries cvs : series) { if (cvs.isEnabled() && cvs.hasData()) { maxLength += cvs.getMaxLabelLength(); } } float density = getContext().getResources().getDisplayMetrics().density; // TODO: This should be function of the number of variables displayed. leftBorder = (int) (density * (4 + 8 * maxLength)); effectiveWidth = w - leftBorder - RIGHT_BORDER; bottomBorder = (int) (density * BOTTOM_BORDER); topBorder = (int) (density * TOP_BORDER); effectiveHeight = h - topBorder - bottomBorder; } private int getX(double distance) { return leftBorder + (int) ((distance * effectiveWidth / maxX) * zoomLevel); } private int getY(ChartValueSeries cvs, double y) { int effectiveSpread = cvs.getInterval() * MAX_INTERVALS; return topBorder + effectiveHeight - (int) ((y - cvs.getMin()) * effectiveHeight / effectiveSpread); } private void drawXLabels(Canvas c) { double interval = (int) (maxX / zoomLevel / 4); boolean shortFormat = false; if (interval < 1) { interval = .5; shortFormat = true; } else if (interval < 5) { interval = 2; } else if (interval < 10) { interval = 5; } else { interval = (interval / 10) * 10; } drawXLabel(c, 0, shortFormat); int numLabels = 1; for (int i = 1; i * interval < maxX; i++) { drawXLabel(c, i * interval, shortFormat); numLabels++; } if (numLabels < 2) { drawXLabel(c, (int) maxX, shortFormat); } } private float drawYLabels(ChartValueSeries cvs, Canvas c, int x) { int interval = cvs.getInterval(); float maxTextWidth = 0; for (int i = 0; i < MAX_INTERVALS; ++i) { maxTextWidth = Math.max(maxTextWidth, drawYLabel(cvs, c, x, i * interval + cvs.getMin())); } return maxTextWidth; } private void drawXLabel(Canvas c, double x, boolean shortFormat) { if (x < 0) { return; } String s = (mode == Mode.BY_DISTANCE) ? (shortFormat ? xShortFormat.format(x) : xFormat.format(x)) : StringUtils.formatTime((long) x); c.drawText(s, getX(x), effectiveHeight + UNIT_BORDER + topBorder, labelPaint); } private float drawYLabel(ChartValueSeries cvs, Canvas c, int x, int y) { int desiredY = (int) ((y - cvs.getMin()) * effectiveHeight / (cvs.getInterval() * MAX_INTERVALS)); desiredY = topBorder + effectiveHeight + FONT_HEIGHT / 2 - desiredY - 1; Paint p = new Paint(cvs.getLabelPaint()); p.setTextAlign(Align.RIGHT); String text = cvs.getFormat().format(y); c.drawText(text, x, desiredY, p); return p.measureText(text); } private void drawXAxis(Canvas canvas) { float rightEdge = getX(maxX); final int y = effectiveHeight + topBorder; canvas.drawLine(leftBorder, y, rightEdge, y, borderPaint); Context c = getContext(); String s = mode == Mode.BY_DISTANCE ? (metricUnits ? c.getString(R.string.kilometer) : c.getString(R.string.mile)) : c.getString(R.string.min); canvas.drawText(s, rightEdge, effectiveHeight + .2f * UNIT_BORDER + topBorder, labelPaint); } private void drawYAxis(Canvas canvas) { canvas.drawRect(0, 0, leftBorder - 1, effectiveHeight + topBorder + UNIT_BORDER + 1, clearPaint); canvas.drawLine(leftBorder, UNIT_BORDER + topBorder, leftBorder, effectiveHeight + topBorder, borderPaint); for (int i = 1; i < MAX_INTERVALS; ++i) { int y = i * effectiveHeight / MAX_INTERVALS + topBorder; canvas.drawLine(leftBorder - 5, y, leftBorder, y, gridPaint); } Context c = getContext(); // TODO: This should really show units for all series. String s = metricUnits ? c.getString(R.string.meter) : c.getString(R.string.feet); canvas.drawText(s, leftBorder - UNIT_BORDER * .2f, UNIT_BORDER * .8f + topBorder, labelPaint); } private synchronized void drawGrid(Canvas c) { if (data.isEmpty()) { return; } float rightEdge = getX(maxX); for (int i = 1; i < MAX_INTERVALS; ++i) { int y = i * effectiveHeight / MAX_INTERVALS + topBorder; c.drawLine(leftBorder, y, rightEdge, y, gridBarPaint); } } /** * Gets one of the chart value series. * The index should be one of the following values: * ELEVATION_SERIES or SPEED_SERIES * * @param index of the value series * @return The chart series at the index */ public ChartValueSeries getChartValueSeries(int index) { return series[index]; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.accounts.Account; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManagerFactory; import com.google.android.apps.mytracks.io.MyMapsFactory; import com.google.android.apps.mytracks.io.mymaps.MapsFacade; import com.google.android.apps.mytracks.io.mymaps.MapsService; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; /** * Activity which displays the list of current My Maps tracks for the user. * Returns RESULT_OK if the user picked a map, and returns "mapid" as an extra. * * @author Rodrigo Damazio */ public class MyMapsList extends Activity implements MapsFacade.MapsListCallback { private static final int MENU_OPEN = 0; private static final int MENU_SHARE = 2; private static final int GET_LOGIN = 1; private MapsFacade mapsClient; private AuthManager auth; private MyMapsListAdapter listAdapter; private int contextPosition; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; menu.add(0, MENU_OPEN, 0, R.string.open_map); menu.add(0, MENU_SHARE, 0, R.string.share_map); } }; private final OnItemClickListener clickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent result = new Intent(); result.putExtra("mapid", (String) listAdapter.getItem(position)); setResult(RESULT_OK, result); finish(); } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); auth = AuthManagerFactory.getAuthManager(this, GET_LOGIN, null, true, MapsService.getServiceName()); setContentView(R.layout.list); listAdapter = new MyMapsListAdapter(this); ListView list = (ListView) findViewById(R.id.maplist); list.setOnItemClickListener(clickListener); list.setOnCreateContextMenuListener(contextMenuListener); list.setAdapter(listAdapter); startLogin(); } private void startLogin() { // Starts in the UI thread. // TODO fix this for non-froyo devices. if (AuthManagerFactory.useModernAuthManager()) { MyTracks.getInstance().getAccountChooser().chooseAccount( MyMapsList.this, new AccountChooser.AccountHandler() { @Override public void handleAccountSelected(Account account) { // Account selection happens in the UI thread. if (account != null) { // The user did not quit and there was a valid google // account. doLogin(account); } } }); } else { doLogin(null); } } private void doLogin(final Account account) { // Starts in the UI thread. auth.doLogin(new Runnable() { public void run() { // Runs in UI thread. mapsClient = MyMapsFactory.newMapsClient(MyMapsList.this, auth); startLookup(); } }, account); } private void startLookup() { // Starts in the UI thread. new Thread() { @Override public void run() { // Communication with Maps happens in its own thread. // This will call onReceivedMapListing below. final boolean success = mapsClient.getMapsList(MyMapsList.this); runOnUiThread(new Runnable() { @Override public void run() { // Updating the UI when done happens in the UI thread. onLookupDone(success); } }); } }.start(); } @Override public void onReceivedMapListing(final String mapId, final String title, final String description, final boolean isPublic) { // Starts in the communication thread. runOnUiThread(new Runnable() { @Override public void run() { // Updating the list with new contents happens in the UI thread. listAdapter.addMapListing(mapId, title, description, isPublic); } }); } private void onLookupDone(boolean success) { // Starts in the UI thread. findViewById(R.id.loading).setVisibility(View.GONE); if (!success) { findViewById(R.id.failed).setVisibility(View.VISIBLE); } TextView emptyView = (TextView) findViewById(R.id.mapslist_empty); ListView list = (ListView) findViewById(R.id.maplist); list.setEmptyView(emptyView); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == GET_LOGIN) { auth.authResult(resultCode, data); } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_OPEN: clickListener.onItemClick(null, null, contextPosition, 0); return true; case MENU_SHARE: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.share_map_subject)); String[] listItem = (String[]) listAdapter.getMapListingArray(contextPosition); shareIntent.putExtra(Intent.EXTRA_TEXT, String.format( getText(R.string.share_map_body_format).toString(), listItem[1], MapsService.buildMapUrl(listItem[0]))); startActivity(Intent.createChooser(shareIntent, getText(R.string.share_map).toString())); return true; } return false; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.RadioButton; import android.widget.RadioGroup; /** * A dialog where the user can choose where to send the tracks to, i.e. * to Google My Maps, Google Docs, etc. * * @author Leif Hendrik Wilden */ public class SendToGoogleDialog extends Dialog { private RadioGroup groupMyMaps; private RadioButton createNewMapRadioButton; private RadioButton pickMapRadioButton; private CheckBox sendToMyMapsCheckBox; private CheckBox sendToFusionTablesCheckBox; private CheckBox sendToDocsCheckBox; private RadioButton sendStatsRadioButton; private RadioButton sendStatsAndPointsRadioButton; private Button sendButton; public SendToGoogleDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.mytracks_send_to_google); Button cancel = (Button) findViewById(R.id.sendtogoogle_cancel); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { MyTracks.getInstance().dismissDialog(DialogManager.DIALOG_SEND_TO_GOOGLE); } }); Button send = (Button) findViewById(R.id.sendtogoogle_send_now); send.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dismiss(); MyTracks.getInstance().sendToGoogle(); } }); OnCheckedChangeListener checkBoxListener = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton button, boolean checked) { sendButton.setEnabled( sendToMyMapsCheckBox.isChecked() || sendToFusionTablesCheckBox.isChecked() || sendToDocsCheckBox.isChecked()); groupMyMaps.setVisibility(sendToMyMapsCheckBox.isChecked() ? View.VISIBLE : View.INVISIBLE); //groupDocs.setVisibility( // sendToDocsCheckBox.isChecked() ? View.VISIBLE : View.INVISIBLE); } }; sendButton = (Button) findViewById(R.id.sendtogoogle_send_now); groupMyMaps = (RadioGroup) findViewById(R.id.sendtogoogle_group_mymaps); sendToMyMapsCheckBox = (CheckBox) findViewById(R.id.sendtogoogle_google_mymaps); sendToMyMapsCheckBox.setOnCheckedChangeListener(checkBoxListener); sendToFusionTablesCheckBox = (CheckBox) findViewById(R.id.sendtogoogle_google_fusiontables); sendToFusionTablesCheckBox.setOnCheckedChangeListener(checkBoxListener); sendToDocsCheckBox = (CheckBox) findViewById(R.id.sendtogoogle_google_docs); sendToDocsCheckBox.setOnCheckedChangeListener(checkBoxListener); createNewMapRadioButton = (RadioButton) findViewById(R.id.sendtogoogle_create_new_map); pickMapRadioButton = (RadioButton) findViewById(R.id.sendtogoogle_pick_existing_map); sendStatsRadioButton = (RadioButton) findViewById(R.id.sendtogoogle_send_stats); sendStatsAndPointsRadioButton = (RadioButton) findViewById( R.id.sendtogoogle_send_stats_and_points); SharedPreferences prefs = getContext().getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (prefs != null) { sendToMyMapsCheckBox.setChecked( prefs.getBoolean( getContext().getString(R.string.send_to_my_maps_key), true)); sendToFusionTablesCheckBox.setChecked( prefs.getBoolean( getContext().getString(R.string.send_to_fusion_tables_key), true)); sendToDocsCheckBox.setChecked( prefs.getBoolean( getContext().getString(R.string.send_to_docs_key), true)); pickMapRadioButton.setChecked( prefs.getBoolean( getContext().getString(R.string.pick_existing_map_key), false)); createNewMapRadioButton.setChecked( !prefs.getBoolean( getContext().getString(R.string.pick_existing_map_key), false)); sendStatsAndPointsRadioButton.setChecked( prefs.getBoolean( getContext().getString(R.string.send_stats_and_points_key), false)); sendStatsRadioButton.setChecked( !prefs.getBoolean( getContext().getString(R.string.send_stats_and_points_key), false)); } } @Override protected void onStop() { SharedPreferences prefs = getContext().getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (prefs != null) { Editor editor = prefs.edit(); if (editor != null) { editor.putBoolean( getContext().getString(R.string.send_to_my_maps_key), sendToMyMapsCheckBox.isChecked()); editor.putBoolean( getContext().getString(R.string.send_to_fusion_tables_key), sendToFusionTablesCheckBox.isChecked()); editor.putBoolean( getContext().getString(R.string.send_to_docs_key), sendToDocsCheckBox.isChecked()); editor.putBoolean( getContext().getString(R.string.pick_existing_map_key), pickMapRadioButton.isChecked()); editor.putBoolean( getContext().getString(R.string.send_stats_and_points_key), sendStatsAndPointsRadioButton.isChecked()); editor.commit(); } } super.onStop(); } public boolean getSendToMyMaps() { return sendToMyMapsCheckBox.isChecked(); } public boolean getSendToFusionTables() { return sendToFusionTablesCheckBox.isChecked(); } public boolean getSendToDocs() { return sendToDocsCheckBox.isChecked(); } public boolean getCreateNewMap() { return createNewMapRadioButton.isChecked(); } public boolean getSendStatsAndPoints() { return sendStatsAndPointsRadioButton.isChecked(); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.util.Log; /** * A utility class that can be used to delete all tracks and track points * from the provider, including asking for confirmation from the user via * a dialog. * * @author Leif Hendrik Wilden */ public class MyTracksDeleteAllTracks extends Handler { private final Context context; private final Runnable done; public MyTracksDeleteAllTracks(Context context, Runnable done) { this.context = context; this.done = done; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage( context.getString(R.string.all_data_will_be_permanently_deleted)); builder.setTitle(context.getString(R.string.are_you_sure_question)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(context.getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); Log.w(MyTracksConstants.TAG, "deleting all!"); MyTracksProviderUtils.Factory.get(context).deleteAllTracks(); SharedPreferences prefs = context.getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); SharedPreferences.Editor editor = prefs.edit(); editor.putLong(context.getString(R.string.selected_track_key), -1); ApiFeatures.getInstance().getApiPlatformAdapter().applyPreferenceChanges(editor); if (done != null) { Handler h = new Handler(); h.post(done); } } }); builder.setNegativeButton(context.getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.ContentValues; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; /** * Screen in which the user enters details about a waypoint. * * @author Leif Hendrik Wilden */ public class MyTracksWaypointDetails extends Activity implements OnClickListener { public static final String WAYPOINT_ID_EXTRA = "com.google.android.apps.mytracks.WAYPOINT_ID"; /** * The id of the way point being edited (taken from bundle, "waypointid") */ private Long waypointId; private EditText name; private EditText description; private AutoCompleteTextView category; private View detailsView; private View statsView; private StatsUtilities utils; private Waypoint waypoint; @Override protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.mytracks_waypoint_details); utils = new StatsUtilities(this); SharedPreferences preferences = getSharedPreferences(MyTracksSettings.SETTINGS_NAME, 0); if (preferences != null) { boolean useMetric = preferences.getBoolean(getString(R.string.metric_units_key), true); utils.setMetricUnits(useMetric); boolean displaySpeed = preferences.getBoolean(getString(R.string.report_speed_key), true); utils.setReportSpeed(displaySpeed); utils.updateWaypointUnits(); utils.setSpeedLabels(); } // Required extra when launching this intent: waypointId = getIntent().getLongExtra(WAYPOINT_ID_EXTRA, -1); if (waypointId < 0) { Log.d(MyTracksConstants.TAG, "MyTracksWaypointsDetails intent was launched w/o waypoint id."); finish(); return; } // Optional extra that can be used to suppress the cancel button: boolean hasCancelButton = getIntent().getBooleanExtra("hasCancelButton", true); name = (EditText) findViewById(R.id.waypointdetails_name); description = (EditText) findViewById(R.id.waypointdetails_description); category = (AutoCompleteTextView) findViewById(R.id.waypointdetails_category); statsView = findViewById(R.id.waypoint_stats); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.waypoint_types, android.R.layout.simple_dropdown_item_1line); category.setAdapter(adapter); detailsView = findViewById(R.id.waypointdetails_description_layout); Button cancel = (Button) findViewById(R.id.waypointdetails_cancel); if (hasCancelButton) { cancel.setOnClickListener(this); cancel.setVisibility(View.VISIBLE); } else { cancel.setVisibility(View.GONE); } Button save = (Button) findViewById(R.id.waypointdetails_save); save.setOnClickListener(this); fillDialog(); } private void fillDialog() { waypoint = MyTracksProviderUtils.Factory.get(this).getWaypoint(waypointId); if (waypoint != null) { name.setText(waypoint.getName()); ImageView icon = (ImageView) findViewById(R.id.waypointdetails_icon); int iconId = -1; switch(waypoint.getType()) { case Waypoint.TYPE_WAYPOINT: description.setText(waypoint.getDescription()); detailsView.setVisibility(View.VISIBLE); category.setText(waypoint.getCategory()); statsView.setVisibility(View.GONE); iconId = R.drawable.blue_pushpin; break; case Waypoint.TYPE_STATISTICS: detailsView.setVisibility(View.GONE); statsView.setVisibility(View.VISIBLE); iconId = R.drawable.ylw_pushpin; TripStatistics waypointStats = waypoint.getStatistics(); utils.setAllStats(waypointStats); utils.setAltitude( R.id.elevation_register, waypoint.getLocation().getAltitude()); break; } icon.setImageDrawable(getResources().getDrawable(iconId)); } } private void saveDialog() { ContentValues values = new ContentValues(); values.put(WaypointsColumns.NAME, name.getText().toString()); if (waypoint != null && waypoint.getType() == Waypoint.TYPE_WAYPOINT) { values.put(WaypointsColumns.DESCRIPTION, description.getText().toString()); values.put(WaypointsColumns.CATEGORY, category.getText().toString()); } getContentResolver().update( WaypointsColumns.CONTENT_URI, values, "_id = " + waypointId, null /*selectionArgs*/); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.waypointdetails_cancel: finish(); break; case R.id.waypointdetails_save: saveDialog(); finish(); break; } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager.BadTokenException; /** * A class to handle all dialog related events for My Tracks. * * @author Sandor Dornbush */ public class DialogManager { public static final int DIALOG_CHART_SETTINGS = 1; public static final int DIALOG_IMPORT_PROGRESS = 2; public static final int DIALOG_PROGRESS = 3; public static final int DIALOG_SEND_TO_GOOGLE = 4; public static final int DIALOG_SEND_TO_GOOGLE_RESULT = 5; public static final int DIALOG_WRITE_PROGRESS = 6; private ProgressDialog progressDialog; private ProgressDialog importProgressDialog; private ProgressDialog writeProgressDialog; private SendToGoogleDialog sendToGoogleDialog; private AlertDialog sendToGoogleResultDialog; private ChartSettingsDialog chartSettingsDialog; private MyTracks activity; public DialogManager(MyTracks activity) { this.activity = activity; } protected Dialog onCreateDialog(int id, Bundle args) { switch (id) { case DIALOG_CHART_SETTINGS: chartSettingsDialog = new ChartSettingsDialog(activity); return chartSettingsDialog; case DIALOG_IMPORT_PROGRESS: importProgressDialog = new ProgressDialog(activity); importProgressDialog.setIcon(android.R.drawable.ic_dialog_info); importProgressDialog.setTitle( activity.getString(R.string.progress_title)); importProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); importProgressDialog.setMessage( activity.getString(R.string.import_progress_message)); return importProgressDialog; case DIALOG_PROGRESS: progressDialog = new ProgressDialog(activity); progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setTitle(activity.getString(R.string.progress_title)); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(""); progressDialog.setMax(100); progressDialog.setProgress(10); return progressDialog; case DIALOG_SEND_TO_GOOGLE: sendToGoogleDialog = new SendToGoogleDialog(activity); return sendToGoogleDialog; case DIALOG_SEND_TO_GOOGLE_RESULT: AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("Title"); builder.setMessage("Message"); builder.setPositiveButton(activity.getString(R.string.ok), null); builder.setNeutralButton(activity.getString(R.string.share_track), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { SendToGoogleDialog sendToGoogleDialog = getSendToGoogleDialog(); final boolean sentToMyMaps = sendToGoogleDialog.getSendToMyMaps(); final boolean sentToFusionTables = sendToGoogleDialog.getSendToFusionTables(); activity.shareLinkToMap(sentToMyMaps, sentToFusionTables); dialog.dismiss(); } }); sendToGoogleResultDialog = builder.create(); return sendToGoogleResultDialog; case DIALOG_WRITE_PROGRESS: writeProgressDialog = new ProgressDialog(activity); writeProgressDialog.setIcon(android.R.drawable.ic_dialog_info); writeProgressDialog.setTitle( activity.getString(R.string.progress_title)); writeProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); writeProgressDialog.setMessage( activity.getString(R.string.write_progress_message)); return writeProgressDialog; } return null; } protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_SEND_TO_GOOGLE: activity.resetSendToGoogleStatus(); break; case DIALOG_SEND_TO_GOOGLE_RESULT: boolean success = activity.getSendToGoogleSuccess(); sendToGoogleResultDialog.setTitle( success ? R.string.success : R.string.error); sendToGoogleResultDialog.setIcon(success ? android.R.drawable.ic_dialog_info : android.R.drawable.ic_dialog_alert); sendToGoogleResultDialog.setMessage(activity.getSendToGoogleResultMessage()); boolean canShare = activity.getSendToFusionTablesTableId() != null && activity.getSendToMyMapsMapId() != null; View share = sendToGoogleResultDialog.findViewById(android.R.id.button3); if (share != null) { share.setVisibility(canShare ? View.VISIBLE : View.GONE); } break; case DIALOG_CHART_SETTINGS: Log.d(MyTracksConstants.TAG, "MyTracks.onPrepare chart dialog"); chartSettingsDialog.setup(activity.getChartActivity()); break; } } public void setProgressMessage(final String message) { activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progressDialog != null) { progressDialog.setMessage(message); } } } }); } public void setProgressValue(final int percent) { activity.runOnUiThread(new Runnable() { public void run() { synchronized (this) { if (progressDialog != null) { progressDialog.setProgress(percent); } } } }); } /** * @return the sendToGoogleDialog */ public SendToGoogleDialog getSendToGoogleDialog() { return sendToGoogleDialog; } /** * Shows a dialog with the given message. * Does it on the UI thread. * * @param success if true, displays an info icon/title, otherwise an error * icon/title * @param message resource string id */ public void showMessageDialog(final int message, final boolean success) { activity.runOnUiThread(new Runnable() { public void run() { AlertDialog dialog = null; AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(activity.getString(message)); builder.setNegativeButton(activity.getString(R.string.ok), null); builder.setIcon(success ? android.R.drawable.ic_dialog_info : android.R.drawable.ic_dialog_alert); builder.setTitle(success ? R.string.success : R.string.error); dialog = builder.create(); dialog.show(); } }); } /** * Just like showDialog, but will catch a BadTokenException that sometimes * (very rarely) gets thrown. This might happen if the user hits the "back" * button immediately after sending tracks to google. * * @param id the dialog id */ public void showDialogSafely(final int id) { activity.runOnUiThread(new Runnable() { public void run() { try { activity.showDialog(id); } catch (BadTokenException e) { Log.w(MyTracksConstants.TAG, "Could not display dialog with id " + id, e); } catch (IllegalStateException e) { Log.w(MyTracksConstants.TAG, "Could not display dialog with id " + id, e); } } }); } /** * Dismisses the progress dialog if it is showing. Executed on the UI thread. */ public void dismissDialogSafely(final int id) { activity.runOnUiThread(new Runnable() { public void run() { try { activity.dismissDialog(id); } catch (IllegalArgumentException e) { // This will be thrown if this dialog was not shown before. } } }); } }
Java
package com.google.android.apps.mytracks; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.database.DataSetObserver; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.TextView; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.Vector; public class MyMapsListAdapter implements ListAdapter { private Vector<String[]> mapsList; private Vector<Boolean> publicList; private Set<DataSetObserver> observerSet; private final Activity activity; public MyMapsListAdapter(Activity activity) { this.activity = activity; mapsList = new Vector<String[]>(); publicList = new Vector<Boolean>(); observerSet = new HashSet<DataSetObserver>(); } public void addMapListing(String mapId, String title, String description, boolean isPublic) { synchronized (mapsList) { // Search through the maps list to see if it has the mapid and // remove it if so, so that we can replace it with updated info for (int i = 0; i < mapsList.size(); ++i) { if (mapId.equals(mapsList.get(i)[0])) { mapsList.remove(i); publicList.remove(i); --i; } } mapsList.add(new String[] { mapId, title, description }); publicList.add(isPublic); } Iterator<DataSetObserver> iter = observerSet.iterator(); while (iter.hasNext()) { iter.next().onChanged(); } } public String[] getMapListingArray(int position) { return mapsList.get(position); } @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return true; } @Override public int getCount() { return mapsList.size(); } @Override public Object getItem(int position) { return mapsList.get(position)[0]; } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = activity.getLayoutInflater().inflate(R.layout.listitem, parent, false); } String[] map = mapsList.get(position); ((TextView) convertView.findViewById(R.id.maplistitem)).setText(map[1]); ((TextView) convertView.findViewById(R.id.maplistdesc)).setText(map[2]); TextView publicUnlisted = (TextView) convertView.findViewById(R.id.maplistpublic); if (publicList.get(position)) { publicUnlisted.setTextColor(Color.RED); publicUnlisted.setText(R.string.public_map); } else { publicUnlisted.setTextColor(Color.GREEN); publicUnlisted.setText(R.string.unlisted_map); } return convertView; } @Override public int getViewTypeCount() { return 1; } @Override public boolean hasStableIds() { return false; } @Override public boolean isEmpty() { return mapsList.isEmpty(); } @Override public void registerDataSetObserver(DataSetObserver observer) { observerSet.add(observer); } @Override public void unregisterDataSetObserver(DataSetObserver observer) { observerSet.remove(observer); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; /** * Creates previous and next arrows for a given activity. * * @author Leif Hendrik Wilden */ public class NavControls { private static final int KEEP_VISIBLE_MILLIS = 4000; private static final boolean FADE_CONTROLS = true; private static final Animation SHOW_NEXT_ANIMATION = new AlphaAnimation(0F, 1F); private static final Animation HIDE_NEXT_ANIMATION = new AlphaAnimation(1F, 0F); private static final Animation SHOW_PREV_ANIMATION = new AlphaAnimation(0F, 1F); private static final Animation HIDE_PREV_ANIMATION = new AlphaAnimation(1F, 0F); /** * A touchable image view. * When touched it changes the navigation control icons accordingly. */ private class TouchLayout extends RelativeLayout implements Runnable { private final boolean isLeft; private final ImageView icon; public TouchLayout(Context context, boolean isLeft) { super(context); this.isLeft = isLeft; this.icon = new ImageView(context); icon.setVisibility(View.GONE); addView(icon); } public void setIcon(Drawable drawable) { icon.setImageDrawable(drawable); icon.setVisibility(View.VISIBLE); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: setPressed(true); shiftIcons(isLeft); // Call the user back handler.post(this); break; case MotionEvent.ACTION_UP: setPressed(false); break; } return super.onTouchEvent(event); } @Override public void run() { touchRunnable.run(); setPressed(false); } } private final Handler handler = new Handler(); private final Runnable dismissControls = new Runnable() { public void run() { hide(); } }; private final TouchLayout prevImage; private final TouchLayout nextImage; private final TypedArray leftIcons; private final TypedArray rightIcons; private final Runnable touchRunnable; private boolean isVisible = false; private int currentIcons; public NavControls(Context context, ViewGroup container, TypedArray leftIcons, TypedArray rightIcons, Runnable touchRunnable) { this.leftIcons = leftIcons; this.rightIcons = rightIcons; this.touchRunnable = touchRunnable; if (leftIcons.length() != rightIcons.length() || leftIcons.length() < 1) { throw new IllegalArgumentException("Invalid icons specified"); } if (touchRunnable == null) { throw new NullPointerException("Runnable cannot be null"); } LayoutParams prevParams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LayoutParams nextParams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); prevParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); prevParams.addRule(RelativeLayout.CENTER_VERTICAL); nextParams.addRule(RelativeLayout.CENTER_VERTICAL); nextImage = new TouchLayout(context, false); prevImage = new TouchLayout(context, true); nextImage.setLayoutParams(nextParams); prevImage.setLayoutParams(prevParams); nextImage.setVisibility(View.INVISIBLE); prevImage.setVisibility(View.INVISIBLE); container.addView(prevImage); container.addView(nextImage); prevImage.setIcon(leftIcons.getDrawable(0)); nextImage.setIcon(rightIcons.getDrawable(0)); this.currentIcons = 0; } private void keepVisible() { if (isVisible && FADE_CONTROLS) { handler.removeCallbacks(dismissControls); handler.postDelayed(dismissControls, KEEP_VISIBLE_MILLIS); } } public void show() { if (!isVisible) { SHOW_PREV_ANIMATION.setDuration(500); SHOW_PREV_ANIMATION.startNow(); prevImage.setPressed(false); prevImage.setAnimation(SHOW_PREV_ANIMATION); prevImage.setVisibility(View.VISIBLE); SHOW_NEXT_ANIMATION.setDuration(500); SHOW_NEXT_ANIMATION.startNow(); nextImage.setPressed(false); nextImage.setAnimation(SHOW_NEXT_ANIMATION); nextImage.setVisibility(View.VISIBLE); isVisible = true; keepVisible(); } else { keepVisible(); } } public void hideNow() { handler.removeCallbacks(dismissControls); isVisible = false; prevImage.clearAnimation(); prevImage.setVisibility(View.INVISIBLE); nextImage.clearAnimation(); nextImage.setVisibility(View.INVISIBLE); } public void hide() { isVisible = false; prevImage.setAnimation(HIDE_PREV_ANIMATION); HIDE_PREV_ANIMATION.setDuration(500); HIDE_PREV_ANIMATION.startNow(); prevImage.setVisibility(View.INVISIBLE); nextImage.setAnimation(HIDE_NEXT_ANIMATION); HIDE_NEXT_ANIMATION.setDuration(500); HIDE_NEXT_ANIMATION.startNow(); nextImage.setVisibility(View.INVISIBLE); } public int getCurrentIcons() { return currentIcons; } private void shiftIcons(boolean isLeft) { // Increment or decrement by one, with wrap around currentIcons = (currentIcons + leftIcons.length() + (isLeft ? -1 : 1)) % leftIcons.length(); prevImage.setIcon(leftIcons.getDrawable(currentIcons)); nextImage.setIcon(rightIcons.getDrawable(currentIcons)); } }
Java