forked from upstream-mirrors/OpenTracks
Modify the check units flow so that it asks the user to pick either
metric or imperial. Metric is the default. Thus no longer need to send the user to the 'Display' settings page.
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Utility class for determining if newer-API features are available on the
|
||||
* current device.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class ApiFeatures {
|
||||
|
||||
/**
|
||||
* The API level of the Android version we are being run under.
|
||||
*/
|
||||
private static final int ANDROID_API_LEVEL = Integer.parseInt(
|
||||
Build.VERSION.SDK);
|
||||
|
||||
private static ApiFeatures instance;
|
||||
|
||||
/**
|
||||
* The API level adapter for the Android version we are being run under.
|
||||
*/
|
||||
private ApiLevelAdapter apiLevelAdapter;
|
||||
|
||||
/**
|
||||
* Returns the singleton instance of this class.
|
||||
*/
|
||||
public static ApiFeatures getInstance() {
|
||||
if (instance == null) {
|
||||
instance = new ApiFeatures();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Injects a specific singleton instance, to be used for unit tests.
|
||||
*/
|
||||
@SuppressWarnings("hiding")
|
||||
public static void injectInstance(ApiFeatures instance) {
|
||||
ApiFeatures.instance = instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow subclasses for mocking, but no direct instantiation.
|
||||
*/
|
||||
protected ApiFeatures() {
|
||||
// It is safe to import unsupported classes as long as we only actually
|
||||
// load the class when supported.
|
||||
if (getApiLevel() >= 9) {
|
||||
apiLevelAdapter = new ApiLevel9Adapter();
|
||||
} else if (getApiLevel() >= 8) {
|
||||
apiLevelAdapter = new ApiLevel8Adapter();
|
||||
} else if (getApiLevel() >= 5) {
|
||||
apiLevelAdapter = new ApiLevel5Adapter();
|
||||
} else {
|
||||
apiLevelAdapter = new ApiLevel3Adapter();
|
||||
}
|
||||
|
||||
Log.i(Constants.TAG, "Using API level adapter " + apiLevelAdapter.getClass());
|
||||
}
|
||||
|
||||
public ApiLevelAdapter getApiAdapter() {
|
||||
return apiLevelAdapter;
|
||||
}
|
||||
|
||||
// API Level 4 Changes
|
||||
|
||||
/**
|
||||
* Returns whether text-to-speech is available.
|
||||
*/
|
||||
public boolean hasTextToSpeech() {
|
||||
return getApiLevel() >= 4;
|
||||
}
|
||||
|
||||
// API Level 5 Changes
|
||||
|
||||
/**
|
||||
* There's a bug (#1587) in Cupcake and Donut which prevents you from
|
||||
* using a SQLiteQueryBuilder twice. That is, if you call buildQuery
|
||||
* on a given instance (to log the statement for debugging), and then
|
||||
* call query on the same instance to make it actually do the query,
|
||||
* it'll regenerate the query for the second call, and will screw it
|
||||
* up. Specifically, it'll add extra parens which don't belong.
|
||||
*/
|
||||
public boolean canReuseSQLiteQueryBuilder() {
|
||||
return getApiLevel() >= 5;
|
||||
}
|
||||
|
||||
// API Level 10 changes
|
||||
|
||||
/**
|
||||
* Returns true if BluetoothDevice.createInsecureRfcommSocketToServiceRecord
|
||||
* is available.
|
||||
*/
|
||||
public boolean hasBluetoothDeviceCreateInsecureRfcommSocketToServiceRecord() {
|
||||
return getApiLevel() >= 10;
|
||||
}
|
||||
|
||||
// Visible for testing.
|
||||
protected int getApiLevel() {
|
||||
return ANDROID_API_LEVEL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import static com.google.android.apps.mytracks.Constants.TAG;
|
||||
|
||||
import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener;
|
||||
import com.google.android.apps.mytracks.services.tasks.PeriodicTask;
|
||||
import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerTask;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.apache.ApacheHttpTransport;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.SharedPreferences.Editor;
|
||||
import android.util.Log;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* API level 3 specific implementation of the {@link ApiLevelAdapter}.
|
||||
*
|
||||
* @author Bartlomiej Niechwiej
|
||||
*/
|
||||
public class ApiLevel3Adapter implements ApiLevelAdapter {
|
||||
|
||||
@Override
|
||||
public void startForeground(Service service,
|
||||
NotificationManager notificationManager, int id,
|
||||
Notification notification) {
|
||||
setServiceForeground(service, true);
|
||||
|
||||
notificationManager.notify(id, notification);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopForeground(Service service,
|
||||
NotificationManager notificationManager, int id) {
|
||||
setServiceForeground(service, false);
|
||||
if (id != -1) {
|
||||
notificationManager.cancel(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PeriodicTask getStatusAnnouncerTask(Context context) {
|
||||
return new StatusAnnouncerTask(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackupPreferencesListener getBackupPreferencesListener(Context context) {
|
||||
return new BackupPreferencesListener() {
|
||||
@Override
|
||||
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
|
||||
// Do nothing
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void setServiceForeground(Service service, boolean foreground) {
|
||||
// setForeground has been completely removed in API level 11, so we use reflection.
|
||||
try {
|
||||
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
|
||||
setForegroundMethod.invoke(service, foreground);
|
||||
} catch (SecurityException e) {
|
||||
Log.e(TAG, "Unable to set service foreground state", e);
|
||||
} catch (NoSuchMethodException e) {
|
||||
Log.e(TAG, "Unable to set service foreground state", e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
Log.e(TAG, "Unable to set service foreground state", e);
|
||||
} catch (IllegalAccessException e) {
|
||||
Log.e(TAG, "Unable to set service foreground state", e);
|
||||
} catch (InvocationTargetException e) {
|
||||
Log.e(TAG, "Unable to set service foreground state", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyPreferenceChanges(Editor editor) {
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableStrictMode() {
|
||||
// Not supported
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] copyByteArray(byte[] input, int start, int end) {
|
||||
int length = end - start;
|
||||
byte[] output = new byte[length];
|
||||
System.arraycopy(input, start, output, 0, length);
|
||||
return output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DecimalFormatSymbols getDecimalFormatSymbols(Locale locale) {
|
||||
return new DecimalFormatSymbols(locale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpTransport getHttpTransport() {
|
||||
return new ApacheHttpTransport();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
|
||||
/**
|
||||
* API level 5 specific implementation of the {@link ApiLevelAdapter}.
|
||||
*
|
||||
* @author Bartlomiej Niechwiej
|
||||
*/
|
||||
public class ApiLevel5Adapter extends ApiLevel3Adapter {
|
||||
|
||||
@Override
|
||||
public void startForeground(Service service,
|
||||
NotificationManager notificationManager, int id,
|
||||
Notification notification) {
|
||||
service.startForeground(id, notification);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopForeground(Service service,
|
||||
NotificationManager notificationManager, int id) {
|
||||
service.stopForeground(id != -1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener;
|
||||
import com.google.android.apps.mytracks.io.backup.BackupPreferencesListenerImpl;
|
||||
import com.google.android.apps.mytracks.services.tasks.FroyoStatusAnnouncerTask;
|
||||
import com.google.android.apps.mytracks.services.tasks.PeriodicTask;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
/**
|
||||
* API level 8 specific implementation of the {@link ApiLevelAdapter}.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class ApiLevel8Adapter extends ApiLevel5Adapter {
|
||||
|
||||
@Override
|
||||
public PeriodicTask getStatusAnnouncerTask(Context context) {
|
||||
return new FroyoStatusAnnouncerTask(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackupPreferencesListener getBackupPreferencesListener(Context context) {
|
||||
return new BackupPreferencesListenerImpl(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
import com.google.api.client.http.javanet.NetHttpTransport;
|
||||
|
||||
import android.content.SharedPreferences.Editor;
|
||||
import android.os.StrictMode;
|
||||
import android.util.Log;
|
||||
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* API level 9 specific implementation of the {@link ApiLevelAdapter}.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class ApiLevel9Adapter extends ApiLevel8Adapter {
|
||||
|
||||
@Override
|
||||
public void applyPreferenceChanges(Editor editor) {
|
||||
// Apply asynchronously
|
||||
editor.apply();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableStrictMode() {
|
||||
Log.d(Constants.TAG, "Enabling strict mode");
|
||||
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
|
||||
.detectDiskWrites()
|
||||
.detectNetwork()
|
||||
.penaltyLog()
|
||||
.build());
|
||||
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
|
||||
.detectAll()
|
||||
.penaltyLog()
|
||||
.build());
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] copyByteArray(byte[] input, int start, int end) {
|
||||
return Arrays.copyOfRange(input, start, end);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DecimalFormatSymbols getDecimalFormatSymbols(Locale locale) {
|
||||
return DecimalFormatSymbols.getInstance(locale);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpTransport getHttpTransport() {
|
||||
return new NetHttpTransport();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener;
|
||||
import com.google.android.apps.mytracks.services.tasks.PeriodicTask;
|
||||
import com.google.api.client.http.HttpTransport;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.NotificationManager;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* A set of methods that may be implemented differently depending on the Android API level.
|
||||
*
|
||||
* @author Bartlomiej Niechwiej
|
||||
*/
|
||||
public interface ApiLevelAdapter {
|
||||
|
||||
/**
|
||||
* Puts the specified service into foreground.
|
||||
*
|
||||
* Due to changes in API level 5.
|
||||
*
|
||||
* @param service the service to be put in foreground.
|
||||
* @param notificationManager the notification manager used to post the given
|
||||
* notification.
|
||||
* @param id the ID of the notification, unique within the application.
|
||||
* @param notification the notification to post.
|
||||
*/
|
||||
void startForeground(Service service, NotificationManager notificationManager,
|
||||
int id, Notification notification);
|
||||
|
||||
/**
|
||||
* Puts the given service into background.
|
||||
*
|
||||
* Due to changes in API level 5.
|
||||
*
|
||||
* @param service the service to put into background.
|
||||
* @param notificationManager the notification manager to user when removing
|
||||
* notifications.
|
||||
* @param id the ID of the notification to be remove, or -1 if the
|
||||
* notification shouldn't be removed.
|
||||
*/
|
||||
void stopForeground(Service service, NotificationManager notificationManager,
|
||||
int id);
|
||||
|
||||
/**
|
||||
* Gets a status announcer task.
|
||||
*
|
||||
* Due to changes in API level 8.
|
||||
*/
|
||||
PeriodicTask getStatusAnnouncerTask(Context context);
|
||||
|
||||
/**
|
||||
* Gets a {@link BackupPreferencesListener}.
|
||||
*
|
||||
* Due to changes in API level 8.
|
||||
*/
|
||||
BackupPreferencesListener getBackupPreferencesListener(Context context);
|
||||
|
||||
/**
|
||||
* Applies all changes done to the given preferences editor.
|
||||
* Changes may or may not be applied immediately.
|
||||
*
|
||||
* Due to changes in API level 9.
|
||||
*/
|
||||
void applyPreferenceChanges(SharedPreferences.Editor editor);
|
||||
|
||||
/**
|
||||
* Enables strict mode where supported, only if this is a development build.
|
||||
*
|
||||
* Due to changes in API level 9.
|
||||
*/
|
||||
void enableStrictMode();
|
||||
|
||||
/**
|
||||
* Copies elements from the input byte array into a new byte array, from
|
||||
* indexes start (inclusive) to end (exclusive). The end index must be less
|
||||
* than or equal to input.length.
|
||||
*
|
||||
* Due to changes in API level 9.
|
||||
*
|
||||
* @param input the input byte array
|
||||
* @param start the start index
|
||||
* @param end the end index
|
||||
* @return a new array containing elements from the input byte array
|
||||
*/
|
||||
byte[] copyByteArray(byte[] input, int start, int end);
|
||||
|
||||
|
||||
/**
|
||||
* Gets an instance of {@link DecimalFormatSymbols} for a locale.
|
||||
*
|
||||
* Due to changes in API level 9.
|
||||
*
|
||||
* @param locale the locale
|
||||
* @return a new instance of {@link DecimalFormatSymbols}
|
||||
*/
|
||||
DecimalFormatSymbols getDecimalFormatSymbols(Locale locale);
|
||||
|
||||
/**
|
||||
* Gets a {@link HttpTransport}.
|
||||
*
|
||||
* Due to changes in API level 9.
|
||||
*/
|
||||
HttpTransport getHttpTransport();
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
|
||||
import android.bluetooth.BluetoothAdapter;
|
||||
import android.bluetooth.BluetoothClass;
|
||||
import android.bluetooth.BluetoothDevice;
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Utilities for dealing with bluetooth devices.
|
||||
* This can be used safely even in systems that don't support bluetooth,
|
||||
* in which case a dummy implementation will be used.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public abstract class BluetoothDeviceUtils {
|
||||
public static final String ANY_DEVICE = "any";
|
||||
private static BluetoothDeviceUtils instance;
|
||||
|
||||
/**
|
||||
* Dummy implementation, for systems that don't support bluetooth.
|
||||
*/
|
||||
private static class DummyImpl extends BluetoothDeviceUtils {
|
||||
@Override
|
||||
public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) {
|
||||
// Do nothing - no devices to add
|
||||
}
|
||||
|
||||
@Override
|
||||
public BluetoothDevice findDeviceMatching(String targetDeviceAddress) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Real implementation, for systems that DO support bluetooth.
|
||||
*/
|
||||
private static class RealImpl extends BluetoothDeviceUtils {
|
||||
private final BluetoothAdapter bluetoothAdapter;
|
||||
|
||||
public RealImpl() {
|
||||
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||||
|
||||
if (bluetoothAdapter == null) {
|
||||
throw new IllegalStateException("Unable to get bluetooth adapter");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses) {
|
||||
ensureNotDiscovering();
|
||||
|
||||
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
|
||||
for (BluetoothDevice device : pairedDevices) {
|
||||
BluetoothClass bluetoothClass = device.getBluetoothClass();
|
||||
if (bluetoothClass != null) {
|
||||
// Not really sure what we want, but I know what we don't want.
|
||||
switch(bluetoothClass.getMajorDeviceClass()) {
|
||||
case BluetoothClass.Device.Major.COMPUTER:
|
||||
case BluetoothClass.Device.Major.PHONE:
|
||||
break;
|
||||
default:
|
||||
deviceAddresses.add(device.getAddress());
|
||||
deviceNames.add(device.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BluetoothDevice findDeviceMatching(String targetDeviceAddress) {
|
||||
if (targetDeviceAddress.equals(ANY_DEVICE)) {
|
||||
return findAnyDevice();
|
||||
} else {
|
||||
return findDeviceByAddress(targetDeviceAddress);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and returns the first suitable bluetooth sensor.
|
||||
*/
|
||||
private BluetoothDevice findAnyDevice() {
|
||||
ensureNotDiscovering();
|
||||
|
||||
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
|
||||
for (BluetoothDevice device : pairedDevices) {
|
||||
// Look for the first paired computer device
|
||||
if (isSuitableDevice(device)) {
|
||||
return device;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and returns a device with the given address, or null if it's not
|
||||
* a suitable sensor.
|
||||
*/
|
||||
private BluetoothDevice findDeviceByAddress(String targetDeviceAddress) {
|
||||
ensureNotDiscovering();
|
||||
|
||||
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(targetDeviceAddress);
|
||||
if (isSuitableDevice(device)) {
|
||||
return device;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the bluetooth adapter is not in discovery mode.
|
||||
*/
|
||||
private void ensureNotDiscovering() {
|
||||
// If it's in discovery mode, cancel that for now.
|
||||
bluetoothAdapter.cancelDiscovery();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given device is a suitable sensor.
|
||||
*
|
||||
* @param device the device to check
|
||||
* @return true if it's suitable, false otherwise
|
||||
*/
|
||||
private boolean isSuitableDevice(BluetoothDevice device) {
|
||||
// Check that the device is bonded
|
||||
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the proper (singleton) instance of this class.
|
||||
*/
|
||||
public static BluetoothDeviceUtils getInstance() {
|
||||
if (instance == null) {
|
||||
if (!isBluetoothMethodSupported()) {
|
||||
Log.d(Constants.TAG, "Using dummy bluetooth utils");
|
||||
instance = new DummyImpl();
|
||||
} else {
|
||||
Log.d(Constants.TAG, "Using real bluetooth utils");
|
||||
try {
|
||||
instance = new RealImpl();
|
||||
} catch (IllegalStateException ise) {
|
||||
Log.w(Constants.TAG, "Oops, I mean, using dummy bluetooth utils", ise);
|
||||
instance = new DummyImpl();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the given lists with the names and addresses of all suitable
|
||||
* bluetooth devices.
|
||||
*
|
||||
* @param deviceNames the list to populate with user-visible names
|
||||
* @param deviceAddresses the list to populate with device addresses
|
||||
*/
|
||||
public abstract void populateDeviceLists(List<String> deviceNames, List<String> deviceAddresses);
|
||||
|
||||
/**
|
||||
* Finds the bluetooth device with the given address.
|
||||
*
|
||||
* @param targetDeviceAddress the address of the device, or
|
||||
* {@link #ANY_DEVICE} for using the first suitable device
|
||||
* @return the device's descriptor, or null if not found
|
||||
*/
|
||||
public abstract BluetoothDevice findDeviceMatching(String targetDeviceAddress);
|
||||
|
||||
/**
|
||||
* @return whether the bluetooth method is supported on this device
|
||||
*/
|
||||
public static boolean isBluetoothMethodSupported() {
|
||||
return Integer.parseInt(Build.VERSION.SDK) >= 5;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
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 java.util.Vector;
|
||||
|
||||
/**
|
||||
* This class will generate google chart server url's.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
public class ChartURLGenerator {
|
||||
|
||||
private static final String CHARTS_BASE_URL =
|
||||
"http://chart.apis.google.com/chart?";
|
||||
|
||||
private ChartURLGenerator() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a chart of a track.
|
||||
*
|
||||
* @param distances An array of distance measurements
|
||||
* @param elevations A matching array of elevation measurements
|
||||
* @param track The track for this chart
|
||||
* @param context The current appplication context
|
||||
*/
|
||||
public static String getChartUrl(Vector<Double> distances,
|
||||
Vector<Double> elevations, Track track, Context context) {
|
||||
SharedPreferences preferences =
|
||||
context.getSharedPreferences(Constants.SETTINGS_NAME, 0);
|
||||
boolean metricUnits = true;
|
||||
if (preferences != null) {
|
||||
metricUnits = preferences.getBoolean(
|
||||
context.getString(R.string.metric_units_key), true);
|
||||
}
|
||||
|
||||
return getChartUrl(distances, elevations, track,
|
||||
context.getString(R.string.elevation_label), metricUnits);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a chart of a track.
|
||||
* This form is for testing without contexts.
|
||||
*
|
||||
* @param distances An array of distance measurements
|
||||
* @param elevations A matching array of elevation measurements
|
||||
* @param track The track for this chart
|
||||
* @param title The title for the chart
|
||||
* @param metricUnits Should the data be displayed in metric units
|
||||
*/
|
||||
public static String getChartUrl(
|
||||
Vector<Double> distances, Vector<Double> elevations,
|
||||
Track track, String title, boolean metricUnits) {
|
||||
if (distances == null || elevations == null || track == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (distances.size() != elevations.size()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Round it up.
|
||||
TripStatistics stats = track.getStatistics();
|
||||
double effectiveMaxY = metricUnits
|
||||
? stats.getMaxElevation()
|
||||
: stats.getMaxElevation() * UnitConversions.M_TO_FT;
|
||||
effectiveMaxY = ((int) (effectiveMaxY / 100)) * 100 + 100;
|
||||
// Round it down.
|
||||
double effectiveMinY = 0;
|
||||
double minElevation = metricUnits
|
||||
? stats.getMinElevation()
|
||||
: stats.getMinElevation() * UnitConversions.M_TO_FT;
|
||||
|
||||
effectiveMinY = ((int) (minElevation / 100)) * 100;
|
||||
if (stats.getMinElevation() < 0) {
|
||||
effectiveMinY -= 100;
|
||||
}
|
||||
double ySpread = effectiveMaxY - effectiveMinY;
|
||||
|
||||
StringBuilder sb = new StringBuilder(CHARTS_BASE_URL);
|
||||
sb.append("&chs=600x350");
|
||||
sb.append("&cht=lxy");
|
||||
|
||||
// Title
|
||||
sb.append("&chtt=");
|
||||
sb.append(title);
|
||||
|
||||
// Labels
|
||||
sb.append("&chxt=x,y");
|
||||
double distKM = stats.getTotalDistance() / 1000.0;
|
||||
double distDisplay =
|
||||
metricUnits ? distKM : (distKM * UnitConversions.KM_TO_MI);
|
||||
int xInterval = ((int) (distDisplay / 6));
|
||||
int yInterval = ((int) (ySpread / 600)) * 100;
|
||||
if (yInterval < 100) {
|
||||
yInterval = 25;
|
||||
}
|
||||
// Range
|
||||
sb.append("&chxr=0,0,");
|
||||
sb.append((int) distDisplay);
|
||||
sb.append(',');
|
||||
sb.append(xInterval);
|
||||
|
||||
sb.append("|1,");
|
||||
sb.append(effectiveMinY);
|
||||
sb.append(',');
|
||||
sb.append(effectiveMaxY);
|
||||
sb.append(',');
|
||||
sb.append(yInterval);
|
||||
|
||||
// Line color
|
||||
sb.append("&chco=009A00");
|
||||
|
||||
// Fill
|
||||
sb.append("&chm=B,00AA00,0,0,0");
|
||||
|
||||
// Grid lines
|
||||
double desiredGrids = ySpread / yInterval;
|
||||
sb.append("&chg=100000,");
|
||||
sb.append(100.0 / desiredGrids);
|
||||
sb.append(",1,0");
|
||||
|
||||
// Data
|
||||
sb.append("&chd=e:");
|
||||
for (int i = 0; i < distances.size(); i++) {
|
||||
int normalized =
|
||||
(int) (getNormalizedDistance(distances.elementAt(i), track) * 4095);
|
||||
sb.append(ChartsExtendedEncoder.getEncodedValue(normalized));
|
||||
}
|
||||
|
||||
sb.append(ChartsExtendedEncoder.getSeparator());
|
||||
for (int i = 0; i < elevations.size(); i++) {
|
||||
int normalized =
|
||||
(int) (getNormalizedElevation(
|
||||
elevations.elementAt(i), effectiveMinY, ySpread) * 4095);
|
||||
sb.append(ChartsExtendedEncoder.getEncodedValue(normalized));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static double getNormalizedDistance(double d, Track track) {
|
||||
return d / track.getStatistics().getTotalDistance();
|
||||
}
|
||||
|
||||
private static double getNormalizedElevation(
|
||||
double d, double effectiveMinY, double ySpread) {
|
||||
return (d - effectiveMinY) / ySpread;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
/**
|
||||
* The singleton class representing the extended encoding of chart data.
|
||||
*/
|
||||
public class ChartsExtendedEncoder {
|
||||
|
||||
// ChartServer data encoding in extended mode
|
||||
private static final String CHARTSERVER_EXTENDED_ENCODING_SEPARATOR = ",";
|
||||
private static final String CHARTSERVER_EXTENDED_ENCODING =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
|
||||
private static final int CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES =
|
||||
CHARTSERVER_EXTENDED_ENCODING.length();
|
||||
private static final String MISSING_POINT_EXTENDED_ENCODING = "__";
|
||||
|
||||
private ChartsExtendedEncoder() { }
|
||||
|
||||
public static String getEncodedValue(int scaled) {
|
||||
int index1 = scaled / CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
|
||||
if (index1 < 0 || index1 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
|
||||
return MISSING_POINT_EXTENDED_ENCODING;
|
||||
}
|
||||
|
||||
int index2 = scaled % CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
|
||||
if (index2 < 0 || index2 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
|
||||
return MISSING_POINT_EXTENDED_ENCODING;
|
||||
}
|
||||
|
||||
return String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index1))
|
||||
+ String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index2));
|
||||
}
|
||||
|
||||
public static String getSeparator() {
|
||||
return CHARTSERVER_EXTENDED_ENCODING_SEPARATOR;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
|
||||
import android.os.Environment;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Utilities for dealing with files.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class FileUtils {
|
||||
/**
|
||||
* The maximum length of a filename, as per the FAT32 specification.
|
||||
*/
|
||||
private static final int MAX_FILENAME_LENGTH = 260;
|
||||
|
||||
/**
|
||||
* A set of characters that are prohibited from being in file names.
|
||||
*/
|
||||
private static final Pattern PROHIBITED_CHAR_PATTERN =
|
||||
Pattern.compile("[^ A-Za-z0-9_.()-]+");
|
||||
|
||||
/**
|
||||
* Builds a path inside the My Tracks directory in the SD card.
|
||||
*
|
||||
* @param components the path components inside the mytracks directory
|
||||
* @return the full path to the destination
|
||||
*/
|
||||
public String buildExternalDirectoryPath(String... components) {
|
||||
StringBuilder dirNameBuilder = new StringBuilder();
|
||||
dirNameBuilder.append(Environment.getExternalStorageDirectory());
|
||||
dirNameBuilder.append(File.separatorChar);
|
||||
dirNameBuilder.append(Constants.SDCARD_TOP_DIR);
|
||||
for (String component : components) {
|
||||
dirNameBuilder.append(File.separatorChar);
|
||||
dirNameBuilder.append(component);
|
||||
}
|
||||
return dirNameBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the SD card is available.
|
||||
*/
|
||||
public boolean isSdCardAvailable() {
|
||||
return Environment.MEDIA_MOUNTED.equals(
|
||||
Environment.getExternalStorageState());
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the input string and make sure it is a valid fat32 file name.
|
||||
*
|
||||
* @param name the name to normalize
|
||||
* @return the sanitized name
|
||||
*/
|
||||
String sanitizeName(String name) {
|
||||
String cleaned = PROHIBITED_CHAR_PATTERN.matcher(name).replaceAll("");
|
||||
|
||||
return (cleaned.length() > MAX_FILENAME_LENGTH)
|
||||
? cleaned.substring(0, MAX_FILENAME_LENGTH)
|
||||
: cleaned.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the given directory exists by creating it and its parents if
|
||||
* necessary.
|
||||
*
|
||||
* @return whether the directory exists (either already existed or was
|
||||
* successfully created)
|
||||
*/
|
||||
public boolean ensureDirectoryExists(File dir) {
|
||||
if (dir.exists() && dir.isDirectory()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (dir.mkdirs()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a filename with the given base name (prefix) and the given
|
||||
* extension, possibly adding a suffix to ensure the file doesn't exist.
|
||||
*
|
||||
* @param directory the directory the file will live in
|
||||
* @param fileBaseName the prefix for the file name
|
||||
* @param extension the file's extension
|
||||
* @return the complete file name, without the directory
|
||||
*/
|
||||
public synchronized String buildUniqueFileName(File directory,
|
||||
String fileBaseName, String extension) {
|
||||
return buildUniqueFileName(directory, fileBaseName, extension, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a filename with the given base name (prefix) and the given
|
||||
* extension, possibly adding a suffix to ensure the file doesn't exist.
|
||||
*
|
||||
* @param directory the directory the file will live in
|
||||
* @param fileBaseName the prefix for the file name
|
||||
* @param extension the file's extension
|
||||
* @param suffix the first numeric suffix to try to use, or 0 for none
|
||||
* @return the complete file name, without the directory
|
||||
*/
|
||||
private String buildUniqueFileName(File directory, String fileBaseName,
|
||||
String extension, int suffix) {
|
||||
String suffixedBaseName = fileBaseName;
|
||||
if (suffix > 0) {
|
||||
suffixedBaseName += " (" + Integer.toString(suffix) + ")";
|
||||
}
|
||||
|
||||
String fullName = suffixedBaseName + "." + extension;
|
||||
String sanitizedName = sanitizeName(fullName);
|
||||
if (!fileExists(directory, sanitizedName)) {
|
||||
return sanitizedName;
|
||||
}
|
||||
|
||||
return buildUniqueFileName(directory, fileBaseName, extension, suffix + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a file with the given name exists in the given directory.
|
||||
* This is isolated so it can be overridden in tests.
|
||||
*/
|
||||
protected boolean fileExists(File directory, String fullName) {
|
||||
File file = new File(directory, fullName);
|
||||
return file.exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2009 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import com.google.android.maps.GeoPoint;
|
||||
|
||||
/**
|
||||
* A rectangle in geographical space.
|
||||
*/
|
||||
public class GeoRect {
|
||||
public int top;
|
||||
public int left;
|
||||
public int bottom;
|
||||
public int right;
|
||||
|
||||
public GeoRect() {
|
||||
top = 0;
|
||||
left = 0;
|
||||
bottom = 0;
|
||||
right = 0;
|
||||
}
|
||||
|
||||
public GeoRect(GeoPoint center, int latSpan, int longSpan) {
|
||||
top = center.getLatitudeE6() - latSpan / 2;
|
||||
left = center.getLongitudeE6() - longSpan / 2;
|
||||
bottom = center.getLatitudeE6() + latSpan / 2;
|
||||
right = center.getLongitudeE6() + longSpan / 2;
|
||||
}
|
||||
|
||||
public GeoPoint getCenter() {
|
||||
return new GeoPoint(top / 2 + bottom / 2, left / 2 + right / 2);
|
||||
}
|
||||
|
||||
public int getLatSpan() {
|
||||
return bottom - top;
|
||||
}
|
||||
|
||||
public int getLongSpan() {
|
||||
return right - left;
|
||||
}
|
||||
|
||||
public boolean contains(GeoPoint geoPoint) {
|
||||
if (geoPoint.getLatitudeE6() >= top
|
||||
&& geoPoint.getLatitudeE6() <= bottom
|
||||
&& geoPoint.getLongitudeE6() >= left
|
||||
&& geoPoint.getLongitudeE6() <= right) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
|
||||
import com.google.android.maps.GeoPoint;
|
||||
|
||||
import android.location.Location;
|
||||
import android.util.Log;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Utility class for decimating tracks at a given level of precision.
|
||||
*
|
||||
* @author Leif Hendrik Wilden
|
||||
*/
|
||||
public class LocationUtils {
|
||||
/**
|
||||
* Computes the distance on the two sphere between the point c0 and the line
|
||||
* segment c1 to c2.
|
||||
*
|
||||
* @param c0 the first coordinate
|
||||
* @param c1 the beginning of the line segment
|
||||
* @param c2 the end of the lone segment
|
||||
* @return the distance in m (assuming spherical earth)
|
||||
*/
|
||||
public static double distance(
|
||||
final Location c0, final Location c1, final Location c2) {
|
||||
if (c1.equals(c2)) {
|
||||
return c2.distanceTo(c0);
|
||||
}
|
||||
|
||||
final double s0lat = c0.getLatitude() * UnitConversions.TO_RADIANS;
|
||||
final double s0lng = c0.getLongitude() * UnitConversions.TO_RADIANS;
|
||||
final double s1lat = c1.getLatitude() * UnitConversions.TO_RADIANS;
|
||||
final double s1lng = c1.getLongitude() * UnitConversions.TO_RADIANS;
|
||||
final double s2lat = c2.getLatitude() * UnitConversions.TO_RADIANS;
|
||||
final double s2lng = c2.getLongitude() * UnitConversions.TO_RADIANS;
|
||||
|
||||
double s2s1lat = s2lat - s1lat;
|
||||
double s2s1lng = s2lng - s1lng;
|
||||
final double u =
|
||||
((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng)
|
||||
/ (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
|
||||
if (u <= 0) {
|
||||
return c0.distanceTo(c1);
|
||||
}
|
||||
if (u >= 1) {
|
||||
return c0.distanceTo(c2);
|
||||
}
|
||||
Location sa = new Location("");
|
||||
sa.setLatitude(c0.getLatitude() - c1.getLatitude());
|
||||
sa.setLongitude(c0.getLongitude() - c1.getLongitude());
|
||||
Location sb = new Location("");
|
||||
sb.setLatitude(u * (c2.getLatitude() - c1.getLatitude()));
|
||||
sb.setLongitude(u * (c2.getLongitude() - c1.getLongitude()));
|
||||
return sa.distanceTo(sb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decimates the given locations for a given zoom level. This uses a
|
||||
* Douglas-Peucker decimation algorithm.
|
||||
*
|
||||
* @param tolerance in meters
|
||||
* @param locations input
|
||||
* @param decimated output
|
||||
*/
|
||||
public static void decimate(double tolerance, ArrayList<Location> locations,
|
||||
ArrayList<Location> decimated) {
|
||||
final int n = locations.size();
|
||||
if (n < 1) {
|
||||
return;
|
||||
}
|
||||
int idx;
|
||||
int maxIdx = 0;
|
||||
Stack<int[]> stack = new Stack<int[]>();
|
||||
double[] dists = new double[n];
|
||||
dists[0] = 1;
|
||||
dists[n - 1] = 1;
|
||||
double maxDist;
|
||||
double dist = 0.0;
|
||||
int[] current;
|
||||
|
||||
if (n > 2) {
|
||||
int[] stackVal = new int[] {0, (n - 1)};
|
||||
stack.push(stackVal);
|
||||
while (stack.size() > 0) {
|
||||
current = stack.pop();
|
||||
maxDist = 0;
|
||||
for (idx = current[0] + 1; idx < current[1]; ++idx) {
|
||||
dist = LocationUtils.distance(
|
||||
locations.get(idx),
|
||||
locations.get(current[0]),
|
||||
locations.get(current[1]));
|
||||
if (dist > maxDist) {
|
||||
maxDist = dist;
|
||||
maxIdx = idx;
|
||||
}
|
||||
}
|
||||
if (maxDist > tolerance) {
|
||||
dists[maxIdx] = maxDist;
|
||||
int[] stackValCurMax = {current[0], maxIdx};
|
||||
stack.push(stackValCurMax);
|
||||
int[] stackValMaxCur = {maxIdx, current[1]};
|
||||
stack.push(stackValMaxCur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
idx = 0;
|
||||
decimated.clear();
|
||||
for (Location l : locations) {
|
||||
if (dists[idx] != 0) {
|
||||
decimated.add(l);
|
||||
i++;
|
||||
}
|
||||
idx++;
|
||||
}
|
||||
Log.d(Constants.TAG, "Decimating " + n + " points to " + i
|
||||
+ " w/ tolerance = " + tolerance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decimates the given track for the given precision.
|
||||
*
|
||||
* @param track a track
|
||||
* @param precision desired precision in meters
|
||||
*/
|
||||
public static void decimate(Track track, double precision) {
|
||||
ArrayList<Location> decimated = new ArrayList<Location>();
|
||||
decimate(precision, track.getLocations(), decimated);
|
||||
track.setLocations(decimated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Limits number of points by dropping any points beyond the given number of
|
||||
* points. Note: That'll actually discard points.
|
||||
*
|
||||
* @param track a track
|
||||
* @param numberOfPoints maximum number of points
|
||||
*/
|
||||
public static void cut(Track track, int numberOfPoints) {
|
||||
ArrayList<Location> locations = track.getLocations();
|
||||
while (locations.size() > numberOfPoints) {
|
||||
locations.remove(locations.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a track in multiple tracks where each piece has less or equal than
|
||||
* maxPoints.
|
||||
*
|
||||
* @param track the track to split
|
||||
* @param maxPoints maximum number of points for each piece
|
||||
* @return a list of one or more track pieces
|
||||
*/
|
||||
public static ArrayList<Track> split(Track track, int maxPoints) {
|
||||
ArrayList<Track> result = new ArrayList<Track>();
|
||||
final int nTotal = track.getLocations().size();
|
||||
int n = 0;
|
||||
Track piece = null;
|
||||
do {
|
||||
piece = new Track();
|
||||
TripStatistics pieceStats = piece.getStatistics();
|
||||
piece.setId(track.getId());
|
||||
piece.setName(track.getName());
|
||||
piece.setDescription(track.getDescription());
|
||||
piece.setCategory(track.getCategory());
|
||||
List<Location> pieceLocations = piece.getLocations();
|
||||
for (int i = n; i < nTotal && pieceLocations.size() < maxPoints; i++) {
|
||||
piece.addLocation(track.getLocations().get(i));
|
||||
}
|
||||
int nPointsPiece = pieceLocations.size();
|
||||
if (nPointsPiece >= 2) {
|
||||
pieceStats.setStartTime(pieceLocations.get(0).getTime());
|
||||
pieceStats.setStopTime(pieceLocations.get(nPointsPiece - 1).getTime());
|
||||
result.add(piece);
|
||||
}
|
||||
n += (pieceLocations.size() - 1);
|
||||
} while (n < nTotal && piece.getLocations().size() > 1);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if a given GeoPoint is valid, i.e. within physical bounds.
|
||||
*
|
||||
* @param geoPoint the point to be tested
|
||||
* @return true, if it is a physical location on earth.
|
||||
*/
|
||||
public static boolean isValidGeoPoint(GeoPoint geoPoint) {
|
||||
return Math.abs(geoPoint.getLatitudeE6()) < 90E6
|
||||
&& Math.abs(geoPoint.getLongitudeE6()) <= 180E6;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given location is a valid (i.e. physically possible) location
|
||||
* on Earth. Note: The special separator locations (which have latitude =
|
||||
* 100) will not qualify as valid. Neither will locations with lat=0 and lng=0
|
||||
* as these are most likely "bad" measurements which often cause trouble.
|
||||
*
|
||||
* @param location the location to test
|
||||
* @return true if the location is a valid location.
|
||||
*/
|
||||
public static boolean isValidLocation(Location location) {
|
||||
return location != null && Math.abs(location.getLatitude()) <= 90
|
||||
&& Math.abs(location.getLongitude()) <= 180;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a location from a GeoPoint.
|
||||
*
|
||||
* @param p a GeoPoint
|
||||
* @return the corresponding location
|
||||
*/
|
||||
public static Location getLocation(GeoPoint p) {
|
||||
Location result = new Location("");
|
||||
result.setLatitude(p.getLatitudeE6() / 1.0E6);
|
||||
result.setLongitude(p.getLongitudeE6() / 1.0E6);
|
||||
return result;
|
||||
}
|
||||
|
||||
public static GeoPoint getGeoPoint(Location location) {
|
||||
return new GeoPoint((int) (location.getLatitude() * 1E6),
|
||||
(int) (location.getLongitude() * 1E6));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is a utility class w/ only static members.
|
||||
*/
|
||||
private LocationUtils() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* Utility functions for android resources.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
public class ResourceUtils {
|
||||
public static CharSequence readFile(Context activity, int id) {
|
||||
BufferedReader in = null;
|
||||
try {
|
||||
in = new BufferedReader(new InputStreamReader(
|
||||
activity.getResources().openRawResource(id)));
|
||||
String line;
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
while ((line = in.readLine()) != null) {
|
||||
buffer.append(line).append('\n');
|
||||
}
|
||||
return buffer;
|
||||
} catch (IOException e) {
|
||||
return "";
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void readBinaryFileToOutputStream(
|
||||
Context activity, int id, OutputStream os) {
|
||||
BufferedInputStream in = null;
|
||||
BufferedOutputStream out = null;
|
||||
try {
|
||||
in = new BufferedInputStream(
|
||||
activity.getResources().openRawResource(id));
|
||||
out = new BufferedOutputStream(os);
|
||||
int b;
|
||||
while ((b = in.read()) != -1) {
|
||||
out.write(b);
|
||||
}
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
return;
|
||||
} finally {
|
||||
if (in != null) {
|
||||
try {
|
||||
in.close();
|
||||
} catch (IOException e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
if (out != null) {
|
||||
try {
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ResourceUtils() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.android.apps.mytracks.content.DescriptionGenerator;
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.content.Waypoint;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.ParsePosition;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.SimpleTimeZone;
|
||||
import java.util.Vector;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Various string manipulation methods.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class StringUtils implements DescriptionGenerator {
|
||||
|
||||
private final Context context;
|
||||
|
||||
/**
|
||||
* Formats a number of milliseconds as a string.
|
||||
*
|
||||
* @param time - A period of time in milliseconds.
|
||||
* @return A string of the format M:SS, MM:SS or HH:MM:SS
|
||||
*/
|
||||
public static String formatTime(long time) {
|
||||
return formatTimeInternal(time, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number of milliseconds as a string. To be used when we need the
|
||||
* hours to be shown even when it is zero, e.g. exporting data to a
|
||||
* spreadsheet.
|
||||
*
|
||||
* @param time - A period of time in milliseconds
|
||||
* @return A string of the format HH:MM:SS even if time is less than 1 hour
|
||||
*/
|
||||
public static String formatTimeAlwaysShowingHours(long time) {
|
||||
return formatTimeInternal(time, true);
|
||||
}
|
||||
|
||||
private static final DecimalFormat SINGLE_DECIMAL_PLACE_FORMAT = new DecimalFormat("#.#");
|
||||
|
||||
/**
|
||||
* Formats a double precision number as decimal number with a single decimal
|
||||
* place.
|
||||
*
|
||||
* @param number A double precision number
|
||||
* @return A string representation of a decimal number, derived from the input
|
||||
* double, with a single decimal place
|
||||
*/
|
||||
public static final String formatSingleDecimalPlace(double number) {
|
||||
return SINGLE_DECIMAL_PLACE_FORMAT.format(number);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats the given text as a CDATA element to be used in a XML file. This
|
||||
* includes adding the starting and ending CDATA tags. Please notice that this
|
||||
* may result in multiple consecutive CDATA tags.
|
||||
*
|
||||
* @param unescaped the unescaped text to be formatted
|
||||
* @return the formatted text, inside one or more CDATA tags
|
||||
*/
|
||||
public static String stringAsCData(String unescaped) {
|
||||
// "]]>" needs to be broken into multiple CDATA segments, like:
|
||||
// "Foo]]>Bar" becomes "<![CDATA[Foo]]]]><![CDATA[>Bar]]>"
|
||||
// (the end of the first CDATA has the "]]", the other has ">")
|
||||
String escaped = unescaped.replaceAll("]]>", "]]]]><![CDATA[>");
|
||||
return "<![CDATA[" + escaped + "]]>";
|
||||
}
|
||||
|
||||
private static final SimpleDateFormat BASE_XML_DATE_FORMAT =
|
||||
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||||
static {
|
||||
BASE_XML_DATE_FORMAT.setTimeZone(new SimpleTimeZone(0, "UTC"));
|
||||
}
|
||||
private static final Pattern XML_DATE_EXTRAS_PATTERN =
|
||||
Pattern.compile("^(\\.\\d+)?(?:Z|([+-])(\\d{2}):(\\d{2}))?$");
|
||||
|
||||
/**
|
||||
* Parses an XML dateTime element as defined by the XML standard.
|
||||
*
|
||||
* @see <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">dateTime</a>
|
||||
*/
|
||||
public static long parseXmlDateTime(String xmlTime) {
|
||||
// Parse the base date (fixed format)
|
||||
ParsePosition position = new ParsePosition(0);
|
||||
Date date = BASE_XML_DATE_FORMAT.parse(xmlTime, position);
|
||||
if (date == null) {
|
||||
throw new IllegalArgumentException("Invalid XML dateTime value: '" + xmlTime
|
||||
+ "' (at position " + position.getErrorIndex() + ")");
|
||||
}
|
||||
|
||||
// Parse the extras
|
||||
Matcher matcher =
|
||||
XML_DATE_EXTRAS_PATTERN.matcher(xmlTime.substring(position.getIndex()));
|
||||
if (!matcher.matches()) {
|
||||
// This will match even an empty string as all groups are optional,
|
||||
// so a non-match means some other garbage was there
|
||||
throw new IllegalArgumentException("Invalid XML dateTime value: " + xmlTime);
|
||||
}
|
||||
|
||||
long time = date.getTime();
|
||||
|
||||
// Account for fractional seconds
|
||||
String fractional = matcher.group(1);
|
||||
if (fractional != null) {
|
||||
// Regex ensures fractional part is in (0,1(
|
||||
float fractionalSeconds = Float.parseFloat(fractional);
|
||||
long fractionalMillis = (long) (fractionalSeconds * 1000.0f);
|
||||
time += fractionalMillis;
|
||||
}
|
||||
|
||||
// Account for timezones
|
||||
String sign = matcher.group(2);
|
||||
String offsetHoursStr = matcher.group(3);
|
||||
String offsetMinsStr = matcher.group(4);
|
||||
if (sign != null && offsetHoursStr != null && offsetMinsStr != null) {
|
||||
// Regex ensures sign is + or -
|
||||
boolean plusSign = sign.equals("+");
|
||||
int offsetHours = Integer.parseInt(offsetHoursStr);
|
||||
int offsetMins = Integer.parseInt(offsetMinsStr);
|
||||
|
||||
// Regex ensures values are >= 0
|
||||
if (offsetHours > 14 || offsetMins > 59) {
|
||||
throw new IllegalArgumentException("Bad timezone in " + xmlTime);
|
||||
}
|
||||
|
||||
long totalOffsetMillis = (offsetMins + offsetHours * 60L) * 60000L;
|
||||
|
||||
// Make time go back to UTC
|
||||
if (plusSign) {
|
||||
time -= totalOffsetMillis;
|
||||
} else {
|
||||
time += totalOffsetMillis;
|
||||
}
|
||||
}
|
||||
|
||||
return time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a number of milliseconds as a string.
|
||||
*
|
||||
* @param time - A period of time in milliseconds
|
||||
* @param alwaysShowHours - Whether to display 00 hours if time is less than 1
|
||||
* hour
|
||||
* @return A string of the format HH:MM:SS
|
||||
*/
|
||||
private static String formatTimeInternal(long time, boolean alwaysShowHours) {
|
||||
int[] parts = getTimeParts(time);
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (parts[2] > 0 || alwaysShowHours) {
|
||||
builder.append(parts[2]);
|
||||
builder.append(':');
|
||||
if (parts[1] <= 9) {
|
||||
builder.append("0");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append(parts[1]);
|
||||
builder.append(':');
|
||||
if (parts[0] <= 9) {
|
||||
builder.append("0");
|
||||
}
|
||||
builder.append(parts[0]);
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the time as an array of parts.
|
||||
*/
|
||||
public static int[] getTimeParts(long time) {
|
||||
if (time < 0) {
|
||||
int[] parts = getTimeParts(time * -1);
|
||||
parts[0] *= -1;
|
||||
parts[1] *= -1;
|
||||
parts[2] *= -1;
|
||||
return parts;
|
||||
}
|
||||
int[] parts = new int[3];
|
||||
|
||||
long seconds = time / 1000;
|
||||
parts[0] = (int) (seconds % 60);
|
||||
int tmp = (int) (seconds / 60);
|
||||
parts[1] = tmp % 60;
|
||||
parts[2] = tmp / 60;
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
public StringUtils(Context context) {
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public String formatTimeLong(long time) {
|
||||
int[] parts = getTimeParts(time);
|
||||
String secLabel =
|
||||
context.getString(parts[0] == 1 ? R.string.second : R.string.seconds);
|
||||
String minLabel =
|
||||
context.getString(parts[1] == 1 ? R.string.minute : R.string.minutes);
|
||||
String hourLabel =
|
||||
context.getString(parts[2] == 1 ? R.string.hour : R.string.hours);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
if (parts[2] != 0) {
|
||||
sb.append(parts[2]);
|
||||
sb.append(" ");
|
||||
sb.append(hourLabel);
|
||||
sb.append(" ");
|
||||
sb.append(parts[1]);
|
||||
sb.append(minLabel);
|
||||
} else {
|
||||
sb.append(parts[1]);
|
||||
sb.append(" ");
|
||||
sb.append(minLabel);
|
||||
sb.append(" ");
|
||||
sb.append(parts[0]);
|
||||
sb.append(secLabel);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a description for a track (with information about the
|
||||
* statistics).
|
||||
*
|
||||
* @param track the track
|
||||
* @return a track description
|
||||
*/
|
||||
public String generateTrackDescription(Track track, Vector<Double> distances,
|
||||
Vector<Double> elevations) {
|
||||
boolean displaySpeed = true;
|
||||
SharedPreferences preferences =
|
||||
context.getSharedPreferences(Constants.SETTINGS_NAME, 0);
|
||||
if (preferences != null) {
|
||||
displaySpeed =
|
||||
preferences.getBoolean(context.getString(R.string.report_speed_key), true);
|
||||
}
|
||||
|
||||
TripStatistics trackStats = track.getStatistics();
|
||||
final double distanceInKm = trackStats.getTotalDistance() / 1000;
|
||||
final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI;
|
||||
final long minElevationInMeters = Math.round(trackStats.getMinElevation());
|
||||
final long minElevationInFeet =
|
||||
Math.round(trackStats.getMinElevation() * UnitConversions.M_TO_FT);
|
||||
final long maxElevationInMeters = Math.round(trackStats.getMaxElevation());
|
||||
final long maxElevationInFeet =
|
||||
Math.round(trackStats.getMaxElevation() * UnitConversions.M_TO_FT);
|
||||
final long elevationGainInMeters =
|
||||
Math.round(trackStats.getTotalElevationGain());
|
||||
final long elevationGainInFeet = Math.round(
|
||||
trackStats.getTotalElevationGain() * UnitConversions.M_TO_FT);
|
||||
|
||||
long minGrade = 0;
|
||||
long maxGrade = 0;
|
||||
double trackMaxGrade = trackStats.getMaxGrade();
|
||||
double trackMinGrade = trackStats.getMinGrade();
|
||||
if (!Double.isNaN(trackMaxGrade)
|
||||
&& !Double.isInfinite(trackMaxGrade)) {
|
||||
maxGrade = Math.round(trackMaxGrade * 100);
|
||||
}
|
||||
if (!Double.isNaN(trackMinGrade) && !Double.isInfinite(trackMinGrade)) {
|
||||
minGrade = Math.round(trackMinGrade * 100);
|
||||
}
|
||||
|
||||
String category = context.getString(R.string.unknown);
|
||||
String trackCategory = track.getCategory();
|
||||
if (trackCategory != null && trackCategory.length() > 0) {
|
||||
category = trackCategory;
|
||||
}
|
||||
|
||||
String averageSpeed =
|
||||
getSpeedString(trackStats.getAverageSpeed(),
|
||||
R.string.average_speed_label,
|
||||
R.string.average_pace_label,
|
||||
displaySpeed);
|
||||
|
||||
String averageMovingSpeed =
|
||||
getSpeedString(trackStats.getAverageMovingSpeed(),
|
||||
R.string.average_moving_speed_label,
|
||||
R.string.average_moving_pace_label,
|
||||
displaySpeed);
|
||||
|
||||
String maxSpeed =
|
||||
getSpeedString(trackStats.getMaxSpeed(),
|
||||
R.string.max_speed_label,
|
||||
R.string.min_pace_label,
|
||||
displaySpeed);
|
||||
|
||||
return String.format("%s<p>"
|
||||
+ "%s: %.2f %s (%.1f %s)<br>"
|
||||
+ "%s: %s<br>"
|
||||
+ "%s: %s<br>"
|
||||
+ "%s %s %s"
|
||||
+ "%s: %d %s (%d %s)<br>"
|
||||
+ "%s: %d %s (%d %s)<br>"
|
||||
+ "%s: %d %s (%d %s)<br>"
|
||||
+ "%s: %d %%<br>"
|
||||
+ "%s: %d %%<br>"
|
||||
+ "%s: %tc<br>"
|
||||
+ "%s: %s<br>"
|
||||
+ "<img border=\"0\" src=\"%s\"/>",
|
||||
|
||||
// Line 1
|
||||
context.getString(R.string.send_to_google_by_mytracks),
|
||||
|
||||
// Line 2
|
||||
context.getString(R.string.total_distance_label),
|
||||
distanceInKm, context.getString(R.string.kilometer),
|
||||
distanceInMiles, context.getString(R.string.mile),
|
||||
|
||||
// Line 3
|
||||
context.getString(R.string.total_time_label),
|
||||
StringUtils.formatTime(trackStats.getTotalTime()),
|
||||
|
||||
// Line 4
|
||||
context.getString(R.string.moving_time_label),
|
||||
StringUtils.formatTime(trackStats.getMovingTime()),
|
||||
|
||||
// Line 5
|
||||
averageSpeed, averageMovingSpeed, maxSpeed,
|
||||
|
||||
// Line 6
|
||||
context.getString(R.string.min_elevation_label),
|
||||
minElevationInMeters, context.getString(R.string.meter),
|
||||
minElevationInFeet, context.getString(R.string.feet),
|
||||
|
||||
// Line 7
|
||||
context.getString(R.string.max_elevation_label),
|
||||
maxElevationInMeters, context.getString(R.string.meter),
|
||||
maxElevationInFeet, context.getString(R.string.feet),
|
||||
|
||||
// Line 8
|
||||
context.getString(R.string.elevation_gain_label),
|
||||
elevationGainInMeters, context.getString(R.string.meter),
|
||||
elevationGainInFeet, context.getString(R.string.feet),
|
||||
|
||||
// Line 9
|
||||
context.getString(R.string.max_grade_label), maxGrade,
|
||||
|
||||
// Line 10
|
||||
context.getString(R.string.min_grade_label), minGrade,
|
||||
|
||||
// Line 11
|
||||
context.getString(R.string.recorded_date),
|
||||
new Date(trackStats.getStartTime()),
|
||||
|
||||
// Line 12
|
||||
context.getString(R.string.category), category,
|
||||
|
||||
// Line 13
|
||||
ChartURLGenerator.getChartUrl(distances, elevations, track, context));
|
||||
}
|
||||
|
||||
private String getSpeedString(double speed, int speedLabel, int paceLabel,
|
||||
boolean displaySpeed) {
|
||||
double speedInKph = speed * 3.6;
|
||||
double speedInMph = speedInKph * UnitConversions.KMH_TO_MPH;
|
||||
if (displaySpeed) {
|
||||
return String.format("%s: %.2f %s (%.1f %s)<br>",
|
||||
context.getString(speedLabel),
|
||||
speedInKph, context.getString(R.string.kilometer_per_hour),
|
||||
speedInMph, context.getString(R.string.mile_per_hour));
|
||||
} else {
|
||||
double paceInKm;
|
||||
double paceInMi;
|
||||
if (speed == 0) {
|
||||
paceInKm = 0.0;
|
||||
paceInMi = 0.0;
|
||||
} else {
|
||||
paceInKm = 60.0 / speedInKph;
|
||||
paceInMi = 60.0 / speedInMph;
|
||||
}
|
||||
return String.format("%s: %.2f %s (%.1f %s)<br>",
|
||||
context.getString(paceLabel),
|
||||
paceInKm, context.getString(R.string.min_per_kilometer),
|
||||
paceInMi, context.getString(R.string.min_per_mile));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a description for a waypoint (with information about the
|
||||
* statistics).
|
||||
*
|
||||
* @return a track description
|
||||
*/
|
||||
public String generateWaypointDescription(Waypoint waypoint) {
|
||||
TripStatistics stats = waypoint.getStatistics();
|
||||
|
||||
final double distanceInKm = stats.getTotalDistance() / 1000;
|
||||
final double distanceInMiles = distanceInKm * UnitConversions.KM_TO_MI;
|
||||
final double averageSpeedInKmh = stats.getAverageSpeed() * 3.6;
|
||||
final double averageSpeedInMph =
|
||||
averageSpeedInKmh * UnitConversions.KMH_TO_MPH;
|
||||
final double movingSpeedInKmh = stats.getAverageMovingSpeed() * 3.6;
|
||||
final double movingSpeedInMph =
|
||||
movingSpeedInKmh * UnitConversions.KMH_TO_MPH;
|
||||
final double maxSpeedInKmh = stats.getMaxSpeed() * 3.6;
|
||||
final double maxSpeedInMph = maxSpeedInKmh * UnitConversions.KMH_TO_MPH;
|
||||
final long minElevationInMeters = Math.round(stats.getMinElevation());
|
||||
final long minElevationInFeet =
|
||||
Math.round(stats.getMinElevation() * UnitConversions.M_TO_FT);
|
||||
final long maxElevationInMeters = Math.round(stats.getMaxElevation());
|
||||
final long maxElevationInFeet =
|
||||
Math.round(stats.getMaxElevation() * UnitConversions.M_TO_FT);
|
||||
final long elevationGainInMeters =
|
||||
Math.round(stats.getTotalElevationGain());
|
||||
final long elevationGainInFeet = Math.round(
|
||||
stats.getTotalElevationGain() * UnitConversions.M_TO_FT);
|
||||
long theMinGrade = 0;
|
||||
long theMaxGrade = 0;
|
||||
double maxGrade = stats.getMaxGrade();
|
||||
double minGrade = stats.getMinGrade();
|
||||
if (!Double.isNaN(maxGrade) &&
|
||||
!Double.isInfinite(maxGrade)) {
|
||||
theMaxGrade = Math.round(maxGrade * 100);
|
||||
}
|
||||
if (!Double.isNaN(minGrade) &&
|
||||
!Double.isInfinite(minGrade)) {
|
||||
theMinGrade = Math.round(minGrade * 100);
|
||||
}
|
||||
final String percent = "%";
|
||||
|
||||
return String.format(
|
||||
"%s: %.2f %s (%.1f %s)\n"
|
||||
+ "%s: %s\n"
|
||||
+ "%s: %s\n"
|
||||
+ "%s: %.2f %s (%.1f %s)\n"
|
||||
+ "%s: %.2f %s (%.1f %s)\n"
|
||||
+ "%s: %.2f %s (%.1f %s)\n"
|
||||
+ "%s: %d %s (%d %s)\n"
|
||||
+ "%s: %d %s (%d %s)\n"
|
||||
+ "%s: %d %s (%d %s)\n"
|
||||
+ "%s: %d %s\n"
|
||||
+ "%s: %d %s\n",
|
||||
context.getString(R.string.distance_label),
|
||||
distanceInKm, context.getString(R.string.kilometer),
|
||||
distanceInMiles, context.getString(R.string.mile),
|
||||
context.getString(R.string.time_label),
|
||||
StringUtils.formatTime(stats.getTotalTime()),
|
||||
context.getString(R.string.moving_time_label),
|
||||
StringUtils.formatTime(stats.getMovingTime()),
|
||||
context.getString(R.string.average_speed_label),
|
||||
averageSpeedInKmh, context.getString(R.string.kilometer_per_hour),
|
||||
averageSpeedInMph, context.getString(R.string.mile_per_hour),
|
||||
context.getString(R.string.average_moving_speed_label),
|
||||
movingSpeedInKmh, context.getString(R.string.kilometer_per_hour),
|
||||
movingSpeedInMph, context.getString(R.string.mile_per_hour),
|
||||
context.getString(R.string.max_speed_label),
|
||||
maxSpeedInKmh, context.getString(R.string.kilometer_per_hour),
|
||||
maxSpeedInMph, context.getString(R.string.mile_per_hour),
|
||||
context.getString(R.string.min_elevation_label),
|
||||
minElevationInMeters, context.getString(R.string.meter),
|
||||
minElevationInFeet, context.getString(R.string.feet),
|
||||
context.getString(R.string.max_elevation_label),
|
||||
maxElevationInMeters, context.getString(R.string.meter),
|
||||
maxElevationInFeet, context.getString(R.string.feet),
|
||||
context.getString(R.string.elevation_gain_label),
|
||||
elevationGainInMeters, context.getString(R.string.meter),
|
||||
elevationGainInFeet, context.getString(R.string.feet),
|
||||
context.getString(R.string.max_grade_label),
|
||||
theMaxGrade, percent,
|
||||
context.getString(R.string.min_grade_label),
|
||||
theMinGrade, percent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.pm.PackageInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.pm.PackageManager.NameNotFoundException;
|
||||
import android.content.pm.Signature;
|
||||
import android.os.PowerManager;
|
||||
import android.os.PowerManager.WakeLock;
|
||||
import android.util.Log;
|
||||
|
||||
/**
|
||||
* Utility class for acessing basic Android functionality.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class SystemUtils {
|
||||
|
||||
private static final int RELEASE_SIGNATURE_HASHCODE = -1855564782;
|
||||
|
||||
/**
|
||||
* Returns whether or not this is a release build.
|
||||
*/
|
||||
public static boolean isRelease(Context context) {
|
||||
try {
|
||||
Signature [] sigs = context.getPackageManager().getPackageInfo(
|
||||
context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
|
||||
for (Signature sig : sigs) {
|
||||
if (sig.hashCode() == RELEASE_SIGNATURE_HASHCODE) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (NameNotFoundException e) {
|
||||
Log.e(Constants.TAG, "Unable to get signatures", e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the My Tracks version from the manifest.
|
||||
*
|
||||
* @return the version, or an empty string in case of failure.
|
||||
*/
|
||||
public static String getMyTracksVersion(Context context) {
|
||||
try {
|
||||
PackageInfo pi = context.getPackageManager().getPackageInfo(
|
||||
"com.google.android.maps.mytracks",
|
||||
PackageManager.GET_META_DATA);
|
||||
return pi.versionName;
|
||||
} catch (NameNotFoundException e) {
|
||||
Log.w(Constants.TAG, "Failed to get version info.", e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public static WakeLock acquireWakeLock(Activity activity, WakeLock wakeLock) {
|
||||
Log.i(Constants.TAG, "LocationUtils: Acquiring wake lock.");
|
||||
try {
|
||||
PowerManager pm = (PowerManager) activity
|
||||
.getSystemService(Context.POWER_SERVICE);
|
||||
if (pm == null) {
|
||||
Log.e(Constants.TAG, "LocationUtils: Power manager not found!");
|
||||
return wakeLock;
|
||||
}
|
||||
if (wakeLock == null) {
|
||||
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
|
||||
Constants.TAG);
|
||||
if (wakeLock == null) {
|
||||
Log.e(Constants.TAG,
|
||||
"LocationUtils: Could not create wake lock (null).");
|
||||
}
|
||||
return wakeLock;
|
||||
}
|
||||
if (!wakeLock.isHeld()) {
|
||||
wakeLock.acquire();
|
||||
if (!wakeLock.isHeld()) {
|
||||
Log.e(Constants.TAG,
|
||||
"LocationUtils: Could not acquire wake lock.");
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
Log.e(Constants.TAG,
|
||||
"LocationUtils: Caught unexpected exception: " + e.getMessage(), e);
|
||||
}
|
||||
return wakeLock;
|
||||
}
|
||||
|
||||
private SystemUtils() {}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
/**
|
||||
* Unit conversion constants.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
public abstract class UnitConversions {
|
||||
|
||||
public static final double KM_TO_MI = 0.621371192;
|
||||
public static final double M_TO_FT = 3.2808399;
|
||||
public static final double MI_TO_M = 1609.344;
|
||||
public static final double MI_TO_FEET = 5280.0;
|
||||
public static final double KMH_TO_MPH = 1000 * M_TO_FT / MI_TO_FEET;
|
||||
public static final double TO_RADIANS = Math.PI / 180.0;
|
||||
public static final double MPH_TO_KMH = 1.609344;
|
||||
|
||||
protected UnitConversions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import android.net.Uri;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Utilities for dealing with content and other types of URIs.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class UriUtils {
|
||||
|
||||
public static boolean matchesContentUri(Uri uri, Uri baseContentUri) {
|
||||
if (uri == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that scheme and authority are the same.
|
||||
if (!uri.getScheme().equals(baseContentUri.getScheme()) ||
|
||||
!uri.getAuthority().equals(baseContentUri.getAuthority())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Checks that all the base path components are in the URI.
|
||||
List<String> uriPathSegments = uri.getPathSegments();
|
||||
List<String> basePathSegments = baseContentUri.getPathSegments();
|
||||
if (basePathSegments.size() > uriPathSegments.size()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < basePathSegments.size(); i++) {
|
||||
if (!uriPathSegments.get(i).equals(basePathSegments.get(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean isFileUri(Uri uri) {
|
||||
return "file".equals(uri.getScheme());
|
||||
}
|
||||
|
||||
private UriUtils() {}
|
||||
}
|
||||
Reference in New Issue
Block a user