code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * 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 com.google.wireless.gdata.client.GDataServiceClient; 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<GDataServiceClient> { private final boolean returnValue; MockGDataWrapper(boolean returnValue) { this.returnValue = returnValue; } @Override public boolean runQuery(QueryFunction<GDataServiceClient> 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) {} } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/docs/DocsHelperTest.java
Java
asf20
3,713
/* * 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.maps.mytracks.R; import com.google.android.testing.mocking.AndroidMock; import com.google.android.testing.mocking.UsesMocks; import android.content.Context; import android.content.res.Resources; import android.test.mock.MockContext; import android.test.mock.MockResources; import java.io.IOException; import java.text.DateFormat; import java.util.Date; import junit.framework.TestCase; /** * Tests for {@link DocsHelper#addTrackRow} * * @author Matthew Simmons */ public class DocsHelper_AddTrackRowTest extends TestCase { private static final long TIME = 1288721514000L; private static final DateFormat DATE_FORMAT = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT); 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>" + "<gsx:date><![CDATA[" + DATE_FORMAT.format(new Date(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[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>" + "</entry>"; assertEquals( "https://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>")); } /** Adds a row to the spreadsheet, using the provided helper. */ @UsesMocks({AuthManager.class, MockResources.class, Track.class}) private void addTrackRow(DocsHelper docsHelper, boolean useMetric) throws IOException { final Resources mockResources = AndroidMock.createMock(MockResources.class); if (useMetric) { AndroidMock.expect(mockResources.getString(R.string.unit_kilometer)) .andReturn("km"); AndroidMock.expect(mockResources.getString(R.string.unit_kilometer_per_hour)) .andReturn("kph"); AndroidMock.expect(mockResources.getString(R.string.unit_meter)) .andReturn("meter"); } else { AndroidMock.expect(mockResources.getString(R.string.unit_mile)) .andReturn("mile"); AndroidMock.expect(mockResources.getString(R.string.unit_mile_per_hour)) .andReturn("mph"); AndroidMock.expect(mockResources.getString(R.string.unit_feet)) .andReturn("feet"); } AndroidMock.replay(mockResources); Context mockContext = new MockContext() { @Override public Resources getResources() { return mockResources; } }; 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); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/docs/DocsHelper_AddTrackRowTest.java
Java
asf20
6,276
/* * 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)); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/backup/DatabaseImporterTest.java
Java
asf20
9,493
/* * 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() { apply(); return true; } @Override public void apply() { preferenceValues = newPreferences; } @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); } 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); } 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.apply(); // 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.apply(); // 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", "")); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/backup/PreferenceBackupHelperTest.java
Java
asf20
5,612
/* * 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()); // 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); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/backup/DatabaseDumperTest.java
Java
asf20
9,591
/* * 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.file; 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.io.file.GpxImporter; 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, IOException { testInvalidXML(INVALID_LOCATION_TEST_GPX); } /** * Test with invalid time - track should be deleted. */ public void testImportTimeFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_TIME_TEST_GPX); } /** * Test with invalid xml - track should be deleted. */ public void testImportXMLFailure() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_XML_TEST_GPX); } /** * Test with invalid altitude - track should be deleted. */ public void testImportInvalidAltitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_ALTITUDE_TEST_GPX); } /** * Test with invalid latitude - track should be deleted. */ public void testImportInvalidLatitude() throws ParserConfigurationException, IOException { testInvalidXML(INVALID_LATITUDE_TEST_GPX); } /** * Test with invalid longitude - track should be deleted. */ public void testImportInvalidLongitude() throws ParserConfigurationException, 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()); } } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxImporterTest.java
Java
asf20
10,732
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.file.KmlTrackWriter; 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 trackToDescribe, Vector<Double> distances, Vector<Double> elevations) { assertSame(KmlTrackWriterTest.super.track, trackToDescribe); 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); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/KmlTrackWriterTest.java
Java
asf20
4,413
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; 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 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; 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; /** * 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) throws Exception { 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; } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackFormatWriterTest.java
Java
asf20
7,311
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.MyTracksLocation; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.FileUtils; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Tests for the GPX track exporter. * * @author Sandor Dornbush */ public class TcxTrackWriterTest extends TrackFormatWriterTest { public void testXmlOutput() throws Exception { TrackFormatWriter writer = new TcxTrackWriter(getContext()); 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(FileUtils.FILE_TIMESTAMP_FORMAT.format(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")); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/TcxTrackWriterTest.java
Java
asf20
2,985
/* * 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.io.file; import java.io.File; /** * A simple, fake {@link TrackWriter} subclass with all methods mocked out. * Tests are expected to override {@link #writeTrack} and/or * {@link #writeTrackAsync}, at the very least. * * @author Matthew Simmons * */ public class MockTrackWriter implements TrackWriter { public OnCompletionListener onCompletionListener; public OnWriteListener onWriteListener; @Override public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } @Override public void setOnWriteListener(OnWriteListener onWriteListener) { this.onWriteListener = onWriteListener; } @Override public void setDirectory(File directory) { throw new UnsupportedOperationException("not implemented"); } @Override public String getAbsolutePath() { throw new UnsupportedOperationException("not implemented"); } @Override public void writeTrackAsync() { throw new UnsupportedOperationException("not implemented"); } @Override public void writeTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public void stopWriteTrack() { throw new UnsupportedOperationException("not implemented"); } @Override public boolean wasSuccess() { return false; } @Override public int getErrorMessage() { return 0; } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/MockTrackWriter.java
Java
asf20
2,036
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.io.file.GpxTrackWriter; import com.google.android.apps.mytracks.io.file.TrackFormatWriter; 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")); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxTrackWriterTest.java
Java
asf20
2,688
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; /** * Tests for the CSV track exporter. * * @author Rodrigo Damazio */ public class CsvTrackWriterTest extends TrackFormatWriterTest { }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/CsvTrackWriterTest.java
Java
asf20
245
/* * 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.file; import static com.google.android.testing.mocking.AndroidMock.expect; import com.google.android.apps.mytracks.io.file.TempFileCleaner; 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); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/TempFileCleanerTest.java
Java
asf20
2,921
/* * 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.io.file; import android.app.ProgressDialog; import android.test.ActivityInstrumentationTestCase2; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; /** * Tests {@link WriteProgressController}. * * @author Matthew Simmons */ public class WriteProgressControllerTest extends ActivityInstrumentationTestCase2<SaveActivity> { public WriteProgressControllerTest() { super(SaveActivity.class); } private static void assertProgress(ProgressDialog dialog, int expectedProgress, int expectedMax) { assertEquals(expectedProgress, dialog.getProgress()); assertEquals(expectedMax, dialog.getMax()); } public void testSimple() throws Exception { final AtomicReference<ProgressDialog> dialogRef = new AtomicReference<ProgressDialog>(); final AtomicReference<Boolean> controllerDoneRef = new AtomicReference<Boolean>(); final Semaphore writerDone = new Semaphore(0); TrackWriter mockWriter = new MockTrackWriter() { @Override public void writeTrackAsync() { onWriteListener.onWrite(1000, 10000); assertProgress(dialogRef.get(), 1000, 10000); onCompletionListener.onComplete(); writerDone.release(); } }; final WriteProgressController controller = new WriteProgressController( getActivity(), mockWriter, SaveActivity.PROGRESS_DIALOG); controller.setOnCompletionListener(new WriteProgressController.OnCompletionListener() { @Override public void onComplete() { controllerDoneRef.set(true); } }); /* * The WriteProgressController constructor calls the mockWriter's * setOnCompletionListener method with a listener that dismisses the * progress dialog. However, this unit test only tests the * WriteProgressController and doesn't actually show any progress dialog. * Thus after the WriteProgressController is setup, we need to call the * mockWriter's setOnCompletionListener method again with an listener that * doesn't dismiss dialog. */ mockWriter.setOnCompletionListener(new TrackWriter.OnCompletionListener() { @Override public void onComplete() { controller.getOnCompletionListener().onComplete(); } }); dialogRef.set(controller.createProgressDialog()); controller.startWrite(); // wait for the writer to finish writerDone.acquire(); assertTrue(controllerDoneRef.get()); } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/WriteProgressControllerTest.java
Java
asf20
3,095
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.file; 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.MyTracksProviderUtils.Factory; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext; import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory; import com.google.android.maps.mytracks.R; 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.IAnswer; import org.easymock.IArgumentMatcher; import org.easymock.IMocksControl; /** * Tests for the track writer. * * @author Rodrigo Damazio */ public class TrackWriterTest extends AndroidTestCase { /** * {@link TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#openFile}. */ private static final class OpenFileTrackWriter extends TrackWriterImpl { private final ByteArrayOutputStream stream; private final boolean canWrite; /** * Constructor. * * @param stream the stream to return from * {@link TrackWriterImpl#newOutputStream}, or null to throw a * {@link FileNotFoundException} * @param canWrite the value that {@link TrackWriterImpl#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 TrackWriterImpl} subclass which mocks out methods called from * {@link TrackWriterImpl#writeTrack}. */ private final class WriteTracksTrackWriter extends TrackWriterImpl { private final boolean openResult; /** * Constructor. * * @param openResult the return value for {@link TrackWriterImpl#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 TrackWriterImpl 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 listener to be run TrackWriter.OnCompletionListener completionListener = mocksControl.createMock(TrackWriter.OnCompletionListener.class); completionListener.onComplete(); mocksControl.replay(); writer.setOnCompletionListener(completionListener); writer.writeTrack(); assertEquals(1, writeDocumentCalls); assertEquals(1, openFileCalls); mocksControl.verify(); } public void testWriteTrack_cancelled() throws Exception { final ByteArrayOutputStream stream = new ByteArrayOutputStream(); writer = new OpenFileTrackWriter( getContext(), providerUtils, track, formatWriter, stream, true); formatWriter.prepare(track, stream); final Location[] locs = { new Location("fake0"), new Location("fake1"), }; fillLocations(locs); assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); formatWriter.writeHeader(); formatWriter.writeBeginTrack(locEq(locs[0])); formatWriter.writeOpenSegment(); formatWriter.writeLocation(locEq(locs[0])); //EasyMock.expectLastCall().andThrow(new InterruptedException()); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { throw new InterruptedException(); } }); mocksControl.replay(); writer.writeTrack(); mocksControl.verify(); assertFalse(writer.wasSuccess()); assertEquals(R.string.sd_card_canceled, writer.getErrorMessage()); } public void testWriteTrack_openFails() { writer = new WriteTracksTrackWriter(getContext(), providerUtils, track, formatWriter, false); // Expect the completion listener to be run TrackWriter.OnCompletionListener completionListener = mocksControl.createMock(TrackWriter.OnCompletionListener.class); completionListener.onComplete(); mocksControl.replay(); writer.setOnCompletionListener(completionListener); 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() throws Exception { writer = new TrackWriterImpl(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() throws Exception { writer = new TrackWriterImpl(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); } } }
0000som143-mytracks
MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackWriterTest.java
Java
asf20
12,582
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); } }
0000som143-mytracks
MyTracks/src/com/dsi/ant/exception/AntInterfaceException.java
Java
asf20
364
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); } }
0000som143-mytracks
MyTracks/src/com/dsi/ant/exception/AntRemoteException.java
Java
asf20
519
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); } }
0000som143-mytracks
MyTracks/src/com/dsi/ant/exception/AntServiceNotConnectedException.java
Java
asf20
435
/* * 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); }
0000som143-mytracks
MyTracks/src/com/dsi/ant/Version.java
Java
asf20
1,193
/* * 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; /** * The Android Ant API is not finalized, and *will* be updated and expanded. * This is the base level ANT messaging API and gives any application full * control over the ANT radio HW. Caution should be exercised when using * this interface. * * Public API for controlling the Ant Service. * * {@hide} */ interface IAnt_6 { // Since version 1 (1.0): boolean enable(); boolean disable(); boolean isEnabled(); boolean ANTTxMessage(in byte[] message); boolean ANTResetSystem(); boolean ANTUnassignChannel(byte channelNumber); boolean ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber); boolean ANTSetChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType); boolean ANTSetChannelPeriod(byte channelNumber, int channelPeriod); boolean ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency); boolean ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetProximitySearch(byte channelNumber, byte searchThreshold); boolean ANTSetChannelTxPower(byte channelNumber, byte txPower); boolean ANTAddChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType, byte listIndex); boolean ANTConfigList(byte channelNumber, byte listSize, byte exclude); boolean ANTOpenChannel(byte channelNumber); boolean ANTCloseChannel(byte channelNumber); boolean ANTRequestMessage(byte channelNumber, byte messageID); boolean ANTSendBroadcastData(byte channelNumber, in byte[] txBuffer); boolean ANTSendAcknowledgedData(byte channelNumber, in byte[] txBuffer); boolean ANTSendBurstTransferPacket(byte control, in byte[] txBuffer); int ANTSendBurstTransfer(byte channelNumber, in byte[] txBuffer); int ANTTransmitBurst(byte channelNumber, in byte[] txBuffer, int initialPacket, boolean containsEndOfBurst); // Since version 4 (1.3): boolean ANTConfigEventBuffering(int screenOnFlushTimerInterval, int screenOnFlushBufferThreshold, int screenOffFlushTimerInterval, int screenOffFlushBufferThreshold); // Since version 2 (1.1): boolean ANTDisableEventBuffering(); // Since version 3 (1.2): int getServiceLibraryVersionCode(); String getServiceLibraryVersionName(); // Since version 6 (1.5): boolean claimInterface(); boolean requestForceClaimInterface(String appName); boolean stopRequestForceClaimInterface(); boolean releaseInterface(); boolean hasClaimedInterface(); }
0000som143-mytracks
MyTracks/src/com/dsi/ant/IAnt_6.aidl
AIDL
asf20
3,249
/* * 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); }
0000som143-mytracks
MyTracks/src/com/dsi/ant/AntDefine.java
Java
asf20
17,797
/* * 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 com.dsi.ant.exception.AntInterfaceException; import com.dsi.ant.exception.AntRemoteException; import com.dsi.ant.exception.AntServiceNotConnectedException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.util.Arrays; /** * 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 Context sContext = null; /** Listens to changes to service connection status. */ private 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 final 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) || ("".equals(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; } }
0000som143-mytracks
MyTracks/src/com/dsi/ant/AntInterface.java
Java
asf20
36,990
/* * 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* be updated and expanded. * This is the base level ANT messaging API and gives any application full * control over the ANT radio HW. Caution should be exercised when using * this interface. * * Public API for controlling the Ant Service. * * {@hide} */ interface IAnt { // Since version 1 (1.0): boolean enable(); boolean disable(); boolean isEnabled(); boolean ANTTxMessage(in byte[] message); boolean ANTResetSystem(); boolean ANTUnassignChannel(byte channelNumber); boolean ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber); boolean ANTSetChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType); boolean ANTSetChannelPeriod(byte channelNumber, int channelPeriod); boolean ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency); boolean ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetProximitySearch(byte channelNumber, byte searchThreshold); boolean ANTSetChannelTxPower(byte channelNumber, byte txPower); boolean ANTAddChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType, byte listIndex); boolean ANTConfigList(byte channelNumber, byte listSize, byte exclude); boolean ANTOpenChannel(byte channelNumber); boolean ANTCloseChannel(byte channelNumber); boolean ANTRequestMessage(byte channelNumber, byte messageID); boolean ANTSendBroadcastData(byte channelNumber, in byte[] txBuffer); boolean ANTSendAcknowledgedData(byte channelNumber, in byte[] txBuffer); boolean ANTSendBurstTransferPacket(byte control, in byte[] txBuffer); int ANTSendBurstTransfer(byte channelNumber, in byte[] txBuffer); int ANTTransmitBurst(byte channelNumber, in byte[] txBuffer, int initialPacket, boolean containsEndOfBurst); // Since version 4 (1.3): boolean ANTConfigEventBuffering(int screenOnFlushTimerInterval, int screenOnFlushBufferThreshold, int screenOffFlushTimerInterval, int screenOffFlushBufferThreshold); // Since version 2 (1.1): boolean ANTDisableEventBuffering(); // Since version 3 (1.2): int getServiceLibraryVersionCode(); String getServiceLibraryVersionName(); }
0000som143-mytracks
MyTracks/src/com/dsi/ant/IAnt.aidl
AIDL
asf20
3,017
/* * 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() { } }
0000som143-mytracks
MyTracks/src/com/dsi/ant/AntMesg.java
Java
asf20
16,889
/* * 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"; }
0000som143-mytracks
MyTracks/src/com/dsi/ant/AntInterfaceIntent.java
Java
asf20
1,521
/* * 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; /** * * API for configuring the non-ANT components of the ANT Service. * * {@hide} */ interface IServiceSettings { void debugLogging(boolean debug); boolean setNumCombinedBurstPackets(int numPackets); int getNumCombinedBurstPackets(); }
0000som143-mytracks
MyTracks/src/com/dsi/ant/IServiceSettings.aidl
AIDL
asf20
902
/* * 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.TrackDataHub; import android.app.Application; /** * MyTracksApplication for keeping global state. * * @author jshih@google.com (Jimmy Shih) */ public class MyTracksApplication extends Application { private TrackDataHub trackDataHub; /** * Gets the application's TrackDataHub. * * Note: use synchronized to make sure only one instance is created per application. */ public synchronized TrackDataHub getTrackDataHub() { if (trackDataHub == null) { trackDataHub = TrackDataHub.newInstance(getApplicationContext()); } return trackDataHub; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/MyTracksApplication.java
Java
asf20
1,268
/* * 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 static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.content.MyTracksLocation; 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.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.tasks.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.LocationUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.location.Location; import android.os.Bundle; 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; import java.util.EnumSet; /** * An activity that displays a chart from the track point provider. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class ChartActivity extends Activity implements TrackDataListener { private static final int CHART_SETTINGS_DIALOG = 1; private final DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); private final DoubleBuffer speedBuffer = new DoubleBuffer(Constants.SPEED_SMOOTHING_FACTOR); private final ArrayList<double[]> pendingPoints = new ArrayList<double[]>(); private TrackDataHub dataHub; // Stats gathered from received data. private double profileLength = 0; private long startTime = -1; private Location lastLocation; private double trackMaxSpeed; // Modes of operation private boolean metricUnits; private boolean reportSpeed; /* * UI elements: */ private ChartView chartView; private MenuItem chartSettingsMenuItem; private LinearLayout busyPane; private ZoomControls zoomControls; /** * 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() { // Get a local reference in case it's set to null concurrently with this. TrackDataHub localDataHub = dataHub; if (localDataHub == null || isFinishing()) { return; } busyPane.setVisibility(View.GONE); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); chartView.setShowPointer(localDataHub.isRecordingSelected()); chartView.invalidate(); } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.w(TAG, "ChartActivity.onCreate"); super.onCreate(savedInstanceState); // 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); LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); layout.addView(chartView, params); 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(); } }); } @Override protected void onResume() { super.onResume(); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); dataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } @Override protected void onPause() { dataHub.unregisterTrackDataListener(this); dataHub = null; super.onPause(); } 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()); } private void setMode(Mode newMode) { if (chartView.getMode() != newMode) { chartView.setMode(newMode); dataHub.reloadDataForListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); chartSettingsMenuItem = menu.add(0, Constants.MENU_CHART_SETTINGS, 0, R.string.menu_chart_view_chart_settings); chartSettingsMenuItem.setIcon(R.drawable.chart_settings); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case Constants.MENU_CHART_SETTINGS: showDialog(CHART_SETTINGS_DIALOG); return true; } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { if (id == CHART_SETTINGS_DIALOG) { final ChartSettingsDialog settingsDialog = new ChartSettingsDialog(this); settingsDialog.setOnClickListener(new OnClickListener() { @Override public void onClick(DialogInterface arg0, int which) { if (which != DialogInterface.BUTTON_POSITIVE) { return; } for (int i = 0; i < ChartView.NUM_SERIES; i++) { chartView.setChartValueSeriesEnabled(i, settingsDialog.isSeriesEnabled(i)); } setMode(settingsDialog.getMode()); chartView.postInvalidate(); } }); return settingsDialog; } return super.onCreateDialog(id); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); if (id == CHART_SETTINGS_DIALOG) { prepareSettingsDialog((ChartSettingsDialog) dialog); } } private void prepareSettingsDialog(ChartSettingsDialog settingsDialog) { settingsDialog.setMode(chartView.getMode()); for (int i = 0; i < ChartView.NUM_SERIES; i++) { settingsDialog.setSeriesEnabled(i, chartView.isChartValueSeriesEnabled(i)); } } /** * 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 result the resulting point to fill out */ private void fillDataPoint(Location location, double result[]) { double timeOrDistance = Double.NaN, elevation = Double.NaN, speed = Double.NaN, power = Double.NaN, cadence = Double.NaN, heartRate = Double.NaN; 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()) { power = sensorData.getPower().getValue(); } if (sensorData.hasCadence() && sensorData.getCadence().getState() == Sensor.SensorState.SENDING && sensorData.getCadence().hasValue()) { cadence = sensorData.getCadence().getValue(); } if (sensorData.hasHeartRate() && sensorData.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorData.getHeartRate().hasValue()) { heartRate = sensorData.getHeartRate().getValue(); } } // TODO: Account for segment splits? Mode mode = chartView.getMode(); switch (mode) { case BY_DISTANCE: timeOrDistance = profileLength / 1000.0; if (lastLocation != null) { double d = lastLocation.distanceTo(location); if (metricUnits) { profileLength += d; } else { profileLength += d * UnitConversions.KM_TO_MI; } } break; case BY_TIME: if (startTime == -1) { // Base case startTime = location.getTime(); } timeOrDistance = (location.getTime() - startTime); break; default: Log.w(TAG, "ChartActivity unknown mode: " + mode); } elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); elevation = 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() <= trackMaxSpeed)) { speedBuffer.setNext(location.getSpeed()); } speed = speedBuffer.getAverage() * 3.6; if (!metricUnits) { speed *= UnitConversions.KM_TO_MI; } if (!reportSpeed) { if (speed != 0) { // Format as hours per unit speed = (60.0 / speed); } else { speed = Double.NaN; } } // Keep a copy so the location can be reused. lastLocation = location; if (result != null) { result[0] = timeOrDistance; result[1] = elevation; result[2] = speed; result[3] = power; result[4] = cadence; result[5] = heartRate; } } @Override public void onProviderStateChange(ProviderState state) { // We don't care. } @Override public void onCurrentLocationChanged(Location loc) { // We don't care. } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { runOnUiThread(new Runnable() { @Override public void run() { busyPane.setVisibility(View.VISIBLE); } }); } @Override public void onTrackUpdated(Track track) { if (track == null || track.getStatistics() == null) { trackMaxSpeed = 0.0; return; } trackMaxSpeed = track.getStatistics().getMaxSpeed(); } @Override public void clearTrackPoints() { profileLength = 0; lastLocation = null; startTime = -1; elevationBuffer.reset(); chartView.reset(); speedBuffer.reset(); pendingPoints.clear(); runOnUiThread(new Runnable() { @Override public void run() { chartView.resetScroll(); } }); } @Override public void onNewTrackPoint(Location loc) { if (LocationUtils.isValidLocation(loc)) { double[] point = new double[6]; fillDataPoint(loc, point); pendingPoints.add(point); } } @Override public void onSampledOutTrackPoint(Location loc) { // Still account for the point in the smoothing buffers. fillDataPoint(loc, null); } @Override public void onSegmentSplit() { // Do nothing. } @Override public void onNewTrackPointsDone() { chartView.addDataPoints(pendingPoints); pendingPoints.clear(); runOnUiThread(updateChart); } @Override public void clearWaypoints() { chartView.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint wpt) { chartView.addWaypoint(wpt); } @Override public void onNewWaypointsDone() { runOnUiThread(updateChart); } @Override public boolean onUnitsChanged(boolean metric) { boolean changed = metric != this.metricUnits; if (!changed) return false; this.metricUnits = metric; chartView.setMetricUnits(metric); return true; // Reload data } @SuppressWarnings("hiding") @Override public boolean onReportSpeedChanged(boolean reportSpeed) { boolean changed = reportSpeed != this.reportSpeed; if (!changed) return false; this.reportSpeed = reportSpeed; chartView.setReportSpeed(reportSpeed, this); return true; // Reload data } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ChartActivity.java
Java
asf20
14,244
/* * 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_markers) .setEnabled(hasRecorded && hasSelectedTrack); menu.findItem(R.id.menu_record_track) .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_record_track: { activity.startRecording(); return true; } case R.id.menu_stop_recording: { activity.stopRecording(); return true; } case R.id.menu_tracks: { activity.startActivityForResult(new Intent(activity, TrackList.class), Constants.SHOW_TRACK); return true; } case R.id.menu_markers: { Intent startIntent = new Intent(activity, WaypointsList.class); startIntent.putExtra("trackid", activity.getSelectedTrackId()); activity.startActivityForResult(startIntent, Constants.SHOW_WAYPOINT); return true; } case R.id.menu_sensor_state: { return startActivity(SensorStateActivity.class); } case R.id.menu_settings: { return startActivity(SettingsActivity.class); } case R.id.menu_aggregated_statistics: { return startActivity(AggregatedStatsActivity.class); } case R.id.menu_help: { return startActivity(WelcomeActivity.class); } } return false; } private boolean startActivity(Class<? extends Activity> activityClass) { activity.startActivity(new Intent(activity, activityClass)); return true; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/MenuManager.java
Java
asf20
2,906
/* * 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.Constants.RESUME_TRACK_EXTRA_NAME; import static com.google.android.apps.mytracks.Constants.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 BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "BootReceiver.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, "BootReceiver: unsupported action"); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/BootReceiver.java
Java
asf20
2,146
/* * 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(String message); public void clearProgressMessage(); public void setProgressValue(int percent); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ProgressIndicator.java
Java
asf20
946
/* * 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 static com.google.android.apps.mytracks.Constants.TAG; 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.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; 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.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; 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; import android.widget.Toast; /** * Activity which shows the list of waypoints in a track. * * @author Leif Hendrik Wilden */ public class WaypointsList extends ListActivity implements View.OnClickListener { private int contextPosition = -1; private long trackId = -1; private long selectedWaypointId = -1; private ListView listView = null; private Button insertWaypointButton = null; private Button insertStatisticsButton = null; private long recordingTrackId = -1; private MyTracksProviderUtils providerUtils; private TrackRecordingServiceConnection serviceConnection; private Cursor waypointsCursor = null; private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.marker_list_context_menu_title); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; contextPosition = info.position; selectedWaypointId = WaypointsList.this.listView.getAdapter() .getItemId(contextPosition); Waypoint waypoint = providerUtils.getWaypoint(info.id); if (waypoint != null) { int type = waypoint.getType(); menu.add(0, Constants.MENU_SHOW, 0, R.string.marker_list_show_on_map); menu.add(0, Constants.MENU_EDIT, 0, R.string.marker_list_edit_marker); menu.add(0, Constants.MENU_DELETE, 0, R.string.marker_list_delete_marker).setEnabled( recordingTrackId < 0 || type == Waypoint.TYPE_WAYPOINT || info.id != providerUtils.getLastWaypointId(recordingTrackId)); } } }; @Override protected void onListItemClick(ListView l, View v, int position, long id) { editWaypoint(id); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { if (!super.onMenuItemSelected(featureId, item)) { switch (item.getItemId()) { case Constants.MENU_SHOW: { Intent result = new Intent(); result.putExtra("trackid", trackId); result.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, selectedWaypointId); setResult(RESULT_OK, result); finish(); return true; } case Constants.MENU_EDIT: { editWaypoint(selectedWaypointId); return true; } case Constants.MENU_DELETE: { deleteWaypoint(selectedWaypointId); } } } return false; } private void editWaypoint(long waypointId) { Intent intent = new Intent(this, WaypointDetails.class); intent.putExtra("trackid", trackId); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, waypointId); startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); providerUtils = MyTracksProviderUtils.Factory.get(this); serviceConnection = new TrackRecordingServiceConnection(this, null); // 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); // TODO: Get rid of selected and recording track IDs long selectedTrackId = -1; if (preferences != null) { recordingTrackId = preferences.getLong(getString(R.string.recording_track_key), -1); selectedTrackId = preferences.getLong(getString(R.string.selected_track_key), -1); } boolean selectedRecording = selectedTrackId > 0 && selectedTrackId == recordingTrackId; 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 protected void onResume() { super.onResume(); serviceConnection.bindIfRunning(); } @Override protected void onDestroy() { serviceConnection.unbind(); super.onDestroy(); } @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 = insertWaypoint(request); if (id < 0) { Toast.makeText(this, R.string.marker_insert_error, Toast.LENGTH_LONG).show(); Log.e(Constants.TAG, "Failed to insert marker."); return; } Intent intent = new Intent(this, WaypointDetails.class); intent.putExtra(WaypointDetails.WAYPOINT_ID_EXTRA, id); startActivity(intent); } private long insertWaypoint(WaypointCreationRequest request) { try { ITrackRecordingService trackRecordingService = serviceConnection.getServiceIfBound(); if (trackRecordingService != null) { long waypointId = trackRecordingService.insertWaypoint(request); if (waypointId >= 0) { Toast.makeText(this, R.string.marker_insert_success, Toast.LENGTH_LONG).show(); return waypointId; } } else { Log.e(TAG, "Not connected to service, not inserting waypoint"); } } catch (RemoteException e) { Log.e(Constants.TAG, "Cannot insert marker.", e); } catch (IllegalStateException e) { Log.e(Constants.TAG, "Cannot insert marker.", e); } return -1; } 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_list_delete_marker_confirm_message)); builder.setTitle(getString(R.string.generic_confirm_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(getString(R.string.generic_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); providerUtils.deleteWaypoint(waypointId, new StringUtils(WaypointsList.this)); } }); builder.setNegativeButton(getString(R.string.generic_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/WaypointsList.java
Java
asf20
11,637
/* * 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.content.SharedPreferences.Editor; 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 DeleteAllTracks extends Handler { private final Context context; private final Runnable done; public DeleteAllTracks(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.track_list_delete_all_confirm_message)); builder.setTitle(context.getString(R.string.generic_confirm_title)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setPositiveButton(context.getString(R.string.generic_yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); Log.w(Constants.TAG, "deleting all!"); MyTracksProviderUtils.Factory.get(context).deleteAllTracks(); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); // TODO: Go through data manager editor.putLong(context.getString(R.string.selected_track_key), -1); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); if (done != null) { Handler h = new Handler(); h.post(done); } } }); builder.setNegativeButton(context.getString(R.string.generic_no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); dialog = builder.create(); dialog.show(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/DeleteAllTracks.java
Java
asf20
3,115
/* * 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/AbsoluteLocationListenerPolicy.java
Java
asf20
1,519
/* * 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.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.services.TrackRecordingService; import com.google.android.apps.mytracks.util.UnitConversions; import android.util.Log; /** * Execute a task on a time or distance schedule. * * @author Sandor Dornbush */ public class PeriodicTaskExecutor { /** * The frequency of the task. * A value greater than zero is a frequency in time. * A value less than zero is considered a frequency in distance. */ private int taskFrequency = 0; /** * The next distance when the task should execute. */ private double nextTaskDistance = 0; /** * Time based executor. */ private TimerTaskExecutor timerExecutor = null; private boolean metricUnits; private final TrackRecordingService service; private final PeriodicTaskFactory factory; private PeriodicTask task; public PeriodicTaskExecutor(TrackRecordingService service, PeriodicTaskFactory factory) { this.service = service; this.factory = factory; } /** * Restores the manager. */ public void restore() { // TODO: Decouple service from this class once and forever. if (!service.isRecording()) { return; } if (!isTimeFrequency()) { if (timerExecutor != null) { timerExecutor.shutdown(); timerExecutor = null; } } if (taskFrequency == 0) { return; } // Try to make the task. task = factory.create(service); // Returning null is ok. if (task == null) { return; } task.start(); if (isTimeFrequency()) { if (timerExecutor == null) { timerExecutor = new TimerTaskExecutor(task, service); } timerExecutor.scheduleTask(taskFrequency * 60000L); } else { // For distance based splits. calculateNextTaskDistance(); } } /** * Shuts down the manager. */ public void shutdown() { if (task != null) { task.shutdown(); task = null; } if (timerExecutor != null) { timerExecutor.shutdown(); timerExecutor = null; } } /** * Calculates the next distance when the task should execute. */ void calculateNextTaskDistance() { // TODO: Decouple service from this class once and forever. if (!service.isRecording() || task == null) { return; } if (!isDistanceFrequency()) { nextTaskDistance = Double.MAX_VALUE; Log.d(TAG, "SplitManager: Distance splits disabled."); return; } double distance = service.getTripStatistics().getTotalDistance() / 1000; if (!metricUnits) { distance *= UnitConversions.KM_TO_MI; } // The index will be negative since the frequency is negative. int index = (int) (distance / taskFrequency); index -= 1; nextTaskDistance = taskFrequency * index; Log.d(TAG, "SplitManager: Next split distance: " + nextTaskDistance); } /** * Updates executer with new trip statistics. */ public void update() { if (!isDistanceFrequency() || task == null) { 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 > nextTaskDistance) { task.run(service); calculateNextTaskDistance(); } } private boolean isTimeFrequency() { return taskFrequency > 0; } private boolean isDistanceFrequency() { return taskFrequency < 0; } /** * Sets the task frequency. * &lt; 0 Use the absolute value as a distance in the current measurement km * or mi * 0 Turn off the task * &gt; 0 Use the value as a time in minutes * @param taskFrequency The frequency in time or distance */ public void setTaskFrequency(int taskFrequency) { Log.d(TAG, "setTaskFrequency: taskFrequency = " + taskFrequency); this.taskFrequency = taskFrequency; restore(); } public void setMetricUnits(boolean metricUnits) { this.metricUnits = metricUnits; calculateNextTaskDistance(); } double getNextTaskDistance() { return nextTaskDistance; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskExecutor.java
Java
asf20
4,846
/* * 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.tasks; import static com.google.android.apps.mytracks.Constants.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) { int result = audioManager.abandonAudioFocus(null); if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) { Log.w(TAG, "FroyoStatusAnnouncerTask: Failed to relinquish audio focus"); } } }; public FroyoStatusAnnouncerTask(Context context) { super(context); audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); } @Override protected void onTtsReady() { super.onTtsReady(); tts.setOnUtteranceCompletedListener(utteranceListener); } @Override protected synchronized void speakAnnouncement(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 for 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); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/FroyoStatusAnnouncerTask.java
Java
asf20
2,743
/* * 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.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import android.util.Log; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import com.google.android.apps.mytracks.services.TrackRecordingService; /** * This class will periodically perform a task. * * @author Sandor Dornbush */ public class TimerTaskExecutor { 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 TimerTaskExecutor(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(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(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); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/TimerTaskExecutor.java
Java
asf20
2,796
/* * 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.tasks; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.TrackRecordingService; import android.content.Context; /** * A simple task to insert statistics markers periodically. * @author Sandor Dornbush */ public class SplitTask implements PeriodicTask { private SplitTask() { } @Override public void run(TrackRecordingService service) { service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS); } @Override public void shutdown() { } @Override public void start() { } /** * Create new SplitTasks. */ public static class Factory implements PeriodicTaskFactory { @Override public PeriodicTask create(Context context) { return new SplitTask(); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/SplitTask.java
Java
asf20
1,444
/* * 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.tasks; 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 implements PeriodicTaskFactory { private final boolean hasTts; public StatusAnnouncerFactory(ApiFeatures apiFeatures) { this.hasTts = apiFeatures.hasTextToSpeech(); } @Override public PeriodicTask create(Context context) { if (hasTts) { return ApiFeatures.getInstance().getApiAdapter().getStatusAnnouncerTask(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; } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerFactory.java
Java
asf20
1,625
/* * 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.tasks; import com.google.android.apps.mytracks.services.TrackRecordingService; /** * 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(); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTask.java
Java
asf20
1,168
/* * 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.tasks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.TrackRecordingService; 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 com.google.common.annotations.VisibleForTesting; 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; /** * The interface to the text to speech engine. */ protected TextToSpeech tts; /** * The response received from the TTS engine after initialization. */ private int initStatus = TextToSpeech.ERROR; /** * Whether the TTS engine is ready. */ 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 != null && tts.isSpeaking()) { // If we're already speaking, stop it. tts.stop(); } } }; public StatusAnnouncerTask(Context context) { this.context = context; } /** * {@inheritDoc} * * Announces the trip status. */ @Override public void run(TrackRecordingService service) { if (service == null) { Log.e(TAG, "StatusAnnouncer TrackRecordingService not initialized"); return; } runWithStatistics(service.getTripStatistics()); } /** * This method exists as a convenience for testing code, allowing said code * to avoid needing to instantiate an entire {@link TrackRecordingService} * just to test the announcer. */ // @VisibleForTesting void runWithStatistics(TripStatistics statistics) { if (statistics == null) { Log.e(TAG, "StatusAnnouncer stats not initialized."); return; } synchronized (this) { checkReady(); if (!ready) { Log.e(TAG, "StatusAnnouncer Tts not ready."); return; } } if (!speechAllowed) { Log.i(Constants.TAG, "Not making announcement - not allowed at this time"); return; } String announcement = getAnnouncement(statistics); Log.d(Constants.TAG, "Announcement: " + announcement); speakAnnouncement(announcement); } protected void speakAnnouncement(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) { boolean metricUnits = true; boolean reportSpeed = true; SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); 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; // d is in kilometers double s = stats.getAverageMovingSpeed() * 3.6; // s is in kilometers per hour if (d == 0) { return context.getString(R.string.voice_total_distance_zero); } if (!metricUnits) { d *= UnitConversions.KM_TO_MI; s *= UnitConversions.KMH_TO_MPH; } if (!reportSpeed) { s = 3600000.0 / s; // converts from speed to pace } // Makes sure s is not NaN. if (Double.isNaN(s)) { s = 0; } String speed; if (reportSpeed) { int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour : R.plurals.voiceSpeedMilesPerHour; speed = context.getResources().getQuantityString(speedId, getQuantityCount(s), s); } else { int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile; speed = String.format(context.getString(paceId), getAnnounceTime((long) s)); } int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers : R.plurals.voiceTotalDistanceMiles; String totalDistance = context.getResources().getQuantityString( totalDistanceId, getQuantityCount(d), d); return context.getString( R.string.voice_template, totalDistance, getAnnounceTime(stats.getMovingTime()), speed); } /** * Gets the plural count to be used by getQuantityString. getQuantityString * only supports integer quantities, not a double quantity like "2.2". * <p> * As a temporary workaround, we convert a double quantity to an integer * quantity. If the double quantity is exactly 0, 1, or 2, then we can return * these integer quantities. Otherwise, we cast the double quantity to an * integer quantity. However, we need to make sure that if the casted value is * 0, 1, or 2, we don't return those, instead, return the next biggest integer * 3. * * @param d the double value */ private int getQuantityCount(double d) { if (d == 0) { return 0; } else if (d == 1) { return 1; } else if (d == 2) { return 2; } else { int count = (int) d; return count < 3 ? 3 : count; } } @Override public void start() { Log.i(Constants.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); } /** * Called when the TTS engine is initialized. */ private void onTtsInit(int status) { Log.i(TAG, "TrackRecordingService.TTS init: " + status); synchronized (this) { // TTS should be valid here but NPE exceptions were reported to the market. initStatus = status; checkReady(); } } /** * Ensures that the TTS is ready (finishing its initialization if needed). */ private void checkReady() { synchronized (this) { if (ready) { // Already done; return; } ready = initStatus == TextToSpeech.SUCCESS && tts != null; Log.d(TAG, "Status announcer ready: " + ready); if (ready) { onTtsReady(); } } } /** * Finishes the TTS engine initialization. * Called once (and only once) when the TTS engine is ready. */ protected void onTtsReady() { // 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(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); } @Override public void shutdown() { // Stop listening to phone state. listenToPhoneState(phoneListener, PhoneStateListener.LISTEN_NONE); if (tts != null) { tts.shutdown(); tts = null; } Log.i(Constants.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; } /** * Gets a string to announce the time. * * @param time the time */ @VisibleForTesting String getAnnounceTime(long time) { int[] parts = StringUtils.getTimeParts(time); String seconds = context.getResources().getQuantityString( R.plurals.voiceSeconds, parts[0], parts[0]); String minutes = context.getResources().getQuantityString( R.plurals.voiceMinutes, parts[1], parts[1]); String hours = context.getResources().getQuantityString( R.plurals.voiceHours, parts[2], parts[2]); StringBuilder sb = new StringBuilder(); if (parts[2] != 0) { sb.append(hours); sb.append(" "); sb.append(minutes); } else { sb.append(minutes); sb.append(" "); sb.append(seconds); } return sb.toString(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java
Java
asf20
10,999
/* * 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.tasks; import android.content.Context; /** * An interface for classes that can create periodic tasks. * * @author Sandor Dornbush */ public interface PeriodicTaskFactory { /** * Creates a periodic task which does voice announcements. * * @return the task, or null if task is not supported */ PeriodicTask create(Context context); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/tasks/PeriodicTaskFactory.java
Java
asf20
998
/* * 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.Constants.TAG; import com.google.android.apps.mytracks.widgets.TrackWidgetProvider; import com.google.android.maps.mytracks.R; import android.app.IntentService; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * A service to control starting and stopping of a recording. This service, * through the AndroidManifest.xml, is configured to only allow components of * the same application to invoke it. Thus this service can be used my MyTracks * app widget, {@link TrackWidgetProvider}, but not by other applications. This * application delegates starting and stopping a recording to * {@link TrackRecordingService} using RPC calls. * * @author jshih@google.com (Jimmy Shih) */ public class ControlRecordingService extends IntentService implements ServiceConnection { private ITrackRecordingService trackRecordingService; private boolean connected = false; public ControlRecordingService() { super(ControlRecordingService.class.getSimpleName()); } @Override public void onCreate() { super.onCreate(); Intent newIntent = new Intent(this, TrackRecordingService.class); startService(newIntent); bindService(newIntent, this, 0); } @Override public void onServiceConnected(ComponentName name, IBinder service) { trackRecordingService = ITrackRecordingService.Stub.asInterface(service); notifyConnected(); } @Override public void onServiceDisconnected(ComponentName name) { connected = false; } /** * Notifies all threads that connection to {@link TrackRecordingService} is * available. */ private synchronized void notifyConnected() { connected = true; notifyAll(); } /** * Waits until the connection to {@link TrackRecordingService} is available. */ private synchronized void waitConnected() { while (!connected) { try { wait(); } catch (InterruptedException e) { // can safely ignore } } } @Override protected void onHandleIntent(Intent intent) { waitConnected(); String action = intent.getAction(); if (action != null) { try { if (action.equals(getString(R.string.track_action_start))) { trackRecordingService.startNewTrack(); } else if (action.equals(getString(R.string.track_action_end))) { trackRecordingService.endCurrentTrack(); } } catch (RemoteException e) { Log.d(TAG, "ControlRecordingService onHandleIntent RemoteException", e); } } unbindService(this); connected = false; } @Override public void onDestroy() { super.onDestroy(); if (connected) { unbindService(this); connected = false; } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/ControlRecordingService.java
Java
asf20
3,530
/* * 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.Constants; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A class that manages reading the shared preferences for the service. * * @author Sandor Dornbush */ public class PreferenceManager implements OnSharedPreferenceChangeListener { private TrackRecordingService service; private SharedPreferences sharedPreferences; private final String announcementFrequencyKey; private final String autoResumeTrackCurrentRetryKey; private final String autoResumeTrackTimeoutKey; private final String maxRecordingDistanceKey; private final String metricUnitsKey; private final String minRecordingDistanceKey; private final String minRecordingIntervalKey; private final String minRequiredAccuracyKey; private final String recordingTrackKey; private final String selectedTrackKey; private final String splitFrequencyKey; public PreferenceManager(TrackRecordingService service) { this.service = service; this.sharedPreferences = service.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (sharedPreferences == null) { Log.w(Constants.TAG, "TrackRecordingService: Couldn't get shared preferences."); throw new IllegalStateException("Couldn't get shared preferences"); } sharedPreferences.registerOnSharedPreferenceChangeListener(this); announcementFrequencyKey = service.getString(R.string.announcement_frequency_key); autoResumeTrackCurrentRetryKey = service.getString(R.string.auto_resume_track_current_retry_key); autoResumeTrackTimeoutKey = service.getString(R.string.auto_resume_track_timeout_key); maxRecordingDistanceKey = service.getString(R.string.max_recording_distance_key); 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); selectedTrackKey = service.getString(R.string.selected_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 preferences, String key) { if (service == null) { Log.w(Constants.TAG, "onSharedPreferenceChanged: a preference change (key = " + key + ") after a call to shutdown()"); return; } if (key == null || key.equals(minRecordingDistanceKey)) { int minRecordingDistance = sharedPreferences.getInt( minRecordingDistanceKey, Constants.DEFAULT_MIN_RECORDING_DISTANCE); service.setMinRecordingDistance(minRecordingDistance); Log.d(Constants.TAG, "TrackRecordingService: minRecordingDistance = " + minRecordingDistance); } if (key == null || key.equals(maxRecordingDistanceKey)) { service.setMaxRecordingDistance(sharedPreferences.getInt( maxRecordingDistanceKey, Constants.DEFAULT_MAX_RECORDING_DISTANCE)); } if (key == null || key.equals(minRecordingIntervalKey)) { int minRecordingInterval = sharedPreferences.getInt( minRecordingIntervalKey, Constants.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, Constants.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, Constants.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.setSplitFrequency( sharedPreferences.getInt(splitFrequencyKey, 0)); } if (key == null || key.equals(metricUnitsKey)) { service.setMetricUnits( sharedPreferences.getBoolean(metricUnitsKey, true)); } } public void setAutoResumeTrackCurrentRetry(int retryAttempts) { Editor editor = sharedPreferences.edit(); editor.putInt(autoResumeTrackCurrentRetryKey, retryAttempts); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void setRecordingTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(recordingTrackKey, id); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void setSelectedTrack(long id) { Editor editor = sharedPreferences.edit(); editor.putLong(selectedTrackKey, id); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } public void shutdown() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); service = null; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/PreferenceManager.java
Java
asf20
7,659
/* * 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/AdaptiveLocationListenerPolicy.java
Java
asf20
2,413
/* * 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.Constants.TAG; import com.google.android.apps.mytracks.util.SystemUtils; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.IBinder.DeathRecipient; import android.os.RemoteException; import android.util.Log; /** * Wrapper for the connection to the track recording service. * This handles connection/disconnection internally, only returning a real * service for use if one is available and connected. * * @author Rodrigo Damazio */ public class TrackRecordingServiceConnection { private ITrackRecordingService boundService; private final DeathRecipient deathRecipient = new DeathRecipient() { @Override public void binderDied() { Log.d(TAG, "Service died"); setBoundService(null); } }; private final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "Connected to service"); try { service.linkToDeath(deathRecipient, 0); } catch (RemoteException e) { Log.e(TAG, "Failed to bind a death recipient", e); } setBoundService(ITrackRecordingService.Stub.asInterface(service)); } @Override public void onServiceDisconnected(ComponentName className) { Log.i(TAG, "Disconnected from service"); setBoundService(null); } }; private final Context context; private final Runnable bindChangedCallback; /** * Constructor. * * @param context the current context * @param bindChangedCallback a callback to be executed when the state of the * service binding changes */ public TrackRecordingServiceConnection(Context context, Runnable bindChangedCallback) { this.context = context; this.bindChangedCallback = bindChangedCallback; } /** * Binds to the service, starting it if necessary. */ public void startAndBind() { bindService(true); } /** * Binds to the service, only if it's already running. */ public void bindIfRunning() { bindService(false); } /** * Unbinds from and stops the service. */ public void stop() { unbind(); Log.d(TAG, "Stopping service"); Intent intent = new Intent(context, TrackRecordingService.class); context.stopService(intent); } /** * Unbinds from the service (but leaves it running). */ public void unbind() { Log.d(TAG, "Unbinding from the service"); try { context.unbindService(serviceConnection); } catch (IllegalArgumentException e) { // Means we weren't bound, which is ok. } setBoundService(null); } /** * Returns the service if connected to it, or null if not connected. */ public ITrackRecordingService getServiceIfBound() { checkBindingAlive(); return boundService; } private void checkBindingAlive() { if (boundService != null && !boundService.asBinder().isBinderAlive()) { setBoundService(null); } } private void bindService(boolean startIfNeeded) { if (boundService != null) { // Already bound. return; } if (!startIfNeeded && !ServiceUtils.isServiceRunning(context)) { // Not running, start not requested. Log.d(TAG, "Service not running, not binding to it."); return; } if (startIfNeeded) { Log.i(TAG, "Starting the service"); Intent intent = new Intent(context, TrackRecordingService.class); context.startService(intent); } Log.i(TAG, "Binding to the service"); Intent intent = new Intent(context, TrackRecordingService.class); int flags = SystemUtils.isRelease(context) ? 0 : Context.BIND_DEBUG_UNBIND; context.bindService(intent, serviceConnection, flags); } private void setBoundService(ITrackRecordingService service) { boundService = service; if (bindChangedCallback != null) { bindChangedCallback.run(); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingServiceConnection.java
Java
asf20
4,731
/* * 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); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/LocationListenerPolicy.java
Java
asf20
1,370
/* * 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.Constants.RESUME_TRACK_EXTRA_NAME; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracks; 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.services.tasks.PeriodicTaskExecutor; import com.google.android.apps.mytracks.services.tasks.SplitTask; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.ApiLevelAdapter; import com.google.android.apps.mytracks.util.LocationUtils; 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.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.Process; 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 { static final int MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS = 3; private NotificationManager notificationManager; private LocationManager locationManager; private WakeLock wakeLock; private int minRecordingDistance = Constants.DEFAULT_MIN_RECORDING_DISTANCE; private int maxRecordingDistance = Constants.DEFAULT_MAX_RECORDING_DISTANCE; private int minRequiredAccuracy = Constants.DEFAULT_MIN_REQUIRED_ACCURACY; private int autoResumeTrackTimeout = Constants.DEFAULT_AUTO_RESUME_TRACK_TIMEOUT; private 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 executor. */ private PeriodicTaskExecutor announcementExecutor; private PeriodicTaskExecutor splitExecutor; 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); private LocationListener locationListener = new LocationListener() { @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 } @Override public void onLocationChanged(final Location location) { if (executorService.isShutdown() || executorService.isTerminated()) { return; } executorService.submit( new Runnable() { @Override public void run() { onLocationChangedAsync(location); } }); } }; /** * 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(Constants.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; /** * A service to run tasks outside of the main thread. */ private ExecutorService executorService; private ServiceBinder binder = new ServiceBinder(this); /* * Application lifetime events: */ /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the onCreate * callback, we cannot tell whether the caller is MyTracks or a third party * app, thus it cannot start/stop a recording or write/update MyTracks * database. However, it can resume a recording. */ @Override public void onCreate() { super.onCreate(); Log.d(TAG, "TrackRecordingService.onCreate"); providerUtils = MyTracksProviderUtils.Factory.get(this); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); setUpTaskExecutors(); executorService = Executors.newSingleThreadExecutor(); 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(TAG, "TrackRecordingService.onCreate: " + "Resetting an orphaned recording track = " + recordingTrackId); } prefManager.setRecordingTrack(recordingTrackId = -1); } showNotification(); } /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the onStart * callback, we cannot tell whether the caller is MyTracks or a third party * app, thus it cannot start/stop a recording or write/update MyTracks * database. However, it can resume a recording. */ @Override public void onStart(Intent intent, int startId) { handleStartCommand(intent, startId); } /* * Note that this service, through the AndroidManifest.xml, is configured to * allow both MyTracks and third party apps to invoke it. For the * onStartCommand callback, we cannot tell whether the caller is MyTracks or a * third party app, thus it cannot start/stop a recording or write/update * MyTracks database. However, it can resume a recording. */ @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(TAG, "TrackRecordingService.handleStartCommand: " + startId); if (intent == null) { return; } // Check if called on phone reboot with resume intent. if (intent.getBooleanExtra(RESUME_TRACK_EXTRA_NAME, false)) { resumeTrack(startId); } } private boolean isTrackInProgress() { return recordingTrackId != -1 || isRecording; } private void resumeTrack(int startId) { Log.d(TAG, "TrackRecordingService: requested resume"); // Make sure that the current track exists and is fresh enough. if (recordingTrack == null || !shouldResumeTrack(recordingTrack)) { Log.i(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(TAG, "TrackRecordingService: resuming"); } @Override public IBinder onBind(Intent intent) { Log.d(TAG, "TrackRecordingService.onBind"); return binder; } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "TrackRecordingService.onUnbind"); return super.onUnbind(intent); } @Override public void onDestroy() { Log.d(TAG, "TrackRecordingService.onDestroy"); isRecording = false; showNotification(); prefManager.shutdown(); prefManager = null; checkLocationListener.cancel(); checkLocationListener = null; timer.cancel(); timer.purge(); unregisterLocationListener(); shutdownTaskExecutors(); 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(); // Shutdown the executor service last to avoid sending events to a dead executor. executorService.shutdown(); super.onDestroy(); } private void setAutoResumeTrackRetries(int retryAttempts) { Log.d(TAG, "Updating auto-resume retry attempts to: " + retryAttempts); prefManager.setAutoResumeTrackCurrentRetry(retryAttempts); } private boolean shouldResumeTrack(Track track) { Log.d(TAG, "shouldResumeTrack: autoResumeTrackTimeout = " + autoResumeTrackTimeout); // Check if we haven't exceeded the maximum number of retry attempts. SharedPreferences sharedPreferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); int retries = sharedPreferences.getInt( getString(R.string.auto_resume_track_current_retry_key), 0); Log.d(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(TAG, "shouldResumeTrack: Not resuming because exceeded the maximum " + "number of auto-resume retries"); return false; } // Increase number of retry attempts. setAutoResumeTrackRetries(retries + 1); // Check for special cases. if (autoResumeTrackTimeout == 0) { // Never resume. Log.d(TAG, "shouldResumeTrack: Auto-resume disabled (never resume)"); return false; } else if (autoResumeTrackTimeout == -1) { // Always resume. Log.d(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(TAG, "shouldResumeTrack: lastModified = " + lastModified + ", autoResumeTrackTimeout: " + autoResumeTrackTimeout); return lastModified > 0 && System.currentTimeMillis() - lastModified <= autoResumeTrackTimeout * 60L * 1000L; } /* * Setup/shutdown methods. */ /** * 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(TAG, "TrackRecordingService: Power manager not found!"); return; } if (wakeLock == null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); if (wakeLock == null) { Log.e(TAG, "TrackRecordingService: Could not create wake lock (null)."); return; } } if (!wakeLock.isHeld()) { wakeLock.acquire(); if (!wakeLock.isHeld()) { Log.e(TAG, "TrackRecordingService: Could not acquire wake lock."); } } } catch (RuntimeException e) { Log.e(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. */ private void showNotification() { final ApiLevelAdapter apiLevelAdapter = ApiFeatures.getInstance().getApiAdapter(); 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.my_tracks_app_name), getString(R.string.track_record_notification), contentIntent); notification.flags += Notification.FLAG_NO_CLEAR; apiLevelAdapter.startForeground(this, notificationManager, 1, notification); } else { apiLevelAdapter.stopForeground(this, notificationManager, 1); } } private void setUpTaskExecutors() { announcementExecutor = new PeriodicTaskExecutor( this, new StatusAnnouncerFactory(ApiFeatures.getInstance())); splitExecutor = new PeriodicTaskExecutor(this, new SplitTask.Factory()); } private void shutdownTaskExecutors() { Log.d(TAG, "TrackRecordingService.shutdownExecuters"); try { announcementExecutor.shutdown(); } finally { announcementExecutor = null; } try { splitExecutor.shutdown(); } finally { splitExecutor = null; } } private void registerLocationListener() { if (locationManager == null) { Log.e(TAG, "TrackRecordingService: Do not have any location manager."); return; } Log.d(TAG, "Preparing to register location listener w/ TrackRecordingService..."); try { long desiredInterval = locationListenerPolicy.getDesiredPollingInterval(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, desiredInterval, locationListenerPolicy.getMinDistance(), // , 0 /* minDistance, get all updates to properly time pauses */ locationListener); currentRecordingInterval = desiredInterval; Log.d(TAG, "...location listener now registered w/ TrackRecordingService @ " + currentRecordingInterval); } catch (RuntimeException e) { Log.e(TAG, "Could not register location listener: " + e.getMessage(), e); } } private void unregisterLocationListener() { if (locationManager == null) { Log.e(TAG, "TrackRecordingService: Do not have any location manager."); return; } locationManager.removeUpdates(locationListener); Log.d(TAG, "Location listener now unregistered w/ TrackRecordingService."); } private String getDefaultActivityType(Context context) { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return prefs.getString(context.getString(R.string.default_activity_key), ""); } /* * Recording lifecycle. */ private long startNewTrack() { Log.d(TAG, "TrackRecordingService.startNewTrack"); if (isTrackInProgress()) { return -1L; } 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)); track.setCategory(getDefaultActivityType(this)); 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); length = 0; showNotification(); registerLocationListener(); sensorManager = SensorManagerFactory.getSensorManager(this); if (sensorManager != null) { sensorManager.onStartTrack(); } // Reset the number of auto-resume retries. setAutoResumeTrackRetries(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); announcementExecutor.restore(); splitExecutor.restore(); return recordingTrackId; } private void restoreStats(Track track) { Log.d(TAG, "Restoring stats of track with ID: " + track.getId()); TripStatistics stats = track.getStatistics(); statsBuilder = new TripStatisticsBuilder(stats.getStartTime()); statsBuilder.setMinRecordingDistance(minRecordingDistance); 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, Constants.MAX_LOADED_TRACK_POINTS, true); if (cursor != null) { if (cursor.moveToLast()) { do { Location location = providerUtils.createLocation(cursor); if (LocationUtils.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(TAG, "Could not get track points cursor."); } } catch (RuntimeException e) { Log.e(TAG, "Error while restoring track.", e); } finally { if (cursor != null) { cursor.close(); } } announcementExecutor.restore(); splitExecutor.restore(); } private void onLocationChangedAsync(Location location) { Log.d(TAG, "TrackRecordingService.onLocationChanged"); try { // Don't record if the service has been asked to pause recording: if (!isRecording) { Log.w(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(TAG, "Location changed, but location is null."); return; } // Don't record if the accuracy is too bad: if (location.getAccuracy() > minRequiredAccuracy) { Log.d(TAG, "Not recording. Bad accuracy."); return; } // At least one track must be available for appending points: recordingTrack = getRecordingTrack(); if (recordingTrack == null) { Log.d(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(); 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(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(lastLocation, lastRecordedLocation, recordingTrackId)) { return; } } } else { Log.d(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(lastLocation, lastRecordedLocation, recordingTrackId)) { return; } 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(TAG, "Inserting a separator."); Location separator = new Location(LocationManager.GPS_PROVIDER); separator.setLongitude(0); separator.setLatitude(100); separator.setTime(lastRecordedLocation.getTime()); providerUtils.insertTrackPoint(separator, recordingTrackId); } if (!insertLocation(location, lastRecordedLocation, recordingTrackId)) { return; } } else { Log.d(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(TAG, "Error in onLocationChanged", e); throw e; } catch (RuntimeException e) { // Safe usually to trap exceptions. Log.e(TAG, "Trapping exception in onLocationChanged", e); throw e; } lastLocation = location; } /** * Inserts a new location in the track points db and updates the corresponding * track in the track db. * * @param location the location to be inserted * @param lastRecordedLocation the last recorded location before this one (or * null if none) * @param trackId the id of the track * @return true if successful. False if SQLite3 threw an exception. */ private boolean insertLocation(Location location, Location lastRecordedLocation, long trackId) { // Keep track of length along recorded track (needed when a waypoint is // inserted): if (LocationUtils.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(TAG, "Caught SQLiteException: " + e.getMessage(), e); return false; } announcementExecutor.update(); splitExecutor.update(); 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); } } private void addLocationToStats(Location location) { if (LocationUtils.isValidLocation(location)) { long now = System.currentTimeMillis(); statsBuilder.addLocation(location, now); waypointStatsBuilder.addLocation(location, now); } } /* * Application lifetime events: ============================ */ 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 (lastLocation == null || statsBuilder == null || statsBuilder.getStatistics() == 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(180); wpt.setLocation(l); } else { wpt.setLocation(lastLocation); 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.marker_waypoint_icon_url)); } else { wpt.setIcon(request.getIconUrl()); } if (request.getName() == null) { wpt.setName(getString(R.string.marker_type_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. */ 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.marker_type_statistics)); waypoint.setStatistics(waypointStatsBuilder.getStatistics()); waypoint.setDescription(utils.generateWaypointDescription(waypoint)); waypoint.setIcon(getString(R.string.marker_statistics_icon_url)); waypoint.setStartId(providerUtils.getLastLocationId(recordingTrackId)); // Create a new stats keeper for the next marker. waypointStatsBuilder = new TripStatisticsBuilder(time); } private void endCurrentTrack() { Log.d(TAG, "TrackRecordingService.endCurrentTrack"); if (!isTrackInProgress()) { return; } announcementExecutor.shutdown(); splitExecutor.shutdown(); isRecording = false; Track recordedTrack = providerUtils.getTrack(recordingTrackId); if (recordedTrack != null) { TripStatistics stats = recordedTrack.getStatistics(); stats.setStopTime(System.currentTimeMillis()); stats.setTotalTime(stats.getStopTime() - stats.getStartTime()); long lastRecordedLocationId = providerUtils.getLastLocationId(recordingTrackId); ContentValues values = new ContentValues(); if (lastRecordedLocationId >= 0 && recordedTrack.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=" + recordedTrack.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); stopSelf(); } 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.permission_notification_value)); SharedPreferences sharedPreferences = getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (sharedPreferences.getBoolean(getString(R.string.allow_access_key), false)) { sendBroadcast(broadcastIntent, getString(R.string.broadcast_notifications_permission)); } } /* * Data/state access. */ private Track getRecordingTrack() { if (recordingTrackId < 0) { return null; } return providerUtils.getTrack(recordingTrackId); } public boolean isRecording() { return isRecording; } public TripStatistics getTripStatistics() { return statsBuilder.getStatistics(); } Location getLastLocation() { return lastLocation; } long getRecordingTrackId() { return recordingTrackId; } void setRecordingTrackId(long recordingTrackId) { this.recordingTrackId = recordingTrackId; } void setMaxRecordingDistance(int maxRecordingDistance) { this.maxRecordingDistance = maxRecordingDistance; } void setMinRecordingDistance(int minRecordingDistance) { this.minRecordingDistance = minRecordingDistance; if (statsBuilder != null && waypointStatsBuilder != null) { statsBuilder.setMinRecordingDistance(minRecordingDistance); waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance); } } void setMinRequiredAccuracy(int minRequiredAccuracy) { this.minRequiredAccuracy = minRequiredAccuracy; } void setLocationListenerPolicy(LocationListenerPolicy locationListenerPolicy) { this.locationListenerPolicy = locationListenerPolicy; } void setAutoResumeTrackTimeout(int autoResumeTrackTimeout) { this.autoResumeTrackTimeout = autoResumeTrackTimeout; } void setAnnouncementFrequency(int announcementFrequency) { announcementExecutor.setTaskFrequency(announcementFrequency); } void setSplitFrequency(int frequency) { splitExecutor.setTaskFrequency(frequency); } void setMetricUnits(boolean metric) { announcementExecutor.setMetricUnits(metric); splitExecutor.setMetricUnits(metric); } /** * 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; private DeathRecipient deathRecipient; public ServiceBinder(TrackRecordingService service) { this.service = service; } // Logic for letting the actual service go up and down. @Override public boolean isBinderAlive() { // Pretend dead if the service went down. return service != null; } @Override public boolean pingBinder() { return isBinderAlive(); } @Override public void linkToDeath(DeathRecipient recipient, int flags) { deathRecipient = recipient; } @Override public boolean unlinkToDeath(DeathRecipient recipient, int flags) { if (!isBinderAlive()) { return false; } deathRecipient = null; return true; } /** * Clears the reference to the outer class to minimize the leak. */ private void detachFromService() { this.service = null; attachInterface(null, null); if (deathRecipient != null) { deathRecipient.binderDied(); } } /** * Checks if the service is available. If not, throws an * {@link IllegalStateException}. */ private void checkService() { if (service == null) { throw new IllegalStateException("The service has been already detached!"); } } /** * Returns true if the RPC caller is from the same application or if the * "Allow access" setting indicates that another app can invoke this service's * RPCs. */ private boolean canAccess() { // As a precondition for access, must check if the service is available. checkService(); if (Process.myPid() == Binder.getCallingPid()) { return true; } else { SharedPreferences sharedPreferences = service.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(service.getString(R.string.allow_access_key), false); } } // Service method delegates. @Override public boolean isRecording() { if (!canAccess()) { return false; } return service.isRecording(); } @Override public long getRecordingTrackId() { if (!canAccess()) { return -1L; } return service.recordingTrackId; } @Override public long startNewTrack() { if (!canAccess()) { return -1L; } 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) { if (!canAccess()) { return -1L; } return service.insertWaypoint(request); } @Override public void endCurrentTrack() { if (!canAccess()) { return; } service.endCurrentTrack(); } @Override public void recordLocation(Location loc) { if (!canAccess()) { return; } service.locationListener.onLocationChanged(loc); } @Override public byte[] getSensorData() { if (!canAccess()) { return null; } if (service.sensorManager == null) { Log.d(TAG, "No sensor manager for data."); return null; } if (service.sensorManager.getSensorDataSet() == null) { Log.d(TAG, "Sensor data set is null."); return null; } return service.sensorManager.getSensorDataSet().toByteArray(); } @Override public int getSensorState() { if (!canAccess()) { return Sensor.SensorState.NONE.getNumber(); } if (service.sensorManager == null) { Log.d(TAG, "No sensor manager for data."); return Sensor.SensorState.NONE.getNumber(); } return service.sensorManager.getSensorState().getNumber(); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java
Java
asf20
44,106
/* * 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.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import java.text.DateFormat; import java.util.Date; /** * Creates a default track name based on the current default track name policy. * * @author Matthew Simmons */ class DefaultTrackNameFactory { 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()) { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); return formatter.format(new Date(startTime)); } else { return String.format(context.getString(R.string.track_name_format), trackId); } } /** Determines whether the preferences allow a timestamp-based track name */ protected boolean useTimestampTrackName() { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return prefs.getBoolean( context.getString(R.string.timestamp_track_name_key), true); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/DefaultTrackNameFactory.java
Java
asf20
2,054
/* * 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.Constants.TAG; import com.google.android.apps.mytracks.Constants; 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.Looper; import android.os.Message; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; /** * Manage the connection to a bluetooth sensor. * * @author Sandor Dornbush */ public class BluetoothSensorManager extends SensorManager { // Local Bluetooth adapter private static final BluetoothAdapter bluetoothAdapter = getDefaultBluetoothAdapter(); // 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; // If BT is not available or not enabled quit. if (!isEnabled()) { return; } setupSensor(); } private void setupSensor() { Log.d(Constants.TAG, "setupSensor()"); // Initialize the BluetoothSensorAdapter to perform bluetooth connections. connectionManager = new BluetoothConnectionManager(messageHandler, parser); } /** * Code for assigning the local bluetooth adapter * * @return The default bluetooth adapter, if one is available, NULL if it isn't. */ private static BluetoothAdapter getDefaultBluetoothAdapter() { // Check if the calling thread is the main application thread, // if it is, do it directly. if (Thread.currentThread().equals(Looper.getMainLooper().getThread())) { return BluetoothAdapter.getDefaultAdapter(); } // If the calling thread, isn't the main application thread, // then get the main application thread to return the default adapter. final ArrayList<BluetoothAdapter> adapters = new ArrayList<BluetoothAdapter>(1); final Object mutex = new Object(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { adapters.add(BluetoothAdapter.getDefaultAdapter()); synchronized (mutex) { mutex.notify(); } } }); while (adapters.isEmpty()) { synchronized (mutex) { try { mutex.wait(1000L); } catch (InterruptedException e) { Log.e(TAG, "Interrupted while waiting for default bluetooth adapter", e); } } } if (adapters.get(0) == null) { Log.w(TAG, "No bluetooth adapter found!"); } return adapters.get(0); } public boolean isEnabled() { return bluetoothAdapter != null && bluetoothAdapter.isEnabled(); } public void setupChannel() { if (!isEnabled() || connectionManager == null) { Log.w(Constants.TAG, "Disabled manager onStartTrack"); return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); String address = prefs.getString(context.getString(R.string.bluetooth_sensor_key), null); if (address == null) { return; } Log.w(Constants.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(Constants.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(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case BluetoothConnectionManager.MESSAGE_STATE_CHANGE: // TODO should we update the SensorManager state var? Log.i(Constants.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(Constants.TAG, "MESSAGE_READ: " + sensorDataSet.toString()); } catch (IllegalArgumentException iae) { sensorDataSet = null; Log.i(Constants.TAG, "Got bad sensor data: " + new String(readBuf, 0, readBuf.length), iae); } catch (RuntimeException re) { sensorDataSet = null; Log.i(Constants.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; } } }; }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothSensorManager.java
Java
asf20
7,066
/* * 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()); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ZephyrSensorManager.java
Java
asf20
853
/* * 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 com.google.android.apps.mytracks.content.Sensor; import com.google.android.maps.mytracks.R; import android.content.Context; /** * A collection of methods for message parsers. * * @author Sandor Dornbush * @author Nico Laum */ 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; } /** * Extract one unsigned short from a little 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 unsignedShortToIntLittleEndian(byte[] buffer, int index) { int r = buffer[index] & 0xFF; r |= (buffer[index + 1] & 0xFF) << 8; return r; } /** * Returns CRC8 (polynomial 0x8C) from byte array buffer[start] to * (excluding) buffer[start + length] * * @param buffer the byte array of data (payload) * @param start the position in the byte array where the payload begins * @param length the length * @return CRC8 value */ public static byte getCrc8(byte[] buffer, int start, int length) { byte crc = 0x0; for (int i = start; i < (start + length); i++) { crc = crc8PushByte(crc, buffer[i]); } return crc; } /** * Updates a CRC8 value by using the next byte passed to this method * * @param crc int of crc value * @param add the next byte to add to the CRC8 calculation */ private static byte crc8PushByte(byte crc, byte add) { crc = (byte) (crc ^ add); for (int i = 0; i < 8; i++) { if ((crc & 0x1) != 0x0) { // Using a 0xFF bit assures that 0-bits are introduced during the shift operation. // Otherwise, implicit casts to signed int could shift in 1-bits if the signed bit is 1. crc = (byte) (((crc & 0xFF) >> 1) ^ 0x8C); } else { crc = (byte) ((crc & 0xFF) >> 1); } } return crc; } public static String getStateAsString(Sensor.SensorState state, Context c) { switch (state) { case NONE: return c.getString(R.string.sensor_type_value_none); case CONNECTING: return c.getString(R.string.sensor_state_connecting); case CONNECTED: return c.getString(R.string.sensor_state_connected); case DISCONNECTED: return c.getString(R.string.sensor_state_disconnected); case SENDING: return c.getString(R.string.sensor_state_sending); default: return ""; } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorUtils.java
Java
asf20
3,576
/* * 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 java.util.Timer; import java.util.TimerTask; import android.util.Log; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; /** * 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(Constants.TAG, "SensorManager state: " + getSensorState()); switch (getSensorState()) { case CONNECTING: long age = System.currentTimeMillis() - getSensorStateTimestamp(); if (age > 2 * RETRY_PERIOD) { Log.i(Constants.TAG, "Retrying connecting SensorManager."); setupChannel(); } break; case DISCONNECTED: Log.i(Constants.TAG, "Re-registering disconnected SensoManager."); 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManager.java
Java
asf20
3,660
/* * 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); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/MessageParser.java
Java
asf20
1,036
/* * 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.AntDefine; import com.dsi.ant.AntInterface; import android.content.Context; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; /** * 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); } /** * Finds the names of in the messages with the given value */ public static String antMessageToString(byte msg) { return findConstByteInClass(AntDefine.class, msg, "MESG_.*_ID"); } /** * Finds the names of in the events with the given value */ public static String antEventToStr(byte event) { return findConstByteInClass(AntDefine.class, event, ".*EVENT.*"); } /** * Finds a set of constant static byte field declarations in the class that have the given value * and whose name match the given pattern * @param cl class to search in * @param value value of constant static byte field declarations to match * @param regexPattern pattern to match against the name of the field * @return a set of the names of fields, expressed as a string */ private static String findConstByteInClass(Class<?> cl, byte value, String regexPattern) { Field[] fields = cl.getDeclaredFields(); Set<String> fieldSet = new HashSet<String>(); for (Field f : fields) { try { if (f.getType() == Byte.TYPE && (f.getModifiers() & Modifier.STATIC) != 0 && f.getName().matches(regexPattern) && f.getByte(null) == value) { fieldSet.add(f.getName()); } } catch (IllegalArgumentException e) { // ignore } catch (IllegalAccessException e) { // ignore } } return fieldSet.toString(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntUtils.java
Java
asf20
2,692
/* * 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntChannelIdMessage.java
Java
asf20
1,647
/* * 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 static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A sensor manager to the PC7 SRM ANT+ bridge. * * @author Sandor Dornbush * @author Umran Abdulla */ public class AntSrmBridgeSensorManager extends AntSensorManager { /* * These constants are defined by the ANT+ spec. */ public static final byte CHANNEL_NUMBER = 0; public static final byte NETWORK_NUMBER = 0; public static final byte DEVICE_TYPE = 12; public static final byte NETWORK_ID = 1; public static final short CHANNEL_PERIOD = 8192; public static final byte RF_FREQUENCY = 50; private static final int INDEX_MESSAGE_TYPE = 1; private static final int INDEX_MESSAGE_ID = 2; private static final int INDEX_MESSAGE_POWER = 3; private static final int INDEX_MESSAGE_SPEED = 5; private static final int INDEX_MESSAGE_CADENCE = 7; private static final int INDEX_MESSAGE_BPM = 8; private static final int MSG_INITIAL = 5; private static final int MSG_DATA = 6; private short deviceNumber; public AntSrmBridgeSensorManager(Context context) { super(context); Log.i(TAG, "new ANT SRM Bridge Sensor Manager created"); deviceNumber = WILDCARD; // First read the the device id that we will be pairing with. SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs != null) { deviceNumber = (short) prefs.getInt(context.getString( R.string.ant_srm_bridge_sensor_id_key), 0); } Log.i(TAG, "Will pair with device: " + deviceNumber); } @Override protected boolean handleMessage(byte messageId, byte[] messageData) { if (super.handleMessage(messageId, messageData)) { return true; } if (!SystemUtils.isRelease(context)) { Log.d(TAG, "Received ANT msg: " + AntUtils.antMessageToString(messageId) + "(" + messageId + ")"); } int channel = messageData[0] & AntDefine.CHANNEL_NUMBER_MASK; switch (channel) { case CHANNEL_NUMBER: decodeChannelMsg(messageId, messageData); break; default: Log.d(TAG, "Unhandled message: " + channel); } return true; } /** * Decode an ant device message. * @param messageData The byte array received from the device. */ private void decodeChannelMsg(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 (deviceNumber == WILDCARD) { try { getAntReceiver().ANTRequestMessage(CHANNEL_NUMBER, 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 messageType = antMessage[INDEX_MESSAGE_TYPE] & 0xFF; Log.d(TAG, "Received message-type=" + messageType); switch (messageType) { case MSG_INITIAL: break; case MSG_DATA: parseDataMsg(antMessage); break; } } private void parseDataMsg(byte[] msg) { int messageId = msg[INDEX_MESSAGE_ID] & 0xFF; Log.d(TAG, "Received message-id=" + messageId); int powerVal = (((msg[INDEX_MESSAGE_POWER] & 0xFF) << 8) | (msg[INDEX_MESSAGE_POWER+1] & 0xFF)); @SuppressWarnings("unused") int speedVal = (((msg[INDEX_MESSAGE_SPEED] & 0xFF) << 8) | (msg[INDEX_MESSAGE_SPEED+1] & 0xFF)); int cadenceVal = (msg[INDEX_MESSAGE_CADENCE] & 0xFF); int bpmVal = (msg[INDEX_MESSAGE_BPM] & 0xFF); long time = System.currentTimeMillis(); Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder() .setValue(powerVal) .setState(Sensor.SensorState.SENDING); /* * Although speed is available from the SRM Bridge, MyTracks doesn't use the value, and * computes speed from the GPS location data. */ // Sensor.SensorData.Builder speed = Sensor.SensorData.newBuilder().setValue(speedVal).setState( // Sensor.SensorState.SENDING); Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder() .setValue(cadenceVal) .setState(Sensor.SensorState.SENDING); Sensor.SensorData.Builder bpm = Sensor.SensorData.newBuilder() .setValue(bpmVal) .setState(Sensor.SensorState.SENDING); sensorData = Sensor.SensorDataSet.newBuilder() .setCreationTime(time) .setPower(power) .setCadence(cadence) .setHeartRate(bpm) .build(); } void handleChannelId(byte[] rawMessage) { AntChannelIdMessage message = new AntChannelIdMessage(rawMessage); deviceNumber = message.getDeviceNumber(); Log.d(TAG, "Found device id: " + deviceNumber); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_srm_bridge_sensor_id_key), deviceNumber); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } private void handleMessageResponse(byte[] rawMessage) { AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage); if (!SystemUtils.isRelease(context)) { Log.d(TAG, "Received ANT Response: " + AntUtils.antMessageToString(message.getMessageId()) + "(" + message.getMessageId() + ")" + ", Code: " + AntUtils.antEventToStr(message.getMessageCode()) + "(" + message.getMessageCode() + ")"); } 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); } } break; case AntMesg.MESG_UNASSIGN_CHANNEL_ID: setSensorState(Sensor.SensorState.DISCONNECTED); Log.i(TAG, "Disconnected from the sensor: " + getSensorState()); break; } } @Override protected void setupAntSensorChannels() { Log.i(TAG, "Setting up ANT sensor channels"); setupAntSensorChannel( NETWORK_NUMBER, CHANNEL_NUMBER, deviceNumber, DEVICE_TYPE, (byte) 0x01, CHANNEL_PERIOD, RF_FREQUENCY, (byte) 0); } public short getDeviceNumber() { return deviceNumber; } void setDeviceNumber(short deviceNumber) { this.deviceNumber = deviceNumber; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSrmBridgeSensorManager.java
Java
asf20
8,355
/* * 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.ant; import static com.google.android.apps.mytracks.Constants.TAG; import com.dsi.ant.AntDefine; import com.dsi.ant.AntMesg; import com.dsi.ant.exception.AntInterfaceException; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putInt(context.getString(R.string.ant_heart_rate_sensor_id_key), deviceNumberHRM); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntDirectSensorManager.java
Java
asf20
5,947
/* * 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) { int value = b0 & 0xFF; value |= (b1 & 0xFF) << 8; return (short)value; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntMessage.java
Java
asf20
1,009
/* * 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntChannelResponseMessage.java
Java
asf20
1,492
/* * 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.ant; import static com.google.android.apps.mytracks.Constants.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.dsi.ant.exception.AntServiceNotConnectedException; 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.SensorManager; 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; /** * 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 ctx, 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 ctx, Intent intent) { String antAction = intent.getAction(); Log.i(TAG, "enter data onReceive" + antAction); if (antAction != null && 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; // 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(); } @Override public void onDestroy() { Log.i(TAG, "destroying AntSensorManager"); cleanAntInterface(); unregisterForAntIntents(); } @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() { setup(); } private synchronized void setup() { // 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"); } cleanAntInterface(); antReceiver = AntInterface.getInstance(context, antServiceListener); if (antReceiver == null) { Log.e(TAG, "Failed to get ANT Receiver"); return; } setSensorState(Sensor.SensorState.CONNECTING); } /** * Cleans up the ANT+ receiver interface, by releasing the interface * and destroying it. */ private void cleanAntInterface() { Log.i(TAG, "Destroying AntSensorManager"); if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return; } try { antReceiver.releaseInterface(); antReceiver.destroy(); antReceiver = null; } catch (AntServiceNotConnectedException e) { Log.i(TAG, "ANT service not connected", e); } catch (AntInterfaceException e) { Log.e(TAG, "failed to release ANT interface", e); } catch (RuntimeException e) { Log.e(TAG, "run-time exception when cleaning the ANT interface", e); } } /** * 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"); if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return; } 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 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(byte, 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) { if (antReceiver == null) { Log.e(TAG, "no ANT receiver"); return false; } 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 void unregisterForAntIntents() { Log.i(TAG, "Unregistering ANT Intents."); try { context.unregisterReceiver(statusReceiver); } catch (IllegalArgumentException e) { Log.w(TAG, "Failed to unregister ANT status receiver", e); } try { context.unregisterReceiver(dataReceiver); } catch (IllegalArgumentException e) { Log.w(TAG, "Failed to unregister ANT data receiver", e); } } 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(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSensorManager.java
Java
asf20
12,821
/* * Copyright (C) 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; /** * A enum which stores static data about ANT sensors. * * @author Matthew Simmons */ public enum AntSensor { SENSOR_HEART_RATE (Constants.ANT_DEVICE_TYPE_HRM), SENSOR_CADENCE (Constants.ANT_DEVICE_TYPE_CADENCE), SENSOR_SPEED (Constants.ANT_DEVICE_TYPE_SPEED), SENSOR_POWER (Constants.ANT_DEVICE_TYPE_POWER); private static class Constants { public static byte ANT_DEVICE_TYPE_POWER = 11; public static byte ANT_DEVICE_TYPE_HRM = 120; public static byte ANT_DEVICE_TYPE_CADENCE = 122; public static byte ANT_DEVICE_TYPE_SPEED = 123; }; private final byte deviceType; private AntSensor(byte deviceType) { this.deviceType = deviceType; } public byte getDeviceType() { return deviceType; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntSensor.java
Java
asf20
1,405
/* * 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ant/AntStartupMessage.java
Java
asf20
1,084
/* * 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.Constants; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; 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 handler A Handler to send messages back to the UI Activity * @param parser A message parser */ 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(Constants.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(Constants.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(Constants.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(Constants.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(Constants.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(Constants.TAG, "Bluetooth connection failed."); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { setState(Sensor.SensorState.DISCONNECTED); Log.i(Constants.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(Constants.TAG, "create() failed", e); } socket = tmp; } private BluetoothSocket getSocket() throws IOException { if (ApiFeatures.getInstance().hasBluetoothDeviceCreateInsecureRfcommSocketToServiceRecord()) { try { return device.createInsecureRfcommSocketToServiceRecord(SPP_UUID); } catch (IOException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } } else { 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(Constants.TAG, "Unable to get insecure connect.", e); } catch (NoSuchMethodException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (IllegalArgumentException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (IllegalAccessException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } catch (InvocationTargetException e) { Log.e(Constants.TAG, "Unable to get insecure connect.", e); } } return device.createRfcommSocketToServiceRecord(SPP_UUID); } @Override public void run() { Log.d(Constants.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(Constants.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(Constants.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(Constants.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(Constants.TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } @Override public void run() { Log.i(Constants.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(Constants.TAG, "Misaligned data, found new message at " + index + " recovering..."); continue; } Log.w(Constants.TAG, "Could not find valid data, dropping data"); offset = 0; continue; } offset = 0; // Send copy of the obtained bytes to the UI Activity. // Avoids memory inconsistency issues. handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer.clone()) .sendToTarget(); } catch (IOException e) { Log.e(Constants.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(Constants.TAG, "Exception during write", e); } } public void cancel() { try { btSocket.close(); } catch (IOException e) { Log.e(Constants.TAG, "close() of connect socket failed", e); } } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/BluetoothConnectionManager.java
Java
asf20
13,646
/* * 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 com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.util.ApiFeatures; import java.util.Arrays; /** * An implementation of a Sensor MessageParser for Zephyr. * * @author Sandor Dornbush * @author Dominik Ršttsches */ public class ZephyrMessageParser implements MessageParser { public static final int ZEPHYR_HXM_BYTE_STX = 0; public static final int ZEPHYR_HXM_BYTE_CRC = 58; public static final int ZEPHYR_HXM_BYTE_ETX = 59; private static final byte[] CADENCE_BUG_FW_ID = {0x1A, 0x00, 0x31, 0x65, 0x50, 0x00, 0x31, 0x62}; private StrideReadings strideReadings; @Override public Sensor.SensorDataSet parseBuffer(byte[] buffer) { Sensor.SensorDataSet.Builder sds = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()); Sensor.SensorData.Builder heartrate = Sensor.SensorData.newBuilder() .setValue(buffer[12] & 0xFF) .setState(Sensor.SensorState.SENDING); sds.setHeartRate(heartrate); Sensor.SensorData.Builder batteryLevel = Sensor.SensorData.newBuilder() .setValue(buffer[11]) .setState(Sensor.SensorState.SENDING); sds.setBatteryLevel(batteryLevel); setCadence(sds, buffer); return sds.build(); } private void setCadence(Sensor.SensorDataSet.Builder sds, byte[] buffer) { // Device Firmware ID, Firmware Version, Hardware ID, Hardware Version // 0x1A00316550003162 produces erroneous values for Cadence and needs // a workaround based on the stride counter. // Firmware values range from field 3 to 10 (inclusive) of the byte buffer. byte[] hardwareFirmwareId = ApiFeatures.getInstance().getApiAdapter() .copyByteArray(buffer, 3, 11); Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder(); if (Arrays.equals(hardwareFirmwareId, CADENCE_BUG_FW_ID)) { if (strideReadings == null) { strideReadings = new StrideReadings(); } strideReadings.updateStrideReading(buffer[54] & 0xFF); if (strideReadings.getCadence() != StrideReadings.CADENCE_NOT_AVAILABLE) { cadence.setValue(strideReadings.getCadence()).setState(Sensor.SensorState.SENDING); } } else { cadence .setValue(SensorUtils.unsignedShortToIntLittleEndian(buffer, 56) / 16) .setState(Sensor.SensorState.SENDING); } sds.setCadence(cadence); } @Override public boolean isValid(byte[] buffer) { // Check STX (Start of Text), ETX (End of Text) and CRC Checksum return buffer.length > ZEPHYR_HXM_BYTE_ETX && buffer[ZEPHYR_HXM_BYTE_STX] == 0x02 && buffer[ZEPHYR_HXM_BYTE_ETX] == 0x03 && SensorUtils.getCrc8(buffer, 3, 55) == buffer[ZEPHYR_HXM_BYTE_CRC]; } @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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/ZephyrMessageParser.java
Java
asf20
3,741
/* * 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 com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager; import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager; import com.google.android.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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { return null; } context = context.getApplicationContext(); String sensor = prefs.getString(context.getString(R.string.sensor_type_key), null); Log.i(Constants.TAG, "Creating sensor of type: " + sensor); if (sensor == null) { return null; } else if (sensor.equals(context.getString(R.string.sensor_type_value_ant))) { return new AntDirectSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_srm_ant_bridge))) { return new AntSrmBridgeSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_zephyr))) { return new ZephyrSensorManager(context); } else if (sensor.equals(context.getString(R.string.sensor_type_value_polar))) { return new PolarSensorManager(context); } else { Log.w(Constants.TAG, "Unable to find sensor type: " + sensor); return null; } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/SensorManagerFactory.java
Java
asf20
2,480
/* * 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; import com.google.android.apps.mytracks.content.Sensor; /** * An implementation of a Sensor MessageParser for Polar Wearlink Bluetooth HRM. * * Polar Bluetooth Wearlink packet example; * Hdr Len Chk Seq Status HeartRate RRInterval_16-bits * FE 08 F7 06 F1 48 03 64 * where; * Hdr always = 254 (0xFE), * Chk = 255 - Len * Seq range 0 to 15 * Status = Upper nibble may be battery voltage * bit 0 is Beat Detection flag. * * Additional packet examples; * FE 08 F7 06 F1 48 03 64 * FE 0A F5 06 F1 48 03 64 03 70 * * @author John R. Gerthoffer */ public class PolarMessageParser implements MessageParser { private int lastHeartRate = 0; /** * Applies Polar packet validation rules to buffer. * Polar packets are checked for following; * offset 0 = header byte, 254 (0xFE). * offset 1 = packet length byte, 8, 10, 12, 14. * offset 2 = check byte, 255 - packet length. * offset 3 = sequence byte, range from 0 to 15. * * @param buffer an array of bytes to parse * @param i buffer offset to beginning of packet. * @return whether buffer has a valid packet at offset i */ private boolean packetValid (byte[] buffer, int i) { boolean headerValid = (buffer[i] & 0xFF) == 0xFE; boolean checkbyteValid = (buffer[i + 2] & 0xFF) == (0xFF - (buffer[i + 1] & 0xFF)); boolean sequenceValid = (buffer[i + 3] & 0xFF) < 16; return headerValid && checkbyteValid && sequenceValid; } @Override public Sensor.SensorDataSet parseBuffer(byte[] buffer) { int heartRate = 0; boolean heartrateValid = false; // Minimum length Polar packets is 8, so stop search 8 bytes before buffer ends. for (int i = 0; i < buffer.length - 8; i++) { heartrateValid = packetValid(buffer,i); if (heartrateValid) { heartRate = buffer[i + 5] & 0xFF; break; } } // If our buffer is corrupted, use decaying last good value. if(!heartrateValid) { heartRate = (int) (lastHeartRate * 0.8); if(heartRate < 50) heartRate = 0; } lastHeartRate = heartRate; // Remember good value for next time. // Heart Rate Sensor.SensorData.Builder b = Sensor.SensorData.newBuilder() .setValue(heartRate) .setState(Sensor.SensorState.SENDING); Sensor.SensorDataSet sds = Sensor.SensorDataSet.newBuilder() .setCreationTime(System.currentTimeMillis()) .setHeartRate(b) .build(); return sds; } /** * Applies packet validation rules to buffer * * @param buffer an array of bytes to parse * @return whether buffer has a valid packet starting at index zero */ @Override public boolean isValid(byte[] buffer) { return packetValid(buffer,0); } /** * Polar uses variable packet sizes; 8, 10, 12, 14 and rarely 16. * The most frequent are 8 and 10. * We will wait for 16 bytes. * This way, we are assured of getting one good one. * * @return the size of buffer needed to parse a good packet */ @Override public int getFrameSize() { return 16; } /** * Searches buffer for the beginning of a valid packet. * * @param buffer an array of bytes to parse * @return index to beginning of good packet, or -1 if none found. */ @Override public int findNextAlignment(byte[] buffer) { // Minimum length Polar packets is 8, so stop search 8 bytes before buffer ends. for (int i = 0; i < buffer.length - 8; i++) { if (packetValid(buffer,i)) { return i; } } return -1; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/PolarMessageParser.java
Java
asf20
4,382
/* * 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; import android.content.Context; /** * PolarSensorManager - A sensor manager for Polar heart rate monitors. */ public class PolarSensorManager extends BluetoothSensorManager { public PolarSensorManager(Context context) { super(context, new PolarMessageParser()); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/sensors/PolarSensorManager.java
Java
asf20
929
/* * 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.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.os.RemoteException; import android.util.Log; import java.util.List; /** * Helper for reading service state. * * @author Rodrigo Damazio */ public class ServiceUtils { /** * Checks whether we're currently recording. * The checking is done by calling the service, if provided, or alternatively by reading * recording state saved to preferences. * * @param ctx the current context * @param service the service, or null if not bound to it * @param preferences the preferences, or null if not available * @return true if the service is recording (or supposed to be recording), false otherwise */ public static boolean isRecording(Context ctx, ITrackRecordingService service, SharedPreferences preferences) { if (service != null) { try { return service.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to check if service is recording", e); } catch (IllegalStateException e) { Log.e(TAG, "Failed to check if service is recording", e); } } if (preferences == null) { preferences = ctx.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); } return preferences.getLong(ctx.getString(R.string.recording_track_key), -1) > 0; } /** * Checks whether the recording service is currently running. * * @param ctx the current context * @return true if the service is running, false otherwise */ public static boolean isServiceRunning(Context ctx) { ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { ComponentName componentName = serviceInfo.service; String serviceName = componentName.getClassName(); if (serviceName.equals(TrackRecordingService.class.getName())) { return true; } } return false; } private ServiceUtils() {} }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/services/ServiceUtils.java
Java
asf20
3,043
package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; 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.util.Log; import java.util.EnumSet; import java.util.Set; /** * External data source manager, which converts system-level events into My Tracks data events. * * @author Rodrigo Damazio */ class DataSourceManager { /** Single interface for receiving system events that were registered for. */ interface DataSourceListener { void notifyTrackUpdated(); void notifyWaypointUpdated(); void notifyPointsUpdated(); void notifyPreferenceChanged(String key); void notifyLocationProviderEnabled(boolean enabled); void notifyLocationProviderAvailable(boolean available); void notifyLocationChanged(Location loc); void notifyHeadingChanged(float heading); } private final DataSourceListener listener; /** Observer for when the tracks table is updated. */ private class TrackObserver extends ContentObserver { public TrackObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyTrackUpdated(); } } /** Observer for when the waypoints table is updated. */ private class WaypointObserver extends ContentObserver { public WaypointObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyWaypointUpdated(); } } /** Observer for when the points table is updated. */ private class PointObserver extends ContentObserver { public PointObserver() { super(contentHandler); } @Override public void onChange(boolean selfChange) { listener.notifyPointsUpdated(); } } /** Listener for when preferences change. */ private class HubSharedPreferenceListener implements OnSharedPreferenceChangeListener { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { listener.notifyPreferenceChanged(key); } } /** Listener for the current location (independent from track data). */ private class CurrentLocationListener implements LocationListener { @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderAvailable(status == LocationProvider.AVAILABLE); } @Override public void onProviderEnabled(String provider) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderEnabled(true); } @Override public void onProviderDisabled(String provider) { if (!LocationManager.GPS_PROVIDER.equals(provider)) return; listener.notifyLocationProviderEnabled(false); } @Override public void onLocationChanged(Location location) { listener.notifyLocationChanged(location); } } /** Listener for compass readings. */ private class CompassListener implements SensorEventListener { @Override public void onSensorChanged(SensorEvent event) { listener.notifyHeadingChanged(event.values[0]); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } } /** Wrapper for registering internal listeners. */ private final DataSourcesWrapper dataSources; // Internal listeners (to receive data from the system) private final Set<ListenerDataType> registeredListeners = EnumSet.noneOf(ListenerDataType.class); private final Handler contentHandler; private final ContentObserver pointObserver; private final ContentObserver waypointObserver; private final ContentObserver trackObserver; private final LocationListener locationListener; private final OnSharedPreferenceChangeListener preferenceListener; private final SensorEventListener compassListener; DataSourceManager(DataSourceListener listener, DataSourcesWrapper dataSources) { this.listener = listener; this.dataSources = dataSources; contentHandler = new Handler(); pointObserver = new PointObserver(); waypointObserver = new WaypointObserver(); trackObserver = new TrackObserver(); compassListener = new CompassListener(); locationListener = new CurrentLocationListener(); preferenceListener = new HubSharedPreferenceListener(); } /** Updates the internal (sensor, position, etc) listeners. */ void updateAllListeners(EnumSet<ListenerDataType> externallyNeededListeners) { EnumSet<ListenerDataType> neededListeners = EnumSet.copyOf(externallyNeededListeners); // Special case - map sampled-out points type to points type since they // correspond to the same internal listener. if (neededListeners.contains(ListenerDataType.SAMPLED_OUT_POINT_UPDATES)) { neededListeners.remove(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); neededListeners.add(ListenerDataType.POINT_UPDATES); } Log.d(TAG, "Updating internal listeners to types " + neededListeners); // Unnecessary = registered - needed Set<ListenerDataType> unnecessaryListeners = EnumSet.copyOf(registeredListeners); unnecessaryListeners.removeAll(neededListeners); // Missing = needed - registered Set<ListenerDataType> missingListeners = EnumSet.copyOf(neededListeners); missingListeners.removeAll(registeredListeners); // Remove all unnecessary listeners. for (ListenerDataType type : unnecessaryListeners) { unregisterListener(type); } // Add all missing listeners. for (ListenerDataType type : missingListeners) { registerListener(type); } // Now all needed types are registered. registeredListeners.clear(); registeredListeners.addAll(neededListeners); } private void registerListener(ListenerDataType type) { switch (type) { case COMPASS_UPDATES: { // Listen to compass Sensor compass = dataSources.getSensor(Sensor.TYPE_ORIENTATION); if (compass != null) { Log.d(TAG, "TrackDataHub: Now registering sensor listener."); dataSources.registerSensorListener(compassListener, compass, SensorManager.SENSOR_DELAY_UI); } break; } case LOCATION_UPDATES: dataSources.requestLocationUpdates(locationListener); break; case POINT_UPDATES: dataSources.registerContentObserver( TrackPointsColumns.CONTENT_URI, false, pointObserver); break; case TRACK_UPDATES: dataSources.registerContentObserver(TracksColumns.CONTENT_URI, false, trackObserver); break; case WAYPOINT_UPDATES: dataSources.registerContentObserver( WaypointsColumns.CONTENT_URI, false, waypointObserver); break; case DISPLAY_PREFERENCES: dataSources.registerOnSharedPreferenceChangeListener(preferenceListener); break; case SAMPLED_OUT_POINT_UPDATES: throw new IllegalArgumentException("Should have been mapped to point updates"); } } private void unregisterListener(ListenerDataType type) { switch (type) { case COMPASS_UPDATES: dataSources.unregisterSensorListener(compassListener); break; case LOCATION_UPDATES: dataSources.removeLocationUpdates(locationListener); break; case POINT_UPDATES: dataSources.unregisterContentObserver(pointObserver); break; case TRACK_UPDATES: dataSources.unregisterContentObserver(trackObserver); break; case WAYPOINT_UPDATES: dataSources.unregisterContentObserver(waypointObserver); break; case DISPLAY_PREFERENCES: dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListener); break; case SAMPLED_OUT_POINT_UPDATES: throw new IllegalArgumentException("Should have been mapped to point updates"); } } /** Unregisters all internal (sensor, position, etc.) listeners. */ void unregisterAllListeners() { dataSources.removeLocationUpdates(locationListener); dataSources.unregisterSensorListener(compassListener); dataSources.unregisterContentObserver(trackObserver); dataSources.unregisterContentObserver(waypointObserver); dataSources.unregisterContentObserver(pointObserver); dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListener); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/DataSourceManager.java
Java
asf20
9,034
/* * 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.content; import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS; import static com.google.android.apps.mytracks.Constants.MAX_NETWORK_AGE_MS; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.hardware.Sensor; 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.net.Uri; import android.util.Log; import android.widget.Toast; /** * Real implementation of the data sources, which talks to system services. * * @author Rodrigo Damazio */ class DataSourcesWrapperImpl implements DataSourcesWrapper { // System services private final SensorManager sensorManager; private final LocationManager locationManager; private final ContentResolver contentResolver; private final SharedPreferences sharedPreferences; private final Context context; DataSourcesWrapperImpl(Context context, SharedPreferences sharedPreferences) { this.context = context; this.sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); this.contentResolver = context.getContentResolver(); this.sharedPreferences = sharedPreferences; } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } @Override public void registerContentObserver(Uri contentUri, boolean descendents, ContentObserver observer) { contentResolver.registerContentObserver(contentUri, descendents, observer); } @Override public void unregisterContentObserver(ContentObserver observer) { contentResolver.unregisterContentObserver(observer); } @Override public Sensor getSensor(int type) { return sensorManager.getDefaultSensor(type); } @Override public void registerSensorListener(SensorEventListener listener, Sensor sensor, int sensorDelay) { sensorManager.registerListener(listener, sensor, sensorDelay); } @Override public void unregisterSensorListener(SensorEventListener listener) { sensorManager.unregisterListener(listener); } @Override public boolean isLocationProviderEnabled(String provider) { return locationManager.isProviderEnabled(provider); } @Override public void requestLocationUpdates(LocationListener listener) { // Check if the provider exists. LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER); if (gpsProvider == null) { listener.onProviderDisabled(LocationManager.GPS_PROVIDER); locationManager.removeUpdates(listener); return; } // Listen to GPS location. String providerName = gpsProvider.getName(); Log.d(Constants.TAG, "TrackDataHub: Using location provider " + providerName); locationManager.requestLocationUpdates(providerName, 0 /*minTime*/, 0 /*minDist*/, listener); // Give an initial update on provider state. if (locationManager.isProviderEnabled(providerName)) { listener.onProviderEnabled(providerName); } else { listener.onProviderDisabled(providerName); } // Listen to network location try { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60 * 5 /*minTime*/, 0 /*minDist*/, listener); } 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(Constants.TAG, "Could not register network location listener.", e); } } @Override public Location getLastKnownLocation() { // TODO: Let's look at more advanced algorithms to determine the best // current location. Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); final long now = System.currentTimeMillis(); if (loc == null || loc.getTime() < now - MAX_LOCATION_AGE_MS) { // We don't have a recent GPS fix, just use cell towers if available loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); int toastResId = R.string.my_location_approximate_location; if (loc == null || loc.getTime() < now - MAX_NETWORK_AGE_MS) { // We don't have a recent cell tower location, let the user know: toastResId = R.string.my_location_no_location; } // Let the user know we have only an approximate location: Toast.makeText(context, context.getString(toastResId), Toast.LENGTH_LONG).show(); } return loc; } @Override public void removeLocationUpdates(LocationListener listener) { locationManager.removeUpdates(listener); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/DataSourcesWrapperImpl.java
Java
asf20
6,040
/* * 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.content; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import android.util.Log; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; /** * Manager for the external data listeners and their listening types. * * @author Rodrigo Damazio */ class TrackDataListeners { /** Internal representation of a listener's registration. */ static class ListenerRegistration { final TrackDataListener listener; final EnumSet<ListenerDataType> types; // State that was last notified to the listener, for resuming after a pause. long lastTrackId; long lastPointId; int lastSamplingFrequency; int numLoadedPoints; public ListenerRegistration(TrackDataListener listener, EnumSet<ListenerDataType> types) { this.listener = listener; this.types = types; } public boolean isInterestedIn(ListenerDataType type) { return types.contains(type); } public void resetState() { lastTrackId = 0L; lastPointId = 0L; lastSamplingFrequency = 0; numLoadedPoints = 0; } @Override public String toString() { return "ListenerRegistration [listener=" + listener + ", types=" + types + ", lastTrackId=" + lastTrackId + ", lastPointId=" + lastPointId + ", lastSamplingFrequency=" + lastSamplingFrequency + ", numLoadedPoints=" + numLoadedPoints + "]"; } } /** Map of external listener to its registration details. */ private final Map<TrackDataListener, ListenerRegistration> registeredListeners = new HashMap<TrackDataListener, ListenerRegistration>(); /** * Map of external paused listener to its registration details. * This will automatically discard listeners which are GCed. */ private final WeakHashMap<TrackDataListener, ListenerRegistration> oldListeners = new WeakHashMap<TrackDataListener, ListenerRegistration>(); /** Map of data type to external listeners interested in it. */ private final Map<ListenerDataType, Set<TrackDataListener>> listenerSetsPerType = new EnumMap<ListenerDataType, Set<TrackDataListener>>(ListenerDataType.class); public TrackDataListeners() { // Create sets for all data types at startup. for (ListenerDataType type : ListenerDataType.values()) { listenerSetsPerType.put(type, new LinkedHashSet<TrackDataListener>()); } } /** * Registers a listener to send data to. * It is ok to call this method before {@link TrackDataHub#start}, and in that case * the data will only be passed to listeners when {@link TrackDataHub#start} is called. * * @param listener the listener to register * @param dataTypes the type of data that the listener is interested in */ public ListenerRegistration registerTrackDataListener(final TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) { Log.d(TAG, "Registered track data listener: " + listener); if (registeredListeners.containsKey(listener)) { throw new IllegalStateException("Listener already registered"); } ListenerRegistration registration = oldListeners.remove(listener); if (registration == null) { registration = new ListenerRegistration(listener, dataTypes); } registeredListeners.put(listener, registration); for (ListenerDataType type : dataTypes) { // This is guaranteed not to be null. Set<TrackDataListener> typeSet = listenerSetsPerType.get(type); typeSet.add(listener); } return registration; } /** * Unregisters a listener to send data to. * * @param listener the listener to unregister */ public void unregisterTrackDataListener(TrackDataListener listener) { Log.d(TAG, "Unregistered track data listener: " + listener); // Remove and keep the corresponding registration. ListenerRegistration match = registeredListeners.remove(listener); if (match == null) { Log.w(TAG, "Tried to unregister listener which is not registered."); return; } // Remove it from the per-type sets for (ListenerDataType type : match.types) { listenerSetsPerType.get(type).remove(listener); } // Keep it around in case it's re-registered soon oldListeners.put(listener, match); } public ListenerRegistration getRegistration(TrackDataListener listener) { ListenerRegistration registration = registeredListeners.get(listener); if (registration == null) { registration = oldListeners.get(listener); } return registration; } public Set<TrackDataListener> getListenersFor(ListenerDataType type) { return listenerSetsPerType.get(type); } public EnumSet<ListenerDataType> getAllRegisteredTypes() { EnumSet<ListenerDataType> listeners = EnumSet.noneOf(ListenerDataType.class); for (ListenerRegistration registration : this.registeredListeners.values()) { listeners.addAll(registration.types); } return listeners; } public boolean hasListeners() { return !registeredListeners.isEmpty(); } public int getNumListeners() { return registeredListeners.size(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/TrackDataListeners.java
Java
asf20
5,939
/* * 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.Constants; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.maps.mytracks.R; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; 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.os.Binder; import android.os.Process; 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); } private boolean canAccess() { if (Binder.getCallingPid() == Process.myPid()) { return true; } else { Context context = getContext(); SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(context.getString(R.string.allow_access_key), false); } } @Override public boolean onCreate() { if (!canAccess()) { return false; } DatabaseHelper dbHelper = new DatabaseHelper(getContext()); try { db = dbHelper.getWritableDatabase(); } catch (SQLiteException e) { Log.e(TAG, "Unable to open database for writing", e); } return db != null; } @Override public int delete(Uri url, String where, String[] selectionArgs) { if (!canAccess()) { return 0; } String table; boolean shouldVacuum = false; switch (urlMatcher.match(url)) { case TRACKPOINTS: table = TRACKPOINTS_TABLE; break; case TRACKS: table = TRACKS_TABLE; shouldVacuum = true; 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); if (shouldVacuum) { // If a potentially large amount of data was deleted, we want to reclaim its space. Log.i(TAG, "Vacuuming the database"); db.execSQL("VACUUM"); } return count; } @Override public String getType(Uri url) { if (!canAccess()) { return null; } 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) { if (!canAccess()) { return null; } 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) { if (!canAccess()) { return 0; } 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) { if (!canAccess()) { return null; } 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(Constants.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) { if (!canAccess()) { return 0; } 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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/MyTracksProvider.java
Java
asf20
17,243
/* * 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 */ } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/ContentTypeIds.java
Java
asf20
1,135
/* * 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.content; import static com.google.android.apps.mytracks.Constants.DEFAULT_MIN_REQUIRED_ACCURACY; import static com.google.android.apps.mytracks.Constants.MAX_DISPLAYED_WAYPOINTS_POINTS; import static com.google.android.apps.mytracks.Constants.MAX_LOCATION_AGE_MS; import static com.google.android.apps.mytracks.Constants.MAX_NETWORK_AGE_MS; import static com.google.android.apps.mytracks.Constants.TAG; import static com.google.android.apps.mytracks.Constants.TARGET_DISPLAYED_TRACK_POINTS; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DataSourceManager.DataSourceListener; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.DoubleBufferedLocationFactory; import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator; import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState; import com.google.android.apps.mytracks.content.TrackDataListeners.ListenerRegistration; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.hardware.GeomagneticField; import android.location.Location; import android.location.LocationManager; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.util.Collections; import java.util.EnumSet; import java.util.Set; /** * Track data hub, which receives data (both live and recorded) from many * different sources and distributes it to those interested after some standard * processing. * * TODO: Simplify the threading model here, it's overly complex and it's not obvious why * certain race conditions won't happen. * * @author Rodrigo Damazio */ public class TrackDataHub { // Preference keys private final String SELECTED_TRACK_KEY; private final String RECORDING_TRACK_KEY; private final String MIN_REQUIRED_ACCURACY_KEY; private final String METRIC_UNITS_KEY; private final String SPEED_REPORTING_KEY; // Overridable constants private final int targetNumPoints; /** Types of data that we can expose. */ public static enum ListenerDataType { /** Listen to when the selected track changes. */ SELECTED_TRACK_CHANGED, /** Listen to when the tracks change. */ TRACK_UPDATES, /** Listen to when the waypoints change. */ WAYPOINT_UPDATES, /** Listen to when the current track points change. */ POINT_UPDATES, /** * Listen to sampled-out points. * Listening to this without listening to {@link #POINT_UPDATES} * makes no sense and may yield unexpected results. */ SAMPLED_OUT_POINT_UPDATES, /** Listen to updates to the current location. */ LOCATION_UPDATES, /** Listen to updates to the current heading. */ COMPASS_UPDATES, /** Listens to changes in display preferences. */ DISPLAY_PREFERENCES; } /** Listener which receives events from the system. */ private class HubDataSourceListener implements DataSourceListener { @Override public void notifyTrackUpdated() { TrackDataHub.this.notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES)); } @Override public void notifyWaypointUpdated() { TrackDataHub.this.notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES)); } @Override public void notifyPointsUpdated() { TrackDataHub.this.notifyPointsUpdated(true, 0, 0, getListenersFor(ListenerDataType.POINT_UPDATES), getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES)); } @Override public void notifyPreferenceChanged(String key) { TrackDataHub.this.notifyPreferenceChanged(key); } @Override public void notifyLocationProviderEnabled(boolean enabled) { hasProviderEnabled = enabled; TrackDataHub.this.notifyFixType(); } @Override public void notifyLocationProviderAvailable(boolean available) { hasFix = available; TrackDataHub.this.notifyFixType(); } @Override public void notifyLocationChanged(Location loc) { TrackDataHub.this.notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } @Override public void notifyHeadingChanged(float heading) { lastSeenMagneticHeading = heading; maybeUpdateDeclination(); TrackDataHub.this.notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES)); } } // Application services private final Context context; private final MyTracksProviderUtils providerUtils; private final SharedPreferences preferences; // Get content notifications on the main thread, send listener callbacks in another. // This ensures listener calls are serialized. private HandlerThread listenerHandlerThread; private Handler listenerHandler; /** Manager for external listeners (those from activities). */ private final TrackDataListeners dataListeners; /** Wrapper for interacting with system data managers. */ private DataSourcesWrapper dataSources; /** Manager for system data listener registrations. */ private DataSourceManager dataSourceManager; /** Condensed listener for system data listener events. */ private final DataSourceListener dataSourceListener = new HubDataSourceListener(); // Cached preference values private int minRequiredAccuracy; private boolean useMetricUnits; private boolean reportSpeed; // Cached sensor readings private float declination; private long lastDeclinationUpdate; private float lastSeenMagneticHeading; // Cached GPS readings private Location lastSeenLocation; private boolean hasProviderEnabled = true; private boolean hasFix; private boolean hasGoodFix; // Transient state about the selected track private long selectedTrackId; private long firstSeenLocationId; private long lastSeenLocationId; private int numLoadedPoints; private int lastSamplingFrequency; private DoubleBufferedLocationFactory locationFactory; private boolean started = false; /** * Builds a new {@link TrackDataHub} instance. */ public synchronized static TrackDataHub newInstance(Context context) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(context); return new TrackDataHub(context, new TrackDataListeners(), preferences, providerUtils, TARGET_DISPLAYED_TRACK_POINTS); } /** * Injection constructor. */ // @VisibleForTesting TrackDataHub(Context ctx, TrackDataListeners listeners, SharedPreferences preferences, MyTracksProviderUtils providerUtils, int targetNumPoints) { this.context = ctx; this.dataListeners = listeners; this.preferences = preferences; this.providerUtils = providerUtils; this.targetNumPoints = targetNumPoints; this.locationFactory = new DoubleBufferedLocationFactory(); SELECTED_TRACK_KEY = context.getString(R.string.selected_track_key); RECORDING_TRACK_KEY = context.getString(R.string.recording_track_key); MIN_REQUIRED_ACCURACY_KEY = context.getString(R.string.min_required_accuracy_key); METRIC_UNITS_KEY = context.getString(R.string.metric_units_key); SPEED_REPORTING_KEY = context.getString(R.string.report_speed_key); resetState(); } /** * Starts listening to data sources and reporting the data to external * listeners. */ public void start() { Log.i(TAG, "TrackDataHub.start"); if (isStarted()) { Log.w(TAG, "Already started, ignoring"); return; } started = true; listenerHandlerThread = new HandlerThread("trackDataContentThread"); listenerHandlerThread.start(); listenerHandler = new Handler(listenerHandlerThread.getLooper()); dataSources = newDataSources(); dataSourceManager = new DataSourceManager(dataSourceListener, dataSources); // This may or may not register internal listeners, depending on whether // we already had external listeners. dataSourceManager.updateAllListeners(getNeededListenerTypes()); loadSharedPreferences(); // If there were listeners already registered, make sure they become up-to-date. loadDataForAllListeners(); } // @VisibleForTesting protected DataSourcesWrapper newDataSources() { return new DataSourcesWrapperImpl(context, preferences); } /** * Stops listening to data sources and reporting the data to external * listeners. */ public void stop() { Log.i(TAG, "TrackDataHub.stop"); if (!isStarted()) { Log.w(TAG, "Not started, ignoring"); return; } // Unregister internal listeners even if there are external listeners registered. dataSourceManager.unregisterAllListeners(); listenerHandlerThread.getLooper().quit(); started = false; dataSources = null; dataSourceManager = null; listenerHandlerThread = null; listenerHandler = null; } private boolean isStarted() { return started; } @Override protected void finalize() throws Throwable { if (isStarted() || (listenerHandlerThread != null && listenerHandlerThread.isAlive())) { Log.e(TAG, "Forgot to stop() TrackDataHub"); } super.finalize(); } private void loadSharedPreferences() { selectedTrackId = preferences.getLong(SELECTED_TRACK_KEY, -1); useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true); reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true); minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY, DEFAULT_MIN_REQUIRED_ACCURACY); } /** Updates known magnetic declination if needed. */ private void maybeUpdateDeclination() { if (lastSeenLocation == null) { // We still don't know where we are. return; } // Update the declination every hour long now = System.currentTimeMillis(); if (now - lastDeclinationUpdate < 60 * 60 * 1000) { return; } lastDeclinationUpdate = now; long timestamp = lastSeenLocation.getTime(); if (timestamp == 0) { // Hack for Samsung phones which don't populate the time field timestamp = now; } declination = getDeclinationFor(lastSeenLocation, timestamp); Log.i(TAG, "Updated magnetic declination to " + declination); } // @VisibleForTesting protected float getDeclinationFor(Location location, long timestamp) { GeomagneticField field = new GeomagneticField( (float) location.getLatitude(), (float) location.getLongitude(), (float) location.getAltitude(), timestamp); return field.getDeclination(); } /** * Forces the current location to be updated and reported to all listeners. * The reported location may be from the network provider if the GPS provider * is not available or doesn't have a fix. */ public void forceUpdateLocation() { if (!isStarted()) { Log.w(TAG, "Not started, not forcing location update"); return; } Log.i(TAG, "Forcing location update"); Location loc = dataSources.getLastKnownLocation(); if (loc != null) { notifyLocationChanged(loc, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } } /** Returns the ID of the currently-selected track. */ public long getSelectedTrackId() { if (!isStarted()) { loadSharedPreferences(); } return selectedTrackId; } /** Returns whether there's a track currently selected. */ public boolean isATrackSelected() { return getSelectedTrackId() > 0; } /** Returns whether the selected track is still being recorded. */ public boolean isRecordingSelected() { if (!isStarted()) { loadSharedPreferences(); } long recordingTrackId = preferences.getLong(RECORDING_TRACK_KEY, -1); return recordingTrackId > 0 && recordingTrackId == selectedTrackId; } /** * Loads the given track and makes it the currently-selected one. * It is ok to call this method before {@link #start}, and in that case * the data will only be passed to listeners when {@link #start} is called. * * @param trackId the ID of the track to load */ public void loadTrack(long trackId) { if (trackId == selectedTrackId) { Log.w(TAG, "Not reloading track, id=" + trackId); return; } // Save the selection to memory and flush. selectedTrackId = trackId; ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges( preferences.edit().putLong(SELECTED_TRACK_KEY, trackId)); // Force it to reload data from the beginning. Log.d(TAG, "Loading track"); resetState(); loadDataForAllListeners(); } /** * Resets the internal state of what data has already been loaded into listeners. */ private void resetState() { firstSeenLocationId = -1; lastSeenLocationId = -1; numLoadedPoints = 0; lastSamplingFrequency = -1; } /** * Unloads the currently-selected track. */ public void unloadCurrentTrack() { loadTrack(-1); } public void registerTrackDataListener( TrackDataListener listener, EnumSet<ListenerDataType> dataTypes) { synchronized (dataListeners) { ListenerRegistration registration = dataListeners.registerTrackDataListener(listener, dataTypes); // Don't load any data or start internal listeners if start() hasn't been // called. When it is called, we'll do both things. if (!isStarted()) return; loadNewDataForListener(registration); dataSourceManager.updateAllListeners(getNeededListenerTypes()); } } public void unregisterTrackDataListener(TrackDataListener listener) { synchronized (dataListeners) { dataListeners.unregisterTrackDataListener(listener); // Don't load any data or start internal listeners if start() hasn't been // called. When it is called, we'll do both things. if (!isStarted()) return; dataSourceManager.updateAllListeners(getNeededListenerTypes()); } } /** * Reloads all track data received so far into the specified listeners. */ public void reloadDataForListener(TrackDataListener listener) { ListenerRegistration registration; synchronized (dataListeners) { registration = dataListeners.getRegistration(listener); registration.resetState(); loadNewDataForListener(registration); } } /** * Reloads all track data received so far into the specified listeners. * * Assumes it's called from a block that synchronizes on {@link #dataListeners}. */ private void loadNewDataForListener(final ListenerRegistration registration) { if (!isStarted()) { Log.w(TAG, "Not started, not reloading"); return; } if (registration == null) { Log.w(TAG, "Not reloading for null registration"); return; } // If a listener happens to be added after this method but before the Runnable below is // executed, it will have triggered a separate call to load data only up to the point this // listener got to. This is ensured by being synchronized on listeners. final boolean isOnlyListener = (dataListeners.getNumListeners() == 1); runInListenerThread(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { // Reload everything if either it's a different track, or the track has been resampled // (this also covers the case of a new registration). boolean reloadAll = registration.lastTrackId != selectedTrackId || registration.lastSamplingFrequency != lastSamplingFrequency; Log.d(TAG, "Doing a " + (reloadAll ? "full" : "partial") + " reload for " + registration); TrackDataListener listener = registration.listener; Set<TrackDataListener> listenerSet = Collections.singleton(listener); if (registration.isInterestedIn(ListenerDataType.DISPLAY_PREFERENCES)) { reloadAll |= listener.onUnitsChanged(useMetricUnits); reloadAll |= listener.onReportSpeedChanged(reportSpeed); } if (reloadAll && registration.isInterestedIn(ListenerDataType.SELECTED_TRACK_CHANGED)) { notifySelectedTrackChanged(selectedTrackId, listenerSet); } if (registration.isInterestedIn(ListenerDataType.TRACK_UPDATES)) { notifyTrackUpdated(listenerSet); } boolean interestedInPoints = registration.isInterestedIn(ListenerDataType.POINT_UPDATES); boolean interestedInSampledOutPoints = registration.isInterestedIn(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); if (interestedInPoints || interestedInSampledOutPoints) { long minPointId = 0; int previousNumPoints = 0; if (reloadAll) { // Clear existing points and send them all again notifyPointsCleared(listenerSet); } else { // Send only new points minPointId = registration.lastPointId + 1; previousNumPoints = registration.numLoadedPoints; } // If this is the only listener we have registered, keep the state that we serve to it as // a reference for other future listeners. if (isOnlyListener && reloadAll) { resetState(); } notifyPointsUpdated(isOnlyListener, minPointId, previousNumPoints, listenerSet, interestedInSampledOutPoints ? listenerSet : Collections.EMPTY_SET); } if (registration.isInterestedIn(ListenerDataType.WAYPOINT_UPDATES)) { notifyWaypointUpdated(listenerSet); } if (registration.isInterestedIn(ListenerDataType.LOCATION_UPDATES)) { if (lastSeenLocation != null) { notifyLocationChanged(lastSeenLocation, true, listenerSet); } else { notifyFixType(); } } if (registration.isInterestedIn(ListenerDataType.COMPASS_UPDATES)) { notifyHeadingChanged(listenerSet); } } }); } /** * Reloads all track data received so far into the specified listeners. */ private void loadDataForAllListeners() { if (!isStarted()) { Log.w(TAG, "Not started, not reloading"); return; } synchronized (dataListeners) { if (!dataListeners.hasListeners()) { Log.d(TAG, "No listeners, not reloading"); return; } } runInListenerThread(new Runnable() { @Override public void run() { // Ignore the return values here, we're already sending the full data set anyway for (TrackDataListener listener : getListenersFor(ListenerDataType.DISPLAY_PREFERENCES)) { listener.onUnitsChanged(useMetricUnits); listener.onReportSpeedChanged(reportSpeed); } notifySelectedTrackChanged(selectedTrackId, getListenersFor(ListenerDataType.SELECTED_TRACK_CHANGED)); notifyTrackUpdated(getListenersFor(ListenerDataType.TRACK_UPDATES)); Set<TrackDataListener> pointListeners = getListenersFor(ListenerDataType.POINT_UPDATES); Set<TrackDataListener> sampledOutPointListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); notifyPointsCleared(pointListeners); notifyPointsUpdated(true, 0, 0, pointListeners, sampledOutPointListeners); notifyWaypointUpdated(getListenersFor(ListenerDataType.WAYPOINT_UPDATES)); if (lastSeenLocation != null) { notifyLocationChanged(lastSeenLocation, true, getListenersFor(ListenerDataType.LOCATION_UPDATES)); } else { notifyFixType(); } notifyHeadingChanged(getListenersFor(ListenerDataType.COMPASS_UPDATES)); } }); } /** * Called when a preference changes. * * @param key the key to the preference that changed */ private void notifyPreferenceChanged(String key) { if (MIN_REQUIRED_ACCURACY_KEY.equals(key)) { minRequiredAccuracy = preferences.getInt(MIN_REQUIRED_ACCURACY_KEY, DEFAULT_MIN_REQUIRED_ACCURACY); } else if (METRIC_UNITS_KEY.equals(key)) { useMetricUnits = preferences.getBoolean(METRIC_UNITS_KEY, true); notifyUnitsChanged(); } else if (SPEED_REPORTING_KEY.equals(key)) { reportSpeed = preferences.getBoolean(SPEED_REPORTING_KEY, true); notifySpeedReportingChanged(); } else if (SELECTED_TRACK_KEY.equals(key)) { long trackId = preferences.getLong(SELECTED_TRACK_KEY, -1); loadTrack(trackId); } } /** Called when the speed/pace reporting preference changes. */ private void notifySpeedReportingChanged() { if (!isStarted()) return; runInListenerThread(new Runnable() { @Override public void run() { Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES); for (TrackDataListener listener : displayListeners) { // TODO: Do the reloading just once for all interested listeners if (listener.onReportSpeedChanged(reportSpeed)) { synchronized (dataListeners) { reloadDataForListener(listener); } } } } }); } /** Called when the metric units setting changes. */ private void notifyUnitsChanged() { if (!isStarted()) return; runInListenerThread(new Runnable() { @Override public void run() { Set<TrackDataListener> displayListeners = getListenersFor(ListenerDataType.DISPLAY_PREFERENCES); for (TrackDataListener listener : displayListeners) { if (listener.onUnitsChanged(useMetricUnits)) { synchronized (dataListeners) { reloadDataForListener(listener); } } } } }); } /** Notifies about the current GPS fix state. */ private void notifyFixType() { final TrackDataListener.ProviderState state; if (!hasProviderEnabled) { state = ProviderState.DISABLED; } else if (!hasFix) { state = ProviderState.NO_FIX; } else if (!hasGoodFix) { state = ProviderState.BAD_FIX; } else { state = ProviderState.GOOD_FIX; } runInListenerThread(new Runnable() { @Override public void run() { // Notify to everyone. Log.d(TAG, "Notifying fix type: " + state); for (TrackDataListener listener : getListenersFor(ListenerDataType.LOCATION_UPDATES)) { listener.onProviderStateChange(state); } } }); } /** * Notifies the the current location has changed, without any filtering. * If the state of GPS fix has changed, that will also be reported. * * @param location the current location * @param listeners the listeners to notify */ private void notifyLocationChanged(Location location, Set<TrackDataListener> listeners) { notifyLocationChanged(location, false, listeners); } /** * Notifies that the current location has changed, without any filtering. * If the state of GPS fix has changed, that will also be reported. * * @param location the current location * @param forceUpdate whether to force the notifications to happen * @param listeners the listeners to notify */ private void notifyLocationChanged(Location location, boolean forceUpdate, final Set<TrackDataListener> listeners) { if (location == null) return; if (listeners.isEmpty()) return; boolean isGpsLocation = location.getProvider().equals(LocationManager.GPS_PROVIDER); boolean oldHasFix = hasFix; boolean oldHasGoodFix = hasGoodFix; long now = System.currentTimeMillis(); if (isGpsLocation) { // We consider a good fix to be a recent one with reasonable accuracy. hasFix = !isLocationOld(location, now, MAX_LOCATION_AGE_MS); hasGoodFix = (location.getAccuracy() <= minRequiredAccuracy); } else { if (!isLocationOld(lastSeenLocation, now, MAX_LOCATION_AGE_MS)) { // This is a network location, but we have a recent/valid GPS location, just ignore this. return; } // We haven't gotten a GPS location in a while (or at all), assume we have no fix anymore. hasFix = false; hasGoodFix = false; // If the network location is recent, we'll use that. if (isLocationOld(location, now, MAX_NETWORK_AGE_MS)) { // Alas, we have no clue where we are. location = null; } } if (hasFix != oldHasFix || hasGoodFix != oldHasGoodFix || forceUpdate) { notifyFixType(); } lastSeenLocation = location; final Location finalLoc = location; runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onCurrentLocationChanged(finalLoc); } } }); } /** * Returns true if the given location is either invalid or too old. * * @param location the location to test * @param now the current timestamp in milliseconds * @param maxAge the maximum age in milliseconds * @return true if it's invalid or too old, false otherwise */ private static boolean isLocationOld(Location location, long now, long maxAge) { return !LocationUtils.isValidLocation(location) || now - location.getTime() > maxAge; } /** * Notifies that the current heading has changed. * * @param listeners the listeners to notify */ private void notifyHeadingChanged(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { float heading = lastSeenMagneticHeading + declination; for (TrackDataListener listener : listeners) { listener.onCurrentHeadingChanged(heading); } } }); } /** * Notifies that a new track has been selected.. * * @param trackId the new selected track * @param listeners the listeners to notify */ private void notifySelectedTrackChanged(long trackId, final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; Log.i(TAG, "New track selected, id=" + trackId); final Track track = providerUtils.getTrack(trackId); runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onSelectedTrackChanged(track, isRecordingSelected()); } } }); } /** * Notifies that the currently-selected track's data has been updated. * * @param listeners the listeners to notify */ private void notifyTrackUpdated(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; final Track track = providerUtils.getTrack(selectedTrackId); runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.onTrackUpdated(track); } } }); } /** * Notifies that waypoints have been updated. * We assume few waypoints, so we reload them all every time. * * @param listeners the listeners to notify */ private void notifyWaypointUpdated(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; // Always reload all the waypoints. final Cursor cursor = providerUtils.getWaypointsCursor( selectedTrackId, 0L, MAX_DISPLAYED_WAYPOINTS_POINTS); runInListenerThread(new Runnable() { @Override public void run() { Log.d(TAG, "Reloading waypoints"); for (TrackDataListener listener : listeners) { listener.clearWaypoints(); } try { if (cursor != null && cursor.moveToFirst()) { do { Waypoint waypoint = providerUtils.createWaypoint(cursor); if (!LocationUtils.isValidLocation(waypoint.getLocation())) { continue; } for (TrackDataListener listener : listeners) { listener.onNewWaypoint(waypoint); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } for (TrackDataListener listener : listeners) { listener.onNewWaypointsDone(); } } }); } /** * Tells listeners to clear the current list of points. * * @param listeners the listeners to notify */ private void notifyPointsCleared(final Set<TrackDataListener> listeners) { if (listeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { for (TrackDataListener listener : listeners) { listener.clearTrackPoints(); } } }); } /** * Notifies the given listeners about track points in the given ID range. * * @param keepState whether to load and save state about the already-notified points. * If true, only new points are reported. * If false, then the whole track will be loaded, without affecting the state. * @param minPointId the first point ID to notify, inclusive, or 0 to determine from * internal state * @param previousNumPoints the number of points to assume were previously loaded for * these listeners, or 0 to assume it's the kept state */ private void notifyPointsUpdated(final boolean keepState, final long minPointId, final int previousNumPoints, final Set<TrackDataListener> sampledListeners, final Set<TrackDataListener> sampledOutListeners) { if (sampledListeners.isEmpty() && sampledOutListeners.isEmpty()) return; runInListenerThread(new Runnable() { @Override public void run() { notifyPointsUpdatedSync(keepState, minPointId, previousNumPoints, sampledListeners, sampledOutListeners); } }); } /** * Synchronous version of the above method. */ private void notifyPointsUpdatedSync(boolean keepState, long minPointId, int previousNumPoints, Set<TrackDataListener> sampledListeners, Set<TrackDataListener> sampledOutListeners) { // If we're loading state, start from after the last seen point up to the last recorded one // (all new points) // If we're not loading state, then notify about all the previously-seen points. if (minPointId <= 0) { minPointId = keepState ? lastSeenLocationId + 1 : 0; } long maxPointId = keepState ? -1 : lastSeenLocationId; // TODO: Move (re)sampling to a separate class. if (numLoadedPoints >= targetNumPoints) { // We're about to exceed the maximum desired number of points, so reload // the whole track with fewer points (the sampling frequency will be // lower). We do this for every listener even if we were loading just for // a few of them (why miss the oportunity?). Log.i(TAG, "Resampling point set after " + numLoadedPoints + " points."); resetState(); synchronized (dataListeners) { sampledListeners = getListenersFor(ListenerDataType.POINT_UPDATES); sampledOutListeners = getListenersFor(ListenerDataType.SAMPLED_OUT_POINT_UPDATES); } maxPointId = -1; minPointId = 0; previousNumPoints = 0; keepState = true; for (TrackDataListener listener : sampledListeners) { listener.clearTrackPoints(); } } // Keep the originally selected track ID so we can stop if it changes. long currentSelectedTrackId = selectedTrackId; // If we're ignoring state, start from the beginning of the track int localNumLoadedPoints = previousNumPoints; if (previousNumPoints <= 0) { localNumLoadedPoints = keepState ? numLoadedPoints : 0; } long localFirstSeenLocationId = keepState ? firstSeenLocationId : -1; long localLastSeenLocationId = minPointId; long lastStoredLocationId = providerUtils.getLastLocationId(currentSelectedTrackId); int pointSamplingFrequency = -1; LocationIterator it = providerUtils.getLocationIterator( currentSelectedTrackId, minPointId, false, locationFactory); while (it.hasNext()) { if (currentSelectedTrackId != selectedTrackId) { // The selected track changed beneath us, stop. break; } Location location = it.next(); long locationId = it.getLocationId(); // If past the last wanted point, stop. // This happens when adding a new listener after data has already been loaded, // in which case we only want to bring that listener up to the point where the others // were. In case it does happen, we should be wasting few points (only the ones not // yet notified to other listeners). if (maxPointId > 0 && locationId > maxPointId) { break; } if (localFirstSeenLocationId == -1) { // This was our first point, keep its ID localFirstSeenLocationId = locationId; } if (pointSamplingFrequency == -1) { // Now we already have at least one point, calculate the sampling // frequency. // It should be noted that a non-obvious consequence of this sampling is that // no matter how many points we get in the newest batch, we'll never exceed // MAX_DISPLAYED_TRACK_POINTS = 2 * TARGET_DISPLAYED_TRACK_POINTS before resampling. long numTotalPoints = lastStoredLocationId - localFirstSeenLocationId; numTotalPoints = Math.max(0L, numTotalPoints); pointSamplingFrequency = (int) (1 + numTotalPoints / targetNumPoints); } notifyNewPoint(location, locationId, lastStoredLocationId, localNumLoadedPoints, pointSamplingFrequency, sampledListeners, sampledOutListeners); localNumLoadedPoints++; localLastSeenLocationId = locationId; } it.close(); if (keepState) { numLoadedPoints = localNumLoadedPoints; firstSeenLocationId = localFirstSeenLocationId; lastSeenLocationId = localLastSeenLocationId; } // Always keep the sampling frequency - if it changes we'll do a full reload above anyway. lastSamplingFrequency = pointSamplingFrequency; for (TrackDataListener listener : sampledListeners) { listener.onNewTrackPointsDone(); // Update the listener state ListenerRegistration registration = dataListeners.getRegistration(listener); if (registration != null) { registration.lastTrackId = currentSelectedTrackId; registration.lastPointId = localLastSeenLocationId; registration.lastSamplingFrequency = pointSamplingFrequency; registration.numLoadedPoints = localNumLoadedPoints; } } } private void notifyNewPoint(Location location, long locationId, long lastStoredLocationId, int loadedPoints, int pointSamplingFrequency, Set<TrackDataListener> sampledListeners, Set<TrackDataListener> sampledOutListeners) { boolean isValid = LocationUtils.isValidLocation(location); if (!isValid) { // Invalid points are segment splits - report those separately. // TODO: Always send last valid point before and first valid point after a split for (TrackDataListener listener : sampledListeners) { listener.onSegmentSplit(); } return; } // 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. boolean recordingSelected = isRecordingSelected(); boolean includeInSample = (loadedPoints % pointSamplingFrequency == 0 || (!recordingSelected && locationId == lastStoredLocationId)); if (!includeInSample) { for (TrackDataListener listener : sampledOutListeners) { listener.onSampledOutTrackPoint(location); } } else { // Point is valid and included in sample. for (TrackDataListener listener : sampledListeners) { // No need to allocate a new location (we can safely reuse the existing). listener.onNewTrackPoint(location); } } } // @VisibleForTesting protected void runInListenerThread(Runnable runnable) { if (listenerHandler == null) { // Use a Throwable to ensure the stack trace is logged. Log.e(TAG, "Tried to use listener thread before start()", new Throwable()); return; } listenerHandler.post(runnable); } private Set<TrackDataListener> getListenersFor(ListenerDataType type) { synchronized (dataListeners) { return dataListeners.getListenersFor(type); } } private EnumSet<ListenerDataType> getNeededListenerTypes() { EnumSet<ListenerDataType> neededTypes = dataListeners.getAllRegisteredTypes(); // We always want preference updates. neededTypes.add(ListenerDataType.DISPLAY_PREFERENCES); return neededTypes; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java
Java
asf20
38,004
/* * 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.content; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import android.location.Location; /** * Listener for track data, for both initial and incremental loading. * * @author Rodrigo Damazio */ public interface TrackDataListener { /** States for the GPS location provider. */ public enum ProviderState { DISABLED, NO_FIX, BAD_FIX, GOOD_FIX; } /** * Called when the location provider changes state. */ void onProviderStateChange(ProviderState state); /** * Called when the current location changes. * This is meant for immediate location display only - track point data is * delivered by other methods below, such as {@link #onNewTrackPoint}. * * @param loc the last known location */ void onCurrentLocationChanged(Location loc); /** * Called when the current heading changes. * * @param heading the current heading, already accounting magnetic declination */ void onCurrentHeadingChanged(double heading); /** * Called when the currently-selected track changes. * This will be followed by calls to data methods such as * {@link #onTrackUpdated}, {@link #clearTrackPoints}, * {@link #onNewTrackPoint(Location)}, etc., even if no track is currently * selected (in which case you'll only get calls to clear the current data). * * @param track the selected track, or null if no track is selected * @param isRecording whether we're currently recording the selected track */ void onSelectedTrackChanged(Track track, boolean isRecording); /** * Called when the track and/or its statistics have been updated. * * @param track the updated version of the track */ void onTrackUpdated(Track track); /** * Called to clear any previously-sent track points. * This can be called at any time that we decide the data needs to be * reloaded, such as when it needs to be resampled. */ void clearTrackPoints(); /** * Called when a new interesting track point is read. * In this case, interesting means that the point has already undergone * sampling and invalid point filtering. * * @param loc the new track point */ void onNewTrackPoint(Location loc); /** * Called when a uninteresting track point is read. * Uninteresting points are all points that get sampled out of the track. * * @param loc the new track point */ void onSampledOutTrackPoint(Location loc); /** * Called when an invalid point (representing a segment split) is read. */ void onSegmentSplit(); /** * Called when we're done (for the time being) sending new points. * This gets called after every batch of calls to {@link #onNewTrackPoint}, * {@link #onSampledOutTrackPoint} and {@link #onSegmentSplit}. */ void onNewTrackPointsDone(); /** * Called to clear any previously-sent waypoints. * This can be called at any time that we decide the data needs to be * reloaded. */ void clearWaypoints(); /** * Called when a new waypoint is read. * * @param wpt the new waypoint */ void onNewWaypoint(Waypoint wpt); /** * Called when we're done (for the time being) sending new waypoints. * This gets called after every batch of calls to {@link #clearWaypoints} and * {@link #onNewWaypoint}. */ void onNewWaypointsDone(); /** * Called when the display units are changed by the user. * * @param metric true if the units are metric, false if imperial * @return true to reload all the data, false otherwise */ boolean onUnitsChanged(boolean metric); /** * Called when the speed/pace display unit is changed by the user. * * @param reportSpeed true to report speed, false for pace * @return true to reload all the data, false otherwise */ boolean onReportSpeedChanged(boolean reportSpeed); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/TrackDataListener.java
Java
asf20
4,537
/* * 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.content; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.hardware.Sensor; import android.hardware.SensorEventListener; import android.location.Location; import android.location.LocationListener; import android.net.Uri; /** * Interface for abstracting registration of external data source listeners. * * @author Rodrigo Damazio */ interface DataSourcesWrapper { // Preferences void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener); void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener); // Content provider void registerContentObserver(Uri contentUri, boolean descendents, ContentObserver observer); void unregisterContentObserver(ContentObserver observer); // Sensors Sensor getSensor(int type); void registerSensorListener(SensorEventListener listener, Sensor sensor, int sensorDelay); void unregisterSensorListener(SensorEventListener listener); // Location boolean isLocationProviderEnabled(String provider); void requestLocationUpdates(LocationListener listener); void removeLocationUpdates(LocationListener listener); Location getLastKnownLocation(); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/content/DataSourcesWrapper.java
Java
asf20
1,913
/* * 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 android.app.Activity; import android.util.Log; import android.widget.TextView; import java.text.NumberFormat; /** * 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 = NumberFormat.getNumberInstance(); private static final NumberFormat ALTITUDE_FORMAT = NumberFormat.getIntegerInstance(); private static final NumberFormat SPEED_FORMAT = NumberFormat.getNumberInstance(); private static final NumberFormat GRADE_FORMAT = NumberFormat.getPercentInstance(); static { LAT_LONG_FORMAT.setMaximumFractionDigits(5); LAT_LONG_FORMAT.setMinimumFractionDigits(5); SPEED_FORMAT.setMaximumFractionDigits(2); SPEED_FORMAT.setMinimumFractionDigits(2); GRADE_FORMAT.setMaximumFractionDigits(1); GRADE_FORMAT.setMinimumFractionDigits(1); } /** * 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.value_unknown); } public void setText(int id, double d, NumberFormat format) { if (!Double.isNaN(d) && !Double.isInfinite(d)) { setText(id, format.format(d)); } else { setUnknown(id); } } 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.unit_meter : R.string.unit_feet); } public void setDistanceUnits(int unitLabelId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(metricUnits ? R.string.unit_kilometer : R.string.unit_mile); } public void setSpeedUnits(int unitLabelId, int unitLabelBottomId) { TextView unitTextView = (TextView) activity.findViewById(unitLabelId); unitTextView.setText(reportSpeed ? (metricUnits ? R.string.unit_kilometer : R.string.unit_mile) : R.string.unit_minute); unitTextView = (TextView) activity.findViewById(unitLabelBottomId); unitTextView.setText(reportSpeed ? R.string.unit_hour : (metricUnits ? R.string.unit_kilometer : R.string.unit_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(Constants.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(Constants.TAG, "Could not find id: " + id); } } public void setSpeedLabels() { setSpeedLabel(R.id.average_speed_label, R.string.stat_average_speed, R.string.stat_average_pace); setSpeedLabel(R.id.average_moving_speed_label, R.string.stat_average_moving_speed, R.string.stat_average_moving_pace); setSpeedLabel(R.id.max_speed_label, R.string.stat_max_speed, R.string.stat_min_pace); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/StatsUtilities.java
Java
asf20
9,192
/* * 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; private OnClickListener clickListener; 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) { if (clickListener != null) { clickListener.onClick(ChartSettingsDialog.this, BUTTON_NEGATIVE); } dismiss(); } }); Button okButton = (Button) findViewById(R.id.chart_settings_ok); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (clickListener != null) { clickListener.onClick(ChartSettingsDialog.this, BUTTON_POSITIVE); } dismiss(); } }); 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 setMode(Mode mode) { RadioGroup rd = (RadioGroup) findViewById(R.id.chart_settings_x); rd.check(mode == Mode.BY_DISTANCE ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); } public void setSeriesEnabled(int seriesIdx, boolean enabled) { series[seriesIdx].setChecked(enabled); } public Mode getMode() { if (distance == null) return Mode.BY_DISTANCE; return distance.isChecked() ? Mode.BY_DISTANCE : Mode.BY_TIME; } public boolean isSeriesEnabled(int seriesIdx) { if (series == null) return true; return series[seriesIdx].isChecked(); } public void setOnClickListener(OnClickListener clickListener) { this.clickListener = clickListener; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ChartSettingsDialog.java
Java
asf20
3,574
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.io.backup.BackupActivityHelper; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.sensors.ant.AntUtils; import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.BluetoothDeviceUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * An activity that let's the user see and edit the settings. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class SettingsActivity extends PreferenceActivity { // Value when the task frequency is off. private static final String TASK_FREQUENCY_OFF = "0"; // Value when the recording interval is 'Adapt battery life'. private static final String RECORDING_INTERVAL_ADAPT_BATTERY_LIFE = "-2"; // Value when the recording interval is 'Adapt accuracy'. private static final String RECORDING_INTERVAL_ADAPT_ACCURACY = "-1"; // Value for the recommended recording interval. private static final String RECORDING_INTERVAL_RECOMMENDED = "0"; // Value when the auto resume timeout is never. private static final String AUTO_RESUME_TIMEOUT_NEVER = "0"; // Value when the auto resume timeout is always. private static final String AUTO_RESUME_TIMEOUT_ALWAYS = "-1"; // Value for the recommended recording distance. private static final String RECORDING_DISTANCE_RECOMMENDED = "5"; // Value for the recommended track distance. private static final String TRACK_DISTANCE_RECOMMENDED = "200"; // Value for the recommended GPS accuracy. private static final String GPS_ACCURACY_RECOMMENDED = "200"; // Value when the GPS accuracy is for excellent GPS signal. private static final String GPS_ACCURACY_EXCELLENT = "10"; // Value when the GPS accuracy is for poor GPS signal. private static final String GPS_ACCURACY_POOR = "5000"; private BackupPreferencesListener backupListener; private SharedPreferences preferences; /** Called when the activity is first created. */ @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); // The volume we want to control is the Text-To-Speech volume ApiFeatures apiFeatures = ApiFeatures.getInstance(); int volumeStream = new StatusAnnouncerFactory(apiFeatures).getVolumeStream(); setVolumeControlStream(volumeStream); // Tell it where to read/write preferences PreferenceManager preferenceManager = getPreferenceManager(); preferenceManager.setSharedPreferencesName(Constants.SETTINGS_NAME); preferenceManager.setSharedPreferencesMode(0); // Set up automatic preferences backup backupListener = apiFeatures.getApiAdapter().getBackupPreferencesListener(this); preferences = preferenceManager.getSharedPreferences(); preferences.registerOnSharedPreferenceChangeListener(backupListener); // Load the preferences to be displayed addPreferencesFromResource(R.xml.preferences); // Disable voice announcement if not available if (!apiFeatures.hasTextToSpeech()) { IntegerListPreference announcementFrequency = (IntegerListPreference) findPreference( getString(R.string.announcement_frequency_key)); announcementFrequency.setEnabled(false); announcementFrequency.setValue(TASK_FREQUENCY_OFF); announcementFrequency.setSummary(R.string.settings_recording_voice_not_available); } setRecordingIntervalOptions(); setAutoResumeTimeoutOptions(); // 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; updateDisplayOptions(isMetric); return true; } }); updateDisplayOptions(metricUnitsPreference.isChecked()); customizeSensorOptionsPreferences(); customizeTrackColorModePreferences(); // Hook up action for resetting all settings Preference resetPreference = findPreference(getString(R.string.reset_key)); resetPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference arg0) { onResetPreferencesClick(); return true; } }); // Add a confirmation dialog for the 'Allow access' preference. final CheckBoxPreference allowAccessPreference = (CheckBoxPreference) findPreference( getString(R.string.allow_access_key)); allowAccessPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if ((Boolean) newValue) { AlertDialog dialog = new AlertDialog.Builder(SettingsActivity.this) .setCancelable(true) .setTitle(getString(R.string.settings_sharing_allow_access)) .setMessage(getString(R.string.settings_sharing_allow_access_confirm_message)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int button) { allowAccessPreference.setChecked(true); } }) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); return false; } else { return true; } } }); } /** * Sets the display options for the 'Time between points' option. */ private void setRecordingIntervalOptions() { String[] values = getResources().getStringArray(R.array.recording_interval_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(RECORDING_INTERVAL_ADAPT_BATTERY_LIFE)) { options[i] = getString(R.string.value_adapt_battery_life); } else if (values[i].equals(RECORDING_INTERVAL_ADAPT_ACCURACY)) { options[i] = getString(R.string.value_adapt_accuracy); } else if (values[i].equals(RECORDING_INTERVAL_RECOMMENDED)) { options[i] = getString(R.string.value_smallest_recommended); } else { int value = Integer.parseInt(values[i]); String format; if (value < 60) { format = getString(R.string.value_integer_second); } else { value = value / 60; format = getString(R.string.value_integer_minute); } options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference( getString(R.string.min_recording_interval_key)); list.setEntries(options); } /** * Sets the display options for the 'Auto-resume timeout' option. */ private void setAutoResumeTimeoutOptions() { String[] values = getResources().getStringArray(R.array.recording_auto_resume_timeout_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(AUTO_RESUME_TIMEOUT_NEVER)) { options[i] = getString(R.string.value_never); } else if (values[i].equals(AUTO_RESUME_TIMEOUT_ALWAYS)) { options[i] = getString(R.string.value_always); } else { int value = Integer.parseInt(values[i]); String format = getString(R.string.value_integer_minute); options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference( getString(R.string.auto_resume_track_timeout_key)); list.setEntries(options); } private void customizeSensorOptionsPreferences() { ListPreference sensorTypePreference = (ListPreference) findPreference(getString(R.string.sensor_type_key)); sensorTypePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { updateSensorSettings((String) newValue); return true; } }); updateSensorSettings(sensorTypePreference.getValue()); if (!AntUtils.hasAntSupport(this)) { // The sensor options screen has a few ANT-specific options which we // need to remove. First, we need to remove the ANT sensor types. // Second, we need to remove the ANT unpairing options. Set<Integer> toRemove = new HashSet<Integer>(); String[] antValues = getResources().getStringArray(R.array.sensor_type_ant_values); for (String antValue : antValues) { toRemove.add(sensorTypePreference.findIndexOfValue(antValue)); } CharSequence[] entries = sensorTypePreference.getEntries(); CharSequence[] entryValues = sensorTypePreference.getEntryValues(); CharSequence[] filteredEntries = new CharSequence[entries.length - toRemove.size()]; CharSequence[] filteredEntryValues = new CharSequence[filteredEntries.length]; for (int i = 0, last = 0; i < entries.length; i++) { if (!toRemove.contains(i)) { filteredEntries[last] = entries[i]; filteredEntryValues[last++] = entryValues[i]; } } sensorTypePreference.setEntries(filteredEntries); sensorTypePreference.setEntryValues(filteredEntryValues); PreferenceScreen sensorOptionsScreen = (PreferenceScreen) findPreference(getString(R.string.sensor_options_key)); sensorOptionsScreen.removePreference(findPreference(getString(R.string.ant_options_key))); } } private void customizeTrackColorModePreferences() { ListPreference trackColorModePreference = (ListPreference) findPreference(getString(R.string.track_color_mode_key)); trackColorModePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { updateTrackColorModeSettings((String) newValue); return true; } }); updateTrackColorModeSettings(trackColorModePreference.getValue()); setTrackColorModePreferenceListeners(); PreferenceCategory speedOptionsCategory = (PreferenceCategory) findPreference( getString(R.string.track_color_mode_fixed_speed_options_key)); speedOptionsCategory.removePreference( findPreference(getString(R.string.track_color_mode_fixed_speed_slow_key))); speedOptionsCategory.removePreference( findPreference(getString(R.string.track_color_mode_fixed_speed_medium_key))); } @Override protected void onResume() { super.onResume(); configureBluetoothPreferences(); Preference backupNowPreference = findPreference(getString(R.string.backup_to_sd_key)); Preference restoreNowPreference = findPreference(getString(R.string.restore_from_sd_key)); Preference resetPreference = findPreference(getString(R.string.reset_key)); // If recording, disable backup/restore/reset // (we don't want to get to inconsistent states) boolean recording = preferences.getLong(getString(R.string.recording_track_key), -1) != -1; backupNowPreference.setEnabled(!recording); restoreNowPreference.setEnabled(!recording); resetPreference.setEnabled(!recording); backupNowPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_backup_now_summary); restoreNowPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_backup_restore_summary); resetPreference.setSummary( recording ? R.string.settings_not_while_recording : R.string.settings_reset_summary); // Add actions to the backup preferences backupNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(SettingsActivity.this); backupHelper.writeBackup(); return true; } }); restoreNowPreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { BackupActivityHelper backupHelper = new BackupActivityHelper(SettingsActivity.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.sensor_type_value_zephyr).equals(sensorType) || getString(R.string.sensor_type_value_polar).equals(sensorType); findPreference( getString(R.string.bluetooth_sensor_key)).setEnabled(usesBluetooth); findPreference( getString(R.string.bluetooth_pairing_key)).setEnabled(usesBluetooth); // Update the ANT+ sensors. // TODO: Only enable on phones that have ANT+. Preference antHrm = findPreference(getString(R.string.ant_heart_rate_sensor_id_key)); Preference antSrm = findPreference(getString(R.string.ant_srm_bridge_sensor_id_key)); if (antHrm != null && antSrm != null) { antHrm .setEnabled(getString(R.string.sensor_type_value_ant).equals(sensorType)); antSrm .setEnabled(getString(R.string.sensor_type_value_srm_ant_bridge).equals(sensorType)); } } private void updateTrackColorModeSettings(String trackColorMode) { boolean usesFixedSpeed = trackColorMode.equals(getString(R.string.display_track_color_value_fixed)); boolean usesDynamicSpeed = trackColorMode.equals(getString(R.string.display_track_color_value_dynamic)); findPreference(getString(R.string.track_color_mode_fixed_speed_slow_display_key)) .setEnabled(usesFixedSpeed); findPreference(getString(R.string.track_color_mode_fixed_speed_medium_display_key)) .setEnabled(usesFixedSpeed); findPreference(getString(R.string.track_color_mode_dynamic_speed_variation_key)) .setEnabled(usesDynamicSpeed); } /** * Updates display options that depends on the preferred distance units, metric or imperial. * * @param isMetric true to use metric units, false to use imperial */ private void updateDisplayOptions(boolean isMetric) { setTaskOptions(isMetric, R.string.announcement_frequency_key); setTaskOptions(isMetric, R.string.split_frequency_key); setRecordingDistanceOptions(isMetric, R.string.min_recording_distance_key); setTrackDistanceOptions(isMetric, R.string.max_recording_distance_key); setGpsAccuracyOptions(isMetric, R.string.min_required_accuracy_key); } /** * Sets the display options for a periodic task. */ private void setTaskOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_task_frequency_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i].equals(TASK_FREQUENCY_OFF)) { options[i] = getString(R.string.value_off); } else if (values[i].startsWith("-")) { int value = Integer.parseInt(values[i].substring(1)); int stringId = isMetric ? R.string.value_integer_kilometer : R.string.value_integer_mile; String format = getString(stringId); options[i] = String.format(format, value); } else { int value = Integer.parseInt(values[i]); String format = getString(R.string.value_integer_minute); options[i] = String.format(format, value); } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'Distance between points' option. */ private void setRecordingDistanceOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_distance_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); if (!isMetric) { value = (int) (value * UnitConversions.M_TO_FT); } String format; if (values[i].equals(RECORDING_DISTANCE_RECOMMENDED)) { int stringId = isMetric ? R.string.value_integer_meter_recommended : R.string.value_integer_feet_recommended; format = getString(stringId); } else { int stringId = isMetric ? R.string.value_integer_meter : R.string.value_integer_feet; format = getString(stringId); } options[i] = String.format(format, value); } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'Distance between Tracks'. */ private void setTrackDistanceOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_track_distance_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); String format; if (isMetric) { int stringId = values[i].equals(TRACK_DISTANCE_RECOMMENDED) ? R.string.value_integer_meter_recommended : R.string.value_integer_meter; format = getString(stringId); options[i] = String.format(format, value); } else { value = (int) (value * UnitConversions.M_TO_FT); if (value < 2000) { int stringId = values[i].equals(TRACK_DISTANCE_RECOMMENDED) ? R.string.value_integer_feet_recommended : R.string.value_integer_feet; format = getString(stringId); options[i] = String.format(format, value); } else { double mile = value / UnitConversions.MI_TO_FEET; format = getString(R.string.value_float_mile); options[i] = String.format(format, mile); } } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Sets the display options for 'GPS accuracy'. */ private void setGpsAccuracyOptions(boolean isMetric, int listId) { String[] values = getResources().getStringArray(R.array.recording_gps_accuracy_values); String[] options = new String[values.length]; for (int i = 0; i < values.length; i++) { int value = Integer.parseInt(values[i]); String format; if (isMetric) { if (values[i].equals(GPS_ACCURACY_RECOMMENDED)) { format = getString(R.string.value_integer_meter_recommended); } else if (values[i].equals(GPS_ACCURACY_EXCELLENT)) { format = getString(R.string.value_integer_meter_excellent_gps); } else if (values[i].equals(GPS_ACCURACY_POOR)) { format = getString(R.string.value_integer_meter_poor_gps); } else { format = getString(R.string.value_integer_meter); } options[i] = String.format(format, value); } else { value = (int) (value * UnitConversions.M_TO_FT); if (value < 2000) { if (values[i].equals(GPS_ACCURACY_RECOMMENDED)) { format = getString(R.string.value_integer_feet_recommended); } else if (values[i].equals(GPS_ACCURACY_EXCELLENT)) { format = getString(R.string.value_integer_feet_excellent_gps); } else { format = getString(R.string.value_integer_feet); } options[i] = String.format(format, value); } else { double mile = value / UnitConversions.MI_TO_FEET; if (values[i].equals(GPS_ACCURACY_POOR)) { format = getString(R.string.value_float_mile_poor_gps); } else { format = getString(R.string.value_float_mile); } options[i] = String.format(format, mile); } } } ListPreference list = (ListPreference) findPreference(getString(listId)); list.setEntries(options); } /** * Configures preference actions related to bluetooth. */ private void configureBluetoothPreferences() { 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); } /** Callback for when user asks to reset all settings. */ private void onResetPreferencesClick() { AlertDialog dialog = new AlertDialog.Builder(this) .setCancelable(true) .setTitle(R.string.settings_reset) .setMessage(R.string.settings_reset_dialog_message) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int button) { onResetPreferencesConfirmed(); } }) .setNegativeButton(android.R.string.cancel, null) .create(); dialog.show(); } /** Callback for when user confirms resetting all settings. */ private void onResetPreferencesConfirmed() { // Change preferences in a separate thread. new Thread() { @Override public void run() { Log.i(TAG, "Resetting all settings"); // Actually wipe preferences (and save synchronously). preferences.edit().clear().commit(); // Give UI feedback in the UI thread. runOnUiThread(new Runnable() { @Override public void run() { // Give feedback to the user. Toast.makeText( SettingsActivity.this, R.string.settings_reset_done, Toast.LENGTH_SHORT).show(); // Restart the settings activity so all changes are loaded. Intent intent = getIntent(); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); } }.start(); } /** * Set the given edit text preference text. * If the units are not metric convert the value before displaying. */ private void viewTrackColorModeSettings(EditTextPreference preference, int id) { CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); if(metricUnitsPreference.isChecked()) { return; } // Convert miles/h to km/h SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); String metricspeed = prefs.getString(getString(id), null); int englishspeed; try { englishspeed = (int) (Double.parseDouble(metricspeed) * UnitConversions.KMH_TO_MPH); } catch (NumberFormatException e) { englishspeed = 0; } preference.getEditText().setText(String.valueOf(englishspeed)); } /** * Saves the given edit text preference value. * If the units are not metric convert the value before saving. */ private void validateTrackColorModeSettings(String newValue, int id) { CheckBoxPreference metricUnitsPreference = (CheckBoxPreference) findPreference( getString(R.string.metric_units_key)); String metricspeed; if(!metricUnitsPreference.isChecked()) { // Convert miles/h to km/h try { metricspeed = String.valueOf( (int) (Double.parseDouble(newValue) * UnitConversions.MPH_TO_KMH) + 1); } catch (NumberFormatException e) { metricspeed = "0"; } } else { metricspeed = newValue; } SharedPreferences prefs = getPreferenceManager().getSharedPreferences(); Editor editor = prefs.edit(); editor.putString(getString(id), metricspeed); ApiFeatures.getInstance().getApiAdapter().applyPreferenceChanges(editor); } /** * Sets the TrackColorMode preference listeners. */ private void setTrackColorModePreferenceListeners() { setTrackColorModePreferenceListener(R.string.track_color_mode_fixed_speed_slow_display_key, R.string.track_color_mode_fixed_speed_slow_key); setTrackColorModePreferenceListener(R.string.track_color_mode_fixed_speed_medium_display_key, R.string.track_color_mode_fixed_speed_medium_key); } /** * Sets a TrackColorMode preference listener. */ private void setTrackColorModePreferenceListener(int displayKey, final int metricKey) { EditTextPreference trackColorModePreference = (EditTextPreference) findPreference(getString(displayKey)); trackColorModePreference.setOnPreferenceChangeListener( new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { validateTrackColorModeSettings((String) newValue, metricKey); return true; } }); trackColorModePreference.setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { viewTrackColorModeSettings((EditTextPreference) preference, metricKey); return true; } }); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/SettingsActivity.java
Java
asf20
28,939
/* * 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.maps; import com.google.android.apps.mytracks.ColoredPath; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import java.util.ArrayList; import java.util.List; /** * A path painter that varies the path colors based on fixed speeds or average speed margin * depending of the TrackPathDescriptor passed to its constructor. * * @author Vangelis S. */ public class DynamicSpeedTrackPathPainter implements TrackPathPainter { private final Paint selectedTrackPaintSlow; private final Paint selectedTrackPaintMedium; private final Paint selectedTrackPaintFast; private final List<ColoredPath> coloredPaths; private final TrackPathDescriptor trackPathDescriptor; private int slowSpeed; private int normalSpeed; public DynamicSpeedTrackPathPainter (Context context, TrackPathDescriptor trackPathDescriptor) { this.trackPathDescriptor = trackPathDescriptor; selectedTrackPaintSlow = TrackPathUtilities.getPaint(R.color.slow_path, context); selectedTrackPaintMedium = TrackPathUtilities.getPaint(R.color.normal_path, context); selectedTrackPaintFast = TrackPathUtilities.getPaint(R.color.fast_path, context); this.coloredPaths = new ArrayList<ColoredPath>(); } @Override public void drawTrack(Canvas canvas) { for(int i = 0; i < coloredPaths.size(); ++i) { ColoredPath coloredPath = coloredPaths.get(i); canvas.drawPath(coloredPath.getPath(), coloredPath.getPathPaint()); } } @Override public void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points) { // Whether to start a new segment on new valid and visible point. boolean newSegment = startLocationIdx <= 0 || !points.get(startLocationIdx - 1).valid; boolean lastVisible = !newSegment; final Point pt = new Point(); clear(); slowSpeed = trackPathDescriptor.getSlowSpeed(); normalSpeed = trackPathDescriptor.getNormalSpeed(); // 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. if (newSegment) { projection.toPixels(geoPoint, pt); newSegment = false; } else { ColoredPath coloredPath; if(loc.speed <= slowSpeed) { coloredPath = new ColoredPath(selectedTrackPaintSlow); } else if(loc.speed <= normalSpeed) { coloredPath = new ColoredPath(selectedTrackPaintMedium); } else { coloredPath = new ColoredPath(selectedTrackPaintFast); } coloredPath.getPath().moveTo(pt.x, pt.y); projection.toPixels(geoPoint, pt); coloredPath.getPath().lineTo(pt.x, pt.y); coloredPaths.add(coloredPath); } } } @Override public void clear() { coloredPaths.clear(); } @Override public boolean needsRedraw() { return trackPathDescriptor.needsRedraw(); } @Override public Path getLastPath() { Path path = new Path(); for(int i = 0; i < coloredPaths.size(); ++i) { path.addPath(coloredPaths.get(i).getPath()); } return path; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathPainter.java
Java
asf20
4,744
/* * 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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A dynamic speed path descriptor. * * @author Vangelis S. */ public class DynamicSpeedTrackPathDescriptor implements TrackPathDescriptor, OnSharedPreferenceChangeListener { private int slowSpeed; private int normalSpeed; private int speedMargin; private double averageMovingSpeed; private final Context context; public DynamicSpeedTrackPathDescriptor(Context context){ this.context = context; SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { speedMargin = 25; return; } prefs.registerOnSharedPreferenceChangeListener(this); speedMargin = Integer.parseInt(prefs.getString( context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25")); } /** * Get the slow speed calculated based on the % below the average speed. * @return The speed limit considered as slow. */ public int getSlowSpeed() { slowSpeed = (int) (averageMovingSpeed - (averageMovingSpeed * speedMargin / 100)); return slowSpeed; } /** * Get the medium speed calculated based on the % above the average speed. * @return The speed limit considered as normal. */ public int getNormalSpeed() { normalSpeed = (int) (averageMovingSpeed + (averageMovingSpeed * speedMargin / 100)); return normalSpeed; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "DynamicSpeedTrackPathDescriptor: onSharedPreferences changed " + key); if (key == null || !key.equals(context.getString(R.string.track_color_mode_dynamic_speed_variation_key))) { return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { speedMargin = 25; return; } speedMargin = Integer.parseInt( prefs.getString( context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "25")); } @Override public boolean needsRedraw() { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long currentTrackId = prefs.getLong(context.getString(R.string.selected_track_key), -1); if(currentTrackId == -1) { // Could not find track. return false; } Track track = MyTracksProviderUtils.Factory.get(context).getTrack(currentTrackId); TripStatistics stats = track.getStatistics(); double newaverageSpeed = (int) Math.floor(stats.getAverageMovingSpeed() * 3.6); if(averageMovingSpeed == 0) { averageMovingSpeed = newaverageSpeed; return true; } double difference = Math.max(averageMovingSpeed, newaverageSpeed); if (difference == 0.0) { difference = 0.0; } else { difference = Math.abs(averageMovingSpeed - newaverageSpeed) / difference * 100; } if(difference >= 20) { averageMovingSpeed = newaverageSpeed; return true; } return false; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java
Java
asf20
4,287
/* * 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.maps; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.android.maps.mytracks.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.Rect; import java.util.List; /** * A path painter that not variates the path colors. * * @author Vangelis S. */ public class SingleColorTrackPathPainter implements TrackPathPainter { private final Paint selectedTrackPaint; private Path path; public SingleColorTrackPathPainter(Context context) { selectedTrackPaint = TrackPathUtilities.getPaint(R.color.red, context); } @Override public void drawTrack(Canvas canvas) { canvas.drawPath(path, selectedTrackPaint); } @Override public void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points) { // Whether to start a new segment on new valid and visible point. boolean newSegment = startLocationIdx <= 0 || !points.get(startLocationIdx - 1).valid; boolean lastVisible = !newSegment; final Point pt = new Point(); // Loop over track points. int numPoints = points.size(); path = newPath(); path.incReserve(numPoints); for (int i = startLocationIdx; i < numPoints ; ++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); } } } @Override public void clear() { path = null; } @Override public boolean needsRedraw() { return false; } @Override public Path getLastPath() { return path; } // Visible for testing public Path newPath() { return new Path(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/SingleColorTrackPathPainter.java
Java
asf20
3,231
/* * 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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.util.Log; /** * A fixed speed path descriptor. * * @author Vangelis S. */ public class FixedSpeedTrackPathDescriptor implements TrackPathDescriptor, OnSharedPreferenceChangeListener { private int slowSpeed; private int normalSpeed; private final Context context; public FixedSpeedTrackPathDescriptor(Context context) { this.context = context; SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { slowSpeed = 9; normalSpeed = 17; return; } prefs.registerOnSharedPreferenceChangeListener(this); try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), "9")); } catch (NumberFormatException e) { slowSpeed = 9; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), "17")); } catch (NumberFormatException e) { normalSpeed = 17; } } /** * Gets the slow speed for reference. * @return The speed limit considered as slow. */ public int getSlowSpeed() { return slowSpeed; } /** * Gets the normal speed for reference. * @return The speed limit considered as normal. */ public int getNormalSpeed() { return normalSpeed; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { Log.d(TAG, "FixedSpeedTrackPathDescriptor: onSharedPreferences changed " + key); if (key == null || (!key.equals(context.getString(R.string.track_color_mode_fixed_speed_slow_key)) && !key.equals(context.getString(R.string.track_color_mode_fixed_speed_medium_key)))) { return; } SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { slowSpeed = 9; normalSpeed = 17; return; } try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), "9")); } catch (NumberFormatException e) { slowSpeed = 9; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), "17")); } catch (NumberFormatException e) { normalSpeed = 17; } } @Override public boolean needsRedraw() { return false; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java
Java
asf20
3,495
/* * 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.maps; /** * An interface for classes which describe how to draw a track path. * * @author Vangelis S. */ public interface TrackPathDescriptor { /** * @return The maximum speed which is considered slow. */ int getSlowSpeed(); /** * @return The maximum speed which is considered normal. */ int getNormalSpeed(); /** * @return True if the path needs to be updated. */ boolean needsRedraw(); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathDescriptor.java
Java
asf20
1,063
/* * 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.maps; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; /** * A factory for TrackPathPainters. * * @author Vangelis S. */ public class TrackPathPainterFactory { private TrackPathPainterFactory() { } /** * Get a new TrackPathPainter. * @param context Context to fetch system preferences. * @return The TrackPathPainter that corresponds to the track color mode setting. */ public static TrackPathPainter getTrackPathPainter(Context context) { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { return new SingleColorTrackPathPainter(context); } String colorMode = prefs.getString(context.getString(R.string.track_color_mode_key), null); Log.i(TAG, "Creating track path painter of type: " + colorMode); if (colorMode == null || colorMode.equals(context.getString(R.string.display_track_color_value_none))) { return new SingleColorTrackPathPainter(context); } else if (colorMode.equals(context.getString(R.string.display_track_color_value_fixed))) { return new DynamicSpeedTrackPathPainter(context, new FixedSpeedTrackPathDescriptor(context)); } else if (colorMode.equals(context.getString(R.string.display_track_color_value_dynamic))) { return new DynamicSpeedTrackPathPainter(context, new DynamicSpeedTrackPathDescriptor(context)); } else { Log.w(TAG, "Using default track path painter. Unrecognized painter: " + colorMode); return new SingleColorTrackPathPainter(context); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainterFactory.java
Java
asf20
2,443
/* * 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.maps; import android.content.Context; import android.graphics.Paint; /** * Various utility functions for TrackPath painting. * * @author Vangelis S. */ public class TrackPathUtilities { public static Paint getPaint(int id, Context context) { Paint paint = new Paint(); paint.setColor(context.getResources().getColor(id)); paint.setStrokeWidth(3); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); return paint; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathUtilities.java
Java
asf20
1,095
/* * 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.maps; import com.google.android.apps.mytracks.MapOverlay.CachedLocation; import com.google.android.maps.Projection; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Rect; import java.util.List; /** * An interface for classes which paint the track path. * * @author Vangelis S. */ public interface TrackPathPainter { /** * Clears the related data. */ void clear(); /** * Draws the path to the canvas. * @param canvas The Canvas to draw upon */ void drawTrack(Canvas canvas); /** * Updates the path. * @param projection The Canvas to draw upon. * @param viewRect The Path to be drawn. * @param startLocationIdx The start point from where update the path. * @param alwaysVisible Flag for alwaysvisible. * @param points The list of points used to update the path. */ void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points); /** * @return True if the path needs to be updated. */ boolean needsRedraw(); /** * @return The path being used currently. */ Path getLastPath(); }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainter.java
Java
asf20
1,812
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.TrackDataHub; import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType; import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.apps.mytracks.io.sendtogoogle.SendActivity; import com.google.android.apps.mytracks.services.tasks.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.LocationUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.mytracks.R; import android.content.ContentUris; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SubMenu; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.view.Window; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.EnumSet; /** * The map view activity of the MyTracks application. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class MapActivity extends com.google.android.maps.MapActivity implements View.OnTouchListener, View.OnClickListener, TrackDataListener { // Saved instance state keys: // --------------------------- private static final String KEY_CURRENT_LOCATION = "currentLocation"; private static final String KEY_KEEP_MY_LOCATION_VISIBLE = "keepMyLocationVisible"; private TrackDataHub dataHub; /** * True if the map should be scrolled so that the pointer is always in the * visible area. */ private boolean keepMyLocationVisible; /** * The current pointer location. * This is kept to quickly center on it when the user requests. */ private Location currentLocation; // UI elements: // ------------- private RelativeLayout screen; private MapView mapView; private MapOverlay mapOverlay; private LinearLayout messagePane; private TextView messageText; private LinearLayout busyPane; private ImageButton optionsBtn; private MenuItem myLocation; private MenuItem toggleLayers; /** * 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 protected void onCreate(Bundle bundle) { Log.d(TAG, "MapActivity.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); // 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 MapOverlay(this); mapView.getOverlays().add(mapOverlay); mapView.setOnTouchListener(this); mapView.setBuiltInZoomControls(true); 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); } @Override protected void onRestoreInstanceState(Bundle bundle) { Log.d(TAG, "MapActivity.onRestoreInstanceState"); if (bundle != null) { super.onRestoreInstanceState(bundle); 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) { showCurrentLocation(); } } else { currentLocation = null; } } } @Override protected void onResume() { Log.d(TAG, "MapActivity.onResume"); super.onResume(); dataHub = ((MyTracksApplication) getApplication()).getTrackDataHub(); dataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.POINT_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.COMPASS_UPDATES)); } @Override protected void onSaveInstanceState(Bundle outState) { Log.d(TAG, "MapActivity.onSaveInstanceState"); outState.putBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, keepMyLocationVisible); if (currentLocation != null) { outState.putParcelable(KEY_CURRENT_LOCATION, currentLocation); } super.onSaveInstanceState(outState); } @Override protected void onPause() { Log.d(TAG, "MapActivity.onPause"); dataHub.unregisterTrackDataListener(this); dataHub = null; super.onPause(); } // Utility functions: // ------------------- /** * Shows the options button if a track is selected, or hide it if not. */ private void updateOptionsButton(boolean trackSelected) { optionsBtn.setVisibility( trackSelected ? 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 = LocationUtils.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 (mapOverlay == null || mapView == null) { return; } mapOverlay.setMyLocation(currentLocation); mapView.postInvalidate(); if (currentLocation != null && keepMyLocationVisible && !locationIsVisible(currentLocation)) { GeoPoint geoPoint = LocationUtils.getGeoPoint(currentLocation); MapController controller = mapView.getController(); controller.animateTo(geoPoint); } } @Override public void onTrackUpdated(Track track) { // We don't care. } /** * Zooms and pans the map so that the given track is visible. * * @param track the track */ private void zoomMapToBoundaries(Track track) { if (mapView == null) { return; } 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 (LocationUtils.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) { MyTracksProviderUtils providerUtils = MyTracksProviderUtils.Factory.get(this); 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(); } } @Override public void onSelectedTrackChanged(final Track track, final boolean isRecording) { runOnUiThread(new Runnable() { @Override public void run() { boolean trackSelected = track != null; updateOptionsButton(trackSelected); mapOverlay.setTrackDrawingEnabled(trackSelected); if (trackSelected) { busyPane.setVisibility(View.VISIBLE); zoomMapToBoundaries(track); mapOverlay.setShowEndMarker(!isRecording); busyPane.setVisibility(View.GONE); } mapView.invalidate(); } }); } private final OnCreateContextMenuListener contextMenuListener = new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle(R.string.track_list_context_menu_title); menu.add(0, Constants.MENU_EDIT, 0, R.string.track_list_edit_track); if (!dataHub.isRecordingSelected()) { String saveFileFormat = getString(R.string.track_list_save_file); String shareFileFormat = getString(R.string.track_list_share_file); String fileTypes[] = getResources().getStringArray(R.array.file_types); menu.add(0, Constants.MENU_SEND_TO_GOOGLE, 0, R.string.track_list_send_google); SubMenu share = menu.addSubMenu(0, Constants.MENU_SHARE, 0, R.string.track_list_share_track); share.add(0, Constants.MENU_SHARE_LINK, 0, R.string.track_list_share_url); share.add( 0, Constants.MENU_SHARE_GPX_FILE, 0, String.format(shareFileFormat, fileTypes[0])); share.add( 0, Constants.MENU_SHARE_KML_FILE, 0, String.format(shareFileFormat, fileTypes[1])); share.add( 0, Constants.MENU_SHARE_CSV_FILE, 0, String.format(shareFileFormat, fileTypes[2])); share.add( 0, Constants.MENU_SHARE_TCX_FILE, 0, String.format(shareFileFormat, fileTypes[3])); SubMenu save = menu.addSubMenu(0, Constants.MENU_WRITE_TO_SD_CARD, 0, R.string.track_list_save_sd); save.add( 0, Constants.MENU_SAVE_GPX_FILE, 0, String.format(saveFileFormat, fileTypes[0])); save.add( 0, Constants.MENU_SAVE_KML_FILE, 0, String.format(saveFileFormat, fileTypes[1])); save.add( 0, Constants.MENU_SAVE_CSV_FILE, 0, String.format(saveFileFormat, fileTypes[2])); save.add( 0, Constants.MENU_SAVE_TCX_FILE, 0, String.format(saveFileFormat, fileTypes[3])); menu.add(0, Constants.MENU_CLEAR_MAP, 0, R.string.track_list_clear_map); menu.add(0, Constants.MENU_DELETE, 0, R.string.track_list_delete_track); } } }; @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case Constants.MENU_SEND_TO_GOOGLE: SendActivity.sendToGoogle(this, dataHub.getSelectedTrackId(), false); return true; case Constants.MENU_SHARE_LINK: SendActivity.sendToGoogle(this, dataHub.getSelectedTrackId(), true); return true; case Constants.MENU_SAVE_GPX_FILE: case Constants.MENU_SAVE_KML_FILE: case Constants.MENU_SAVE_CSV_FILE: case Constants.MENU_SAVE_TCX_FILE: case Constants.MENU_SHARE_GPX_FILE: case Constants.MENU_SHARE_KML_FILE: case Constants.MENU_SHARE_CSV_FILE: case Constants.MENU_SHARE_TCX_FILE: SaveActivity.handleExportTrackAction(this, dataHub.getSelectedTrackId(), Constants.getActionFromMenuId(item.getItemId())); return true; case Constants.MENU_EDIT: { Intent intent = new Intent(this, TrackDetails.class); // TODO: Pass in a content URI intent.putExtra("trackid", dataHub.getSelectedTrackId()); startActivity(intent); return true; } case Constants.MENU_DELETE: { Uri uri = ContentUris.withAppendedId( TracksColumns.CONTENT_URI, dataHub.getSelectedTrackId()); Intent intent = new Intent(Intent.ACTION_DELETE, uri); startActivity(intent); return true; } case Constants.MENU_CLEAR_MAP: dataHub.unloadCurrentTrack(); return true; default: return super.onMenuItemSelected(featureId, item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); myLocation = menu.add(0, Constants.MENU_MY_LOCATION, 0, R.string.menu_map_view_my_location); myLocation.setIcon(android.R.drawable.ic_menu_mylocation); toggleLayers = menu.add(0, Constants.MENU_TOGGLE_LAYERS, 0, R.string.menu_map_view_satellite_mode); toggleLayers.setIcon(android.R.drawable.ic_menu_mapmode); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { toggleLayers.setTitle(mapView.isSatellite() ? R.string.menu_map_view_map_mode : R.string.menu_map_view_satellite_mode); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case Constants.MENU_MY_LOCATION: { dataHub.forceUpdateLocation(); keepMyLocationVisible = true; if (mapView.getZoomLevel() < 18) { mapView.getController().setZoom(18); } if (currentLocation != null) { showCurrentLocation(); } return true; } case Constants.MENU_TOGGLE_LAYERS: { mapView.setSatellite(!mapView.isSatellite()); return true; } } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { if (v == messagePane) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } 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 onProviderStateChange(ProviderState state) { final int messageId; final boolean isGpsDisabled; switch (state) { case DISABLED: messageId = R.string.gps_need_to_enable; isGpsDisabled = true; break; case NO_FIX: case BAD_FIX: messageId = R.string.gps_wait_for_fix; isGpsDisabled = false; break; case GOOD_FIX: // Nothing to show. messageId = -1; isGpsDisabled = false; break; default: throw new IllegalArgumentException("Unexpected state: " + state); } runOnUiThread(new Runnable() { @Override public void run() { if (messageId != -1) { messageText.setText(messageId); messagePane.setVisibility(View.VISIBLE); if (isGpsDisabled) { // Give a warning about this state. Toast.makeText(MapActivity.this, R.string.gps_not_found, Toast.LENGTH_LONG).show(); // Make clicking take the user to the location settings. messagePane.setOnClickListener(MapActivity.this); } else { messagePane.setOnClickListener(null); } } else { messagePane.setVisibility(View.GONE); } screen.requestLayout(); } }); } @Override public void onCurrentLocationChanged(Location location) { currentLocation = location; showCurrentLocation(); } @Override public void onCurrentHeadingChanged(double heading) { synchronized (this) { if (mapOverlay.setHeading((float) heading)) { mapView.postInvalidate(); } } } @Override public void clearWaypoints() { mapOverlay.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (LocationUtils.isValidLocation(waypoint.getLocation())) { // TODO: Optimize locking inside addWaypoint mapOverlay.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { mapView.postInvalidate(); } @Override public void clearTrackPoints() { mapOverlay.clearPoints(); } @Override public void onNewTrackPoint(Location loc) { mapOverlay.addLocation(loc); } @Override public void onSegmentSplit() { mapOverlay.addSegmentSplit(); } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onNewTrackPointsDone() { mapView.postInvalidate(); } @Override public boolean onUnitsChanged(boolean metric) { // We don't care. return false; } @Override public boolean onReportSpeedChanged(boolean reportSpeed) { // We don't care. return false; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/MapActivity.java
Java
asf20
19,988
/* * 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 android.graphics.Paint; import android.graphics.Path; /** * Represents a colored {@code Path} to save its relative color for drawing. * @author Vangelis S. */ public class ColoredPath { private final Path path; private final Paint pathPaint; /** * Constructor for a ColoredPath by color. */ public ColoredPath(int color) { path = new Path(); pathPaint = new Paint(); pathPaint.setColor(color); pathPaint.setStrokeWidth(3); pathPaint.setStyle(Paint.Style.STROKE); pathPaint.setAntiAlias(true); } /** * Constructor for a ColoredPath by Paint. */ public ColoredPath(Paint paint) { path = new Path(); pathPaint = paint; } /** * @return the path */ public Path getPath() { return path; } /** * @return the pathPaint */ public Paint getPathPaint() { return pathPaint; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ColoredPath.java
Java
asf20
1,528
/* * 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; } } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/IntegerListPreference.java
Java
asf20
2,836
/* * 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_sensor_ant_not_paired); } else { setSummary( String.format(getContext().getString(R.string.settings_sensor_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_sensor_ant_not_paired); return true; } }); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/AntPreference.java
Java
asf20
1,879
/* * 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.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; 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 WaypointDetails 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); 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(Constants.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.INVISIBLE); } 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()); name.setImeOptions(EditorInfo.IME_ACTION_DONE); 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; } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/WaypointDetails.java
Java
asf20
6,068
/* * 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 static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; 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(Constants.SPEED_SMOOTHING_FACTOR); /** * A buffer of the recent elevation readings in meters. */ private final DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); /** * A buffer of the distance between recent gps readings in meters. */ private final DoubleBuffer distanceBuffer = new DoubleBuffer(Constants.DISTANCE_SMOOTHING_FACTOR); /** * A buffer of the recent grade calculations. */ private final DoubleBuffer gradeBuffer = new DoubleBuffer(Constants.GRADE_SMOOTHING_FACTOR); /** * The total number of locations in this trip. */ private long totalLocations = 0; private int minRecordingDistance = Constants.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(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 < Constants.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(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(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 > Constants.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 < Constants.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; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java
Java
asf20
11,514
/* * 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(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/stats/DoubleBuffer.java
Java
asf20
3,566
/* * 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.widgets; import static com.google.android.apps.mytracks.Constants.SETTINGS_NAME; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.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.apps.mytracks.services.ControlRecordingService; 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.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.ContentObserver; import android.os.Handler; import android.util.Log; import android.widget.RemoteViews; /** * An AppWidgetProvider for displaying key track statistics (distance, time, * speed) from the current or most recent track. * * @author Sandor Dornbush * @author Paul R. Saxman */ public class TrackWidgetProvider extends AppWidgetProvider implements OnSharedPreferenceChangeListener { class TrackObserver extends ContentObserver { public TrackObserver() { super(contentHandler); } public void onChange(boolean selfChange) { updateTrack(null); } } private final Handler contentHandler; private MyTracksProviderUtils providerUtils; private Context context; private String unknown; private String distanceLabel; private String speedLabel; private String paceLabel; private TrackObserver trackObserver; private boolean isMetric; private boolean reportSpeed; private long selectedTrackId; private SharedPreferences sharedPreferences; private String TRACK_STARTED_ACTION; private String TRACK_STOPPED_ACTION; public TrackWidgetProvider() { super(); contentHandler = new Handler(); selectedTrackId = -1; } private void initialize(Context aContext) { if (this.context != null) { return; } this.context = aContext; trackObserver = new TrackObserver(); providerUtils = MyTracksProviderUtils.Factory.get(context); unknown = context.getString(R.string.value_unknown); sharedPreferences = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE); sharedPreferences.registerOnSharedPreferenceChangeListener(this); onSharedPreferenceChanged(sharedPreferences, null); context.getContentResolver().registerContentObserver( TracksColumns.CONTENT_URI, true, trackObserver); TRACK_STARTED_ACTION = context.getString(R.string.track_started_broadcast_action); TRACK_STOPPED_ACTION = context.getString(R.string.track_stopped_broadcast_action); } @Override public void onReceive(Context aContext, Intent intent) { super.onReceive(aContext, intent); initialize(aContext); selectedTrackId = intent.getLongExtra( context.getString(R.string.track_id_broadcast_extra), selectedTrackId); String action = intent.getAction(); Log.d(TAG, "TrackWidgetProvider.onReceive: trackId=" + selectedTrackId + ", action=" + action); if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action) || AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) || TRACK_STARTED_ACTION.equals(action) || TRACK_STOPPED_ACTION.equals(action)) { updateTrack(action); } } @Override public void onDisabled(Context aContext) { if (trackObserver != null) { aContext.getContentResolver().unregisterContentObserver(trackObserver); } if (sharedPreferences != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } } private void updateTrack(String action) { Track track = null; if (selectedTrackId != -1) { Log.d(TAG, "TrackWidgetProvider.updateTrack: Retrieving specified track."); track = providerUtils.getTrack(selectedTrackId); } else { Log.d(TAG, "TrackWidgetProvider.updateTrack: Attempting to retrieve previous track."); // TODO we should really read the pref. track = providerUtils.getLastTrack(); } AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName widget = new ComponentName(context, TrackWidgetProvider.class); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.track_widget); // Make all of the stats open the mytracks activity. Intent intent = new Intent(context, MyTracks.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.appwidget_track_statistics, pendingIntent); if (action != null) { updateViewButton(views, action); } updateViewTrackStatistics(views, track); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(widget); for (int appWidgetId : appWidgetIds) { appWidgetManager.updateAppWidget(appWidgetId, views); } } /** * Update the widget's button with the appropriate intent and icon. * * @param views The RemoteViews containing the button * @param action The action broadcast from the track service */ private void updateViewButton(RemoteViews views, String action) { if (TRACK_STARTED_ACTION.equals(action)) { // If a new track is started by this appwidget or elsewhere, // toggle the button to active and have it disable the track if pressed. setButtonIntent(views, R.string.track_action_end, R.drawable.appwidget_button_enabled); } else { // If a track is stopped by this appwidget or elsewhere, // toggle the button to inactive and have it start a new track if pressed. setButtonIntent(views, R.string.track_action_start, R.drawable.appwidget_button_disabled); } } /** * Set up the main widget button. * * @param views The widget views * @param action The resource id of the action to fire when the button is pressed * @param icon The resource id of the icon to show for the button */ private void setButtonIntent(RemoteViews views, int action, int icon) { Intent intent = new Intent(context, ControlRecordingService.class); intent.setAction(context.getString(action)); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.appwidget_button, pendingIntent); views.setImageViewResource(R.id.appwidget_button, icon); } /** * Update the specified widget's view with the distance, time, and speed of * the specified track. * * @param views The RemoteViews to update with statistics * @param track The track to extract statistics from. */ protected void updateViewTrackStatistics(RemoteViews views, Track track) { if (track == null) { views.setTextViewText(R.id.appwidget_distance_text, unknown); views.setTextViewText(R.id.appwidget_time_text, unknown); views.setTextViewText(R.id.appwidget_speed_text, unknown); return; } TripStatistics stats = track.getStatistics(); // TODO replace this with format strings and miles. // convert meters to kilometers double displayDistance = stats.getTotalDistance() / 1000; if (!isMetric) { displayDistance *= UnitConversions.KM_TO_MI; } String distance = StringUtils.formatSingleDecimalPlace(displayDistance) + " " + this.distanceLabel; // convert ms to minutes String time = StringUtils.formatTime(stats.getMovingTime()); String speed = unknown; if (!Double.isNaN(stats.getAverageMovingSpeed())) { // Convert m/s to km/h double displaySpeed = stats.getAverageMovingSpeed() * 3.6; if (!isMetric) { displaySpeed *= UnitConversions.KMH_TO_MPH; } if (reportSpeed) { speed = StringUtils.formatSingleDecimalPlace(displaySpeed) + " " + this.speedLabel; } else { long displayPace = (long) (3600000.0 / displaySpeed); speed = StringUtils.formatTime(displayPace) + " " + paceLabel; } } views.setTextViewText(R.id.appwidget_distance_text, distance); views.setTextViewText(R.id.appwidget_time_text, time); views.setTextViewText(R.id.appwidget_speed_text, speed); } @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { String metricUnitsKey = context.getString(R.string.metric_units_key); if (key == null || key.equals(metricUnitsKey)) { isMetric = prefs.getBoolean(metricUnitsKey, true); distanceLabel = context.getString(isMetric ? R.string.unit_kilometer : R.string.unit_mile); speedLabel = context.getString( isMetric ? R.string.unit_kilometer_per_hour : R.string.unit_mile_per_hour); paceLabel = context.getString( isMetric ? R.string.unit_minute_per_kilometer : R.string.unit_minute_per_mile); } String reportSpeedKey = context.getString(R.string.report_speed_key); if (key == null || key.equals(reportSpeedKey)) { reportSpeed = prefs.getBoolean(reportSpeedKey, true); } String selectedTrackKey = context.getString(R.string.selected_track_key); if (key == null || key.equals(selectedTrackKey)) { selectedTrackId = prefs.getLong(selectedTrackKey, -1); Log.d(TAG, "TrackWidgetProvider setting selecting track from preference: " + selectedTrackId); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/widgets/TrackWidgetProvider.java
Java
asf20
10,365
/* * 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.content.TracksColumns; import com.google.android.apps.mytracks.io.file.GpxImporter; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; 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 FileUtils fileUtils; private boolean singleTrackSelected; private String gpxPath; private WakeLock wakeLock; private ProgressDialog progress; private int gpxFileCount; private int importSuccessCount; private long importedTrackIds[]; public ImportAllTracks(Activity activity) { this(activity, null); } /** * Constructor to import tracks. * * @param activity the activity * @param path path of the gpx file to import and display. If null, then just * import all the gpx files under MyTracks/gpx and do not display any * track. */ public ImportAllTracks(Activity activity, String path) { Log.i(Constants.TAG, "ImportAllTracks: Starting"); this.activity = activity; fileUtils = new FileUtils(); singleTrackSelected = path != null; gpxPath = path == null ? fileUtils.buildExternalDirectoryPath("gpx") : path; new Thread(runner).start(); } 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId == -1) { wakeLock = SystemUtils.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(Constants.TAG, "ImportAllTracks: Releasing wake lock."); } activity.runOnUiThread(new Thread() { @Override public void run() { showDoneDialog(); } }); } private void showDoneDialog() { Log.i(Constants.TAG, "ImportAllTracks: Done"); AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (gpxFileCount == 0) { builder.setMessage(activity.getString(R.string.import_no_file, gpxPath)); } else { String totalFiles = activity.getResources().getQuantityString( R.plurals.importGpxFiles, gpxFileCount, gpxFileCount); builder.setMessage( activity.getString(R.string.import_success, importSuccessCount, totalFiles, gpxPath)); } builder.setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (singleTrackSelected) { long lastTrackId = importedTrackIds[importedTrackIds.length - 1]; Uri trackUri = ContentUris.withAppendedId(TracksColumns.CONTENT_URI, lastTrackId); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(trackUri, TracksColumns.CONTENT_ITEMTYPE); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); activity.finish(); } } }); builder.show(); } private void makeProgressDialog(final int trackCount) { String importMsg = activity.getString(R.string.track_list_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(Constants.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(Constants.TAG, "ImportAllTracks: importing: " + gpxFile.getName()); try { importedTrackIds = GpxImporter.importGPXFile(new FileInputStream(gpxFile), providerUtils); return true; } catch (FileNotFoundException e) { Log.w(Constants.TAG, "GPX file wasn't found/went missing: " + gpxFile.getAbsolutePath(), e); } catch (ParserConfigurationException e) { Log.w(Constants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (SAXException e) { Log.w(Constants.TAG, "Error parsing file: " + gpxFile.getAbsolutePath(), e); } catch (IOException e) { Log.w(Constants.TAG, "Error reading file: " + gpxFile.getAbsolutePath(), e); } Toast.makeText(activity, activity.getString(R.string.import_error, gpxFile.getName()), Toast.LENGTH_LONG).show(); return false; } /** * Gets a list of the GPX files. If singleTrackSelected is true, returns a * list containing just the gpxPath file. If singleTrackSelected is false, * returns a list of GPX files under the gpxPath directory. */ private List<File> getGpxFiles() { List<File> gpxFiles = new LinkedList<File>(); File file = new File(gpxPath); if (singleTrackSelected) { gpxFiles.add(file); } else { File[] gpxFileCandidates = file.listFiles(); if (gpxFileCandidates != null) { for (File candidate : gpxFileCandidates) { if (!candidate.isDirectory() && candidate.getName().endsWith(".gpx")) { gpxFiles.add(candidate); } } } } return gpxFiles; } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ImportAllTracks.java
Java
asf20
8,788
/* * 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.Paint.Style; import android.graphics.Path; import java.text.NumberFormat; /** * 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 NumberFormat 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 fillColor The paint for filling the chart * @param strokeColor The paint for stroking the outside the chart, optional * @param zoomSettings The settings related to zooming * @param titleId The title ID * * TODO: Get rid of Context and inject appropriate values instead. */ public ChartValueSeries( Context context, int fillColor, int strokeColor, ZoomSettings zoomSettings, int titleId) { this.format = NumberFormat.getIntegerInstance(); 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 number format for this series */ NumberFormat 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(); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ChartValueSeries.java
Java
asf20
8,023
/* * 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.file.TrackWriter; import com.google.android.apps.mytracks.io.file.TrackWriterFactory; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.database.Cursor; 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(Constants.TAG, "Unknown export format: " + which); } } }; public ExportAllTracks(Activity activity) { this.activity = activity; Log.i(Constants.TAG, "ExportAllTracks: Starting"); String exportFileFormat = activity.getString(R.string.track_list_export_file); String fileTypes[] = activity.getResources().getStringArray(R.array.file_types); String[] choices = new String[fileTypes.length]; for (int i = 0; i < fileTypes.length; i++) { choices[i] = String.format(exportFileFormat, fileTypes[i]); } AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.track_list_export_all); builder.setSingleChoiceItems(choices, 0, itemClick); builder.setPositiveButton(R.string.generic_ok, positiveClick); builder.setNegativeButton(R.string.generic_cancel, null); builder.show(); } private final DialogInterface.OnClickListener positiveClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new Thread(runner, "SendToMyMaps").start(); } }; 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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); long recordingTrackId = -1; if (prefs != null) { recordingTrackId = prefs.getLong(activity.getString(R.string.recording_track_key), -1); } if (recordingTrackId != -1) { wakeLock = SystemUtils.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(Constants.TAG, "ExportAllTracks: Releasing wake lock."); } Log.i(Constants.TAG, "ExportAllTracks: Done"); showToast(R.string.export_success, Toast.LENGTH_SHORT); } private void makeProgressDialog(final int trackCount) { String exportMsg = activity.getString(R.string.track_list_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(Constants.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(Constants.TAG, "ExportAllTracks: exporting: " + id); TrackWriter writer = TrackWriterFactory.newWriter(activity, providerUtils, id, format); if (writer == null) { showToast(R.string.export_error, Toast.LENGTH_LONG); return; } writer.writeTrack(); if (!writer.wasSuccess()) { // Abort the whole export on the first error. showToast(writer.getErrorMessage(), Toast.LENGTH_LONG); return; } } } finally { if (cursor != null) { cursor.close(); } if (progress != null) { synchronized (this) { progress.dismiss(); progress = null; } } } } private void showToast(final int messageId, final int length) { activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, messageId, length).show(); } }); } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/ExportAllTracks.java
Java
asf20
7,509
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.Context; 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(Constants.TAG, "StatsActivity: onSharedPreferences changed " + key); if (key != null) { if (key.equals(getString(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( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); 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.stat_speed, R.string.stat_pace); 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); } } }
0000som143-mytracks
MyTracks/src/com/google/android/apps/mytracks/AggregatedStatsActivity.java
Java
asf20
3,708