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 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.gdata.maps; /** * Metadata about a Google Maps map. */ public class MapsMapMetadata { private String title; private String description; private String gdataEditUri; private boolean searchable; public MapsMapMetadata() { title = ""; description = ""; gdataEditUri = ""; searchable = false; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getSearchable() { return searchable; } public void setSearchable(boolean searchable) { this.searchable = searchable; } public String getGDataEditUri() { return gdataEditUri; } public void setGDataEditUri(String editUri) { this.gdataEditUri = editUri; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/gdata/maps/MapsMapMetadata.java
Java
asf20
1,001
/* * 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.gdata; import com.google.wireless.gdata.client.QueryParams; import android.text.TextUtils; import android.util.Log; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Simple implementation of the QueryParams interface. */ // TODO: deal with categories public class QueryParamsImpl extends QueryParams { private final Map<String, String> mParams = new HashMap<String, String>(); @Override public void clear() { setEntryId(null); mParams.clear(); } @Override public String generateQueryUrl(String feedUrl) { if (TextUtils.isEmpty(getEntryId()) && mParams.isEmpty()) { // nothing to do return feedUrl; } // handle entry IDs if (!TextUtils.isEmpty(getEntryId())) { if (!mParams.isEmpty()) { throw new IllegalStateException("Cannot set both an entry ID " + "and other query paramters."); } return feedUrl + '/' + getEntryId(); } // otherwise, append the querystring params. StringBuilder sb = new StringBuilder(); sb.append(feedUrl); Set<String> params = mParams.keySet(); boolean first = true; if (feedUrl.contains("?")) { first = false; } else { sb.append('?'); } for (String param : params) { if (first) { first = false; } else { sb.append('&'); } sb.append(param); sb.append('='); String value = mParams.get(param); String encodedValue = null; try { encodedValue = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException uee) { // should not happen. Log.w("QueryParamsImpl", "UTF-8 not supported -- should not happen. " + "Using default encoding.", uee); encodedValue = URLEncoder.encode(value); } sb.append(encodedValue); } return sb.toString(); } @Override public String getParamValue(String param) { if (!(mParams.containsKey(param))) { return null; } return mParams.get(param); } @Override public void setParamValue(String param, String value) { mParams.put(param, value); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/gdata/QueryParamsImpl.java
Java
asf20
2,857
/* * 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.gdata; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.client.QueryParams; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.serializer.GDataSerializer; import android.text.TextUtils; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; /** * Implementation of a GDataClient using GoogleHttpClient to make HTTP requests. * Always issues GETs and POSTs, using the X-HTTP-Method-Override header when a * PUT or DELETE is desired, to avoid issues with firewalls, etc., that do not * allow methods other than GET or POST. */ public class AndroidGDataClient implements GDataClient { private static final String TAG = "GDataClient"; private static final boolean DEBUG = false; private static final String X_HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override"; private static final int MAX_REDIRECTS = 10; private final HttpClient httpClient; /** * Interface for creating HTTP requests. Used by * {@link AndroidGDataClient#createAndExecuteMethod}, since HttpUriRequest * does not allow for changing the URI after creation, e.g., when you want to * follow a redirect. */ private interface HttpRequestCreator { HttpUriRequest createRequest(URI uri); } private static class GetRequestCreator implements HttpRequestCreator { public HttpUriRequest createRequest(URI uri) { return new HttpGet(uri); } } private static class PostRequestCreator implements HttpRequestCreator { private final String mMethodOverride; private final HttpEntity mEntity; public PostRequestCreator(String methodOverride, HttpEntity entity) { mMethodOverride = methodOverride; mEntity = entity; } public HttpUriRequest createRequest(URI uri) { HttpPost post = new HttpPost(uri); if (mMethodOverride != null) { post.addHeader(X_HTTP_METHOD_OVERRIDE, mMethodOverride); } post.setEntity(mEntity); return post; } } // MAJOR TODO: make this work across redirects (if we can reset the // InputStream). // OR, read the bits into a local buffer (yuck, the media could be large). private static class MediaPutRequestCreator implements HttpRequestCreator { private final InputStream mMediaInputStream; private final String mContentType; public MediaPutRequestCreator(InputStream mediaInputStream, String contentType) { mMediaInputStream = mediaInputStream; mContentType = contentType; } public HttpUriRequest createRequest(URI uri) { HttpPost post = new HttpPost(uri); post.addHeader(X_HTTP_METHOD_OVERRIDE, "PUT"); InputStreamEntity entity = new InputStreamEntity(mMediaInputStream, -1 /* read until EOF */); entity.setContentType(mContentType); post.setEntity(entity); return post; } } /** * Creates a new AndroidGDataClient. */ public AndroidGDataClient() { httpClient = new DefaultHttpClient(); } public void close() { } /* * (non-Javadoc) * * @see GDataClient#encodeUri(java.lang.String) */ public String encodeUri(String uri) { String encodedUri; try { encodedUri = URLEncoder.encode(uri, "UTF-8"); } catch (UnsupportedEncodingException uee) { // should not happen. Log.e("JakartaGDataClient", "UTF-8 not supported -- should not happen. " + "Using default encoding.", uee); encodedUri = URLEncoder.encode(uri); } return encodedUri; } /* * (non-Javadoc) * * @see com.google.wireless.gdata.client.GDataClient#createQueryParams() */ public QueryParams createQueryParams() { return new QueryParamsImpl(); } // follows redirects private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null; int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException( "StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); } /** * Gets the input stream from a response entity. If the entity is gzipped * then this will get a stream over the uncompressed data. * * @param entity the entity whose content should be read * @return the input stream to read from * @throws IOException */ private static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) { return responseStream; } Header header = entity.getContentEncoding(); if (header == null) { return responseStream; } String contentEncoding = header.getValue(); if (contentEncoding == null) { return responseStream; } if (contentEncoding.contains("gzip")){ responseStream = new GZIPInputStream(responseStream); } return responseStream; } /* * (non-Javadoc) * * @see GDataClient#getFeedAsStream(java.lang.String, java.lang.String) */ public InputStream getFeedAsStream(String feedUrl, String authToken) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new GetRequestCreator(), feedUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to access feed."); } public InputStream getMediaEntryAsStream(String mediaEntryUrl, String authToken) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new GetRequestCreator(), mediaEntryUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to access media entry."); } /* * (non-Javadoc) * * @see GDataClient#createEntry */ public InputStream createEntry(String feedUrl, String authToken, GDataSerializer entry) throws HttpException, IOException { HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_CREATE); InputStream in = createAndExecuteMethod(new PostRequestCreator(null /* override */, entity), feedUrl, authToken); if (in != null) { return in; } throw new IOException("Unable to create entry."); } /* * (non-Javadoc) * * @see GDataClient#updateEntry */ public InputStream updateEntry(String editUri, String authToken, GDataSerializer entry) throws HttpException, IOException { HttpEntity entity = createEntityForEntry(entry, GDataSerializer.FORMAT_UPDATE); InputStream in = createAndExecuteMethod(new PostRequestCreator("PUT", entity), editUri, authToken); if (in != null) { return in; } throw new IOException("Unable to update entry."); } /* * (non-Javadoc) * * @see GDataClient#deleteEntry */ public void deleteEntry(String editUri, String authToken) throws HttpException, IOException { if (StringUtils.isEmpty(editUri)) { throw new IllegalArgumentException( "you must specify an non-empty edit url"); } InputStream in = createAndExecuteMethod( new PostRequestCreator("DELETE", null /* entity */), editUri, authToken); if (in == null) { throw new IOException("Unable to delete entry."); } try { in.close(); } catch (IOException ioe) { // ignore } } public InputStream updateMediaEntry(String editUri, String authToken, InputStream mediaEntryInputStream, String contentType) throws HttpException, IOException { InputStream in = createAndExecuteMethod(new MediaPutRequestCreator( mediaEntryInputStream, contentType), editUri, authToken); if (in != null) { return in; } throw new IOException("Unable to write media entry."); } private HttpEntity createEntityForEntry(GDataSerializer entry, int format) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { entry.serialize(baos, format); } catch (IOException ioe) { Log.e(TAG, "Unable to serialize entry.", ioe); throw ioe; } catch (ParseException pe) { Log.e(TAG, "Unable to serialize entry.", pe); throw new IOException("Unable to serialize entry: " + pe.getMessage()); } byte[] entryBytes = baos.toByteArray(); if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) { try { Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8")); } catch (UnsupportedEncodingException uee) { // should not happen throw new IllegalStateException("UTF-8 should be supported!", uee); } } AbstractHttpEntity entity = new ByteArrayEntity(entryBytes); entity.setContentType(entry.getContentType()); return entity; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/gdata/AndroidGDataClient.java
Java
asf20
14,518
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.io.docs.SendDocsActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.content.Intent; /** * An activity to send a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesActivity extends AbstractSendActivity { @Override protected AbstractSendAsyncTask createAsyncTask() { return new SendFusionTablesAsyncTask(this, sendRequest.getTrackId(), sendRequest.getAccount()); } @Override protected String getServiceName() { return getString(R.string.send_google_fusion_tables); } @Override protected void startNextActivity(boolean success, boolean isCancel) { sendRequest.setFusionTablesSuccess(success); Class<?> next = getNextClass(sendRequest, isCancel); Intent intent = new Intent(this, next).putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); startActivity(intent); finish(); } @VisibleForTesting Class<?> getNextClass(SendRequest request, boolean isCancel) { if (isCancel) { return UploadResultActivity.class; } else { if (request.isSendDocs()) { return SendDocsActivity.class; } else { return UploadResultActivity.class; } } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesActivity.java
Java
asf20
2,260
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.util.Strings; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * AsyncTask to send a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { private static final String APP_NAME_PREFIX = "Google-MyTracks-"; private static final String SQL_KEY = "sql="; private static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; private static final String FUSION_TABLES_BASE_URL = "https://www.google.com/fusiontables/api/query"; private static final int MAX_POINTS_PER_UPLOAD = 2048; private static final String GDATA_VERSION = "2"; private static final int PROGRESS_CREATE_TABLE = 0; private static final int PROGRESS_UNLIST_TABLE = 5; private static final int PROGRESS_UPLOAD_DATA_MIN = 10; private static final int PROGRESS_UPLOAD_DATA_MAX = 90; private static final int PROGRESS_UPLOAD_WAYPOINTS = 95; private static final int PROGRESS_COMPLETE = 100; // See http://support.google.com/fusiontables/bin/answer.py?hl=en&answer=185991 private static final String MARKER_TYPE_START = "large_green"; private static final String MARKER_TYPE_END = "large_red"; private static final String MARKER_TYPE_WAYPOINT = "large_yellow"; private static final String TAG = SendFusionTablesAsyncTask.class.getSimpleName(); private final Context context; private final long trackId; private final Account account; private final MyTracksProviderUtils myTracksProviderUtils; private final HttpRequestFactory httpRequestFactory; // The following variables are for per upload states private String authToken; private String tableId; int currentSegment; public SendFusionTablesAsyncTask( SendFusionTablesActivity activity, long trackId, Account account) { super(activity); this.trackId = trackId; this.account = account; context = activity.getApplicationContext(); myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context); HttpTransport transport = ApiAdapterFactory.getApiAdapter().getHttpTransport(); httpRequestFactory = transport.createRequestFactory(new MethodOverride()); } @Override protected void closeConnection() { // No action needed for Google Fusion Tables } @Override protected void saveResult() { Track track = myTracksProviderUtils.getTrack(trackId); if (track != null) { track.setTableId(tableId); myTracksProviderUtils.updateTrack(track); } else { Log.d(TAG, "No track"); } } @Override protected boolean performTask() { // Reset the per upload states authToken = null; tableId = null; currentSegment = 1; try { authToken = AccountManager.get(context).blockingGetAuthToken( account, SendFusionTablesUtils.SERVICE, false); } catch (OperationCanceledException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (AuthenticatorException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (IOException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } Track track = myTracksProviderUtils.getTrack(trackId); if (track == null) { Log.d(TAG, "Track is null"); return false; } // Create a new table publishProgress(PROGRESS_CREATE_TABLE); if (!createNewTable(track)) { // Retry upload in case the auth token is invalid return retryTask(); } // Unlist table publishProgress(PROGRESS_UNLIST_TABLE); if (!unlistTable()) { return false; } // Upload all the track points plus the start and end markers publishProgress(PROGRESS_UPLOAD_DATA_MIN); if (!uploadAllTrackPoints(track)) { return false; } // Upload all the waypoints publishProgress(PROGRESS_UPLOAD_WAYPOINTS); if (!uploadWaypoints()) { return false; } publishProgress(PROGRESS_COMPLETE); return true; } @Override protected void invalidateToken() { AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); } /** * Creates a new table. * * @param track the track * @return true if success. */ private boolean createNewTable(Track track) { String query = "CREATE TABLE '" + SendFusionTablesUtils.escapeSqlString(track.getName()) + "' (name:STRING,description:STRING,geometry:LOCATION,marker:STRING)"; return sendQuery(query, true); } /** * Unlists a table. * * @return true if success. */ private boolean unlistTable() { String query = "UPDATE TABLE " + tableId + " SET VISIBILITY = UNLISTED"; return sendQuery(query, false); } /** * Uploads all the points in a track. * * @param track the track * @return true if success. */ private boolean uploadAllTrackPoints(Track track) { Cursor locationsCursor = null; try { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = prefs.getBoolean(context.getString(R.string.metric_units_key), true); locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); if (locationsCursor == null) { Log.d(TAG, "Location cursor is null"); return false; } int locationsCount = locationsCursor.getCount(); List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; // For chart server, limit the number of elevation readings to 250. int elevationSamplingFrequency = Math.max(1, (int) (locationsCount / 250.0)); TripStatisticsBuilder tripStatisticsBuilder = new TripStatisticsBuilder( track.getStatistics().getStartTime()); DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); for (int i = 0; i < locationsCount; i++) { locationsCursor.moveToPosition(i); Location location = myTracksProviderUtils.createLocation(locationsCursor); locations.add(location); if (i == 0) { // Create a start marker String name = context.getString(R.string.marker_label_start, track.getName()); if (!createNewPoint(name, "", location, MARKER_TYPE_START)) { Log.d(TAG, "Unable to create the start marker"); return false; } } // Add to the distances and elevations vectors if (LocationUtils.isValidLocation(location)) { tripStatisticsBuilder.addLocation(location, location.getTime()); // All points go into the smoothing buffer elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); if (i % elevationSamplingFrequency == 0) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); } lastLocation = location; } // Upload periodically int readCount = i + 1; if (readCount % MAX_POINTS_PER_UPLOAD == 0) { if (!prepareAndUploadPoints(track, locations, false)) { Log.d(TAG, "Unable to upload points"); return false; } updateProgress(readCount, locationsCount); locations.clear(); } } // Do a final upload with the remaining locations if (!prepareAndUploadPoints(track, locations, true)) { Log.d(TAG, "Unable to upload points"); return false; } // Create an end marker if (lastLocation != null) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); DescriptionGenerator descriptionGenerator = new DescriptionGeneratorImpl(context); track.setDescription("<p>" + track.getDescription() + "</p><p>" + descriptionGenerator.generateTrackDescription(track, distances, elevations) + "</p>"); String name = context.getString(R.string.marker_label_end, track.getName()); if (!createNewPoint(name, track.getDescription(), lastLocation, MARKER_TYPE_END)) { Log.d(TAG, "Unable to create the end marker"); return false; } } return true; } finally { if (locationsCursor != null) { locationsCursor.close(); } } } /** * Prepares and uploads a list of locations from a track. * * @param track the track * @param locations the locations from the track * @param lastBatch true if it is the last batch of locations */ private boolean prepareAndUploadPoints(Track track, List<Location> locations, boolean lastBatch) { // Prepare locations ArrayList<Track> splitTracks = SendToGoogleUtils.prepareLocations(track, locations); // Upload segments boolean onlyOneSegment = lastBatch && currentSegment == 1 && splitTracks.size() == 1; for (Track splitTrack : splitTracks) { if (!onlyOneSegment) { splitTrack.setName(context.getString( R.string.send_google_track_part_label, splitTrack.getName(), currentSegment)); } if (!createNewLineString(splitTrack)) { Log.d(TAG, "Upload points failed"); return false; } currentSegment++; } return true; } /** * Uploads all the waypoints. * * @return true if success. */ private boolean uploadWaypoints() { Cursor cursor = null; try { cursor = myTracksProviderUtils.getWaypointsCursor( trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { // This will skip the first waypoint (it carries the stats for the // track). while (cursor.moveToNext()) { Waypoint wpt = myTracksProviderUtils.createWaypoint(cursor); if (!createNewPoint( wpt.getName(), wpt.getDescription(), wpt.getLocation(), MARKER_TYPE_WAYPOINT)) { Log.d(TAG, "Upload waypoints failed"); return false; } } } return true; } finally { if (cursor != null) { cursor.close(); } } } /** * Creates a new row in Google Fusion Tables representing a marker as a * point. * * @param name the marker name * @param description the marker description * @param location the marker location * @param type the marker type * @return true if success. */ private boolean createNewPoint( String name, String description, Location location, String type) { String query = "INSERT INTO " + tableId + " (name,description,geometry,marker) VALUES " + SendFusionTablesUtils.formatSqlValues( name, description, SendFusionTablesUtils.getKmlPoint(location), type); return sendQuery(query, false); } /** * Creates a new row in Google Fusion Tables representing the track as a * line segment. * * @param track the track * @return true if success. */ private boolean createNewLineString(Track track) { String query = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + SendFusionTablesUtils.formatSqlValues(track.getName(), track.getDescription(), SendFusionTablesUtils.getKmlLineString(track.getLocations())); return sendQuery(query, false); } /** * Sends a query to Google Fusion Tables. * * @param query the Fusion Tables SQL query * @param setTableId true to set the table id * @return true if success. */ private boolean sendQuery(String query, boolean setTableId) { Log.d(TAG, "SendQuery: " + query); if (isCancelled()) { return false; } GenericUrl url = new GenericUrl(FUSION_TABLES_BASE_URL); String sql = SQL_KEY + URLEncoder.encode(query); ByteArrayInputStream inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql)); InputStreamContent inputStreamContent = new InputStreamContent(null, inputStream); HttpRequest request; try { request = httpRequestFactory.buildPostRequest(url, inputStreamContent); } catch (IOException e) { Log.d(TAG, "Unable to build request", e); return false; } GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName(APP_NAME_PREFIX + SystemUtils.getMyTracksVersion(context)); headers.gdataVersion = GDATA_VERSION; headers.setGoogleLogin(authToken); headers.setContentType(CONTENT_TYPE); request.setHeaders(headers); HttpResponse response; try { response = request.execute(); } catch (IOException e) { Log.d(TAG, "Unable to execute request", e); return false; } boolean isSuccess = response.isSuccessStatusCode(); if (isSuccess) { InputStream content = null; try { content = response.getContent(); if (setTableId) { tableId = SendFusionTablesUtils.getTableId(content); if (tableId == null) { Log.d(TAG, "tableId is null"); return false; } } } catch (IOException e) { Log.d(TAG, "Unable to get response", e); return false; } finally { if (content != null) { try { content.close(); } catch (IOException e) { Log.d(TAG, "Unable to close content", e); } } } } else { Log.d(TAG, "sendQuery failed: " + response.getStatusMessage() + ": " + response.getStatusCode()); return false; } return true; } /** * Updates the progress based on the number of locations uploaded. * * @param uploaded the number of uploaded locations * @param total the number of total locations */ private void updateProgress(int uploaded, int total) { double totalPercentage = (double) uploaded / total; double scaledPercentage = totalPercentage * (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN; publishProgress((int) scaledPercentage); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java
Java
asf20
16,270
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.fusiontables; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.api.client.util.Strings; import com.google.common.annotations.VisibleForTesting; import android.location.Location; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Locale; /** * Utilities for sending a track to Google Fusion Tables. * * @author Jimmy Shih */ public class SendFusionTablesUtils { public static final String SERVICE = "fusiontables"; private static final String UTF8 = "UTF8"; private static final String TABLE_ID = "tableid"; private static final String MAP_URL = "https://www.google.com/fusiontables/embedviz?" + "viz=MAP&q=select+col0,+col1,+col2,+col3+from+%s+&h=false&lat=%f&lng=%f&z=%d&t=1&l=col2"; private static final String TAG = SendFusionTablesUtils.class.getSimpleName(); private SendFusionTablesUtils() {} /** * Gets the url to visualize a fusion table on a map. * * @param track the track * @return the url. */ public static String getMapUrl(Track track) { if (track == null || track.getStatistics() == null || track.getTableId() == null) { Log.e(TAG, "Invalid track"); return null; } // TODO(jshih): Determine the correct bounding box and zoom level that // will show the entire track. TripStatistics stats = track.getStatistics(); double latE6 = stats.getBottom() + (stats.getTop() - stats.getBottom()) / 2; double lonE6 = stats.getLeft() + (stats.getRight() - stats.getLeft()) / 2; int z = 15; // We explicitly format with Locale.US because we need the latitude and // longitude to be formatted in a locale-independent manner. Specifically, // we need the decimal separator to be a period rather than a comma. return String.format( Locale.US, MAP_URL, track.getTableId(), latE6 / 1.E6, lonE6 / 1.E6, z); } /** * Formats an array of values as a SQL VALUES like * ('value1','value2',...,'value_n'). Escapes single quotes with two single * quotes. * * @param values an array of values to format * @return the formated SQL VALUES. */ public static String formatSqlValues(String... values) { StringBuilder builder = new StringBuilder("("); for (int i = 0; i < values.length; i++) { if (i > 0) { builder.append(','); } builder.append('\''); builder.append(escapeSqlString(values[i])); builder.append('\''); } builder.append(")"); return builder.toString(); } /** * Escapes a SQL string. Escapes single quotes with two single quotes. * * @param string the string * @return the escaped string. */ public static String escapeSqlString(String string) { return string.replaceAll("'", "''"); } /** * Gets a KML Point value representing a location. * * @param location the location * @return the KML Point value. */ public static String getKmlPoint(Location location) { StringBuilder builder = new StringBuilder("<Point><coordinates>"); if (location != null) { appendLocation(location, builder); } builder.append("</coordinates></Point>"); return builder.toString(); } /** * Gets a KML LineString value representing an array of locations. * * @param locations the locations. * @return the KML LineString value. */ public static String getKmlLineString(ArrayList<Location> locations) { StringBuilder builder = new StringBuilder("<LineString><coordinates>"); if (locations != null) { for (int i = 0; i < locations.size(); i++) { if (i != 0) { builder.append(' '); } appendLocation(locations.get(i), builder); } } builder.append("</coordinates></LineString>"); return builder.toString(); } /** * Appends a location to a string builder using "longitude,latitude[,altitude]" format. * * @param location the location * @param builder the string builder */ @VisibleForTesting static void appendLocation(Location location, StringBuilder builder) { builder.append(location.getLongitude()).append(",").append(location.getLatitude()); if (location.hasAltitude()) { builder.append(","); builder.append(location.getAltitude()); } } /** * Gets the table id from an input streawm. * * @param inputStream input stream * @return table id or null if not available. */ public static String getTableId(InputStream inputStream) { if (inputStream == null) { Log.d(TAG, "inputStream is null"); return null; } byte[] result = new byte[1024]; int read; try { read = inputStream.read(result); } catch (IOException e) { Log.d(TAG, "Unable to read result", e); return null; } if (read == -1) { Log.d(TAG, "no data read"); return null; } String s; try { s = new String(result, 0, read, UTF8); } catch (UnsupportedEncodingException e) { Log.d(TAG, "Unable to parse result", e); return null; } String[] lines = s.split(Strings.LINE_SEPARATOR); if (lines.length > 1 && lines[0].equals(TABLE_ID)) { // returns the next line return lines[1]; } else { Log.d(TAG, "Response is not valid: " + s); return null; } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesUtils.java
Java
asf20
6,096
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; /** * Activity to backup data to the SD card. * * @author Jimmy Shih */ public class BackupActivity extends Activity { private static final int DIALOG_PROGRESS_ID = 0; private BackupAsyncTask backupAsyncTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object retained = getLastNonConfigurationInstance(); if (retained instanceof BackupAsyncTask) { backupAsyncTask = (BackupAsyncTask) retained; backupAsyncTask.setActivity(this); } else { backupAsyncTask = new BackupAsyncTask(this); backupAsyncTask.execute(); } } @Override public Object onRetainNonConfigurationInstance() { backupAsyncTask.setActivity(null); return backupAsyncTask; } @Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_PROGRESS_ID) { return null; } return DialogUtils.createSpinnerProgressDialog( this, R.string.settings_backup_now_progress_message, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); } /** * Invokes when the associated AsyncTask completes. * * @param success true if the AsyncTask is successful * @param messageId message id to display to user */ public void onAsyncTaskCompleted(boolean success, int messageId) { removeDialog(DIALOG_PROGRESS_ID); Toast.makeText(this, messageId, success ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show(); finish(); } /** * Shows the progress dialog. */ public void showProgressDialog() { showDialog(DIALOG_PROGRESS_ID); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/BackupActivity.java
Java
asf20
2,588
/* * 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.Constants; import android.annotation.TargetApi; import android.app.backup.BackupAgent; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.content.Context; import android.content.SharedPreferences; import android.os.ParcelFileDescriptor; import android.util.Log; import java.io.IOException; /** * Backup agent used to backup and restore all preferences. * We use a regular {@link BackupAgent} instead of the convenient helpers in * order to be future-proof (assuming we'll want to back up tracks later). * * @author Rodrigo Damazio */ @TargetApi(8) public class MyTracksBackupAgent extends BackupAgent { private static final String PREFERENCES_ENTITY = "prefs"; @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { Log.i(Constants.TAG, "Performing backup"); SharedPreferences preferences = this.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); backupPreferences(data, preferences); Log.i(Constants.TAG, "Backup complete"); } private void backupPreferences(BackupDataOutput data, SharedPreferences preferences) throws IOException { PreferenceBackupHelper preferenceDumper = createPreferenceBackupHelper(); byte[] dumpedContents = preferenceDumper.exportPreferences(preferences); data.writeEntityHeader(PREFERENCES_ENTITY, dumpedContents.length); data.writeEntityData(dumpedContents, dumpedContents.length); } protected PreferenceBackupHelper createPreferenceBackupHelper() { return new PreferenceBackupHelper(); } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { Log.i(Constants.TAG, "Restoring from backup"); while (data.readNextHeader()) { String key = data.getKey(); Log.d(Constants.TAG, "Restoring entity " + key); if (key.equals(PREFERENCES_ENTITY)) { restorePreferences(data); } else { Log.e(Constants.TAG, "Found unknown backup entity: " + key); data.skipEntityData(); } } Log.i(Constants.TAG, "Done restoring from backup"); } /** * Restores all preferences from the backup. * * @param data the backup data to read from * @throws IOException if there are any errors while reading */ private void restorePreferences(BackupDataInput data) throws IOException { int dataSize = data.getDataSize(); byte[] dataBuffer = new byte[dataSize]; int read = data.readEntityData(dataBuffer, 0, dataSize); if (read != dataSize) { throw new IOException("Failed to read all the preferences data"); } SharedPreferences preferences = this.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); PreferenceBackupHelper importer = createPreferenceBackupHelper(); importer.importPreferences(dataBuffer, preferences); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/MyTracksBackupAgent.java
Java
asf20
3,673
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.widget.Toast; import java.util.Arrays; import java.util.Comparator; import java.util.Date; /** * An activity to choose a date to restore from. * * @author Jimmy Shih */ public class RestoreChooserActivity extends Activity { private static final Comparator<Date> REVERSE_DATE_ORDER = new Comparator<Date>() { @Override public int compare(Date s1, Date s2) { return s2.compareTo(s1); } }; private static final int DIALOG_CHOOSER_ID = 0; private Date[] backupDates; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ExternalFileBackup externalFileBackup = new ExternalFileBackup(this); // Get the list of existing backups if (!FileUtils.isSdCardAvailable()) { Toast.makeText(this, R.string.sd_card_error_no_storage, Toast.LENGTH_LONG).show(); finish(); return; } if (!externalFileBackup.isBackupsDirectoryAvailable(false)) { Toast.makeText(this, R.string.settings_backup_restore_no_backup, Toast.LENGTH_LONG).show(); finish(); return; } backupDates = externalFileBackup.getAvailableBackups(); if (backupDates == null || backupDates.length == 0) { Toast.makeText(this, R.string.settings_backup_restore_no_backup, Toast.LENGTH_LONG).show(); finish(); return; } if (backupDates.length == 1) { startActivity(new Intent(this, RestoreActivity.class) .putExtra(RestoreActivity.EXTRA_DATE, backupDates[0].getTime())); finish(); return; } Arrays.sort(backupDates, REVERSE_DATE_ORDER); showDialog(DIALOG_CHOOSER_ID); } @Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_CHOOSER_ID) { return null; } String items[] = new String[backupDates.length]; for (int i = 0; i < backupDates.length; i++) { items[i] = StringUtils.formatDateTime(this, backupDates[i].getTime()); } return new AlertDialog.Builder(this) .setCancelable(true) .setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(RestoreChooserActivity.this, RestoreActivity.class).putExtra( RestoreActivity.EXTRA_DATE, backupDates[which].getTime())); finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .setTitle(R.string.settings_backup_restore_select_title) .create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/RestoreChooserActivity.java
Java
asf20
3,671
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.maps.mytracks.R; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.util.Date; /** * AsyncTask to restore data from the SD card. * * @author Jimmy Shih */ public class RestoreAsyncTask extends AsyncTask<Void, Integer, Boolean> { private static final String TAG = RestoreAsyncTask.class.getSimpleName(); private RestoreActivity restoreActivity; private final Date date; private final ExternalFileBackup externalFileBackup; // true if the AsyncTask result is success private boolean success; // true if the AsyncTask has completed private boolean completed; // message id to return to the activity private int messageId; /** * Creates an AsyncTask. * * @param restoreActivity the activity currently associated with this * AsyncTask * @param date the date to retore from */ public RestoreAsyncTask(RestoreActivity restoreActivity, Date date) { this.restoreActivity = restoreActivity; this.date = date; this.externalFileBackup = new ExternalFileBackup(restoreActivity); success = false; completed = false; messageId = R.string.sd_card_error_read_file; } /** * Sets the current {@link RestoreActivity} associated with this AyncTask. * * @param activity the current {@link RestoreActivity}, can be null */ public void setActivity(RestoreActivity activity) { this.restoreActivity = activity; if (completed && restoreActivity != null) { restoreActivity.onAsyncTaskCompleted(success, messageId); } } @Override protected void onPreExecute() { if (restoreActivity != null) { restoreActivity.showProgressDialog(); } } @Override protected Boolean doInBackground(Void... params) { try { externalFileBackup.restoreFromDate(date); messageId = R.string.sd_card_success_read_file; return true; } catch (IOException e) { Log.d(TAG, "IO exception", e); return false; } } @Override protected void onPostExecute(Boolean result) { success = result; completed = true; if (restoreActivity != null) { restoreActivity.onAsyncTaskCompleted(success, messageId); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/RestoreAsyncTask.java
Java
asf20
2,879
/* * 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.backup; import android.annotation.TargetApi; import android.app.backup.BackupManager; import android.content.Context; import android.content.SharedPreferences; /** * Implementation of {@link BackupPreferencesListener} that calls the * {@link BackupManager}. <br> * For API Level 8 or higher. * * @author Jimmy Shih */ @TargetApi(8) public class Api8BackupPreferencesListener implements BackupPreferencesListener { private final BackupManager backupManager; public Api8BackupPreferencesListener(Context context) { this.backupManager = new BackupManager(context); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { backupManager.dataChanged(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/Api8BackupPreferencesListener.java
Java
asf20
1,362
/* * 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.OnSharedPreferenceChangeListener; /** * Shared preferences listener which notifies the backup system about new data * being available for backup. * * @author Rodrigo Damazio */ public interface BackupPreferencesListener extends OnSharedPreferenceChangeListener { }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/BackupPreferencesListener.java
Java
asf20
955
/* * 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 static com.google.android.apps.mytracks.content.ContentTypeIds.*; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; public class BackupColumns { /** Columns that go into the backup. */ public static final String[] POINTS_BACKUP_COLUMNS = { TrackPointsColumns._ID, TrackPointsColumns.TRACKID, TrackPointsColumns.LATITUDE, TrackPointsColumns.LONGITUDE, TrackPointsColumns.ALTITUDE, TrackPointsColumns.BEARING, TrackPointsColumns.TIME, TrackPointsColumns.ACCURACY, TrackPointsColumns.SPEED, TrackPointsColumns.SENSOR }; public static final byte[] POINTS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, BLOB_TYPE_ID }; public static final String[] TRACKS_BACKUP_COLUMNS = { TracksColumns._ID, TracksColumns.NAME, TracksColumns.DESCRIPTION, TracksColumns.CATEGORY, TracksColumns.STARTID, TracksColumns.STOPID, TracksColumns.STARTTIME, TracksColumns.STOPTIME, TracksColumns.NUMPOINTS, TracksColumns.TOTALDISTANCE, TracksColumns.TOTALTIME, TracksColumns.MOVINGTIME, TracksColumns.AVGSPEED, TracksColumns.AVGMOVINGSPEED, TracksColumns.MAXSPEED, TracksColumns.MINELEVATION, TracksColumns.MAXELEVATION, TracksColumns.ELEVATIONGAIN, TracksColumns.MINGRADE, TracksColumns.MAXGRADE, TracksColumns.MINLAT, TracksColumns.MAXLAT, TracksColumns.MINLON, TracksColumns.MAXLON, TracksColumns.MAPID, TracksColumns.TABLEID}; public static final byte[] TRACKS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID}; public static final String[] WAYPOINTS_BACKUP_COLUMNS = { WaypointsColumns._ID, WaypointsColumns.TRACKID, WaypointsColumns.NAME, WaypointsColumns.DESCRIPTION, WaypointsColumns.CATEGORY, WaypointsColumns.ICON, WaypointsColumns.TYPE, WaypointsColumns.LENGTH, WaypointsColumns.DURATION, WaypointsColumns.STARTTIME, WaypointsColumns.STARTID, WaypointsColumns.STOPID, WaypointsColumns.LATITUDE, WaypointsColumns.LONGITUDE, WaypointsColumns.ALTITUDE, WaypointsColumns.BEARING, WaypointsColumns.TIME, WaypointsColumns.ACCURACY, WaypointsColumns.SPEED, WaypointsColumns.TOTALDISTANCE, WaypointsColumns.TOTALTIME, WaypointsColumns.MOVINGTIME, WaypointsColumns.AVGSPEED, WaypointsColumns.AVGMOVINGSPEED, WaypointsColumns.MAXSPEED, WaypointsColumns.MINELEVATION, WaypointsColumns.MAXELEVATION, WaypointsColumns.ELEVATIONGAIN, WaypointsColumns.MINGRADE, WaypointsColumns.MAXGRADE }; public static final byte[] WAYPOINTS_BACKUP_COLUMN_TYPES = { LONG_TYPE_ID, LONG_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, STRING_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, INT_TYPE_ID, INT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, LONG_TYPE_ID, LONG_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID, FLOAT_TYPE_ID }; }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/BackupColumns.java
Java
asf20
4,267
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.maps.mytracks.R; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; /** * AsyncTask to backup data to the SD card. * * @author Jimmy Shih */ public class BackupAsyncTask extends AsyncTask<Void, Integer, Boolean> { private static final String TAG = BackupAsyncTask.class.getSimpleName(); private BackupActivity backupActivity; private final ExternalFileBackup externalFileBackup; // true if the AsyncTask result is success private boolean success; // true if the AsyncTask has completed private boolean completed; // message id to return to the activity private int messageId; /** * Creates an AsyncTask. * * @param backupActivity the activity currently associated with this * AsyncTask */ public BackupAsyncTask(BackupActivity backupActivity) { this.backupActivity = backupActivity; this.externalFileBackup = new ExternalFileBackup(backupActivity); success = false; completed = false; messageId = R.string.sd_card_error_write_file; } /** * Sets the current {@link BackupActivity} associated with this AyncTask. * * @param activity the current {@link BackupActivity}, can be null */ public void setActivity(BackupActivity activity) { this.backupActivity = activity; if (completed && backupActivity != null) { backupActivity.onAsyncTaskCompleted(success, messageId); } } @Override protected void onPreExecute() { if (backupActivity != null) { backupActivity.showProgressDialog(); } } @Override protected Boolean doInBackground(Void... params) { if (!FileUtils.isSdCardAvailable()) { messageId = R.string.sd_card_error_no_storage; return false; } if (!externalFileBackup.isBackupsDirectoryAvailable(true)) { messageId = R.string.sd_card_error_create_dir; return false; } try { externalFileBackup.writeToDefaultFile(); messageId = R.string.sd_card_success_write_file; return true; } catch (IOException e) { Log.d(TAG, "IO exception", e); return false; } } @Override protected void onPostExecute(Boolean result) { success = result; completed = true; if (backupActivity != null) { backupActivity.onAsyncTaskCompleted(success, messageId); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/BackupAsyncTask.java
Java
asf20
3,055
/* * 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.Cursor; import android.database.MergeCursor; import java.io.DataOutputStream; import java.io.IOException; /** * Database dumper which is able to write only part of the database * according to some query. * * This dumper is symmetrical to {@link DatabaseImporter}. * * @author Rodrigo Damazio */ class DatabaseDumper { /** The names of the columns being dumped. */ private final String[] columnNames; /** The types of the columns being dumped. */ private final byte[] columnTypes; /** Whether to output null fields. */ private final boolean outputNullFields; // Temporary state private int[] columnIndices; private boolean[] hasFields; public DatabaseDumper(String[] columnNames, byte[] columnTypes, boolean outputNullFields) { if (columnNames.length != columnTypes.length) { throw new IllegalArgumentException("Names don't match types"); } this.columnNames = columnNames; this.columnTypes = columnTypes; this.outputNullFields = outputNullFields; } /** * Writes the header plus all rows that can be read from the given cursor. * This assumes the cursor will have the same column and column indices on * every row (and thus may not work with a {@link MergeCursor}). */ public void writeAllRows(Cursor cursor, DataOutputStream writer) throws IOException { writeHeaders(cursor, cursor.getCount(), writer); if (!cursor.moveToFirst()) { return; } do { writeOneRow(cursor, writer); } while (cursor.moveToNext()); } /** * Writes just the headers for the data that will come from the given cursor. * The headers include column information and the number of rows that will be * written. * * @param cursor the cursor to get columns from * @param numRows the number of rows that will be later written * @param writer the output to write to * @throws IOException if there are errors while writing */ public void writeHeaders(Cursor cursor, int numRows, DataOutputStream writer) throws IOException { initializeCachedValues(cursor); writeQueryMetadata(numRows, writer); } /** * Writes the current row from the cursor. The cursor is not advanced. * This must be called after {@link #writeHeaders}. * * @param cursor the cursor to write data from * @param writer the output to write to * @throws IOException if there are any errors while writing */ public void writeOneRow(Cursor cursor, DataOutputStream writer) throws IOException { if (columnIndices == null) { throw new IllegalStateException( "Cannot write rows before writing the header"); } if (columnIndices.length > Long.SIZE) { throw new IllegalArgumentException("Too many fields"); } // Build a bitmap of which fields are present long fields = 0; for (int i = 0; i < columnIndices.length; i++) { hasFields[i] = !cursor.isNull(columnIndices[i]); fields |= (hasFields[i] ? 1 : 0) << i; } writer.writeLong(fields); // Actually write the present fields for (int i = 0; i < columnIndices.length; i++) { if (hasFields[i]) { writeCell(columnIndices[i], columnTypes[i], cursor, writer); } else if (outputNullFields) { writeDummyCell(columnTypes[i], writer); } } } /** * Initializes the column indices and other temporary state for reading from * the given cursor. */ private void initializeCachedValues(Cursor cursor) { // These indices are constant for every row (unless we're fed a MergeCursor) if (cursor instanceof MergeCursor) { throw new IllegalArgumentException("Cannot use a MergeCursor"); } columnIndices = new int[columnNames.length]; for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; columnIndices[i] = cursor.getColumnIndexOrThrow(columnName); } hasFields = new boolean[columnIndices.length]; } /** * Writes metadata about the query to be dumped. * * @param numRows the number of rows that will be dumped * @param writer the output to write to * @throws IOException if there are any errors while writing */ private void writeQueryMetadata( int numRows, DataOutputStream writer) throws IOException { // Write column data writer.writeInt(columnNames.length); for (int i = 0; i < columnNames.length; i++) { String columnName = columnNames[i]; byte columnType = columnTypes[i]; writer.writeUTF(columnName); writer.writeByte(columnType); } // Write the number of rows writer.writeInt(numRows); } /** * Writes a single cell of the database to the output. * * @param columnIdx the column index to read from * @param columnTypeId the type of the column to be read * @param cursor the cursor to read from * @param writer the output to write to * @throws IOException if there are any errors while writing */ private void writeCell( int columnIdx, byte columnTypeId, Cursor cursor, DataOutputStream writer) throws IOException { switch (columnTypeId) { case ContentTypeIds.LONG_TYPE_ID: writer.writeLong(cursor.getLong(columnIdx)); return; case ContentTypeIds.DOUBLE_TYPE_ID: writer.writeDouble(cursor.getDouble(columnIdx)); return; case ContentTypeIds.FLOAT_TYPE_ID: writer.writeFloat(cursor.getFloat(columnIdx)); return; case ContentTypeIds.BOOLEAN_TYPE_ID: writer.writeBoolean(cursor.getInt(columnIdx) != 0); return; case ContentTypeIds.INT_TYPE_ID: writer.writeInt(cursor.getInt(columnIdx)); return; case ContentTypeIds.STRING_TYPE_ID: writer.writeUTF(cursor.getString(columnIdx)); return; case ContentTypeIds.BLOB_TYPE_ID: { byte[] blob = cursor.getBlob(columnIdx); writer.writeInt(blob.length); writer.write(blob); return; } default: throw new IllegalArgumentException( "Type " + columnTypeId + " not supported"); } } /** * Writes a dummy cell value to the output. * * @param columnTypeId the type of the value to write * @throws IOException if there are any errors while writing */ private void writeDummyCell(byte columnTypeId, DataOutputStream writer) throws IOException { switch (columnTypeId) { case ContentTypeIds.LONG_TYPE_ID: writer.writeLong(0L); return; case ContentTypeIds.DOUBLE_TYPE_ID: writer.writeDouble(0.0); return; case ContentTypeIds.FLOAT_TYPE_ID: writer.writeFloat(0.0f); return; case ContentTypeIds.BOOLEAN_TYPE_ID: writer.writeBoolean(false); return; case ContentTypeIds.INT_TYPE_ID: writer.writeInt(0); return; case ContentTypeIds.STRING_TYPE_ID: writer.writeUTF(""); return; case ContentTypeIds.BLOB_TYPE_ID: writer.writeInt(0); return; default: throw new IllegalArgumentException( "Type " + columnTypeId + " not supported"); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/DatabaseDumper.java
Java
asf20
7,903
/* * 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 com.google.android.apps.mytracks.util.ApiAdapterFactory; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; /** * Helper for backing up and restoring shared preferences. * * @author Rodrigo Damazio */ class PreferenceBackupHelper { private static final int BUFFER_SIZE = 2048; /** * Exports all shared preferences from the given object as a byte array. * * @param preferences the preferences to export * @return the corresponding byte array * @throws IOException if there are any errors while writing to the byte array */ public byte[] exportPreferences(SharedPreferences preferences) throws IOException { ByteArrayOutputStream bufStream = new ByteArrayOutputStream(BUFFER_SIZE); DataOutputStream outWriter = new DataOutputStream(bufStream); exportPreferences(preferences, outWriter); return bufStream.toByteArray(); } /** * Exports all shared preferences from the given object into the given output * stream. * * @param preferences the preferences to export * @param outWriter the stream to write them to * @throws IOException if there are any errors while writing the output */ public void exportPreferences( SharedPreferences preferences, DataOutputStream outWriter) throws IOException { Map<String, ?> values = preferences.getAll(); outWriter.writeInt(values.size()); for (Map.Entry<String, ?> entry : values.entrySet()) { writePreference(entry.getKey(), entry.getValue(), outWriter); } outWriter.flush(); } /** * Imports all preferences from the given byte array. * * @param data the byte array to read preferences from * @param preferences the shared preferences to edit * @throws IOException if there are any errors while reading */ public void importPreferences(byte[] data, SharedPreferences preferences) throws IOException { ByteArrayInputStream bufStream = new ByteArrayInputStream(data); DataInputStream reader = new DataInputStream(bufStream); importPreferences(reader, preferences); } /** * Imports all preferences from the given stream. * * @param reader the stream to read from * @param preferences the shared preferences to edit * @throws IOException if there are any errors while reading */ public void importPreferences(DataInputStream reader, SharedPreferences preferences) throws IOException { Editor editor = preferences.edit(); editor.clear(); int numPreferences = reader.readInt(); for (int i = 0; i < numPreferences; i++) { String name = reader.readUTF(); byte typeId = reader.readByte(); readAndSetPreference(name, typeId, reader, editor); } ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } /** * Reads a single preference and sets it into the given editor. * * @param name the name of the preference to read * @param typeId the type ID of the preference to read * @param reader the reader to read from * @param editor the editor to set the preference in * @throws IOException if there are errors while reading */ private void readAndSetPreference(String name, byte typeId, DataInputStream reader, Editor editor) throws IOException { switch (typeId) { case ContentTypeIds.BOOLEAN_TYPE_ID: editor.putBoolean(name, reader.readBoolean()); return; case ContentTypeIds.LONG_TYPE_ID: editor.putLong(name, reader.readLong()); return; case ContentTypeIds.FLOAT_TYPE_ID: editor.putFloat(name, reader.readFloat()); return; case ContentTypeIds.INT_TYPE_ID: editor.putInt(name, reader.readInt()); return; case ContentTypeIds.STRING_TYPE_ID: editor.putString(name, reader.readUTF()); return; } } /** * Writes a single preference. * * @param name the name of the preference to write * @param value the correctly-typed value of the preference * @param writer the writer to write to * @throws IOException if there are errors while writing */ private void writePreference(String name, Object value, DataOutputStream writer) throws IOException { writer.writeUTF(name); if (value instanceof Boolean) { writer.writeByte(ContentTypeIds.BOOLEAN_TYPE_ID); writer.writeBoolean((Boolean) value); } else if (value instanceof Integer) { writer.writeByte(ContentTypeIds.INT_TYPE_ID); writer.writeInt((Integer) value); } else if (value instanceof Long) { writer.writeByte(ContentTypeIds.LONG_TYPE_ID); writer.writeLong((Long) value); } else if (value instanceof Float) { writer.writeByte(ContentTypeIds.FLOAT_TYPE_ID); writer.writeFloat((Float) value); } else if (value instanceof String) { writer.writeByte(ContentTypeIds.STRING_TYPE_ID); writer.writeUTF((String) value); } else { throw new IllegalArgumentException( "Type " + value.getClass().getName() + " not supported"); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/PreferenceBackupHelper.java
Java
asf20
5,984
/* * 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 static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.TrackPointsColumns; import com.google.android.apps.mytracks.content.TracksColumns; import com.google.android.apps.mytracks.content.WaypointsColumns; import com.google.android.apps.mytracks.util.FileUtils; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; /** * Handler for writing or reading single-file backups. * * @author Rodrigo Damazio */ class ExternalFileBackup { // Filename format - in UTC private static final SimpleDateFormat BACKUP_FILENAME_FORMAT = new SimpleDateFormat("'backup-'yyyy-MM-dd_HH-mm-ss'.zip'"); static { BACKUP_FILENAME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final String BACKUPS_SUBDIR = "backups"; private static final int BACKUP_FORMAT_VERSION = 1; private static final String ZIP_ENTRY_NAME = "backup.mytracks.v" + BACKUP_FORMAT_VERSION; private static final int COMPRESSION_LEVEL = 8; private final Context context; public ExternalFileBackup(Context context) { this.context = context; } /** * Returns whether the backups directory is (or can be made) available. * * @param create whether to try creating the directory if it doesn't exist */ public boolean isBackupsDirectoryAvailable(boolean create) { return getBackupsDirectory(create) != null; } /** * Returns the backup directory, or null if not available. * * @param create whether to try creating the directory if it doesn't exist */ private File getBackupsDirectory(boolean create) { String dirName = FileUtils.buildExternalDirectoryPath(BACKUPS_SUBDIR); final File dir = new File(dirName); Log.d(Constants.TAG, "Dir: " + dir.getAbsolutePath()); if (create) { // Try to create - if that fails, return null return FileUtils.ensureDirectoryExists(dir) ? dir : null; } else { // Return it if it already exists, otherwise return null return dir.isDirectory() ? dir : null; } } /** * Returns a list of available backups to be restored. */ public Date[] getAvailableBackups() { File dir = getBackupsDirectory(false); if (dir == null) { return null; } String[] fileNames = dir.list(); List<Date> backupDates = new ArrayList<Date>(fileNames.length); for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; try { backupDates.add(BACKUP_FILENAME_FORMAT.parse(fileName)); } catch (ParseException e) { // Not a backup file, ignore } } return backupDates.toArray(new Date[backupDates.size()]); } /** * Writes the backup to the default file. */ public void writeToDefaultFile() throws IOException { writeToFile(getFileForDate(new Date())); } /** * Restores the backup from the given date. */ public void restoreFromDate(Date when) throws IOException { restoreFromFile(getFileForDate(when)); } /** * Produces the proper file descriptor for the given backup date. */ private File getFileForDate(Date when) { File dir = getBackupsDirectory(false); String fileName = BACKUP_FILENAME_FORMAT.format(when); File file = new File(dir, fileName); return file; } /** * Synchronously writes a backup to the given file. */ private void writeToFile(File outputFile) throws IOException { Log.d(Constants.TAG, "Writing backup to file " + outputFile.getAbsolutePath()); // Create all the auxiliary classes that will do the writing PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); DatabaseDumper trackDumper = new DatabaseDumper( BackupColumns.TRACKS_BACKUP_COLUMNS, BackupColumns.TRACKS_BACKUP_COLUMN_TYPES, false); DatabaseDumper waypointDumper = new DatabaseDumper( BackupColumns.WAYPOINTS_BACKUP_COLUMNS, BackupColumns.WAYPOINTS_BACKUP_COLUMN_TYPES, false); DatabaseDumper pointDumper = new DatabaseDumper( BackupColumns.POINTS_BACKUP_COLUMNS, BackupColumns.POINTS_BACKUP_COLUMN_TYPES, false); // Open the target for writing FileOutputStream outputStream = new FileOutputStream(outputFile); ZipOutputStream compressedStream = new ZipOutputStream(outputStream); compressedStream.setLevel(COMPRESSION_LEVEL); compressedStream.putNextEntry(new ZipEntry(ZIP_ENTRY_NAME)); DataOutputStream outWriter = new DataOutputStream(compressedStream); try { // Dump the entire contents of each table ContentResolver contentResolver = context.getContentResolver(); Cursor tracksCursor = contentResolver.query( TracksColumns.CONTENT_URI, null, null, null, null); try { trackDumper.writeAllRows(tracksCursor, outWriter); } finally { tracksCursor.close(); } Cursor waypointsCursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null, null, null, null); try { waypointDumper.writeAllRows(waypointsCursor, outWriter); } finally { waypointsCursor.close(); } Cursor pointsCursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, null, null, null); try { pointDumper.writeAllRows(pointsCursor, outWriter); } finally { pointsCursor.close(); } // Dump preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.exportPreferences(preferences, outWriter); } catch (IOException e) { // We tried to delete the partially created file, but do nothing // if that also fails. if (!outputFile.delete()) { Log.w(TAG, "Failed to delete file " + outputFile.getAbsolutePath()); } throw e; } finally { compressedStream.closeEntry(); compressedStream.close(); } } /** * Synchronously restores the backup from the given file. */ private void restoreFromFile(File inputFile) throws IOException { Log.d(Constants.TAG, "Restoring from file " + inputFile.getAbsolutePath()); PreferenceBackupHelper preferencesHelper = new PreferenceBackupHelper(); ContentResolver resolver = context.getContentResolver(); DatabaseImporter trackImporter = new DatabaseImporter(TracksColumns.CONTENT_URI, resolver, false); DatabaseImporter waypointImporter = new DatabaseImporter(WaypointsColumns.CONTENT_URI, resolver, false); DatabaseImporter pointImporter = new DatabaseImporter(TrackPointsColumns.CONTENT_URI, resolver, false); ZipFile zipFile = new ZipFile(inputFile, ZipFile.OPEN_READ); ZipEntry zipEntry = zipFile.getEntry(ZIP_ENTRY_NAME); if (zipEntry == null) { throw new IOException("Invalid backup ZIP file"); } InputStream compressedStream = zipFile.getInputStream(zipEntry); DataInputStream reader = new DataInputStream(compressedStream); try { // Delete all previous contents of the tables and preferences. resolver.delete(TracksColumns.CONTENT_URI, null, null); resolver.delete(TrackPointsColumns.CONTENT_URI, null, null); resolver.delete(WaypointsColumns.CONTENT_URI, null, null); // Import the new contents of each table trackImporter.importAllRows(reader); waypointImporter.importAllRows(reader); pointImporter.importAllRows(reader); // Restore preferences SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); preferencesHelper.importPreferences(reader, preferences); } finally { compressedStream.close(); zipFile.close(); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/ExternalFileBackup.java
Java
asf20
9,040
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.backup; import com.google.android.apps.mytracks.TrackListActivity; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import java.util.Date; /** * An activity to restore data from the SD card. * * @author Jimmy Shih */ public class RestoreActivity extends Activity { public static final String EXTRA_DATE = "date"; private static final String TAG = RestoreActivity.class.getSimpleName(); private static final int DIALOG_PROGRESS_ID = 0; private RestoreAsyncTask restoreAsyncTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object retained = getLastNonConfigurationInstance(); if (retained instanceof RestoreAsyncTask) { restoreAsyncTask = (RestoreAsyncTask) retained; restoreAsyncTask.setActivity(this); } else { long date = getIntent().getLongExtra(EXTRA_DATE, -1L); if (date == -1L) { Log.d(TAG, "Invalid date"); finish(); return; } restoreAsyncTask = new RestoreAsyncTask(this, new Date(date)); restoreAsyncTask.execute(); } } @Override public Object onRetainNonConfigurationInstance() { restoreAsyncTask.setActivity(null); return restoreAsyncTask; } @Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_PROGRESS_ID) { return null; } return DialogUtils.createSpinnerProgressDialog(this, R.string.settings_backup_restore_progress_message, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); } /** * Invokes when the associated AsyncTask completes. * * @param success true if the AsyncTask is successful * @param messageId message id to display to user */ public void onAsyncTaskCompleted(boolean success, int messageId) { removeDialog(DIALOG_PROGRESS_ID); Toast.makeText(this, messageId, success ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show(); startActivity(new Intent(this, TrackListActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); } /** * Shows the progress dialog. */ public void showProgressDialog() { showDialog(DIALOG_PROGRESS_ID); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/RestoreActivity.java
Java
asf20
3,188
/* * 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.ContentResolver; import android.content.ContentValues; import android.net.Uri; import java.io.DataInputStream; import java.io.IOException; /** * Database importer which reads values written by {@link DatabaseDumper}. * * @author Rodrigo Damazio */ public class DatabaseImporter { /** Maximum number of entries in a bulk insertion */ private static final int DEFAULT_BULK_SIZE = 1024; private final Uri destinationUri; private final ContentResolver resolver; private final boolean readNullFields; private final int bulkSize; // Metadata read from the reader private String[] columnNames; private byte[] columnTypes; public DatabaseImporter(Uri destinationUri, ContentResolver resolver, boolean readNullFields) { this(destinationUri, resolver, readNullFields, DEFAULT_BULK_SIZE); } protected DatabaseImporter(Uri destinationUri, ContentResolver resolver, boolean readNullFields, int bulkSize) { this.destinationUri = destinationUri; this.resolver = resolver; this.readNullFields = readNullFields; this.bulkSize = bulkSize; } /** * Reads the header which includes metadata about the table being imported. * * @throws IOException if there are any problems while reading */ private void readHeaders(DataInputStream reader) throws IOException { int numColumns = reader.readInt(); columnNames = new String[numColumns]; columnTypes = new byte[numColumns]; for (int i = 0; i < numColumns; i++) { columnNames[i] = reader.readUTF(); columnTypes[i] = reader.readByte(); } } /** * Imports all rows from the reader into the database. * Insertion is done in bulks for efficiency. * * @throws IOException if there are any errors while reading */ public void importAllRows(DataInputStream reader) throws IOException { readHeaders(reader); ContentValues[] valueBulk = new ContentValues[bulkSize]; int numValues = 0; int numRows = reader.readInt(); int numColumns = columnNames.length; // For each row for (int r = 0; r < numRows; r++) { if (valueBulk[numValues] == null) { valueBulk[numValues] = new ContentValues(numColumns); } else { // Reuse values objects valueBulk[numValues].clear(); } // Read the fields bitmap long fields = reader.readLong(); for (int c = 0; c < numColumns; c++) { if ((fields & 1) == 1) { // Field is present, read into values readOneCell(columnNames[c], columnTypes[c], valueBulk[numValues], reader); } else if (readNullFields) { // Field not present but still written, read and discard readOneCell(columnNames[c], columnTypes[c], null, reader); } fields >>= 1; } numValues++; // If we have enough values, flush them as a bulk insertion if (numValues >= bulkSize) { doBulkInsert(valueBulk); numValues = 0; } } // Do a final bulk insert with the leftovers if (numValues > 0) { ContentValues[] leftovers = new ContentValues[numValues]; System.arraycopy(valueBulk, 0, leftovers, 0, numValues); doBulkInsert(leftovers); } } protected void doBulkInsert(ContentValues[] values) { resolver.bulkInsert(destinationUri, values); } /** * Reads a single cell from the reader. * * @param name the name of the column to be read * @param typeId the type ID of the column to be read * @param values the {@link ContentValues} object to put the read cell value * in - if null, the value is just discarded * @throws IOException if there are any problems while reading */ private void readOneCell(String name, byte typeId, ContentValues values, DataInputStream reader) throws IOException { switch (typeId) { case ContentTypeIds.BOOLEAN_TYPE_ID: { boolean value = reader.readBoolean(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.LONG_TYPE_ID: { long value = reader.readLong(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.DOUBLE_TYPE_ID: { double value = reader.readDouble(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.FLOAT_TYPE_ID: { Float value = reader.readFloat(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.INT_TYPE_ID: { int value = reader.readInt(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.STRING_TYPE_ID: { String value = reader.readUTF(); if (values != null) { values.put(name, value); } return; } case ContentTypeIds.BLOB_TYPE_ID: { int blobLength = reader.readInt(); if (blobLength != 0) { byte[] blob = new byte[blobLength]; int readBytes = reader.read(blob, 0, blobLength); if (readBytes != blobLength) { throw new IOException(String.format( "Short read on column %s; expected %d bytes, read %d", name, blobLength, readBytes)); } if (values != null) { values.put(name, blob); } } return; } default: throw new IOException("Read unknown type " + typeId); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/backup/DatabaseImporter.java
Java
asf20
6,240
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; 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.io.gdata.GDataClientFactory; import com.google.android.apps.mytracks.io.gdata.docs.DocumentsClient; import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient; import com.google.android.apps.mytracks.io.gdata.docs.XmlDocsGDataParserFactory; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.common.gdata.AndroidXmlParserFactory; import com.google.android.maps.mytracks.R; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata2.client.AuthenticationException; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.util.Log; import java.io.IOException; /** * AsyncTask to send a track to Google Docs. * * @author Jimmy Shih */ public class SendDocsAsyncTask extends AbstractSendAsyncTask { private static final int PROGRESS_GET_SPREADSHEET_ID = 0; private static final int PROGRESS_CREATE_SPREADSHEET = 25; private static final int PROGRESS_GET_WORKSHEET_ID = 50; private static final int PROGRESS_ADD_TRACK_INFO = 75; private static final int PROGRESS_COMPLETE = 100; private static final String TAG = SendDocsAsyncTask.class.getSimpleName(); private final long trackId; private final Account account; private final Context context; private final MyTracksProviderUtils myTracksProviderUtils; private final GDataClient gDataClient; private final DocumentsClient documentsClient; private final SpreadsheetsClient spreadsheetsClient; // The following variables are for per upload states private String documentsAuthToken; private String spreadsheetsAuthToken; private String spreadsheetId; private String worksheetId; public SendDocsAsyncTask(SendDocsActivity activity, long trackId, Account account) { super(activity); this.trackId = trackId; this.account = account; context = activity.getApplicationContext(); myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context); gDataClient = GDataClientFactory.getGDataClient(context); documentsClient = new DocumentsClient( gDataClient, new XmlDocsGDataParserFactory(new AndroidXmlParserFactory())); spreadsheetsClient = new SpreadsheetsClient( gDataClient, new XmlDocsGDataParserFactory(new AndroidXmlParserFactory())); } @Override protected void closeConnection() { if (gDataClient != null) { gDataClient.close(); } } @Override protected void saveResult() { // No action for Google Docs } @Override protected boolean performTask() { // Reset the per upload states documentsAuthToken = null; spreadsheetsAuthToken = null; spreadsheetId = null; worksheetId = null; try { documentsAuthToken = AccountManager.get(context).blockingGetAuthToken( account, documentsClient.getServiceName(), false); spreadsheetsAuthToken = AccountManager.get(context).blockingGetAuthToken( account, spreadsheetsClient.getServiceName(), false); } catch (OperationCanceledException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (AuthenticatorException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (IOException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } Track track = myTracksProviderUtils.getTrack(trackId); if (track == null) { Log.d(TAG, "Track is null"); return false; } String title = context.getString(R.string.my_tracks_app_name); if (track.getCategory() != null && !track.getCategory().equals("")) { title += "-" + track.getCategory(); } // Get the spreadsheet ID publishProgress(PROGRESS_GET_SPREADSHEET_ID); if (!fetchSpreadSheetId(title, false)) { return retryTask(); } // Create a new spreadsheet if necessary publishProgress(PROGRESS_CREATE_SPREADSHEET); if (spreadsheetId == null) { if (!createSpreadSheet(title)) { Log.d(TAG, "Unable to create a new spreadsheet"); return false; } // The previous creation might have succeeded even though GData // reported an error. Seems to be a know bug. // See http://code.google.com/p/gdata-issues/issues/detail?id=929 // Try to find the created spreadsheet. if (spreadsheetId == null) { if (!fetchSpreadSheetId(title, true)) { Log.d(TAG, "Unable to check if the new spreadsheet is created"); return false; } if (spreadsheetId == null) { Log.d(TAG, "Unable to create a new spreadsheet"); return false; } } } // Get the worksheet ID publishProgress(PROGRESS_GET_WORKSHEET_ID); if (!fetchWorksheetId()) { return retryTask(); } if (worksheetId == null) { Log.d(TAG, "Unable to get a worksheet ID"); return false; } // Add the track info publishProgress(PROGRESS_ADD_TRACK_INFO); if (!addTrackInfo(track)) { Log.d(TAG, "Unable to add track info"); return false; } publishProgress(PROGRESS_COMPLETE); return true; } @Override protected void invalidateToken() { AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, documentsAuthToken); AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, spreadsheetsAuthToken); } /** * Fetches the spreadsheet id. Sets the instance variable * {@link SendDocsAsyncTask#spreadsheetId}. * * @param title the spreadsheet title * @param waitFirst wait before checking * @return true if completes. */ private boolean fetchSpreadSheetId(String title, boolean waitFirst) { if (isCancelled()) { return false; } if (waitFirst) { try { Thread.sleep(5000); } catch (InterruptedException e) { Log.d(TAG, "Unable to wait", e); return false; } } try { spreadsheetId = SendDocsUtils.getSpreadsheetId(title, documentsClient, documentsAuthToken); } catch (ParseException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } if (spreadsheetId == null) { // Waiting a few seconds and trying again. Maybe the server just had a // hickup (unfortunately that happens quite a lot...). try { Thread.sleep(5000); } catch (InterruptedException e) { Log.d(TAG, "Unable to wait", e); return false; } try { spreadsheetId = SendDocsUtils.getSpreadsheetId(title, documentsClient, documentsAuthToken); } catch (ParseException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to fetch spreadsheet ID", e); return false; } } return true; } /** * Creates a spreadsheet. If successful, sets the instance variable * {@link SendDocsAsyncTask#spreadsheetId}. * * @param spreadsheetTitle the spreadsheet title * @return true if completes. */ private boolean createSpreadSheet(String spreadsheetTitle) { if (isCancelled()) { return false; } try { spreadsheetId = SendDocsUtils.createSpreadsheet(spreadsheetTitle, documentsAuthToken, context); } catch (IOException e) { Log.d(TAG, "Unable to create spreadsheet", e); return false; } return true; } /** * Fetches the worksheet ID. Sets the instance variable * {@link SendDocsAsyncTask#worksheetId}. * * @return true if completes. */ private boolean fetchWorksheetId() { if (isCancelled()) { return false; } try { worksheetId = SendDocsUtils.getWorksheetId( spreadsheetId, spreadsheetsClient, spreadsheetsAuthToken); } catch (IOException e) { Log.d(TAG, "Unable to fetch worksheet ID", e); return false; } catch (AuthenticationException e) { Log.d(TAG, "Unable to fetch worksheet ID", e); return false; } catch (ParseException e) { Log.d(TAG, "Unable to fetch worksheet ID", e); return false; } return true; } /** * Adds track info to a worksheet. * * @param track the track * @return true if completes. */ private boolean addTrackInfo(Track track) { if (isCancelled()) { return false; } try { SendDocsUtils.addTrackInfo(track, spreadsheetId, worksheetId, spreadsheetsAuthToken, context); } catch (IOException e) { Log.d(TAG, "Unable to add track info", e); return false; } return true; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsAsyncTask.java
Java
asf20
10,052
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity; import com.google.android.maps.mytracks.R; import android.content.Intent; /** * An activity to send a track to Google Docs. * * @author Jimmy Shih */ public class SendDocsActivity extends AbstractSendActivity { @Override protected AbstractSendAsyncTask createAsyncTask() { return new SendDocsAsyncTask(this, sendRequest.getTrackId(), sendRequest.getAccount()); } @Override protected String getServiceName() { return getString(R.string.send_google_docs); } @Override protected void startNextActivity(boolean success, boolean isCancel) { sendRequest.setDocsSuccess(success); Intent intent = new Intent(this, UploadResultActivity.class) .putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); startActivity(intent); finish(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsActivity.java
Java
asf20
1,730
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.docs; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.gdata.docs.DocumentsClient; import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient; import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient.WorksheetEntry; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ResourceUtils; 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 com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata2.client.AuthenticationException; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.text.NumberFormat; import java.util.Locale; /** * Utilities for sending a track to Google Docs. * * @author Sandor Dornbush * @author Matthew Simmons */ public class SendDocsUtils { private static final String GET_SPREADSHEET_BY_TITLE_URI = "https://docs.google.com/feeds/documents/private/full?" + "category=mine,spreadsheet&title=%s&title-exact=true"; private static final String CREATE_SPREADSHEET_URI = "https://docs.google.com/feeds/documents/private/full"; private static final String GET_WORKSHEETS_URI = "https://spreadsheets.google.com/feeds/worksheets/%s/private/full"; private static final String GET_WORKSHEET_URI = "https://spreadsheets.google.com/feeds/list/%s/%s/private/full"; private static final String SPREADSHEET_ID_PREFIX = "https://docs.google.com/feeds/documents/private/full/spreadsheet%3A"; private static final String CONTENT_TYPE = "Content-Type"; private static final String ATOM_FEED_MIME_TYPE = "application/atom+xml"; private static final String OPENDOCUMENT_SPREADSHEET_MIME_TYPE = "application/x-vnd.oasis.opendocument.spreadsheet"; private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION_PREFIX = "GoogleLogin auth="; private static final String SLUG = "Slug"; // Google Docs can only parse numbers in the English locale. private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.ENGLISH); private static final NumberFormat INTEGER_FORMAT = NumberFormat.getIntegerInstance( Locale.ENGLISH); static { NUMBER_FORMAT.setMaximumFractionDigits(2); NUMBER_FORMAT.setMinimumFractionDigits(2); } private static final String TAG = SendDocsUtils.class.getSimpleName(); private SendDocsUtils() {} /** * Gets the spreadsheet id of a spreadsheet. Returns null if the spreadsheet * doesn't exist. * * @param title the title of the spreadsheet * @param documentsClient the documents client * @param authToken the auth token * @return spreadsheet id or null if it doesn't exist. */ public static String getSpreadsheetId( String title, DocumentsClient documentsClient, String authToken) throws IOException, ParseException, HttpException { GDataParser gDataParser = null; try { String uri = String.format(GET_SPREADSHEET_BY_TITLE_URI, URLEncoder.encode(title)); gDataParser = documentsClient.getParserForFeed(Entry.class, uri, authToken); gDataParser.init(); while (gDataParser.hasMoreData()) { Entry entry = gDataParser.readNextEntry(null); String entryTitle = entry.getTitle(); if (entryTitle.equals(title)) { return getEntryId(entry); } } return null; } finally { if (gDataParser != null) { gDataParser.close(); } } } /** * Gets the id from an entry. Returns null if not available. * * @param entry the entry */ @VisibleForTesting static String getEntryId(Entry entry) { String entryId = entry.getId(); if (entryId.startsWith(SPREADSHEET_ID_PREFIX)) { return entryId.substring(SPREADSHEET_ID_PREFIX.length()); } return null; } /** * Creates a new spreadsheet with the given title. Returns the spreadsheet ID * if successful. Returns null otherwise. Note that it is possible that a new * spreadsheet is created, but the returned ID is null. * * @param title the title * @param authToken the auth token * @param context the context */ public static String createSpreadsheet(String title, String authToken, Context context) throws IOException { URL url = new URL(CREATE_SPREADSHEET_URI); URLConnection conn = url.openConnection(); conn.addRequestProperty(CONTENT_TYPE, OPENDOCUMENT_SPREADSHEET_MIME_TYPE); conn.addRequestProperty(SLUG, title); conn.addRequestProperty(AUTHORIZATION, AUTHORIZATION_PREFIX + authToken); conn.setDoOutput(true); OutputStream outputStream = conn.getOutputStream(); ResourceUtils.readBinaryFileToOutputStream( context, R.raw.mytracks_empty_spreadsheet, outputStream); // Get the response BufferedReader bufferedReader = null; StringBuilder resultBuilder = new StringBuilder(); try { bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { resultBuilder.append(line); } } catch (FileNotFoundException e) { // The GData API sometimes throws an error, even though creation of // the document succeeded. In that case let's just return. The caller // then needs to check if the doc actually exists. Log.d(TAG, "Unable to read result after creating a spreadsheet", e); return null; } finally { outputStream.close(); if (bufferedReader != null) { bufferedReader.close(); } } return getNewSpreadsheetId(resultBuilder.toString()); } /** * Gets the spreadsheet id from a create spreadsheet result. * * @param result the create spreadsheet result */ @VisibleForTesting static String getNewSpreadsheetId(String result) { int idTagIndex = result.indexOf("<id>"); if (idTagIndex == -1) { return null; } int idTagCloseIndex = result.indexOf("</id>", idTagIndex); if (idTagCloseIndex == -1) { return null; } int idStringStart = result.indexOf(SPREADSHEET_ID_PREFIX, idTagIndex); if (idStringStart == -1) { return null; } return result.substring(idStringStart + SPREADSHEET_ID_PREFIX.length(), idTagCloseIndex); } /** * Gets the first worksheet ID of a spreadsheet. Returns null if not * available. * * @param spreadsheetId the spreadsheet ID * @param spreadsheetClient the spreadsheet client * @param authToken the auth token */ public static String getWorksheetId( String spreadsheetId, SpreadsheetsClient spreadsheetClient, String authToken) throws IOException, AuthenticationException, ParseException { GDataParser gDataParser = null; try { String uri = String.format(GET_WORKSHEETS_URI, spreadsheetId); gDataParser = spreadsheetClient.getParserForWorksheetsFeed(uri, authToken); gDataParser.init(); if (!gDataParser.hasMoreData()) { Log.d(TAG, "No worksheet"); return null; } // Get the first worksheet WorksheetEntry worksheetEntry = (WorksheetEntry) gDataParser.readNextEntry(new WorksheetEntry()); return getWorksheetEntryId(worksheetEntry); } finally { if (gDataParser != null) { gDataParser.close(); } } } /** * Gets the worksheet id from a worksheet entry. Returns null if not available. * * @param entry the worksheet entry */ @VisibleForTesting static String getWorksheetEntryId(WorksheetEntry entry) { String id = entry.getId(); int lastSlash = id.lastIndexOf('/'); if (lastSlash == -1) { Log.d(TAG, "No id"); return null; } return id.substring(lastSlash + 1); } /** * Adds a track's info as a row in a worksheet. * * @param track the track * @param spreadsheetId the spreadsheet ID * @param worksheetId the worksheet ID * @param authToken the auth token * @param context the context */ public static void addTrackInfo( Track track, String spreadsheetId, String worksheetId, String authToken, Context context) throws IOException { String worksheetUri = String.format(GET_WORKSHEET_URI, spreadsheetId, worksheetId); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = prefs.getBoolean(context.getString(R.string.metric_units_key), true); addRow(worksheetUri, getRowContent(track, metricUnits, context), authToken); } /** * Gets the row content containing the track's info. * * @param track the track * @param metricUnits true to use metric * @param context the context */ @VisibleForTesting static String getRowContent(Track track, boolean metricUnits, Context context) { TripStatistics stats = track.getStatistics(); String distanceUnit = context.getString( metricUnits ? R.string.unit_kilometer : R.string.unit_mile); String speedUnit = context.getString( metricUnits ? R.string.unit_kilometer_per_hour : R.string.unit_mile_per_hour); String elevationUnit = context.getString( metricUnits ? R.string.unit_meter : R.string.unit_feet); StringBuilder builder = new StringBuilder().append("<entry xmlns='http://www.w3.org/2005/Atom' " + "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"); appendTag(builder, "name", track.getName()); appendTag(builder, "description", track.getDescription()); appendTag(builder, "date", StringUtils.formatDateTime(context, stats.getStartTime())); appendTag(builder, "totaltime", StringUtils.formatElapsedTimeWithHour(stats.getTotalTime())); appendTag(builder, "movingtime", StringUtils.formatElapsedTimeWithHour(stats.getMovingTime())); appendTag(builder, "distance", getDistance(stats.getTotalDistance(), metricUnits)); appendTag(builder, "distanceunit", distanceUnit); appendTag(builder, "averagespeed", getSpeed(stats.getAverageSpeed(), metricUnits)); appendTag(builder, "averagemovingspeed", getSpeed(stats.getAverageMovingSpeed(), metricUnits)); appendTag(builder, "maxspeed", getSpeed(stats.getMaxSpeed(), metricUnits)); appendTag(builder, "speedunit", speedUnit); appendTag(builder, "elevationgain", getElevation(stats.getTotalElevationGain(), metricUnits)); appendTag(builder, "minelevation", getElevation(stats.getMinElevation(), metricUnits)); appendTag(builder, "maxelevation", getElevation(stats.getMaxElevation(), metricUnits)); appendTag(builder, "elevationunit", elevationUnit); if (track.getMapId().length() > 0) { appendTag(builder, "map", String.format("%s?msa=0&msid=%s", Constants.MAPSHOP_BASE_URL, track.getMapId())); } builder.append("</entry>"); return builder.toString(); } /** * Appends a name-value pair as a gsx tag to a string builder. * * @param stringBuilder the string builder * @param name the name * @param value the value */ @VisibleForTesting static void appendTag(StringBuilder stringBuilder, String name, String value) { stringBuilder .append("<gsx:") .append(name) .append(">") .append(StringUtils.formatCData(value)) .append("</gsx:") .append(name) .append(">"); } /** * Gets the distance. Performs unit conversion and formatting. * * @param distanceInMeter the distance in meters * @param metricUnits true to use metric */ @VisibleForTesting static final String getDistance(double distanceInMeter, boolean metricUnits) { double distanceInKilometer = distanceInMeter * UnitConversions.M_TO_KM; double distance = metricUnits ? distanceInKilometer : distanceInKilometer * UnitConversions.KM_TO_MI; return NUMBER_FORMAT.format(distance); } /** * Gets the speed. Performs unit conversion and formatting. * * @param speedInMeterPerSecond the speed in meters per second * @param metricUnits true to use metric */ @VisibleForTesting static final String getSpeed(double speedInMeterPerSecond, boolean metricUnits) { double speedInKilometerPerHour = speedInMeterPerSecond * UnitConversions.MS_TO_KMH; double speed = metricUnits ? speedInKilometerPerHour : speedInKilometerPerHour * UnitConversions.KM_TO_MI; return NUMBER_FORMAT.format(speed); } /** * Gets the elevation. Performs unit conversion and formatting. * * @param elevationInMeter the elevation value in meters * @param metricUnits true to use metric */ @VisibleForTesting static final String getElevation(double elevationInMeter, boolean metricUnits) { double elevation = metricUnits ? elevationInMeter : elevationInMeter * UnitConversions.M_TO_FT; return INTEGER_FORMAT.format(elevation); } /** * Adds a row to a Google Spreadsheet worksheet. * * @param worksheetUri the worksheet URI * @param rowContent the row content * @param authToken the auth token */ private static final void addRow(String worksheetUri, String rowContent, String authToken) throws IOException { URL url = new URL(worksheetUri); URLConnection conn = url.openConnection(); conn.addRequestProperty(CONTENT_TYPE, ATOM_FEED_MIME_TYPE); conn.addRequestProperty(AUTHORIZATION, AUTHORIZATION_PREFIX + authToken); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(rowContent); writer.flush(); // Get the response BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((reader.readLine()) != null) { // Just read till the end } writer.close(); reader.close(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/docs/SendDocsUtils.java
Java
asf20
15,176
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.maps; import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; /** * An activity to choose a Google Map. * * @author Jimmy Shih */ public class ChooseMapActivity extends Activity { private static final int DIALOG_PROGRESS_ID = 0; private static final int DIALOG_ERROR_ID = 1; private SendRequest sendRequest; private ChooseMapAsyncTask asyncTask; @VisibleForTesting ArrayAdapter<ListItem> arrayAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sendRequest = getIntent().getParcelableExtra(SendRequest.SEND_REQUEST_KEY); setContentView(R.layout.choose_map); arrayAdapter = new ArrayAdapter<ListItem>(this, R.layout.choose_map_item, new ArrayList< ListItem>()) { @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.choose_map_item, parent, false); } MapsMapMetadata mapData = getItem(position).getMapData(); TextView title = (TextView) convertView.findViewById(R.id.choose_map_list_item_title); title.setText(mapData.getTitle()); TextView description = (TextView) convertView.findViewById( R.id.choose_map_list_item_description); String descriptionText = mapData.getDescription(); if (descriptionText == null || descriptionText.equals("")) { description.setVisibility(View.GONE); } else { description.setVisibility(View.VISIBLE); description.setText(descriptionText); } TextView searchStatus = (TextView) convertView.findViewById( R.id.choose_map_list_item_search_status); searchStatus.setTextColor(mapData.getSearchable() ? Color.RED : Color.GREEN); searchStatus.setText(mapData.getSearchable() ? R.string.maps_list_public_label : R.string.maps_list_unlisted_label); return convertView; } }; ListView list = (ListView) findViewById(R.id.choose_map_list_view); list.setEmptyView(findViewById(R.id.choose_map_empty_view)); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startNextActivity(arrayAdapter.getItem(position).getMapId()); } }); list.setAdapter(arrayAdapter); Object retained = getLastNonConfigurationInstance(); if (retained instanceof ChooseMapAsyncTask) { asyncTask = (ChooseMapAsyncTask) retained; asyncTask.setActivity(this); } else { asyncTask = new ChooseMapAsyncTask(this, sendRequest.getAccount()); asyncTask.execute(); } } @Override public Object onRetainNonConfigurationInstance() { asyncTask.setActivity(null); return asyncTask; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS_ID: return DialogUtils.createSpinnerProgressDialog( this, R.string.maps_list_progress_message, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { asyncTask.cancel(true); finish(); } }); case DIALOG_ERROR_ID: return new AlertDialog.Builder(this) .setCancelable(true) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(R.string.maps_list_error) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int arg1) { finish(); } }) .setTitle(R.string.generic_error_title) .create(); default: return null; } } /** * Invokes when the associated AsyncTask completes. * * @param success true if success * @param mapIds an array of map ids * @param mapData an array of map data */ public void onAsyncTaskCompleted( boolean success, ArrayList<String> mapIds, ArrayList<MapsMapMetadata> mapData) { removeProgressDialog(); if (success) { arrayAdapter.clear(); // To prevent displaying the emptyView message momentarily before the // arrayAdapter is set, don't set the emptyView message in the xml layout. // Instead, set it only when needed. if (mapIds.size() == 0) { TextView emptyView = (TextView) findViewById(R.id.choose_map_empty_view); emptyView.setText(R.string.maps_list_no_maps); } else { for (int i = 0; i < mapIds.size(); i++) { arrayAdapter.add(new ListItem(mapIds.get(i), mapData.get(i))); } } } else { showErrorDialog(); } } /** * Shows the progress dialog. */ public void showProgressDialog() { showDialog(DIALOG_PROGRESS_ID); } /** * Shows the error dialog. */ @VisibleForTesting void showErrorDialog() { showDialog(DIALOG_ERROR_ID); } /** * Remove the progress dialog. */ @VisibleForTesting void removeProgressDialog() { removeDialog(DIALOG_PROGRESS_ID); } /** * Starts the next activity, {@link SendMapsActivity}. * * @param mapId the chosen map id */ private void startNextActivity(String mapId) { sendRequest.setMapId(mapId); Intent intent = new Intent(this, SendMapsActivity.class) .putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); startActivity(intent); finish(); } /** * A class containing {@link ChooseMapActivity} list item. * * @author Jimmy Shih */ @VisibleForTesting class ListItem { private String mapId; private MapsMapMetadata mapData; private ListItem(String mapId, MapsMapMetadata mapData) { this.mapId = mapId; this.mapData = mapData; } /** * Gets the map id. */ public String getMapId() { return mapId; } /** * Gets the map data. */ public MapsMapMetadata getMapData() { return mapData; } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/maps/ChooseMapActivity.java
Java
asf20
7,719
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.maps; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.gdata.maps.MapsClient; import com.google.android.apps.mytracks.io.gdata.maps.MapsFeature; import com.google.android.apps.mytracks.io.gdata.maps.MapsGDataConverter; import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata; import com.google.android.maps.GeoPoint; import com.google.common.annotations.VisibleForTesting; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.parser.ParseException; import android.location.Location; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.util.ArrayList; /** * Utilities for sending a track to Google Maps. * * @author Jimmy Shih */ public class SendMapsUtils { private static final String EMPTY_TITLE = "-"; private static final int LINE_COLOR = 0x80FF0000; private static final String TAG = SendMapsUtils.class.getSimpleName(); private SendMapsUtils() {} /** * Gets the Google Maps url for a track. * * @param track the track * @return the url if available. */ public static String getMapUrl(Track track) { if (track == null || track.getMapId() == null) { Log.e(TAG, "Invalid track"); return null; } return MapsClient.buildMapUrl(track.getMapId()); } /** * Creates a new Google Map. * * @param title title of the map * @param description description of the map * @param isPublic true if the map can be public * @param mapsClient the maps client * @param authToken the auth token * @return map id of the created map if successful. */ public static String createNewMap( String title, String description, boolean isPublic, MapsClient mapsClient, String authToken) throws ParseException, HttpException, IOException { String mapFeed = MapsClient.getMapsFeed(); MapsMapMetadata metaData = new MapsMapMetadata(); metaData.setTitle(title); metaData.setDescription(description); metaData.setSearchable(isPublic); Entry entry = MapsGDataConverter.getMapEntryForMetadata(metaData); Entry result = mapsClient.createEntry(mapFeed, authToken, entry); if (result == null) { Log.d(TAG, "No result when creating a new map"); return null; } return MapsClient.getMapIdFromMapEntryId(result.getId()); } /** * Uploads a start/end marker to Google Maps. * * @param mapId the map id * @param title the marker title * @param description the marker description * @param iconUrl the marker icon URL * @param location the marker location * @param mapsClient the maps client * @param authToken the auth token * @param mapsGDataConverter the maps gdata converter * @return true if success. */ public static boolean uploadMarker(String mapId, String title, String description, String iconUrl, Location location, MapsClient mapsClient, String authToken, MapsGDataConverter mapsGDataConverter) throws ParseException, HttpException, IOException { String featuresFeed = MapsClient.getFeaturesFeed(mapId); MapsFeature mapsFeature = buildMapsMarkerFeature( title, description, iconUrl, getGeoPoint(location)); Entry entry = mapsGDataConverter.getEntryForFeature(mapsFeature); try { mapsClient.createEntry(featuresFeed, authToken, entry); } catch (IOException e) { // Retry once (often IOException is thrown on a timeout) Log.d(TAG, "Retry upload marker", e); mapsClient.createEntry(featuresFeed, authToken, entry); } return true; } /** * Uploads a waypoint as a marker feature to Google Maps. * * @param mapId the map id * @param waypoint the waypoint * @param mapsClient the maps client * @param authToken the auth token * @param mapsGDataConverter the maps gdata converter * @return true if success. */ public static boolean uploadWaypoint(String mapId, Waypoint waypoint, MapsClient mapsClient, String authToken, MapsGDataConverter mapsGDataConverter) throws ParseException, HttpException, IOException { String featuresFeed = MapsClient.getFeaturesFeed(mapId); MapsFeature feature = buildMapsMarkerFeature(waypoint.getName(), waypoint.getDescription(), waypoint.getIcon(), getGeoPoint(waypoint.getLocation())); Entry entry = mapsGDataConverter.getEntryForFeature(feature); try { mapsClient.createEntry(featuresFeed, authToken, entry); } catch (IOException e) { // Retry once (often IOException is thrown on a timeout) Log.d(TAG, "Retry upload waypoint", e); mapsClient.createEntry(featuresFeed, authToken, entry); } return true; } /** * Uploads a segment as a line feature to Google Maps. * * @param mapId the map id * @param title the segment title * @param locations the segment locations * @param mapsClient the maps client * @param authToken the auth token * @param mapsGDataConverter the maps gdata converter * @return true if success. */ public static boolean uploadSegment(String mapId, String title, ArrayList<Location> locations, MapsClient mapsClient, String authToken, MapsGDataConverter mapsGDataConverter) throws ParseException, HttpException, IOException { String featuresFeed = MapsClient.getFeaturesFeed(mapId); Entry entry = mapsGDataConverter.getEntryForFeature(buildMapsLineFeature(title, locations)); try { mapsClient.createEntry(featuresFeed, authToken, entry); } catch (IOException e) { // Retry once (often IOException is thrown on a timeout) Log.d(TAG, "Retry upload track points", e); mapsClient.createEntry(featuresFeed, authToken, entry); } return true; } /** * Builds a map marker feature. * * @param title feature title * @param description the feature description * @param iconUrl the feature icon URL * @param geoPoint the marker */ @VisibleForTesting static MapsFeature buildMapsMarkerFeature( String title, String description, String iconUrl, GeoPoint geoPoint) { MapsFeature mapsFeature = new MapsFeature(); mapsFeature.setType(MapsFeature.MARKER); mapsFeature.generateAndroidId(); // Feature must have a name (otherwise GData upload may fail) mapsFeature.setTitle(TextUtils.isEmpty(title) ? EMPTY_TITLE : title); mapsFeature.setDescription(description.replaceAll("\n", "<br>")); mapsFeature.setIconUrl(iconUrl); mapsFeature.addPoint(geoPoint); return mapsFeature; } /** * Builds a maps line feature from a set of locations. * * @param title the feature title * @param locations set of locations */ @VisibleForTesting static MapsFeature buildMapsLineFeature(String title, ArrayList<Location> locations) { MapsFeature mapsFeature = new MapsFeature(); mapsFeature.setType(MapsFeature.LINE); mapsFeature.generateAndroidId(); // Feature must have a name (otherwise GData upload may fail) mapsFeature.setTitle(TextUtils.isEmpty(title) ? EMPTY_TITLE : title); mapsFeature.setColor(LINE_COLOR); for (Location location : locations) { mapsFeature.addPoint(getGeoPoint(location)); } return mapsFeature; } /** * Gets a {@link GeoPoint} from a {@link Location}. * * @param location the location */ @VisibleForTesting static GeoPoint getGeoPoint(Location location) { return new GeoPoint( (int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsUtils.java
Java
asf20
8,288
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.maps; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.DescriptionGenerator; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.gdata.GDataClientFactory; import com.google.android.apps.mytracks.io.gdata.maps.MapsClient; import com.google.android.apps.mytracks.io.gdata.maps.MapsConstants; import com.google.android.apps.mytracks.io.gdata.maps.MapsGDataConverter; import com.google.android.apps.mytracks.io.gdata.maps.XmlMapsGDataParserFactory; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.common.gdata.AndroidXmlParserFactory; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.parser.ParseException; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.xmlpull.v1.XmlPullParserException; /** * AsyncTask to send a track to Google Maps. * <p> * IMPORTANT: While this code is Apache-licensed, please notice that usage of * the Google Maps servers through this API is only allowed for the My Tracks * application. Other applications looking to upload maps data should look into * using the Google Fusion Tables API. * * @author Jimmy Shih */ public class SendMapsAsyncTask extends AbstractSendAsyncTask { private static final String START_ICON_URL = "http://maps.google.com/mapfiles/ms/micons/green-dot.png"; private static final String END_ICON_URL = "http://maps.google.com/mapfiles/ms/micons/red-dot.png"; private static final int MAX_POINTS_PER_UPLOAD = 500; private static final int PROGRESS_FETCH_MAP_ID = 5; @VisibleForTesting static final int PROGRESS_UPLOAD_DATA_MIN = 10; @VisibleForTesting static final int PROGRESS_UPLOAD_DATA_MAX = 90; private static final int PROGRESS_UPLOAD_WAYPOINTS = 95; private static final int PROGRESS_COMPLETE = 100; private static final String TAG = SendMapsAsyncTask.class.getSimpleName(); private final long trackId; private final Account account; private final String chooseMapId; private final MyTracksProviderUtils myTracksProviderUtils; private final Context context; private final GDataClient gDataClient; private final MapsClient mapsClient; // The following variables are for per upload states private MapsGDataConverter mapsGDataConverter; private String authToken; private String mapId; int currentSegment; public SendMapsAsyncTask(SendMapsActivity activity, long trackId, Account account, String chooseMapId) { this(activity, trackId, account, chooseMapId, MyTracksProviderUtils.Factory.get(activity .getApplicationContext())); } /** * This constructor is created for test. */ @VisibleForTesting public SendMapsAsyncTask ( SendMapsActivity activity, long trackId, Account account, String chooseMapId, MyTracksProviderUtils myTracksProviderUtils) { super(activity); this.trackId = trackId; this.account = account; this.chooseMapId = chooseMapId; this.myTracksProviderUtils = myTracksProviderUtils; context = activity.getApplicationContext(); gDataClient = GDataClientFactory.getGDataClient(context); mapsClient = new MapsClient( gDataClient, new XmlMapsGDataParserFactory(new AndroidXmlParserFactory())); } @Override protected void closeConnection() { if (gDataClient != null) { gDataClient.close(); } } @Override protected void saveResult() { Track track = myTracksProviderUtils.getTrack(trackId); if (track != null) { track.setMapId(mapId); myTracksProviderUtils.updateTrack(track); } else { Log.d(TAG, "No track"); } } @Override protected boolean performTask() { // Reset the per upload states mapsGDataConverter = null; authToken = null; mapId = null; currentSegment = 1; // Create a maps gdata converter try { mapsGDataConverter = new MapsGDataConverter(); } catch (XmlPullParserException e) { Log.d(TAG, "Unable to create a maps gdata converter", e); return false; } // Get auth token try { authToken = AccountManager.get(context).blockingGetAuthToken( account, MapsConstants.SERVICE_NAME, false); } catch (OperationCanceledException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (AuthenticatorException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } catch (IOException e) { Log.d(TAG, "Unable to get auth token", e); return retryTask(); } // Get the track Track track = myTracksProviderUtils.getTrack(trackId); if (track == null) { Log.d(TAG, "Track is null"); return false; } // Fetch the mapId, create a new map if necessary publishProgress(PROGRESS_FETCH_MAP_ID); if (!fetchSendMapId(track)) { Log.d("TAG", "Unable to upload all track points"); return retryTask(); } // Upload all the track points plus the start and end markers publishProgress(PROGRESS_UPLOAD_DATA_MIN); if (!uploadAllTrackPoints(track)) { Log.d("TAG", "Unable to upload all track points"); return retryTask(); } // Upload all the waypoints publishProgress(PROGRESS_UPLOAD_WAYPOINTS); if (!uploadWaypoints()) { Log.d("TAG", "Unable to upload waypoints"); return false; } publishProgress(PROGRESS_COMPLETE); return true; } @Override protected void invalidateToken() { AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); } /** * Fetches the {@link SendMapsAsyncTask#mapId} instance variable for * sending a track to Google Maps. * * @param track the Track * @return true if able to fetch the mapId variable. */ @VisibleForTesting boolean fetchSendMapId(Track track) { if (isCancelled()) { return false; } if (chooseMapId != null) { mapId = chooseMapId; return true; } else { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean mapPublic = sharedPreferences.getBoolean( context.getString(R.string.default_map_public_key), true); try { String description = track.getCategory() + "\n" + track.getDescription() + "\n" + context.getString(R.string.send_google_by_my_tracks, "", ""); mapId = SendMapsUtils.createNewMap( track.getName(), description, mapPublic, mapsClient, authToken); } catch (ParseException e) { Log.d(TAG, "Unable to create a new map", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to create a new map", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to create a new map", e); return false; } return mapId != null; } } /** * Uploads all the points in a track. * * @param track the track * @return true if success. */ @VisibleForTesting boolean uploadAllTrackPoints(Track track) { Cursor locationsCursor = null; try { SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = prefs.getBoolean(context.getString(R.string.metric_units_key), true); locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); if (locationsCursor == null) { Log.d(TAG, "Location cursor is null"); return false; } int locationsCount = locationsCursor.getCount(); List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; // For chart server, limit the number of elevation readings to 250. int elevationSamplingFrequency = Math.max(1, (int) (locationsCount / 250.0)); TripStatisticsBuilder tripStatisticsBuilder = new TripStatisticsBuilder( track.getStatistics().getStartTime()); DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); for (int i = 0; i < locationsCount; i++) { locationsCursor.moveToPosition(i); Location location = myTracksProviderUtils.createLocation(locationsCursor); locations.add(location); if (i == 0) { // Create a start marker if (!uploadMarker(context.getString(R.string.marker_label_start, track.getName()), "", START_ICON_URL, location)) { Log.d(TAG, "Unable to create a start marker"); return false; } } // Add to the distances and elevations vectors if (LocationUtils.isValidLocation(location)) { tripStatisticsBuilder.addLocation(location, location.getTime()); // All points go into the smoothing buffer elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); if (i % elevationSamplingFrequency == 0) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); } lastLocation = location; } // Upload periodically int readCount = i + 1; if (readCount % MAX_POINTS_PER_UPLOAD == 0) { if (!prepareAndUploadPoints(track, locations, false)) { Log.d(TAG, "Unable to upload points"); return false; } updateProgress(readCount, locationsCount); locations.clear(); } } // Do a final upload with the remaining locations if (!prepareAndUploadPoints(track, locations, true)) { Log.d(TAG, "Unable to upload points"); return false; } // Create an end marker if (lastLocation != null) { distances.add(tripStatisticsBuilder.getStatistics().getTotalDistance()); elevations.add(elevationBuffer.getAverage()); track.setDescription(getTrackDescription(track, distances, elevations)); if (!uploadMarker(context.getString(R.string.marker_label_end, track.getName()), track.getDescription(), END_ICON_URL, lastLocation)) { Log.d(TAG, "Unable to create an end marker"); return false; } } return true; } finally { if (locationsCursor != null) { locationsCursor.close(); } } } /** * Gets the description of a track. * * @param track the track * @param distances distance vectors * @param elevations elevation vectors * @return the description of a track. */ @VisibleForTesting String getTrackDescription(Track track, Vector<Double> distances, Vector<Double> elevations) { DescriptionGenerator descriptionGenerator = new DescriptionGeneratorImpl(context); return "<p>" + track.getDescription() + "</p><p>" + descriptionGenerator.generateTrackDescription(track, distances, elevations) + "</p>"; } /** * Prepares and uploads a list of locations from a track. * * @param track the track * @param locations the locations from the track * @param lastBatch true if it is the last batch of locations * @return true if success. */ @VisibleForTesting boolean prepareAndUploadPoints(Track track, List<Location> locations, boolean lastBatch) { // Prepare locations ArrayList<Track> splitTracks = SendToGoogleUtils.prepareLocations(track, locations); // Upload segments boolean onlyOneSegment = lastBatch && currentSegment == 1 && splitTracks.size() == 1; for (Track segment : splitTracks) { if (!onlyOneSegment) { segment.setName(context.getString( R.string.send_google_track_part_label, segment.getName(), currentSegment)); } if (!uploadSegment(segment.getName(), segment.getLocations())) { Log.d(TAG, "Unable to upload segment"); return false; } currentSegment++; } return true; } /** * Uploads a marker. * * @param title marker title * @param description marker description * @param iconUrl marker marker icon * @param location marker location * @return true if success. */ @VisibleForTesting boolean uploadMarker( String title, String description, String iconUrl, Location location) { if (isCancelled()) { return false; } try { if (!SendMapsUtils.uploadMarker(mapId, title, description, iconUrl, location, mapsClient, authToken, mapsGDataConverter)) { Log.d(TAG, "Unable to upload marker"); return false; } } catch (ParseException e) { Log.d(TAG, "Unable to upload marker", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to upload marker", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to upload marker", e); return false; } return true; } /** * Uploads a segment * * @param title segment title * @param locations segment locations * @return true if success */ private boolean uploadSegment(String title, ArrayList<Location> locations) { if (isCancelled()) { return false; } try { if (!SendMapsUtils.uploadSegment( mapId, title, locations, mapsClient, authToken, mapsGDataConverter)) { Log.d(TAG, "Unable to upload track points"); return false; } } catch (ParseException e) { Log.d(TAG, "Unable to upload track points", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to upload track points", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to upload track points", e); return false; } return true; } /** * Uploads all the waypoints. * * @return true if success. */ @VisibleForTesting boolean uploadWaypoints() { Cursor cursor = null; try { cursor = myTracksProviderUtils.getWaypointsCursor( trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { // This will skip the first waypoint (it carries the stats for the // track). while (cursor.moveToNext()) { if (isCancelled()) { return false; } Waypoint waypoint = myTracksProviderUtils.createWaypoint(cursor); try { if (!SendMapsUtils.uploadWaypoint( mapId, waypoint, mapsClient, authToken, mapsGDataConverter)) { Log.d(TAG, "Unable to upload waypoint"); return false; } } catch (ParseException e) { Log.d(TAG, "Unable to upload waypoint", e); return false; } catch (HttpException e) { Log.d(TAG, "Unable to upload waypoint", e); return false; } catch (IOException e) { Log.d(TAG, "Unable to upload waypoint", e); return false; } } } return true; } finally { if (cursor != null) { cursor.close(); } } } /** * Updates the progress based on the number of locations uploaded. * * @param uploaded the number of uploaded locations * @param total the number of total locations */ @VisibleForTesting void updateProgress(int uploaded, int total) { publishProgress(getPercentage(uploaded, total)); } /** * Count the percentage of the number of locations uploaded. * * @param uploaded the number of uploaded locations * @param total the number of total locations */ @VisibleForTesting static int getPercentage(int uploaded, int total) { double totalPercentage = (double) uploaded / total; double scaledPercentage = totalPercentage * (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN; return (int) scaledPercentage; } /** * Gets the mapID. * * @return mapId */ @VisibleForTesting String getMapId() { return mapId; } /** * Sets the value of mapsGDataConverter. * * @param mapsGDataConverter new value of mapsGDataConverter */ @VisibleForTesting void setMapsGDataConverter(MapsGDataConverter mapsGDataConverter) { this.mapsGDataConverter = mapsGDataConverter; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java
Java
asf20
18,296
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.maps; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.io.gdata.GDataClientFactory; import com.google.android.apps.mytracks.io.gdata.maps.MapFeatureEntry; import com.google.android.apps.mytracks.io.gdata.maps.MapsClient; import com.google.android.apps.mytracks.io.gdata.maps.MapsConstants; import com.google.android.apps.mytracks.io.gdata.maps.MapsGDataConverter; import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata; import com.google.android.apps.mytracks.io.gdata.maps.XmlMapsGDataParserFactory; import com.google.android.common.gdata.AndroidXmlParserFactory; import com.google.common.annotations.VisibleForTesting; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.util.ArrayList; /** * AsyncTask for {@link ChooseMapActivity} to get all the maps from Google Maps. * * @author Jimmy Shih */ public class ChooseMapAsyncTask extends AsyncTask<Void, Integer, Boolean> { private static final String TAG = ChooseMapAsyncTask.class.getSimpleName(); private ChooseMapActivity activity; private final Account account; private final Context context; private final GDataClient gDataClient; private final MapsClient mapsClient; /** * True if can retry sending to Google Fusion Tables. */ private boolean canRetry; /** * True if the AsyncTask has completed. */ private boolean completed; /** * True if the result is success. */ private boolean success; // The following variables are for per request states private String authToken; private ArrayList<String> mapIds; private ArrayList<MapsMapMetadata> mapData; public ChooseMapAsyncTask(ChooseMapActivity activity, Account account) { this(activity, account, activity.getApplicationContext(), GDataClientFactory .getGDataClient(activity.getApplicationContext()), new MapsClient( GDataClientFactory.getGDataClient(activity.getApplicationContext()), new XmlMapsGDataParserFactory(new AndroidXmlParserFactory()))); } /** * Creates this constructor for test. */ public ChooseMapAsyncTask(ChooseMapActivity activity, Account account, Context context, GDataClient gDataClient, MapsClient mapsClient) { this.activity = activity; this.account = account; this.context = context; this.gDataClient = gDataClient; this.mapsClient = mapsClient; canRetry = true; completed = false; success = false; } /** * Sets the activity associated with this AyncTask. * * @param activity the activity. */ public void setActivity(ChooseMapActivity activity) { this.activity = activity; if (completed && activity != null) { activity.onAsyncTaskCompleted(success, mapIds, mapData); } } @Override protected void onPreExecute() { activity.showProgressDialog(); } @Override protected Boolean doInBackground(Void... params) { try { return getMaps(); } finally { if (gDataClient != null) { gDataClient.close(); } } } @Override protected void onPostExecute(Boolean result) { success = result; completed = true; if (activity != null) { activity.onAsyncTaskCompleted(success, mapIds, mapData); } } /** * Gets all the maps from Google Maps. * * @return true if success. */ @VisibleForTesting boolean getMaps() { // Reset the per request states authToken = null; mapIds = new ArrayList<String>(); mapData = new ArrayList<MapsMapMetadata>(); try { authToken = AccountManager.get(context).blockingGetAuthToken( account, MapsConstants.SERVICE_NAME, false); } catch (OperationCanceledException e) { Log.d(TAG, "Unable to get auth token", e); return retryUpload(); } catch (AuthenticatorException e) { Log.d(TAG, "Unable to get auth token", e); return retryUpload(); } catch (IOException e) { Log.d(TAG, "Unable to get auth token", e); return retryUpload(); } if (isCancelled()) { return false; } GDataParser gDataParser = null; try { gDataParser = mapsClient.getParserForFeed( MapFeatureEntry.class, MapsClient.getMapsFeed(), authToken); gDataParser.init(); while (gDataParser.hasMoreData()) { MapFeatureEntry entry = (MapFeatureEntry) gDataParser.readNextEntry(null); mapIds.add(MapsGDataConverter.getMapidForEntry(entry)); mapData.add(MapsGDataConverter.getMapMetadataForEntry(entry)); } } catch (ParseException e) { Log.d(TAG, "Unable to get maps", e); return retryUpload(); } catch (IOException e) { Log.d(TAG, "Unable to get maps", e); return retryUpload(); } catch (HttpException e) { Log.d(TAG, "Unable to get maps", e); return retryUpload(); } finally { if (gDataParser != null) { gDataParser.close(); } } return true; } /** * Retries upload. Invalidates the authToken. If can retry, invokes * {@link ChooseMapAsyncTask#getMaps()}. Returns false if cannot retry. */ @VisibleForTesting boolean retryUpload() { if (isCancelled()) { return false; } AccountManager.get(context).invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); if (canRetry) { canRetry = false; return getMaps(); } return false; } /** * Gets the complete status of task. */ @VisibleForTesting boolean getCompleted() { return completed; } /** * Sets the complete status of task. * @param completed */ @VisibleForTesting void setCompleted(boolean completed) { this.completed = completed; } /** * Sets the status of canRetry. * @param canRetry status of canRetry */ @VisibleForTesting void setCanRetry(boolean canRetry) { this.canRetry = canRetry; } /** * Gets the status of canRetry. */ @VisibleForTesting boolean getCanRetry() { return canRetry; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/maps/ChooseMapAsyncTask.java
Java
asf20
7,054
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.maps; import com.google.android.apps.mytracks.io.docs.SendDocsActivity; import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendActivity; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest; import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.content.Intent; /** * An activity to send a track to Google Maps. * * @author Jimmy Shih */ public class SendMapsActivity extends AbstractSendActivity { @Override protected AbstractSendAsyncTask createAsyncTask() { return new SendMapsAsyncTask( this, sendRequest.getTrackId(), sendRequest.getAccount(), sendRequest.getMapId()); } @Override protected String getServiceName() { return getString(R.string.send_google_maps); } @Override protected void startNextActivity(boolean success, boolean isCancel) { sendRequest.setMapsSuccess(success); Class<?> next = getNextClass(sendRequest, isCancel); Intent intent = new Intent(this, next).putExtra(SendRequest.SEND_REQUEST_KEY, sendRequest); startActivity(intent); finish(); } @VisibleForTesting Class<?> getNextClass(SendRequest request, boolean isCancel) { if (isCancel) { return UploadResultActivity.class; } else { if (request.isSendFusionTables()) { return SendFusionTablesActivity.class; } else if (request.isSendDocs()) { return SendDocsActivity.class; } else { return UploadResultActivity.class; } } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsActivity.java
Java
asf20
2,407
/* * 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 com.google.android.apps.mytracks.services.RemoveTempFilesService; import com.google.android.apps.mytracks.util.AnalyticsUtils; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.maps.mytracks.BuildConfig; import android.app.Application; import android.content.Intent; /** * MyTracksApplication for keeping global state. * * @author Jimmy Shih */ public class MyTracksApplication extends Application { private TrackDataHub trackDataHub; @Override public void onCreate() { if (BuildConfig.DEBUG) { ApiAdapterFactory.getApiAdapter().enableStrictMode(); } AnalyticsUtils.sendPageViews(this, "/appstart"); startService(new Intent(this, RemoveTempFilesService.class)); } /** * 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; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/MyTracksApplication.java
Java
asf20
1,789
/* * 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.apps.mytracks.util.PreferencesUtils; 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.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 final int speedMarginDefault; private double averageMovingSpeed; private final Context context; @VisibleForTesting static final int CRITICAL_DIFFERENCE_PERCENTAGE = 20; public DynamicSpeedTrackPathDescriptor(Context context) { this.context = context; speedMarginDefault = Integer.parseInt(context .getString(R.string.color_mode_dynamic_percentage_default)); SharedPreferences prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { speedMargin = speedMarginDefault; return; } prefs.registerOnSharedPreferenceChangeListener(this); speedMargin = getSpeedMargin(prefs); } @VisibleForTesting int getSpeedMargin(SharedPreferences sharedPreferences) { try { return Integer.parseInt(sharedPreferences.getString( context.getString(R.string.track_color_mode_dynamic_speed_variation_key), Integer.toString(speedMarginDefault))); } catch (NumberFormatException e) { return speedMarginDefault; } } /** * 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; } /** * Gets 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 = speedMarginDefault; return; } speedMargin = getSpeedMargin(prefs); } @Override public boolean needsRedraw() { long selectedTrackId = PreferencesUtils.getSelectedTrackId(context); if (selectedTrackId == -1L) { // Could not find track. return false; } Track track = MyTracksProviderUtils.Factory.get(context).getTrack(selectedTrackId); TripStatistics stats = track.getStatistics(); double newAverageMovingSpeed = (int) Math.floor( stats.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH); return isDifferenceSignificant(averageMovingSpeed, newAverageMovingSpeed); } /** * Checks whether the old speed and the new speed differ significantly or not. */ public boolean isDifferenceSignificant(double oldAverageMovingSpeed, double newAverageMovingSpeed) { if (oldAverageMovingSpeed == 0) { if (newAverageMovingSpeed == 0) { return false; } else { averageMovingSpeed = newAverageMovingSpeed; return true; } } // Here, both oldAverageMovingSpeed and newAverageMovingSpeed are not zero. double maxValue = Math.max(oldAverageMovingSpeed, newAverageMovingSpeed); double differencePercentage = Math.abs(oldAverageMovingSpeed - newAverageMovingSpeed) / maxValue * 100; if (differencePercentage >= CRITICAL_DIFFERENCE_PERCENTAGE) { averageMovingSpeed = newAverageMovingSpeed; return true; } return false; } /** * Gets the value of variable speedMargin to check the result of test. * @return the value of speedMargin. */ @VisibleForTesting int getSpeedMargin() { return speedMargin; } /** * Sets the value of newAverageMovingSpeed to test the method isDifferenceSignificant. * @param newAverageMovingSpeed the value to set. */ @VisibleForTesting void setAverageMovingSpeed(double newAverageMovingSpeed) { averageMovingSpeed = newAverageMovingSpeed; } /** * Gets the value of averageMovingSpeed to check the result of test. * * @return the value of averageMovingSpeed */ @VisibleForTesting double getAverageMovingSpeed() { return averageMovingSpeed; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathDescriptor.java
Java
asf20
5,933
/* * 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(); }
0359xiaodong-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 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 com.google.common.annotations.VisibleForTesting; 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) { path = new Path(); updatePath(projection, viewRect, startLocationIdx, alwaysVisible, points, path); } /** * 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 always visible. * @param points The list of points used to update the path. * @param pathToUpdate The path to be created. */ @VisibleForTesting void updatePath(Projection projection, Rect viewRect, int startLocationIdx, Boolean alwaysVisible, List<CachedLocation> points, Path pathToUpdate) { pathToUpdate.incReserve(points.size()); // 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. for (int i = startLocationIdx; i < points.size(); ++i) { CachedLocation loc = points.get(i); // Check if valid, if not then indicate a new segment. if (!loc.valid) { newSegment = true; continue; } final GeoPoint geoPoint = loc.geoPoint; // Check if this breaks the existing segment. boolean visible = alwaysVisible || viewRect.contains(geoPoint.getLongitudeE6(), geoPoint.getLatitudeE6()); if (!visible && !lastVisible) { // This is a point outside view not connected to a visible one. newSegment = true; } lastVisible = visible; // Either move to beginning of a new segment or continue the old one. projection.toPixels(geoPoint, pt); if (newSegment) { pathToUpdate.moveTo(pt.x, pt.y); newSegment = false; } else { pathToUpdate.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(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/SingleColorTrackPathPainter.java
Java
asf20
3,885
/* * 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; } }
0359xiaodong-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(); }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/TrackPathPainter.java
Java
asf20
1,812
/* * 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); } } }
0359xiaodong-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 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 int slowDefault; private final int normalDefault; private final Context context; public FixedSpeedTrackPathDescriptor(Context context) { this.context = context; slowDefault = Integer.parseInt(context.getString(R.string.color_mode_fixed_slow_default)); normalDefault = Integer.parseInt(context.getString(R.string.color_mode_fixed_medium_default)); SharedPreferences prefs = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (prefs == null) { slowSpeed = slowDefault; normalSpeed = normalDefault; return; } prefs.registerOnSharedPreferenceChangeListener(this); try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), Integer.toString(slowDefault))); } catch (NumberFormatException e) { slowSpeed = slowDefault; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), Integer.toString(normalDefault))); } catch (NumberFormatException e) { normalSpeed = normalDefault; } } /** * 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 = slowDefault; normalSpeed = normalDefault; return; } try { slowSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_slow_key), Integer.toString(slowDefault))); } catch (NumberFormatException e) { slowSpeed = slowDefault; } try { normalSpeed = Integer.parseInt(prefs.getString(context.getString( R.string.track_color_mode_fixed_speed_medium_key), Integer.toString(normalDefault))); } catch (NumberFormatException e) { normalSpeed = normalDefault; } } @Override public boolean needsRedraw() { return false; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/FixedSpeedTrackPathDescriptor.java
Java
asf20
3,952
/* * 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 com.google.common.annotations.VisibleForTesting; 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; } /** * Returns coloredPaths. * * @return coloredPaths */ @VisibleForTesting List<ColoredPath> getColoredPaths() { return coloredPaths; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/maps/DynamicSpeedTrackPathPainter.java
Java
asf20
4,964
/* * 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 { private final static int DEFAULT_PERSISTEDINT = 0; public AntPreference(Context context) { super(context); init(); } public AntPreference(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { int sensorId = getPersistedInt(AntPreference.DEFAULT_PERSISTEDINT); 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; } }); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/AntPreference.java
Java
asf20
1,967
/* * 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.maps.mytracks.R; import android.content.Context; import android.text.TextUtils; import android.text.format.DateUtils; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Various string manipulation methods. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class StringUtils { private static final SimpleDateFormat ISO_8601_DATE_TIME_FORMAT = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); private static final SimpleDateFormat ISO_8601_BASE = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss"); private static final Pattern ISO_8601_EXTRAS = Pattern.compile( "^(\\.\\d+)?(?:Z|([+-])(\\d{2}):(\\d{2}))?$"); static { ISO_8601_DATE_TIME_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); ISO_8601_BASE.setTimeZone(TimeZone.getTimeZone("UTC")); } private StringUtils() {} /** * Formats the time based on user's phone date/time preferences. * * @param context the context * @param time the time in milliseconds */ public static String formatTime(Context context, long time) { return android.text.format.DateFormat.getTimeFormat(context).format(time); } /** * Formats the date and time based on user's phone date/time preferences. * * @param context the context * @param time the time in milliseconds */ public static String formatDateTime(Context context, long time) { return android.text.format.DateFormat.getDateFormat(context).format(time) + " " + formatTime(context, time); } /** * Formats the time using the ISO 8601 date time format with fractional * seconds in UTC time zone. * * @param time the time in milliseconds */ public static String formatDateTimeIso8601(long time) { return ISO_8601_DATE_TIME_FORMAT.format(time); } /** * Formats the elapsed timed in the form "MM:SS" or "H:MM:SS". * * @param time the time in milliseconds */ public static String formatElapsedTime(long time) { return DateUtils.formatElapsedTime(time / 1000); } /** * Formats the elapsed time in the form "H:MM:SS". * * @param time the time in milliseconds */ public static String formatElapsedTimeWithHour(long time) { String value = formatElapsedTime(time); return TextUtils.split(value, ":").length == 2 ? "0:" + value : value; } /** * Formats the distance. * * @param context the context * @param distance the distance in meters * @param metric true to use metric. False to use imperial */ public static String formatDistance(Context context, double distance, boolean metric) { if (metric) { if (distance > 2000.0) { distance *= UnitConversions.M_TO_KM; return context.getString(R.string.value_float_kilometer, distance); } else { return context.getString(R.string.value_float_meter, distance); } } else { if (distance * UnitConversions.M_TO_MI > 2) { distance *= UnitConversions.M_TO_MI; return context.getString(R.string.value_float_mile, distance); } else { distance *= UnitConversions.M_TO_FT; return context.getString(R.string.value_float_feet, distance); } } } /** * Formats the speed. * * @param context the context * @param speed the speed in meters per second * @param metric true to use metric. False to use imperial * @param reportSpeed true to report as speed. False to report as pace */ public static String formatSpeed( Context context, double speed, boolean metric, boolean reportSpeed) { if (Double.isNaN(speed) || Double.isInfinite(speed)) { return context.getString(R.string.value_unknown); } if (metric) { speed = speed * UnitConversions.MS_TO_KMH; if (reportSpeed) { return context.getString(R.string.value_float_kilometer_hour, speed); } else { double paceInMinute = speed == 0 ? 0.0 : 60 / speed; return context.getString(R.string.value_float_minute_kilometer, paceInMinute); } } else { speed = speed * UnitConversions.MS_TO_KMH * UnitConversions.KM_TO_MI; if (reportSpeed) { return context.getString(R.string.value_float_mile_hour, speed); } else { double paceInMinute = speed == 0 ? 0.0 : 60 / speed; return context.getString(R.string.value_float_minute_mile, paceInMinute); } } } /** * Formats the elapsed time and distance. * * @param context the context * @param elapsedTime the elapsed time in milliseconds * @param distance the distance in meters * @param metric true to use metric. False to use imperial */ public static String formatTimeDistance( Context context, long elapsedTime, double distance, boolean metric) { return formatElapsedTime(elapsedTime) + " " + formatDistance(context, distance, metric); } /** * Formats the given text as a XML CDATA element. This includes adding the * starting and ending CDATA tags. Please notice that this may result in * multiple consecutive CDATA tags. * * @param text the given text */ public static String formatCData(String text) { return "<![CDATA[" + text.replaceAll("]]>", "]]]]><![CDATA[>") + "]]>"; } /** * Gets the time, in milliseconds, from an XML date time string as defined at * http://www.w3.org/TR/xmlschema-2/#dateTime * * @param xmlDateTime the XML date time string */ public static long getTime(String xmlDateTime) { // Parse the date time base ParsePosition position = new ParsePosition(0); Date date = ISO_8601_BASE.parse(xmlDateTime, position); if (date == null) { throw new IllegalArgumentException("Invalid XML dateTime value: " + xmlDateTime + " (at position " + position.getErrorIndex() + ")"); } // Parse the date time extras Matcher matcher = ISO_8601_EXTRAS.matcher(xmlDateTime.substring(position.getIndex())); if (!matcher.matches()) { // This will match even an empty string as all groups are optional. Thus a // non-match means invalid content. throw new IllegalArgumentException("Invalid XML dateTime value: " + xmlDateTime); } 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: " + xmlDateTime); } long totalOffsetMillis = (offsetMins + offsetHours * 60L) * 60000L; // Convert to UTC if (plusSign) { time -= totalOffsetMillis; } else { time += totalOffsetMillis; } } return time; } /** * Gets the time as an array of three integers. Index 0 contains the number of * seconds, index 1 contains the number of minutes, and index 2 contains the * number of hours. * * @param time the time in milliseconds * @return an array of 3 elements. */ 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 minutes = (int) (seconds / 60); parts[1] = minutes % 60; parts[2] = minutes / 60; return parts; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/StringUtils.java
Java
asf20
8,887
/* * 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.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.Calendar; /** * Utilities for EULA. * * @author Jimmy Shih */ public class EulaUtils { private static final String EULA_PREFERENCE_FILE = "eula"; // Accepting Google mobile terms of service private static final String EULA_PREFERENCE_KEY = "eula.google_mobile_tos_accepted"; // Google's mobile page private static final String HOST_NAME = "m.google.com"; private EulaUtils() {} public static boolean getEulaValue(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( EULA_PREFERENCE_FILE, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(EULA_PREFERENCE_KEY, false); } public static void setEulaValue(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( EULA_PREFERENCE_FILE, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putBoolean(EULA_PREFERENCE_KEY, true); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } public static String getEulaMessage(Context context) { return context.getString(R.string.eula_date) + "\n\n" + context.getString(R.string.eula_body, HOST_NAME) + "\n\n" + context.getString(R.string.eula_footer, HOST_NAME) + "\n\n" + "©" + Calendar.getInstance().get(Calendar.YEAR); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/EulaUtils.java
Java
asf20
2,179
/* * 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 com.google.common.annotations.VisibleForTesting; import android.os.Environment; import java.io.File; /** * Utilities for dealing with files. * * @author Rodrigo Damazio */ public class FileUtils { private FileUtils() {} /** * The maximum FAT32 path length. See the FAT32 spec at * http://msdn.microsoft.com/en-us/windows/hardware/gg463080 */ @VisibleForTesting static final int MAX_FAT32_PATH_LENGTH = 260; /** * Returns whether the SD card is available. */ public static boolean isSdCardAvailable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); } /** * 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 static boolean ensureDirectoryExists(File dir) { if (dir.exists() && dir.isDirectory()) { return true; } if (dir.mkdirs()) { return true; } return false; } /** * 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 static 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(); } /** * 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 static synchronized String buildUniqueFileName( File directory, String fileBaseName, String extension) { return buildUniqueFileName(directory, fileBaseName, extension, 0); } /** * Builds a filename with the given base and the given extension, possibly * adding a suffix to ensure the file doesn't exist. * * @param directory the directory the filename will be located in * @param base the base for the filename * @param extension the extension for the filename * @param suffix the first numeric suffix to try to use, or 0 for none * @return the complete filename, without the directory */ private static String buildUniqueFileName( File directory, String base, String extension, int suffix) { String suffixName = ""; if (suffix > 0) { suffixName += "(" + Integer.toString(suffix) + ")"; } suffixName += "." + extension; String baseName = sanitizeFileName(base); baseName = truncateFileName(directory, baseName, suffixName); String fullName = baseName + suffixName; if (!new File(directory, fullName).exists()) { return fullName; } return buildUniqueFileName(directory, base, extension, suffix + 1); } /** * Sanitizes the name as a valid fat32 filename. For simplicity, fat32 * filename characters may be any combination of letters, digits, or * characters with code point values greater than 127. Replaces the invalid * characters with "_" and collapses multiple "_" together. * * @param name name */ @VisibleForTesting static String sanitizeFileName(String name) { StringBuffer buffer = new StringBuffer(name.length()); for (int i = 0; i < name.length(); i++) { int codePoint = name.codePointAt(i); char character = name.charAt(i); if (Character.isLetterOrDigit(character) || codePoint > 127 || isSpecialFat32(character)) { buffer.appendCodePoint(codePoint); } else { buffer.append("_"); } } String result = buffer.toString(); return result.replaceAll("_+", "_"); } /** * Returns true if it is a special FAT32 character. * * @param character the character */ private static boolean isSpecialFat32(char character) { switch (character) { case '$': case '%': case '\'': case '-': case '_': case '@': case '~': case '`': case '!': case '(': case ')': case '{': case '}': case '^': case '#': case '&': case '+': case ',': case ';': case '=': case '[': case ']': case ' ': return true; default: return false; } } /** * Truncates the name if necessary so the filename path length (directory + * name + suffix) meets the Fat32 path limit. * * @param directory directory * @param name name * @param suffix suffix */ @VisibleForTesting static String truncateFileName(File directory, String name, String suffix) { // 1 at the end accounts for the FAT32 filename trailing NUL character int requiredLength = directory.getPath().length() + suffix.length() + 1; if (name.length() + requiredLength > MAX_FAT32_PATH_LENGTH) { int limit = MAX_FAT32_PATH_LENGTH - requiredLength; return name.substring(0, limit); } else { return name; } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/FileUtils.java
Java
asf20
6,188
/* * 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.os.Build; /** * A factory to get the {@link ApiAdapter} for the current device. * * @author Rodrigo Damazio */ public class ApiAdapterFactory { private static ApiAdapter apiAdapter; /** * Gets the {@link ApiAdapter} for the current device. */ public static ApiAdapter getApiAdapter() { if (apiAdapter == null) { if (Build.VERSION.SDK_INT >= 14) { apiAdapter = new Api14Adapter(); return apiAdapter; } else if (Build.VERSION.SDK_INT >= 11) { apiAdapter = new Api11Adapter(); return apiAdapter; } else if (Build.VERSION.SDK_INT >= 10) { apiAdapter = new Api10Adapter(); return apiAdapter; } else if (Build.VERSION.SDK_INT >= 9) { apiAdapter = new Api9Adapter(); return apiAdapter; } else if (Build.VERSION.SDK_INT >= 8) { apiAdapter = new Api8Adapter(); return apiAdapter; } else { apiAdapter = new Api7Adapter(); return apiAdapter; } } return apiAdapter; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/ApiAdapterFactory.java
Java
asf20
1,683
/* * 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, Context.MODE_PRIVATE); 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.stat_elevation), 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() * UnitConversions.M_TO_KM; 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; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/ChartURLGenerator.java
Java
asf20
5,321
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * Utilities for checking units. * * @author Jimmy Shih */ public class CheckUnitsUtils { private static final String CHECK_UNITS_PREFERENCE_FILE = "checkunits"; private static final String CHECK_UNITS_PREFERENCE_KEY = "checkunits.checked"; private CheckUnitsUtils() {} public static boolean getCheckUnitsValue(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( CHECK_UNITS_PREFERENCE_FILE, Context.MODE_PRIVATE); return sharedPreferences.getBoolean(CHECK_UNITS_PREFERENCE_KEY, false); } public static void setCheckUnitsValue(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences( CHECK_UNITS_PREFERENCE_FILE, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit().putBoolean(CHECK_UNITS_PREFERENCE_KEY, true); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/CheckUnitsUtils.java
Java
asf20
1,688
/* * 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 class UnitConversions { private UnitConversions() {} // multiplication factor to convert kilometers to miles public static final double KM_TO_MI = 0.621371192; // multiplication factor to convert miles to kilometers public static final double MI_TO_KM = 1 / KM_TO_MI; // multiplication factor to convert miles to feet public static final double MI_TO_FT = 5280.0; // multiplication factor to convert feet to miles public static final double FT_TO_MI = 1 / MI_TO_FT; // multiplication factor to convert meters to kilometers public static final double M_TO_KM = 1 / 1000.0; // multiplication factor to convert meters per second to kilometers per hour public static final double MS_TO_KMH = 3.6; // multiplication factor to convert meters to miles public static final double M_TO_MI = M_TO_KM * KM_TO_MI; // multiplication factor to convert meters to feet public static final double M_TO_FT = M_TO_MI * MI_TO_FT; // multiplication factor to convert degrees to radians public static final double DEG_TO_RAD = Math.PI / 180.0; }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/UnitConversions.java
Java
asf20
1,791
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; /** * Utilities for creating dialogs. * * @author Jimmy Shih */ public class DialogUtils { private DialogUtils() {} /** * Creates a confirmation dialog. * * @param context the context * @param messageId the confirmation message id * @param onClickListener the listener to invoke when the user clicks OK */ public static Dialog createConfirmationDialog( Context context, int messageId, DialogInterface.OnClickListener onClickListener) { return new AlertDialog.Builder(context) .setCancelable(true) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(context.getString(messageId)) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, onClickListener) .setTitle(R.string.generic_confirm_title) .create(); } /** * Creates a spinner progress dialog. * * @param context the context * @param messageId the progress message id * @param onCancelListener the cancel listener */ public static ProgressDialog createSpinnerProgressDialog( Context context, int messageId, DialogInterface.OnCancelListener onCancelListener) { return createProgressDialog(true, context, messageId, onCancelListener); } /** * Creates a horizontal progress dialog. * * @param context the context * @param messageId the progress message id * @param onCancelListener the cancel listener * @param formatArgs the format arguments for the messageId */ public static ProgressDialog createHorizontalProgressDialog(Context context, int messageId, DialogInterface.OnCancelListener onCancelListener, Object... formatArgs) { return createProgressDialog(false, context, messageId, onCancelListener, formatArgs); } /** * Creates a progress dialog. * * @param spinner true to use the spinner style * @param context the context * @param messageId the progress message id * @param onCancelListener the cancel listener * @param formatArgs the format arguments for the message id */ private static ProgressDialog createProgressDialog(boolean spinner, Context context, int messageId, DialogInterface.OnCancelListener onCancelListener, Object... formatArgs) { ProgressDialog progressDialog = new ProgressDialog(context); progressDialog.setCancelable(true); progressDialog.setIcon(android.R.drawable.ic_dialog_info); progressDialog.setIndeterminate(true); progressDialog.setMessage(context.getString(messageId, formatArgs)); progressDialog.setOnCancelListener(onCancelListener); progressDialog.setProgressStyle(spinner ? ProgressDialog.STYLE_SPINNER : ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle(R.string.generic_progress_title); return progressDialog; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/DialogUtils.java
Java
asf20
3,663
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import com.google.android.maps.mytracks.R; import android.content.Context; /** * Utitlites for sending pageviews to Google Analytics. * * @author Jimmy Shih */ public class AnalyticsUtils { private AnalyticsUtils() {} public static void sendPageViews(Context context, String ... pages) { GoogleAnalyticsTracker tracker = GoogleAnalyticsTracker.getInstance(); tracker.start(context.getString(R.string.my_tracks_analytics_id), context); tracker.setProductVersion("android-mytracks", SystemUtils.getMyTracksVersion(context)); for (String page : pages) { tracker.trackPageView(page); } tracker.dispatch(); tracker.stop(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/AnalyticsUtils.java
Java
asf20
1,375
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.services.sensors.BluetoothConnectionManager; import android.annotation.TargetApi; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; import java.io.IOException; /** * API level 10 specific implementation of the {@link ApiAdapter}. * * @author Jimmy Shih */ @TargetApi(10) public class Api10Adapter extends Api9Adapter { @Override public BluetoothSocket getBluetoothSocket(BluetoothDevice bluetoothDevice) throws IOException { try { return bluetoothDevice.createInsecureRfcommSocketToServiceRecord( BluetoothConnectionManager.SPP_UUID); } catch (IOException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } return bluetoothDevice.createRfcommSocketToServiceRecord(BluetoothConnectionManager.SPP_UUID); }; }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api10Adapter.java
Java
asf20
1,569
/* * 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.TrackEditActivity; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingService; import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.RemoteException; import android.util.Log; import java.util.List; /** * Utilities for {@link TrackRecordingServiceConnection}. * * @author Rodrigo Damazio */ public class TrackRecordingServiceConnectionUtils { private static final String TAG = TrackRecordingServiceConnectionUtils.class.getSimpleName(); private TrackRecordingServiceConnectionUtils() {} /** * Returns true if the recording service is running. * * @param context the current context */ public static boolean isRecordingServiceRunning(Context context) { ActivityManager activityManager = (ActivityManager) context.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 (TrackRecordingService.class.getName().equals(serviceName)) { return true; } } return false; } /** * Returns true if recording. Checks with the track recording service if * available. If not, checks with the shared preferences. * * @param context the current context * @param trackRecordingServiceConnection the track recording service * connection */ public static boolean isRecording( Context context, TrackRecordingServiceConnection trackRecordingServiceConnection) { ITrackRecordingService trackRecordingService = trackRecordingServiceConnection .getServiceIfBound(); if (trackRecordingService != null) { try { return trackRecordingService.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); } } return PreferencesUtils.getRecordingTrackId(context) != -1L; } /** * Stops the track recording service connection. * * @param context the context * @param trackRecordingServiceConnection the track recording service * connection */ public static void stop( Context context, TrackRecordingServiceConnection trackRecordingServiceConnection) { ITrackRecordingService trackRecordingService = trackRecordingServiceConnection .getServiceIfBound(); if (trackRecordingService != null) { try { /* * Need to remember the recordingTrackId before calling endCurrentTrack. * endCurrentTrack sets the value to -1L. */ long recordingTrackId = PreferencesUtils.getRecordingTrackId(context); trackRecordingService.endCurrentTrack(); if (recordingTrackId != -1L) { Intent intent = new Intent(context, TrackEditActivity.class) .putExtra(TrackEditActivity.EXTRA_SHOW_CANCEL, false) .putExtra(TrackEditActivity.EXTRA_TRACK_ID, recordingTrackId); context.startActivity(intent); } } catch (Exception e) { Log.e(TAG, "Unable to stop recording.", e); } } else { PreferencesUtils.setRecordingTrackId(context, -1L); } trackRecordingServiceConnection.stop(); } /** * Resumes the track recording service connection. * * @param context the context * @param trackRecordingServiceConnection the track recording service * connection */ public static void resume( Context context, TrackRecordingServiceConnection trackRecordingServiceConnection) { trackRecordingServiceConnection.bindIfRunning(); if (!isRecordingServiceRunning(context)) { PreferencesUtils.setRecordingTrackId(context, -1L); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/TrackRecordingServiceConnectionUtils.java
Java
asf20
4,899
/* * 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.ContextualActionModeCallback; 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.Activity; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.SharedPreferences; import android.view.MenuItem; import android.widget.ListView; import java.io.IOException; /** * A set of methods that may be implemented differently depending on the Android * API level. * * @author Bartlomiej Niechwiej */ public interface ApiAdapter { /** * Gets a status announcer task. * <p> * Due to changes in API level 8. * * @param context the context */ public PeriodicTask getStatusAnnouncerTask(Context context); /** * Gets a {@link BackupPreferencesListener}. * <p> * Due to changes in API level 8. * * @param context the context */ public BackupPreferencesListener getBackupPreferencesListener(Context context); /** * Applies all the changes done to a given preferences editor. Changes may or * may not be applied immediately. * <p> * Due to changes in API level 9. * * @param editor the editor */ public void applyPreferenceChanges(SharedPreferences.Editor editor); /** * Enables strict mode where supported, only if this is a development build. * <p> * Due to changes in API level 9. */ public void enableStrictMode(); /** * Copies elements from an 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 the input length. * <p> * 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. */ public byte[] copyByteArray(byte[] input, int start, int end); /** * Gets a {@link HttpTransport}. * <p> * Due to changes in API level 9. */ public HttpTransport getHttpTransport(); /** * Gets a {@link BluetoothSocket}. * <p> * Due to changes in API level 10. * * @param bluetoothDevice */ public BluetoothSocket getBluetoothSocket(BluetoothDevice bluetoothDevice) throws IOException; /** * Hides the title. If the platform supports the action bar, do nothing. * Ideally, with the action bar, we would like to collapse the navigation tabs * into the action bar. However, collapsing is not supported by the * compatibility library. * <p> * Due to changes in API level 11. * * @param activity the activity */ public void hideTitle(Activity activity); /** * Configures the action bar with the Home button as an Up button. If the * platform doesn't support the action bar, do nothing. * <p> * Due to changes in API level 11. * * @param activity the activity */ public void configureActionBarHomeAsUp(Activity activity); /** * Configures the list view context menu. * <p> * Due to changes in API level 11. * * @param activity the activity * @param listView the list view * @param menuId the menu resource id * @param actionModeTitleId the id of the list view item TextView to be used * as the action mode title * @param contextualActionModeCallback the callback when an item is selected * in the contextual action mode */ public void configureListViewContextualMenu(Activity activity, ListView listView, int menuId, int actionModeTitleId, ContextualActionModeCallback contextualActionModeCallback); /** * Configures the search widget. * * Due to changes in API level 11. * * @param activity the activity * @param menuItem the search menu item */ public void configureSearchWidget(Activity activity, MenuItem menuItem); /** * Handles the search menu selection. Returns true if handled. * * Due to changes in API level 11. * * @param activity the activity */ public boolean handleSearchMenuSelection(Activity activity); /** * Handles the search key press. Returns true if handled. * * Due to changes in API level 14. * * @param menu the search menu */ public boolean handleSearchKey(MenuItem menu); }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/ApiAdapter.java
Java
asf20
5,097
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.io.backup.Api8BackupPreferencesListener; import com.google.android.apps.mytracks.services.tasks.Api8StatusAnnouncerTask; import com.google.android.apps.mytracks.services.tasks.PeriodicTask; import android.content.Context; /** * API level 8 specific implementation of the {@link ApiAdapter}. * * @author Jimmy Shih */ public class Api8Adapter extends Api7Adapter { @Override public PeriodicTask getStatusAnnouncerTask(Context context) { return new Api8StatusAnnouncerTask(context); } @Override public BackupPreferencesListener getBackupPreferencesListener(Context context) { return new Api8BackupPreferencesListener(context); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api8Adapter.java
Java
asf20
1,417
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.view.MenuItem; /** * API level 14 specific implementation of the {@link ApiAdapter}. * * @author Jimmy Shih */ @TargetApi(14) public class Api14Adapter extends Api11Adapter { @Override public void configureActionBarHomeAsUp(Activity activity) { ActionBar actionBar = activity.getActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public boolean handleSearchKey(MenuItem menuItem) { menuItem.expandActionView(); return true; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api14Adapter.java
Java
asf20
1,275
/* * 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.DEG_TO_RAD; final double s0lng = c0.getLongitude() * UnitConversions.DEG_TO_RAD; final double s1lat = c1.getLatitude() * UnitConversions.DEG_TO_RAD; final double s1lng = c1.getLongitude() * UnitConversions.DEG_TO_RAD; final double s2lat = c2.getLatitude() * UnitConversions.DEG_TO_RAD; final double s2lng = c2.getLongitude() * UnitConversions.DEG_TO_RAD; 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() { } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/LocationUtils.java
Java
asf20
8,165
/* * 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.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import java.util.List; import java.util.Set; /** * Utilities for dealing with bluetooth devices. * * @author Rodrigo Damazio */ public class BluetoothDeviceUtils { private BluetoothDeviceUtils() {} /** * Populates the device names and the device addresses with all the suitable * bluetooth devices. * * @param bluetoothAdapter the bluetooth adapter * @param deviceNames list of device names * @param deviceAddresses list of device addresses */ public static void populateDeviceLists( BluetoothAdapter bluetoothAdapter, List<String> deviceNames, List<String> deviceAddresses) { // Ensure the bluetooth adapter is not in discovery mode. bluetoothAdapter.cancelDiscovery(); 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()); } } } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/BluetoothDeviceUtils.java
Java
asf20
2,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 com.google.android.apps.mytracks.ContextualActionModeCallback; import com.google.android.apps.mytracks.io.backup.BackupPreferencesListener; import com.google.android.apps.mytracks.services.sensors.BluetoothConnectionManager; 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.Activity; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import android.view.MenuItem; import android.view.Window; import android.widget.ListView; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * API level 7 specific implementation of the {@link ApiAdapter}. * * @author Bartlomiej Niechwiej */ public class Api7Adapter implements ApiAdapter { @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 } }; } @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 HttpTransport getHttpTransport() { return new ApacheHttpTransport(); } @Override public BluetoothSocket getBluetoothSocket(BluetoothDevice bluetoothDevice) throws IOException { try { Class<? extends BluetoothDevice> c = bluetoothDevice.getClass(); Method insecure = c.getMethod("createInsecureRfcommSocket", Integer.class); insecure.setAccessible(true); return (BluetoothSocket) insecure.invoke(bluetoothDevice, 1); } catch (SecurityException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (NoSuchMethodException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (IllegalArgumentException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (IllegalAccessException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } catch (InvocationTargetException e) { Log.d(Constants.TAG, "Unable to create insecure connection", e); } return bluetoothDevice.createRfcommSocketToServiceRecord(BluetoothConnectionManager.SPP_UUID); } @Override public void hideTitle(Activity activity) { activity.requestWindowFeature(Window.FEATURE_NO_TITLE); } @Override public void configureActionBarHomeAsUp(Activity activity) { // Do nothing } @Override public void configureListViewContextualMenu(Activity activity, ListView listView, int menuId, int actionModeTitleId, ContextualActionModeCallback contextualActionModeCallback) { activity.registerForContextMenu(listView); } @Override public void configureSearchWidget(Activity activity, MenuItem menuItem) { // Do nothing } @Override public boolean handleSearchMenuSelection(Activity activity) { activity.onSearchRequested(); return true; } @Override public boolean handleSearchKey(MenuItem menuItem) { // Return false and allow the framework to handle the search key. return false; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api7Adapter.java
Java
asf20
4,634
/* * 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; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/GeoRect.java
Java
asf20
1,684
/* * 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() { } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/ResourceUtils.java
Java
asf20
2,378
/* * 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() {} }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/UriUtils.java
Java
asf20
1,730
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import android.annotation.TargetApi; import android.content.SharedPreferences.Editor; import android.os.StrictMode; import android.util.Log; import java.util.Arrays; /** * API level 9 specific implementation of the {@link ApiAdapter}. * * @author Rodrigo Damazio */ @TargetApi(9) public class Api9Adapter extends Api8Adapter { @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 HttpTransport getHttpTransport() { return new NetHttpTransport(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api9Adapter.java
Java
asf20
1,876
/* * 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; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/ChartsExtendedEncoder.java
Java
asf20
1,963
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.ContextualActionModeCallback; import android.annotation.TargetApi; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import android.widget.SearchView; import android.widget.TextView; /** * API level 11 specific implementation of the {@link ApiAdapter}. * * @author Jimmy Shih */ @TargetApi(11) public class Api11Adapter extends Api10Adapter { @Override public void hideTitle(Activity activity) { // Do nothing } @Override public void configureActionBarHomeAsUp(Activity activity) { activity.getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public void configureListViewContextualMenu(final Activity activity, ListView listView, final int menuId, final int actionModeTitleId, final ContextualActionModeCallback contextualActionModeCallback) { listView.setOnItemLongClickListener(new OnItemLongClickListener() { ActionMode actionMode; @Override public boolean onItemLongClick( AdapterView<?> parent, View view, int position, final long id) { if (actionMode != null) { return false; } actionMode = activity.startActionMode(new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(menuId, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Return false to indicate no change. return false; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return contextualActionModeCallback.onClick(item.getItemId(), id); } }); TextView textView = (TextView) view.findViewById(actionModeTitleId); if (textView != null) { actionMode.setTitle(textView.getText()); } view.setSelected(true); return true; } }); }; @Override public void configureSearchWidget(Activity activity, MenuItem menuItem) { SearchManager searchManager = (SearchManager) activity.getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menuItem.getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(activity.getComponentName())); } @Override public boolean handleSearchMenuSelection(Activity activity) { // Returns false to allow the platform to expand the search widget. return false; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java
Java
asf20
3,616
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.apps.mytracks.Constants; import com.google.android.maps.mytracks.R; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; /** * Utilities to access preferences stored in {@link SharedPreferences}. * * @author Jimmy Shih */ public class PreferencesUtils { private PreferencesUtils() {} /** * Gets the recording track id key. * * @param context the context */ public static String getRecordingTrackIdKey(Context context) { return getKey(context, R.string.recording_track_id_key); } /** * Gets the recording track id. * * @param context the context */ public static long getRecordingTrackId(Context context) { return getLong(context, R.string.recording_track_id_key); } /** * Sets the recording track id. * * @param context the context * @param trackId the track id */ public static void setRecordingTrackId(Context context, long trackId) { setLong(context, R.string.recording_track_id_key, trackId); } /** * Gets the selected track id key. * * @param context the context */ public static String getSelectedTrackIdKey(Context context) { return getKey(context, R.string.selected_track_id_key); } /** * Gets the selected track id. * * @param context the context */ public static long getSelectedTrackId(Context context) { return getLong(context, R.string.selected_track_id_key); } /** * Sets the selected track id. * * @param context the context * @param trackId the track id */ public static void setSelectedTrackId(Context context, long trackId) { setLong(context, R.string.selected_track_id_key, trackId); } /** * Gets a preference key * * @param context the context * @param keyId the key id */ private static String getKey(Context context, int keyId) { return context.getString(keyId); } /** * Gets a long preference value. * * @param context the context * @param keyId the key id */ private static long getLong(Context context, int keyId) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); return sharedPreferences.getLong(getKey(context, keyId), -1L); } /** * Sets a long preference value. * * @param context the context * @param keyId the key id * @param value the value */ private static void setLong(Context context, int keyId, long value) { SharedPreferences sharedPreferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); Editor editor = sharedPreferences.edit(); editor.putLong(getKey(context, keyId), value); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/PreferencesUtils.java
Java
asf20
3,503
/* * 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.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; /** * Utility class for acessing basic Android functionality. * * @author Rodrigo Damazio */ public class SystemUtils { /** * 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() {} }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/SystemUtils.java
Java
asf20
2,886
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.util; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.widget.TextView; /** * Utilities for updating the statistics UI labels and values. * * @author Jimmy Shih */ public class StatsUtils { private StatsUtils() {} /** * Sets a speed label. * * @param activity the activity * @param id the speed label resource id * @param speedId the speed string id * @param paceId the pace string id * @param reportSpeed true to report speed */ public static void setSpeedLabel( Activity activity, int id, int speedId, int paceId, boolean reportSpeed) { TextView textView = (TextView) activity.findViewById(id); textView.setText(reportSpeed ? speedId : paceId); } /** * Sets a speed value. * * @param activity the activity * @param id the speed value resource id * @param speed the speed in meters per second * @param reportSpeed true to report speed * @param metricUnits true to display in metric units */ public static void setSpeedValue( Activity activity, int id, double speed, boolean reportSpeed, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); speed *= UnitConversions.MS_TO_KMH; String value; if (metricUnits) { if (reportSpeed) { value = activity.getString(R.string.value_float_kilometer_hour, speed); } else { // convert from hours to minutes double pace = speed == 0 ? 0.0 : 60.0 / speed; value = activity.getString(R.string.value_float_minute_kilometer, pace); } } else { speed *= UnitConversions.KM_TO_MI; if (reportSpeed) { value = activity.getString(R.string.value_float_mile_hour, speed); } else { // convert from hours to minutes double pace = speed == 0 ? 0.0 : 60.0 / speed; value = activity.getString(R.string.value_float_minute_mile, pace); } } textView.setText(value); } /** * Sets a distance value. * * @param activity the activity * @param id the distance value resource id * @param distance the distance in meters * @param metricUnits true to display in metric units */ public static void setDistanceValue( Activity activity, int id, double distance, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); distance *= UnitConversions.M_TO_KM; String value; if (metricUnits) { value = activity.getString(R.string.value_float_kilometer, distance); } else { distance *= UnitConversions.KM_TO_MI; value = activity.getString(R.string.value_float_mile, distance); } textView.setText(value); } /** * Sets a time value. * * @param activity the activity * @param id the time value resource id * @param time the time */ public static void setTimeValue(Activity activity, int id, long time) { TextView textView = (TextView) activity.findViewById(id); textView.setText(StringUtils.formatElapsedTime(time)); } /** * Sets an altitude value. * * @param activity the activity * @param id the altitude value resource id * @param altitude the altitude in meters * @param metricUnits true to display in metric units */ public static void setAltitudeValue( Activity activity, int id, double altitude, boolean metricUnits) { TextView textView = (TextView) activity.findViewById(id); String value; if (Double.isNaN(altitude) || Double.isInfinite(altitude)) { value = activity.getString(R.string.value_unknown); } else { if (metricUnits) { value = activity.getString(R.string.value_float_meter, altitude); } else { altitude *= UnitConversions.M_TO_FT; value = activity.getString(R.string.value_float_feet, altitude); } } textView.setText(value); } /** * Sets a grade value. * * @param activity the activity * @param id the grade value resource id * @param grade the grade in fraction between 0 and 1 */ public static void setGradeValue(Activity activity, int id, double grade) { TextView textView = (TextView) activity.findViewById(id); String value; if (Double.isNaN(grade) || Double.isInfinite(grade)) { value = activity.getString(R.string.value_unknown); } else { value = activity.getString(R.string.value_integer_percent, Math.round(grade * 100)); } textView.setText(value); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/util/StatsUtils.java
Java
asf20
5,106
/* * 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.util.DialogUtils; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.UriUtils; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; /** * An activity to import GPX files from the SD card. Optionally to import one * GPX file and display it in My Tracks. * * @author Rodrigo Damazio */ public class ImportActivity extends Activity { public static final String EXTRA_IMPORT_ALL = "import_all"; private static final String TAG = ImportActivity.class.getSimpleName(); private static final int DIALOG_PROGRESS_ID = 0; private static final int DIALOG_RESULT_ID = 1; private ImportAsyncTask importAsyncTask; private ProgressDialog progressDialog; private boolean importAll; // path on the SD card to import private String path; // number of succesfully imported files private int successCount; // number of files to import private int totalCount; // last successfully imported track id private long trackId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); importAll = intent.getBooleanExtra(EXTRA_IMPORT_ALL, false); if (importAll) { path = FileUtils.buildExternalDirectoryPath("gpx"); } else { String action = intent.getAction(); if (!(Intent.ACTION_ATTACH_DATA.equals(action) || Intent.ACTION_VIEW.equals(action))) { Log.d(TAG, "Invalid action: " + intent); finish(); return; } Uri data = intent.getData(); if (!UriUtils.isFileUri(data)) { Log.d(TAG, "Invalid data: " + intent); finish(); return; } path = data.getPath(); } Object retained = getLastNonConfigurationInstance(); if (retained instanceof ImportAsyncTask) { importAsyncTask = (ImportAsyncTask) retained; importAsyncTask.setActivity(this); } else { importAsyncTask = new ImportAsyncTask(this, importAll, path); importAsyncTask.execute(); } } @Override public Object onRetainNonConfigurationInstance() { importAsyncTask.setActivity(null); return importAsyncTask; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS_ID: progressDialog = DialogUtils.createHorizontalProgressDialog( this, R.string.import_progress_message, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { importAsyncTask.cancel(true); finish(); } }); return progressDialog; case DIALOG_RESULT_ID: String message; if (successCount == 0) { message = getString(R.string.import_no_file, path); } else { String totalFiles = getResources() .getQuantityString(R.plurals.importGpxFiles, totalCount, totalCount); message = getString(R.string.import_success, successCount, totalFiles, path); } return new AlertDialog.Builder(this) .setCancelable(true) .setMessage(message) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (!importAll && trackId != -1L) { Intent intent = new Intent(ImportActivity.this, TrackDetailActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(TrackDetailActivity.EXTRA_TRACK_ID, trackId); startActivity(intent); } finish(); } }) .create(); default: return null; } } /** * Invokes when the associated AsyncTask completes. * * @param success true if the AsyncTask is successful * @param imported the number of files successfully imported * @param total the total number of files to import * @param id the last successfully imported track id */ public void onAsyncTaskCompleted(boolean success, int imported, int total, long id) { successCount = imported; totalCount = total; trackId = id; removeDialog(DIALOG_PROGRESS_ID); if (success) { showDialog(DIALOG_RESULT_ID); } else { Toast.makeText(this, getString(R.string.import_error, path), Toast.LENGTH_LONG).show(); finish(); } } /** * Shows the progress dialog. */ public void showProgressDialog() { showDialog(DIALOG_PROGRESS_ID); } /** * Sets the progress dialog value. * * @param number the number of files imported * @param max the maximum number of files */ public void setProgressDialogValue(int number, int max) { if (progressDialog != null) { progressDialog.setIndeterminate(false); progressDialog.setMax(max); progressDialog.setProgress(Math.min(number, max)); } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/ImportActivity.java
Java
asf20
6,243
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.util.EulaUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to show EULA. * * @author Jimmy Shih */ public class EulaDialogFragment extends DialogFragment { public static final String EULA_DIALOG_TAG = "eulaDialog"; private static final String KEY_HAS_ACCEPTED = "hasAccepted"; /** * Creates a new instance of {@link EulaDialogFragment}. * * @param hasAccepted true if the user has accepted the eula. */ public static EulaDialogFragment newInstance(boolean hasAccepted) { Bundle bundle = new Bundle(); bundle.putBoolean(KEY_HAS_ACCEPTED, hasAccepted); EulaDialogFragment eulaDialogFragment = new EulaDialogFragment(); eulaDialogFragment.setArguments(bundle); return eulaDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { boolean hasAccepted = getArguments().getBoolean(KEY_HAS_ACCEPTED); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) .setCancelable(true) .setMessage(EulaUtils.getEulaMessage(getActivity())) .setTitle(R.string.eula_title); if (hasAccepted) { builder.setPositiveButton(R.string.generic_ok, null); } else { builder.setNegativeButton(R.string.eula_decline, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getActivity().finish(); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { getActivity().finish(); } }) .setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EulaUtils.setEulaValue(getActivity()); new WelcomeDialogFragment().show( getActivity().getSupportFragmentManager(), WelcomeDialogFragment.WELCOME_DIALOG_TAG); } }); } return builder.create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/EulaDialogFragment.java
Java
asf20
2,911
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.MarkerListActivity; import com.google.android.apps.mytracks.content.DescriptionGeneratorImpl; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete one marker. * * @author Jimmy Shih */ public class DeleteOneMarkerDialogFragment extends DialogFragment { public static final String DELETE_ONE_MARKER_DIALOG_TAG = "deleteOneMarkerDialog"; private static final String KEY_MARKER_ID = "markerId"; public static DeleteOneMarkerDialogFragment newInstance(long markerId) { Bundle bundle = new Bundle(); bundle.putLong(KEY_MARKER_ID, markerId); DeleteOneMarkerDialogFragment deleteOneMarkerDialogFragment = new DeleteOneMarkerDialogFragment(); deleteOneMarkerDialogFragment.setArguments(bundle); return deleteOneMarkerDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.marker_delete_one_marker_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()).deleteWaypoint( getArguments().getLong(KEY_MARKER_ID), new DescriptionGeneratorImpl(getActivity())); startActivity(new Intent(getActivity(), MarkerListActivity.class).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); } }); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/DeleteOneMarkerDialogFragment.java
Java
asf20
2,470
/* * 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.fragments; import com.google.android.apps.mytracks.MyTracksApplication; import com.google.android.apps.mytracks.StatsUtilities; 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.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ScrollView; import java.util.EnumSet; /** * A fragment to display track statistics to the user. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class StatsFragment extends Fragment implements TrackDataListener { private static final String TAG = StatsFragment.class.getSimpleName(); private StatsUtilities statsUtilities; private TrackDataHub trackDataHub; private UiUpdateThread uiUpdateThread; // The start time of the current track. private long startTime = -1L; // A runnable to update the total time field. private final Runnable updateTotalTime = new Runnable() { public void run() { if (isRecording()) { statsUtilities.setTime(R.id.total_time_register, System.currentTimeMillis() - startTime); } } }; /** * A thread that updates the total time field every second. */ private class UiUpdateThread extends Thread { @Override public void run() { Log.d(TAG, "UI update thread started"); while (PreferencesUtils.getRecordingTrackId(getActivity()) != -1L) { getActivity().runOnUiThread(updateTotalTime); try { Thread.sleep(1000L); } catch (InterruptedException e) { Log.d(TAG, "UI update thread caught exception", e); break; } } Log.d(TAG, "UI update thread finished"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); statsUtilities = new StatsUtilities(getActivity()); } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.stats, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ScrollView scrollView = (ScrollView) getActivity().findViewById(R.id.scrolly); scrollView.setScrollBarStyle(ScrollView.SCROLLBARS_OUTSIDE_INSET); updateLabels(); setLocationUnknown(); } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); if (uiUpdateThread != null) { uiUpdateThread.interrupt(); uiUpdateThread = null; } } @Override public void onProviderStateChange(ProviderState state) { if (state == ProviderState.DISABLED || state == ProviderState.NO_FIX) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { setLocationUnknown(); } }); } } @Override public void onCurrentLocationChanged(final Location location) { if (isRecording()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (location != null) { setLocation(location); } else { setLocationUnknown(); } } }); } } @Override public void onCurrentHeadingChanged(double heading) { // We don't care. } @Override public void onSelectedTrackChanged(Track track, boolean isRecording) { if (uiUpdateThread == null && isRecording) { uiUpdateThread = new UiUpdateThread(); uiUpdateThread.start(); } else if (uiUpdateThread != null && !isRecording) { uiUpdateThread.interrupt(); uiUpdateThread = null; } } @Override public void onTrackUpdated(final Track track) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (track == null || track.getStatistics() == null) { statsUtilities.setAllToUnknown(); return; } startTime = track.getStatistics().getStartTime(); if (!isRecording()) { statsUtilities.setTime(R.id.total_time_register, track.getStatistics().getTotalTime()); setLocationUnknown(); } statsUtilities.setAllStats(track.getStatistics()); } }); } @Override public void clearTrackPoints() { // We don't care. } @Override public void onNewTrackPoint(Location loc) { // We don't care. } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onSegmentSplit() { // We don't care. } @Override public void onNewTrackPointsDone() { // We don't care. } @Override public void clearWaypoints() { // We don't care. } @Override public void onNewWaypoint(Waypoint wpt) { // We don't care. } @Override public void onNewWaypointsDone() { // We don't care. } @Override public boolean onUnitsChanged(boolean metric) { if (statsUtilities.isMetricUnits() == metric) { return false; } statsUtilities.setMetricUnits(metric); getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateLabels(); } }); return true; } @Override public boolean onReportSpeedChanged(boolean speed) { if (statsUtilities.isReportSpeed() == speed) { return false; } statsUtilities.setReportSpeed(speed); getActivity().runOnUiThread(new Runnable() { @Override public void run() { updateLabels(); } }); return true; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can * be accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can * be accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Returns true if recording. Needs to be synchronized because trackDataHub * can be accessed by multiple threads. */ private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } /** * Updates the labels. */ private void updateLabels() { statsUtilities.updateUnits(); statsUtilities.setSpeedLabel(R.id.speed_label, R.string.stat_speed, R.string.stat_pace); statsUtilities.setSpeedLabels(); } /** * Sets the current location. * * @param location the current location */ private void setLocation(Location location) { statsUtilities.setAltitude(R.id.elevation_register, location.getAltitude()); statsUtilities.setLatLong(R.id.latitude_register, location.getLatitude()); statsUtilities.setLatLong(R.id.longitude_register, location.getLongitude()); statsUtilities.setSpeed(R.id.speed_register, location.getSpeed() * UnitConversions.MS_TO_KMH); } /** * Sets the current location to unknown. */ private void setLocationUnknown() { statsUtilities.setUnknown(R.id.elevation_register); statsUtilities.setUnknown(R.id.latitude_register); statsUtilities.setUnknown(R.id.longitude_register); statsUtilities.setUnknown(R.id.speed_register); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java
Java
asf20
8,906
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete all tracks. * * @author Jimmy Shih */ public class DeleteAllTrackDialogFragment extends DialogFragment { public static final String DELETE_ALL_TRACK_DIALOG_TAG = "deleteAllTrackDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.track_list_delete_all_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()).deleteAllTracks(); } }); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/DeleteAllTrackDialogFragment.java
Java
asf20
1,615
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import static com.google.android.apps.mytracks.Constants.CHART_TAB_TAG; import com.google.android.apps.mytracks.ChartView; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; import android.widget.CheckBox; import android.widget.RadioGroup; /** * A DialogFragment to show chart settings. * * @author Jimmy Shih */ public class ChartSettingsDialogFragment extends DialogFragment { public static final String CHART_SETTINGS_DIALOG_TAG = "chartSettingsDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final ChartFragment chartFragment = (ChartFragment) getActivity() .getSupportFragmentManager().findFragmentByTag(CHART_TAB_TAG); View view = getActivity().getLayoutInflater().inflate(R.layout.chart_settings, null); final RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.chart_settings_x); radioGroup.check(chartFragment.getMode() == ChartView.Mode.BY_DISTANCE ? R.id.chart_settings_by_distance : R.id.chart_settings_by_time); final CheckBox[] checkBoxes = new CheckBox[ChartView.NUM_SERIES]; checkBoxes[ChartView.ELEVATION_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_elevation); checkBoxes[ChartView.SPEED_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_speed); checkBoxes[ChartView.POWER_SERIES] = (CheckBox) view.findViewById(R.id.chart_settings_power); checkBoxes[ChartView.CADENCE_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_cadence); checkBoxes[ChartView.HEART_RATE_SERIES] = (CheckBox) view.findViewById( R.id.chart_settings_heart_rate); // set checkboxes values for (int i = 0; i < ChartView.NUM_SERIES; i++) { checkBoxes[i].setChecked(chartFragment.isChartValueSeriesEnabled(i)); } checkBoxes[ChartView.SPEED_SERIES].setText(chartFragment.isReportSpeed() ? R.string.stat_speed : R.string.stat_pace); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setNegativeButton(R.string.generic_cancel, null) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { chartFragment.setMode( radioGroup.getCheckedRadioButtonId() == R.id.chart_settings_by_distance ? ChartView.Mode.BY_DISTANCE : ChartView.Mode.BY_TIME); for (int i = 0; i < ChartView.NUM_SERIES; i++) { chartFragment.setChartValueSeriesEnabled(i, checkBoxes[i].isChecked()); } chartFragment.update(); } }) .setTitle(R.string.menu_chart_settings) .setView(view) .create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/ChartSettingsDialogFragment.java
Java
asf20
3,572
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.CheckUnitsUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to check preferred units. * * @author Jimmy Shih */ public class CheckUnitsDialogFragment extends DialogFragment { public static final String CHECK_UNITS_DIALOG_TAG = "checkUnitsDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CheckUnitsUtils.setCheckUnitsValue(getActivity()); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CheckUnitsUtils.setCheckUnitsValue(getActivity()); int position = ((AlertDialog) dialog).getListView().getSelectedItemPosition(); SharedPreferences sharedPreferences = getActivity() .getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE); ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(sharedPreferences.edit() .putBoolean(getString(R.string.metric_units_key), position == 0)); } }) .setSingleChoiceItems(new CharSequence[] { getString(R.string.preferred_units_metric), getString(R.string.preferred_units_imperial) }, 0, null) .setTitle(R.string.preferred_units_title) .create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/CheckUnitsDialogFragment.java
Java
asf20
2,636
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.io.file.SaveActivity; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to install Google Earth. * * @author Jimmy Shih */ public class InstallEarthDialogFragment extends DialogFragment { public static final String INSTALL_EARTH_DIALOG_TAG = "installEarthDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setMessage(R.string.track_detail_install_earth_message) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent().setData(Uri.parse(SaveActivity.GOOGLE_EARTH_MARKET_URL))); } }) .create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/InstallEarthDialogFragment.java
Java
asf20
1,795
/* * 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.fragments; import com.google.android.apps.mytracks.ChartView; import com.google.android.apps.mytracks.ChartView.Mode; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.MyTracksApplication; 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.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.common.annotations.VisibleForTesting; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.ZoomControls; import java.util.ArrayList; import java.util.EnumSet; /** * A fragment to display track chart to the user. * * @author Sandor Dornbush * @author Rodrigo Damazio */ public class ChartFragment extends Fragment implements TrackDataListener { // Android reports 128 when the speed is invalid private static final int INVALID_SPEED = 128; 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 trackDataHub; // Stats gathered from the received data private double totalDistance = 0.0; private long startTime = -1L; private Location lastLocation = null; private double trackMaxSpeed = 0.0; // Modes of operation private boolean metricUnits = true; private boolean reportSpeed = true; // UI elements private ChartView chartView; private LinearLayout busyPane; private ZoomControls zoomControls; /** * A runnable that 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() { if (trackDataHub == null) { return; } busyPane.setVisibility(View.GONE); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); chartView.setShowPointer(isRecording()); chartView.invalidate(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Create a chartView here to store data thus won't need to reload all the * data on every onStart or onResume. */ chartView = new ChartView(getActivity()); }; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.mytracks_charts, container, false); busyPane = (LinearLayout) view.findViewById(R.id.elevation_busypane); zoomControls = (ZoomControls) view.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(); } }); return view; } @Override public void onStart() { super.onStart(); ViewGroup layout = (ViewGroup) getActivity().findViewById(R.id.elevation_chart); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layout.addView(chartView, layoutParams); } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); getActivity().runOnUiThread(updateChart); } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); } @Override public void onStop() { super.onStop(); ViewGroup layout = (ViewGroup) getActivity().findViewById(R.id.elevation_chart); layout.removeView(chartView); } /** * Sets the chart view mode. * * @param mode the chart view mode */ public void setMode(Mode mode) { if (chartView.getMode() != mode) { chartView.setMode(mode); reloadTrackDataHub(); } } /** * Gets the chart view mode. */ public Mode getMode() { return chartView.getMode(); } /** * Enables or disables the chart value series. * * @param index the index of the series * @param enabled true to enable, false to disable */ public void setChartValueSeriesEnabled(int index, boolean enabled) { chartView.setChartValueSeriesEnabled(index, enabled); } /** * Returns true if the chart value series is enabled. * * @param index the index of the series */ public boolean isChartValueSeriesEnabled(int index) { return chartView.isChartValueSeriesEnabled(index); } /** * Returns true to report speed instead of pace. */ public boolean isReportSpeed() { return reportSpeed; } /** * Updates the chart. */ public void update() { chartView.postInvalidate(); } @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) { getActivity().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() { totalDistance = 0.0; startTime = -1L; lastLocation = null; elevationBuffer.reset(); speedBuffer.reset(); pendingPoints.clear(); chartView.reset(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.resetScroll(); } }); } @Override public void onNewTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { double[] data = new double[6]; fillDataPoint(location, data); pendingPoints.add(data); } } @Override public void onSampledOutTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { // Still account for the point in the smoothing buffers. fillDataPoint(location, null); } } @Override public void onSegmentSplit() { // Do nothing. } @Override public void onNewTrackPointsDone() { chartView.addDataPoints(pendingPoints); pendingPoints.clear(); getActivity().runOnUiThread(updateChart); } @Override public void clearWaypoints() { chartView.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { chartView.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { getActivity().runOnUiThread(updateChart); } @Override public boolean onUnitsChanged(boolean metric) { if (metricUnits == metric) { return false; } metricUnits = metric; chartView.setMetricUnits(metricUnits); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.requestLayout(); } }); return true; } @Override public boolean onReportSpeedChanged(boolean speed) { if (reportSpeed == speed) { return false; } reportSpeed = speed; chartView.setReportSpeed(speed, getActivity()); getActivity().runOnUiThread(new Runnable() { @Override public void run() { chartView.requestLayout(); } }); return true; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.TRACK_UPDATES, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES, ListenerDataType.DISPLAY_PREFERENCES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Returns true if recording. Needs to be synchronized because trackDataHub * can be accessed by multiple threads. */ private synchronized boolean isRecording() { return trackDataHub != null && trackDataHub.isRecordingSelected(); } /** * Reloads the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void reloadTrackDataHub() { if (trackDataHub != null) { trackDataHub.reloadDataForListener(this); } } /** * To zoom in. */ private void zoomIn() { chartView.zoomIn(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } /** * To zoom out. */ private void zoomOut() { chartView.zoomOut(); zoomControls.setIsZoomInEnabled(chartView.canZoomIn()); zoomControls.setIsZoomOutEnabled(chartView.canZoomOut()); } /** * Given a location, fill in a data point, an array of double[6]. <br> * data[0] = time/distance <br> * data[1] = elevation <br> * data[2] = speed <br> * data[3] = power <br> * data[4] = cadence <br> * data[5] = heart rate <br> * * @param location the location * @param data the data point to fill in, can be null */ @VisibleForTesting void fillDataPoint(Location location, double data[]) { double timeOrDistance = Double.NaN; double elevation = Double.NaN; double speed = Double.NaN; double power = Double.NaN; double cadence = Double.NaN; double heartRate = Double.NaN; // TODO: Use TripStatisticsBuilder if (chartView.getMode() == Mode.BY_DISTANCE) { if (lastLocation != null) { double distance = lastLocation.distanceTo(location) * UnitConversions.M_TO_KM; if (metricUnits) { totalDistance += distance; } else { totalDistance += distance * UnitConversions.KM_TO_MI; } } timeOrDistance = totalDistance; } else { if (startTime == -1L) { startTime = location.getTime(); } timeOrDistance = location.getTime() - startTime; } elevationBuffer.setNext(metricUnits ? location.getAltitude() : location.getAltitude() * UnitConversions.M_TO_FT); elevation = elevationBuffer.getAverage(); if (lastLocation == null) { if (Math.abs(location.getSpeed() - INVALID_SPEED) > 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() * UnitConversions.MS_TO_KMH; if (!metricUnits) { speed *= UnitConversions.KM_TO_MI; } if (!reportSpeed) { speed = speed == 0 ? 0.0 : 60.0 / speed; } if (location instanceof MyTracksLocation && ((MyTracksLocation) location).getSensorDataSet() != null) { SensorDataSet sensorDataSet = ((MyTracksLocation) location).getSensorDataSet(); if (sensorDataSet.hasPower() && sensorDataSet.getPower().getState() == Sensor.SensorState.SENDING && sensorDataSet.getPower().hasValue()) { power = sensorDataSet.getPower().getValue(); } if (sensorDataSet.hasCadence() && sensorDataSet.getCadence().getState() == Sensor.SensorState.SENDING && sensorDataSet.getCadence().hasValue()) { cadence = sensorDataSet.getCadence().getValue(); } if (sensorDataSet.hasHeartRate() && sensorDataSet.getHeartRate().getState() == Sensor.SensorState.SENDING && sensorDataSet.getHeartRate().hasValue()) { heartRate = sensorDataSet.getHeartRate().getValue(); } } if (data != null) { data[0] = timeOrDistance; data[1] = elevation; data[2] = speed; data[3] = power; data[4] = cadence; data[5] = heartRate; } lastLocation = location; } @VisibleForTesting ChartView getChartView() { return chartView; } @VisibleForTesting void setChartView(ChartView view) { chartView = view; } @VisibleForTesting void setTrackMaxSpeed(double value) { trackMaxSpeed = value; } @VisibleForTesting void setMetricUnits(boolean value) { metricUnits = value; } @VisibleForTesting void setReportSpeed(boolean value) { reportSpeed = value; } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java
Java
asf20
14,827
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; import android.widget.TextView; /** * A DialogFragment to show information about My Tracks. * * @author Jimmy Shih */ public class AboutDialogFragment extends DialogFragment { public static final String ABOUT_DIALOG_TAG = "aboutDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = getActivity().getLayoutInflater().inflate(R.layout.about, null); TextView aboutVersion = (TextView) view.findViewById(R.id.about_version); aboutVersion.setText(SystemUtils.getMyTracksVersion(getActivity())); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setNegativeButton(R.string.about_license, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EulaDialogFragment.newInstance(true).show( getActivity().getSupportFragmentManager(), EulaDialogFragment.EULA_DIALOG_TAG); } }) .setPositiveButton(R.string.generic_ok, null) .setTitle(R.string.help_about) .setView(view) .create(); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/AboutDialogFragment.java
Java
asf20
2,066
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.maps.mytracks.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; /** * A DialogFrament to show the welcome info. * * @author Jimmy Shih */ public class WelcomeDialogFragment extends DialogFragment { public static final String WELCOME_DIALOG_TAG = "welcomeDialog"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { View view = getActivity().getLayoutInflater().inflate(R.layout.welcome, null); return new AlertDialog.Builder(getActivity()) .setCancelable(true) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { checkUnits(); } }) .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { checkUnits(); } }) .setTitle(R.string.welcome_title) .setView(view) .create(); } private void checkUnits() { new CheckUnitsDialogFragment().show( getActivity().getSupportFragmentManager(), CheckUnitsDialogFragment.CHECK_UNITS_DIALOG_TAG); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/WelcomeDialogFragment.java
Java
asf20
2,016
/* * 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.fragments; import com.google.android.apps.mytracks.MapOverlay; import com.google.android.apps.mytracks.MyTracksApplication; import com.google.android.apps.mytracks.TrackDetailActivity; 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.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.stats.TripStatistics; 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.Intent; import android.location.Location; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import java.util.EnumSet; /** * A fragment to display map to the user. * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class MapFragment extends Fragment implements View.OnTouchListener, View.OnClickListener, TrackDataListener { private static final String KEY_CURRENT_LOCATION = "currentLocation"; private static final String KEY_KEEP_MY_LOCATION_VISIBLE = "keepMyLocationVisible"; private TrackDataHub trackDataHub; // True to keep my location visible. private boolean keepMyLocationVisible; // True to zoom to my location. Only apply when keepMyLocationVisible is true. private boolean zoomToMyLocation; // The track id of the marker to show. private long markerTrackId; // The marker id to show private long markerId; // The current selected track id. Set in onSelectedTrackChanged. private long currentSelectedTrackId; // The current location. Set in onCurrentLocationChanged. private Location currentLocation; // UI elements private View mapViewContainer; private MapOverlay mapOverlay; private RelativeLayout screen; private MapView mapView; private LinearLayout messagePane; private TextView messageText; private LinearLayout busyPane; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mapViewContainer = ((TrackDetailActivity) getActivity()).getMapViewContainer(); mapOverlay = new MapOverlay(getActivity()); screen = (RelativeLayout) mapViewContainer.findViewById(R.id.screen); mapView = (MapView) mapViewContainer.findViewById(R.id.map); mapView.requestFocus(); mapView.setOnTouchListener(this); mapView.setBuiltInZoomControls(true); mapView.getOverlays().add(mapOverlay); messagePane = (LinearLayout) mapViewContainer.findViewById(R.id.messagepane); messageText = (TextView) mapViewContainer.findViewById(R.id.messagetext); busyPane = (LinearLayout) mapViewContainer.findViewById(R.id.busypane); return mapViewContainer; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { keepMyLocationVisible = savedInstanceState.getBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, false); currentLocation = (Location) savedInstanceState.getParcelable(KEY_CURRENT_LOCATION); if (currentLocation != null) { updateCurrentLocation(); } } } @Override public void onResume() { super.onResume(); resumeTrackDataHub(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(KEY_KEEP_MY_LOCATION_VISIBLE, keepMyLocationVisible); if (currentLocation != null) { outState.putParcelable(KEY_CURRENT_LOCATION, currentLocation); } } @Override public void onPause() { super.onPause(); pauseTrackDataHub(); } @Override public void onDestroyView() { super.onDestroyView(); ViewGroup parentViewGroup = (ViewGroup) mapViewContainer.getParent(); if (parentViewGroup != null) { parentViewGroup.removeView(mapViewContainer); } } /** * Shows my location. */ public void showMyLocation() { updateTrackDataHub(); keepMyLocationVisible = true; zoomToMyLocation = true; if (currentLocation != null) { updateCurrentLocation(); } } /** * Shows the marker. * * @param id the marker id */ private void showMarker(long id) { MyTracksProviderUtils MyTracksProviderUtils = Factory.get(getActivity()); Waypoint waypoint = MyTracksProviderUtils.getWaypoint(id); if (waypoint != null && waypoint.getLocation() != null) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint((int) (waypoint.getLocation().getLatitude() * 1E6), (int) (waypoint.getLocation().getLongitude() * 1E6)); mapView.getController().setCenter(center); mapView.getController().setZoom(mapView.getMaxZoomLevel()); mapView.invalidate(); } } /** * Shows the marker. * * @param trackId the track id * @param id the marker id */ public void showMarker(long trackId, long id) { /* * Synchronize to prevent race condition in changing markerTrackId and * markerId variables. */ synchronized (this) { if (trackId == currentSelectedTrackId) { showMarker(id); markerTrackId = -1L; markerId = -1L; return; } markerTrackId = trackId; markerId = id; } } /** * Returns true if in satellite mode. */ public boolean isSatelliteView() { return mapView.isSatellite(); } /** * Sets the satellite mode * * @param enabled true for satellite mode, false for map mode */ public void setSatelliteView(boolean enabled) { mapView.setSatellite(enabled); } @Override public boolean onTouch(View view, MotionEvent event) { if (keepMyLocationVisible && event.getAction() == MotionEvent.ACTION_MOVE) { if (!isVisible(currentLocation)) { /* * Only set to false when no longer visible. Thus can keep showing the * current location with the next location update. */ keepMyLocationVisible = false; } } return false; } @Override public void onClick(View v) { if (v == messagePane) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } } @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: messageId = -1; isGpsDisabled = false; break; default: throw new IllegalArgumentException("Unexpected state: " + state); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (messageId != -1) { messageText.setText(messageId); messagePane.setVisibility(View.VISIBLE); if (isGpsDisabled) { Toast.makeText(getActivity(), R.string.gps_not_found, Toast.LENGTH_LONG).show(); // Click to show the location source settings messagePane.setOnClickListener(MapFragment.this); } else { messagePane.setOnClickListener(null); } } else { messagePane.setVisibility(View.GONE); } screen.requestLayout(); } }); } @Override public void onCurrentLocationChanged(Location location) { currentLocation = location; updateCurrentLocation(); } @Override public void onCurrentHeadingChanged(double heading) { if (mapOverlay.setHeading((float) heading)) { mapView.postInvalidate(); } } @Override public void onSelectedTrackChanged(final Track track, final boolean isRecording) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { boolean hasTrack = track != null; mapOverlay.setTrackDrawingEnabled(hasTrack); if (hasTrack) { busyPane.setVisibility(View.VISIBLE); synchronized (this) { /* * Synchronize to prevent race condition in changing markerTrackId * and markerId variables. */ currentSelectedTrackId = track.getId(); updateMap(track); } mapOverlay.setShowEndMarker(!isRecording); busyPane.setVisibility(View.GONE); } mapView.invalidate(); } }); } @Override public void onTrackUpdated(Track track) { // We don't care. } @Override public void clearTrackPoints() { mapOverlay.clearPoints(); } @Override public void onNewTrackPoint(Location location) { if (LocationUtils.isValidLocation(location)) { mapOverlay.addLocation(location); } } @Override public void onSampledOutTrackPoint(Location loc) { // We don't care. } @Override public void onSegmentSplit() { mapOverlay.addSegmentSplit(); } @Override public void onNewTrackPointsDone() { mapView.postInvalidate(); } @Override public void clearWaypoints() { mapOverlay.clearWaypoints(); } @Override public void onNewWaypoint(Waypoint waypoint) { if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { // TODO: Optimize locking inside addWaypoint mapOverlay.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { 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; } /** * Resumes the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void resumeTrackDataHub() { trackDataHub = ((MyTracksApplication) getActivity().getApplication()).getTrackDataHub(); trackDataHub.registerTrackDataListener(this, EnumSet.of( ListenerDataType.SELECTED_TRACK_CHANGED, ListenerDataType.WAYPOINT_UPDATES, ListenerDataType.POINT_UPDATES, ListenerDataType.LOCATION_UPDATES, ListenerDataType.COMPASS_UPDATES)); } /** * Pauses the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void pauseTrackDataHub() { trackDataHub.unregisterTrackDataListener(this); trackDataHub = null; } /** * Updates the trackDataHub. Needs to be synchronized because trackDataHub can be * accessed by multiple threads. */ private synchronized void updateTrackDataHub() { if (trackDataHub != null) { trackDataHub.forceUpdateLocation(); } } /** * Updates the map by either zooming to the requested marker or showing the track. * * @param track the track */ private void updateMap(Track track) { if (track.getId() == markerTrackId) { // Show the marker showMarker(markerId); markerTrackId = -1L; markerId = -1L; } else { // Show the track showTrack(track); } } /** * Returns true if the location is visible. * * @param location the location */ private boolean isVisible(Location location) { if (location == null || mapView == null) { return false; } GeoPoint mapCenter = mapView.getMapCenter(); int latitudeSpan = mapView.getLatitudeSpan(); int longitudeSpan = mapView.getLongitudeSpan(); /* * The bottom of the mapView is obscured by the zoom controls, subtract its * height from the visible area. */ GeoPoint zoomControlBottom = mapView.getProjection().fromPixels(0, mapView.getHeight()); GeoPoint zoomControlTop = mapView.getProjection().fromPixels( 0, mapView.getHeight() - mapView.getZoomButtonsController().getZoomControls().getHeight()); int zoomControlMargin = Math.abs(zoomControlTop.getLatitudeE6() - zoomControlBottom.getLatitudeE6()); GeoRect geoRect = new GeoRect(mapCenter, latitudeSpan, longitudeSpan); geoRect.top += zoomControlMargin; GeoPoint geoPoint = LocationUtils.getGeoPoint(location); return geoRect.contains(geoPoint); } /** * Updates the current location and centers it if necessary. */ private void updateCurrentLocation() { if (mapOverlay == null || mapView == null) { return; } mapOverlay.setMyLocation(currentLocation); mapView.postInvalidate(); if (currentLocation != null && keepMyLocationVisible && !isVisible(currentLocation)) { GeoPoint geoPoint = LocationUtils.getGeoPoint(currentLocation); MapController mapController = mapView.getController(); mapController.animateTo(geoPoint); if (zoomToMyLocation) { // Only zoom in the first time we show the location. zoomToMyLocation = false; if (mapView.getZoomLevel() < mapView.getMaxZoomLevel()) { mapController.setZoom(mapView.getMaxZoomLevel()); } } } } /** * Shows the track. * * @param track the track */ private void showTrack(Track track) { if (mapView == null || track == null || track.getNumberOfPoints() < 2) { return; } TripStatistics tripStatistics = track.getStatistics(); int bottom = tripStatistics.getBottom(); int left = tripStatistics.getLeft(); int latitudeSpanE6 = tripStatistics.getTop() - bottom; int longitudeSpanE6 = tripStatistics.getRight() - left; if (latitudeSpanE6 > 0 && latitudeSpanE6 < 180E6 && longitudeSpanE6 > 0 && longitudeSpanE6 < 360E6) { keepMyLocationVisible = false; GeoPoint center = new GeoPoint(bottom + latitudeSpanE6 / 2, left + longitudeSpanE6 / 2); if (LocationUtils.isValidGeoPoint(center)) { mapView.getController().setCenter(center); mapView.getController().zoomToSpan(latitudeSpanE6, longitudeSpanE6); } } } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java
Java
asf20
15,469
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.fragments; import com.google.android.apps.mytracks.TrackListActivity; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.util.DialogUtils; import com.google.android.maps.mytracks.R; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.DialogFragment; /** * A DialogFragment to delete one track. * * @author Jimmy Shih */ public class DeleteOneTrackDialogFragment extends DialogFragment { public static final String DELETE_ONE_TRACK_DIALOG_TAG = "deleteOneTrackDialog"; private static final String KEY_TRACK_ID = "trackId"; public static DeleteOneTrackDialogFragment newInstance(long trackId) { Bundle bundle = new Bundle(); bundle.putLong(KEY_TRACK_ID, trackId); DeleteOneTrackDialogFragment deleteOneTrackDialogFragment = new DeleteOneTrackDialogFragment(); deleteOneTrackDialogFragment.setArguments(bundle); return deleteOneTrackDialogFragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return DialogUtils.createConfirmationDialog(getActivity(), R.string.track_detail_delete_confirm_message, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MyTracksProviderUtils.Factory.get(getActivity()) .deleteTrack(getArguments().getLong(KEY_TRACK_ID)); startActivity(new Intent(getActivity(), TrackListActivity.class).addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)); } }); } }
0359xiaodong-mytracks
MyTracks/src/com/google/android/apps/mytracks/fragments/DeleteOneTrackDialogFragment.java
Java
asf20
2,325
package com.xyz.tag.html; import java.io.Serializable; public interface XYIHTMLTag extends Serializable { public String draw(); }
001-tag
trunk/src/com/xyz/tag/html/XYIHTMLTag.java
Java
asf20
145
package com.xyz.tag.html; public class XYHtmlConstants { /* 元素名 */ public static final String element_div = "div"; public static final String element_span = "span"; public static final String element_label = "label"; public static final String element_a = "a"; public static final String element_table = "table"; public static final String element_tr = "tr"; public static final String element_td = "td"; /* 属性名 */ public static final String attribute_id = "id"; public static final String attribute_name = "name"; public static final String attribute_classs = "class"; public static final String attribute_style = "style"; public static final String attribute_href = "href"; public static final String attribute_target = "target"; /* 符号 */ public static final String sign_lt = "<"; public static final String sign_gt = ">"; public static final String sign_slash = "/"; public static final String sign_backslash = "\\"; public static final String sign_eq = "="; public static final String sign_quot = "\""; public static final String sign_acute = "'"; public static final String sign_colon = ":"; public static final String sign_semicolon = ";"; }
001-tag
trunk/src/com/xyz/tag/html/XYHtmlConstants.java
Java
asf20
1,617
package com.xyz.tag.html.element; import com.xyz.tag.html.XYHtmlConstants; public class XYElementA extends XYElement { public XYElementA() { super( XYHtmlConstants.element_a ); } public void setName( String name ) { addAttribute( XYHtmlConstants.attribute_name, name ); } public void setHref( String href ) { addAttribute( XYHtmlConstants.attribute_href, href ); } public void setTarget( String target ) { addAttribute( XYHtmlConstants.attribute_target, target ); } private static final long serialVersionUID = 5844668518614160729L; }
001-tag
trunk/src/com/xyz/tag/html/element/XYElementA.java
Java
asf20
602
package com.xyz.tag.html.element; import com.xyz.tag.html.XYIHTMLTag; public class XYText implements XYIHTMLTag { private static final long serialVersionUID = 8397445138431377308L; private String text; public XYText( String text ) { if ( text == null ) this.text = ""; else this.text = text; } @Override public String draw() { return text; } public String getText() { return text; } }
001-tag
trunk/src/com/xyz/tag/html/element/XYText.java
Java
asf20
464
package com.xyz.tag.html.element; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.html.XYIAttribute; import com.xyz.tag.html.XYIElement; import com.xyz.tag.html.XYIHTMLTag; import com.xyz.tag.html.attribute.XYAttribute; import com.xyz.tag.util.StringUtil; public class XYElement implements XYIElement { private static final long serialVersionUID = 2014161164499768349L; private String elementName = null; private List<XYIHTMLTag> elements = null; private Set<XYIAttribute> attributes = null; public XYElement( String elementName ) { this( elementName, null, null ); } public XYElement( String elementName, Set<XYIAttribute> attributes ) { this( elementName, attributes, null ); } public XYElement( String elementName, List<XYIHTMLTag> elements ) { this( elementName, null, elements ); } public XYElement( String elementName, Set<XYIAttribute> attributes, List<XYIHTMLTag> elements ) { this.elementName = elementName; this.attributes = attributes; this.elements = elements; } @Override public XYIElement addElement( XYIHTMLTag element ) { if ( element != null ) { if ( elements == null ) { elements = new ArrayList<XYIHTMLTag>(); } elements.add( element ); } return this; } @Override public XYIElement addElements( XYIHTMLTag... elements ) { if ( elements != null && elements.length > 0 ) { return addElements( Arrays.asList( elements ) ); } return this; } @Override public XYIElement addElements( List<XYIHTMLTag> elements ) { if ( elements != null && !elements.isEmpty() ) { if ( this.elements == null ) { this.elements = new ArrayList<XYIHTMLTag>(); } this.elements.addAll( elements ); } return this; } @Override public XYIElement addAttribute( String name, String value ) { return addAttribute( new XYAttribute( name, value ) ); } @Override public XYIElement addAttribute( XYIAttribute attribute ) { if ( attribute != null ) { if ( attributes == null ) { attributes = new HashSet<XYIAttribute>(); } attributes.add( attribute ); } return this; } @Override public XYIElement addAttributes( XYIAttribute... attributes ) { if ( attributes != null && attributes.length > 0 ) { return addAttributes( new HashSet<XYIAttribute>( Arrays.asList( attributes ) ) ); } return this; } @Override public XYIElement addAttributes( Set<XYIAttribute> attributes ) { if ( attributes != null && !attributes.isEmpty() ) { if ( this.attributes == null ) { this.attributes = new HashSet<XYIAttribute>(); } this.attributes.addAll( attributes ); } return this; } @Override public XYIElement setElements( XYIHTMLTag... elements ) { if ( elements != null && elements.length > 0 ) { return setElements( Arrays.asList( elements ) ); } return this; } @Override public XYIElement setElements( List<XYIHTMLTag> elements ) { this.elements = elements; return this; } @Override public XYIElement setAttributes( Set<XYIAttribute> attributes ) { this.attributes = attributes; return this; } @Override public void setId( String id ) { addAttribute( XYHtmlConstants.attribute_id, id ); } @Override public void setClasss( String classs ) { addAttribute( XYHtmlConstants.attribute_classs, classs ); } @Override public void addClasss( String classs ) { appendToAttributeValue( XYHtmlConstants.attribute_classs, classs ); } @Override public String draw() { StringBuffer html = new StringBuffer(); html.append( XYHtmlConstants.sign_lt ); html.append( this.elementName ); if ( attributes != null && !attributes.isEmpty() ) { Iterator<XYIAttribute> iterator = attributes.iterator(); while ( iterator.hasNext() ) { html.append( " " ); html.append( iterator.next().draw() ); } } if ( elements != null && !elements.isEmpty() ) { html.append( XYHtmlConstants.sign_gt ); for ( XYIHTMLTag element : elements ) { html.append( element.draw() ); } html.append( XYHtmlConstants.sign_lt ).append( XYHtmlConstants.sign_slash ).append( this.elementName ) .append( XYHtmlConstants.sign_gt ); } else { html.append( XYHtmlConstants.sign_slash + XYHtmlConstants.sign_gt ); } return html.toString(); } protected void appendToAttributeValue( String name, String value ) { if ( !StringUtil.isEmpty( name ) && !StringUtil.isEmpty( value ) ) { if ( attributes != null && !attributes.isEmpty() ) { boolean found = false; for ( XYIAttribute attribute : attributes ) { if ( attribute.getName() != null && attribute.getName().equalsIgnoreCase( name ) ) { attribute.setValue( attribute.getValue() + " " + value ); found = true; break; } } if ( !found ) { addAttribute( name, value ); } } else { addAttribute( name, value ); } } } @Override public void setStyle( String style ) { } @Override public void addStyle( String style ) { } }
001-tag
trunk/src/com/xyz/tag/html/element/XYElement.java
Java
asf20
5,582
package com.xyz.tag.html; import java.util.List; import java.util.Set; public interface XYIElement extends XYIHTMLTag { public void setId( String id ); public void setClasss( String classs ); public void addClasss( String classs ); public void setStyle( String style ); public void addStyle( String style ); public XYIElement addElement( XYIHTMLTag element ); public XYIElement addElements( XYIHTMLTag... elements ); public XYIElement addElements( List<XYIHTMLTag> elements ); public XYIElement addAttribute( String name, String value ); public XYIElement addAttribute( XYIAttribute attribute ); public XYIElement addAttributes( XYIAttribute... attributes ); public XYIElement addAttributes( Set<XYIAttribute> attributes ); public XYIElement setElements( XYIHTMLTag... elements ); public XYIElement setElements( List<XYIHTMLTag> elements ); public XYIElement setAttributes( Set<XYIAttribute> attributes ); }
001-tag
trunk/src/com/xyz/tag/html/XYIElement.java
Java
asf20
994
package com.xyz.tag.html; public interface XYIAttribute extends XYIHTMLTag { public String getName(); public void setName( String name ); public String getValue(); public void setValue( String value ); }
001-tag
trunk/src/com/xyz/tag/html/XYIAttribute.java
Java
asf20
229
package com.xyz.tag.html.attribute; import java.util.HashSet; import java.util.Set; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.util.StringUtil; public class XYAttributeStyle extends XYAttribute { private Set<XYAttributeStyleValue> styles = null; public XYAttributeStyle() { super( XYHtmlConstants.attribute_style ); } public XYAttributeStyle addStyle( String name, String value ) { if ( !StringUtil.isEmpty( name ) && !StringUtil.isEmpty( value ) ) { addStyle( new XYAttributeStyleValue( name, value ) ); } return this; } public XYAttributeStyle addStyle( XYAttributeStyleValue styleValue ) { if ( styles == null ) { styles = new HashSet<XYAttributeStyleValue>(); } styles.add( styleValue ); return this; } @Override public String draw() { StringBuffer html = new StringBuffer(); if ( styles != null && !styles.isEmpty() ) { html.append( XYHtmlConstants.attribute_style ).append( XYHtmlConstants.sign_eq ) .append( XYHtmlConstants.sign_quot ); for ( XYAttributeStyleValue styleValue : styles ) { html.append( styleValue.getName() ).append( XYHtmlConstants.sign_colon ).append( styleValue.getValue() ) .append( XYHtmlConstants.sign_semicolon ); } html.append( XYHtmlConstants.sign_quot ); } return html.toString(); } private class XYAttributeStyleValue { private String name; private String value; public XYAttributeStyleValue( String name, String value ) { this.name = name; this.value = value; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals( Object o ) { return name.equalsIgnoreCase( ( (XYAttributeStyleValue)o ).getName() ); } public String getName() { return name; } public String getValue() { return value; } } private static final long serialVersionUID = 9006660492122768338L; }
001-tag
trunk/src/com/xyz/tag/html/attribute/XYAttributeStyle.java
Java
asf20
2,082
package com.xyz.tag.html.attribute; import com.xyz.tag.html.XYHtmlConstants; import com.xyz.tag.html.XYIAttribute; import com.xyz.tag.util.StringUtil; public class XYAttribute implements XYIAttribute { private static final long serialVersionUID = 5475759902995632006L; private String name; private String value; public XYAttribute( String name ) { this( name, null ); } public XYAttribute( String name, String value ) { this.name = name; this.value = value; } @Override public String draw() { StringBuffer sb = new StringBuffer(); if ( !StringUtil.isEmpty( name ) ) { sb.append( name ); if ( !StringUtil.isEmpty( value ) ) { sb.append( XYHtmlConstants.sign_eq ).append( XYHtmlConstants.sign_quot ).append( getValue() ) .append( XYHtmlConstants.sign_quot ); } } return sb.toString(); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals( Object o ) { return name.equals( ( (XYAttribute)o ).getName() ); } public String getName() { return name; } public void setName( String name ) { this.name = name; } public String getValue() { return value; } public void setValue( String value ) { this.value = value; } }
001-tag
trunk/src/com/xyz/tag/html/attribute/XYAttribute.java
Java
asf20
1,359
package com.xyz.tag.util; public class StringUtil { public static boolean isEmpty( String str ) { if ( str != null && str.trim().length() > 0 ) { return false; } return true; } }
001-tag
trunk/src/com/xyz/tag/util/StringUtil.java
Java
asf20
204
package com.xyz.tag.util; import com.xyz.tag.html.XYHtmlConstants; public class HtmlUtil { public static String drawNameAndValue( String name, String value ) { StringBuffer html = new StringBuffer(); if ( !StringUtil.isEmpty( name ) ) { html.append( name ); if ( !StringUtil.isEmpty( value ) ) { html.append( XYHtmlConstants.sign_eq ).append( XYHtmlConstants.sign_quot ).append( value ) .append( XYHtmlConstants.sign_quot ); } } return html.toString(); } }
001-tag
trunk/src/com/xyz/tag/util/HtmlUtil.java
Java
asf20
538
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapResponse extends CoapMessage{ /* TODO: Response Code is part of BasicCoapResponse */ public CoapResponseCode getResponseCode(); public void setMaxAge(int maxAge); public long getMaxAge(); public void setETag(byte[] etag); public byte[] getETag(); public void setResponseCode(CoapResponseCode responseCode); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapResponse.java
Java
asf20
514
package org.ws4d.coap.interfaces; import java.util.Vector; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapRequest extends CoapMessage{ public void setUriHost(String host); public void setUriPort(int port); public void setUriPath(String path); public void setUriQuery(String query); public void setProxyUri(String proxyUri); public void setToken(byte[] token); public void addAccept(CoapMediaType mediaType); public Vector<CoapMediaType> getAccept(CoapMediaType mediaType); public String getUriHost(); public int getUriPort(); public String getUriPath(); public Vector<String> getUriQuery(); public String getProxyUri(); public void addETag(byte[] etag); public Vector<byte[]> getETag(); public CoapRequestCode getRequestCode(); public void setRequestCode(CoapRequestCode requestCode); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapRequest.java
Java
asf20
1,011
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.CoapBlockOption.CoapBlockSize; public interface CoapChannel { public void sendMessage(CoapMessage msg); /*TODO: close when finished, & abort()*/ public void close(); public InetAddress getRemoteAddress(); public int getRemotePort(); /* handles an incomming message */ public void handleMessage(CoapMessage message); /*TODO: implement Error Type*/ public void lostConnection(boolean notReachable, boolean resetByServer); public CoapBlockSize getMaxReceiveBlocksize(); public void setMaxReceiveBlocksize(CoapBlockSize maxReceiveBlocksize); public CoapBlockSize getMaxSendBlocksize(); public void setMaxSendBlocksize(CoapBlockSize maxSendBlocksize); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannel.java
Java
asf20
908
package org.ws4d.coap.interfaces; import java.net.InetAddress; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapSocketHandler { // public void registerResponseListener(CoapResponseListener // responseListener); // public void unregisterResponseListener(CoapResponseListener // responseListener); // public int sendRequest(CoapMessage request); // public void sendResponse(CoapResponse response); // public void establish(DatagramSocket socket); // public void testConfirmation(int msgID); // // public boolean isOpen(); /* TODO */ public CoapClientChannel connect(CoapClient client, InetAddress remoteAddress, int remotePort); public void close(); public void sendMessage(CoapMessage msg); public CoapChannelManager getChannelManager(); int getLocalPort(); void removeClientChannel(CoapClientChannel channel); void removeServerChannel(CoapServerChannel channel); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapSocketHandler.java
Java
asf20
978
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClient extends CoapChannelListener { public void onResponse(CoapClientChannel channel, CoapResponse response); public void onConnectionFailed(CoapClientChannel channel, boolean notReachable, boolean resetByServer); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapClient.java
Java
asf20
366
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapResponseCode; public interface CoapServerChannel extends CoapChannel { /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode); /* creates a normal response */ public CoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType); /* creates a separate response and acks the current request witch an empty ACK in case of a CON. * The separate response can be send later using sendSeparateResponse() */ public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode); /* used by a server to send a separate response */ public void sendSeparateResponse(CoapResponse response); /* used by a server to create a notification (observing resources), reliability is base on the request packet type (con or non) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber); /* used by a server to create a notification (observing resources) */ public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable); /* used by a server to send a notification (observing resources) */ public void sendNotification(CoapResponse response); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapServerChannel.java
Java
asf20
1,516
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapServer extends CoapChannelListener { public CoapServer onAccept(CoapRequest request); public void onRequest(CoapServerChannel channel, CoapRequest request); public void onSeparateResponseFailed(CoapServerChannel channel); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapServer.java
Java
asf20
373
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ import java.net.InetAddress; import org.ws4d.coap.messages.BasicCoapRequest; public interface CoapChannelManager { public int getNewMessageID(); /* called by the socket Listener to create a new Server Channel * the Channel Manager then asked the Server Listener if he wants to accept a new connection */ public CoapServerChannel createServerChannel(CoapSocketHandler socketHandler, CoapMessage message, InetAddress addr, int port); /* creates a server socket listener for incoming connections */ public void createServerListener(CoapServer serverListener, int localPort); /* called by a client to create a connection * TODO: allow client to bind to a special port */ public CoapClientChannel connect(CoapClient client, InetAddress addr, int port); /* This function is for testing purposes only, to have a determined message id*/ public void setMessageId(int globalMessageId); public void initRandom(); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannelManager.java
Java
asf20
1,751
package org.ws4d.coap.interfaces; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapChannelListener { }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapChannelListener.java
Java
asf20
158
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.interfaces; import org.ws4d.coap.messages.AbstractCoapMessage.CoapHeaderOptionType; import org.ws4d.coap.messages.CoapBlockOption; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapMessage { public static final int RESPONSE_TIMEOUT_MS = 2000; public static final double RESPONSE_RANDOM_FACTOR = 1.5; public static final int MAX_RETRANSMIT = 4; /* TODO: what is the right value? */ public static final int ACK_RST_RETRANS_TIMEOUT_MS = 120000; /* returns the value of the internal message code * in case of an error this function returns -1 */ public int getMessageCodeValue(); public int getMessageID(); public void setMessageID(int msgID); public byte[] serialize(); public void incRetransCounterAndTimeout(); public CoapPacketType getPacketType(); public byte[] getPayload(); public void setPayload(byte[] payload); public void setPayload(char[] payload); public void setPayload(String payload); public int getPayloadLength(); public void setContentType(CoapMediaType mediaType); public CoapMediaType getContentType(); public byte[] getToken(); // public URI getRequestUri(); // // public void setRequestUri(URI uri); //TODO:allow this method only for Clients, Define Token Type CoapBlockOption getBlock1(); void setBlock1(CoapBlockOption blockOption); CoapBlockOption getBlock2(); void setBlock2(CoapBlockOption blockOption); public Integer getObserveOption(); public void setObserveOption(int sequenceNumber); public void removeOption(CoapHeaderOptionType optionType); //TODO: could this compromise the internal state? public String toString(); public CoapChannel getChannel(); public void setChannel(CoapChannel channel); public int getTimeout(); public boolean maxRetransReached(); public boolean isReliable(); public boolean isRequest(); public boolean isResponse(); public boolean isEmpty(); /* unique by remote address, remote port, local port and message id */ public int hashCode(); public boolean equals(Object obj); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapMessage.java
Java
asf20
3,026
package org.ws4d.coap.interfaces; import org.ws4d.coap.messages.CoapRequestCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public interface CoapClientChannel extends CoapChannel { public CoapRequest createRequest(boolean reliable, CoapRequestCode requestCode); public void setTrigger(Object o); public Object getTrigger(); }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/interfaces/CoapClientChannel.java
Java
asf20
383
package org.ws4d.coap.tools; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class TimeoutHashMap<K, V> extends HashMap<Object, Object>{ private static final long serialVersionUID = 4987370276778256858L; /* chronological list to remove expired elements when update() is called */ LinkedList<TimoutType<K>> timeoutQueue = new LinkedList<TimoutType<K>>(); /* Default Timeout is one minute */ long timeout = 60000; public TimeoutHashMap(long timeout){ this.timeout = timeout; } @Override public Object put(Object key, Object value) { long expires = System.currentTimeMillis() + timeout; TimoutType<V> timeoutValue = new TimoutType<V>((V) value, expires); TimoutType<K> timeoutKey = new TimoutType<K>((K) key, expires); timeoutQueue.add(timeoutKey); timeoutValue = (TimoutType<V>) super.put((K) key, timeoutValue); if (timeoutValue != null){ return timeoutValue.object; } return null; } @Override public Object get(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.get(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public Object remove(Object key) { TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(key); if (timeoutValueIsValid(timeoutValue)){ return timeoutValue.object; } return null; } @Override public void clear() { super.clear(); timeoutQueue.clear(); } /* remove expired elements */ public void update(){ while(true) { TimoutType<K> timeoutKey = timeoutQueue.peek(); if (timeoutKey == null){ /* if the timeoutKey queue is empty, there must be no more elements in the hashmap * otherwise there is a bug in the implementation */ if (!super.isEmpty()){ throw new IllegalStateException("Error in TimeoutHashMap. Timeout queue is empty but hashmap not!"); } return; } long now = System.currentTimeMillis(); if (now > timeoutKey.expires){ timeoutQueue.poll(); TimoutType<V> timeoutValue = (TimoutType<V>) super.remove(timeoutKey.object); if (timeoutValueIsValid(timeoutValue)){ /* This is a very special case which happens if an entry is overridden: * - put V with K * - put V2 with K * - K is expired but V2 not * because this is expected to be happened very seldom, we "reput" V2 to the hashmap * wich is better than every time to making a get and than a remove */ super.put(timeoutKey.object, timeoutValue); } } else { /* Key is not expired -> break the loop */ break; } } } @Override public Object clone() { // TODO implement function throw new IllegalStateException(); // return super.clone(); } @Override public boolean containsKey(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsKey(arg0); } @Override public boolean containsValue(Object arg0) { // TODO implement function throw new IllegalStateException(); // return super.containsValue(arg0); } @Override public Set<Entry<Object, Object>> entrySet() { // TODO implement function throw new IllegalStateException(); // return super.entrySet(); } @Override public boolean isEmpty() { // TODO implement function throw new IllegalStateException(); // return super.isEmpty(); } @Override public Set<Object> keySet() { // TODO implement function throw new IllegalStateException(); // return super.keySet(); } @Override public void putAll(Map<? extends Object, ? extends Object> arg0) { // TODO implement function throw new IllegalStateException(); // super.putAll(arg0); } @Override public int size() { // TODO implement function throw new IllegalStateException(); // return super.size(); } @Override public Collection<Object> values() { // TODO implement function throw new IllegalStateException(); // return super.values(); } /* private classes and methods */ private boolean timeoutValueIsValid(TimoutType<V> timeoutValue){ return timeoutValue != null && System.currentTimeMillis() < timeoutValue.expires; } private class TimoutType<T>{ public T object; public long expires; public TimoutType(T object, long expires) { super(); this.object = object; this.expires = expires; } } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/tools/TimeoutHashMap.java
Java
asf20
4,776
/* Copyright [2011] [University of Rostock] * * 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 org.ws4d.coap.connection; import java.net.InetAddress; import org.ws4d.coap.interfaces.CoapChannel; import org.ws4d.coap.interfaces.CoapMessage; import org.ws4d.coap.interfaces.CoapRequest; import org.ws4d.coap.interfaces.CoapResponse; import org.ws4d.coap.interfaces.CoapServer; import org.ws4d.coap.interfaces.CoapServerChannel; import org.ws4d.coap.interfaces.CoapSocketHandler; import org.ws4d.coap.messages.BasicCoapRequest; import org.ws4d.coap.messages.BasicCoapResponse; import org.ws4d.coap.messages.CoapEmptyMessage; import org.ws4d.coap.messages.CoapMediaType; import org.ws4d.coap.messages.CoapPacketType; import org.ws4d.coap.messages.CoapResponseCode; /** * @author Christian Lerche <christian.lerche@uni-rostock.de> */ public class BasicCoapServerChannel extends BasicCoapChannel implements CoapServerChannel{ CoapServer server = null; public BasicCoapServerChannel(CoapSocketHandler socketHandler, CoapServer server, InetAddress remoteAddress, int remotePort) { super(socketHandler, remoteAddress, remotePort); this.server = server; } @Override public void close() { socketHandler.removeServerChannel(this); } @Override public void handleMessage(CoapMessage message) { /* message MUST be a request */ if (message.isEmpty()){ return; } if (!message.isRequest()){ return; //throw new IllegalStateException("Incomming server message is not a request"); } BasicCoapRequest request = (BasicCoapRequest) message; CoapChannel channel = request.getChannel(); /* TODO make this cast safe */ server.onRequest((CoapServerChannel) channel, request); } /*TODO: implement */ public void lostConnection(boolean notReachable, boolean resetByServer){ server.onSeparateResponseFailed(this); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode) { return createResponse(request, responseCode, null); } @Override public BasicCoapResponse createResponse(CoapMessage request, CoapResponseCode responseCode, CoapMediaType contentType){ BasicCoapResponse response; if (request.getPacketType() == CoapPacketType.CON) { response = new BasicCoapResponse(CoapPacketType.ACK, responseCode, request.getMessageID(), request.getToken()); } else if (request.getPacketType() == CoapPacketType.NON) { response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } if (contentType != null && contentType != CoapMediaType.UNKNOWN){ response.setContentType(contentType); } response.setChannel(this); return response; } @Override public CoapResponse createSeparateResponse(CoapRequest request, CoapResponseCode responseCode) { BasicCoapResponse response = null; if (request.getPacketType() == CoapPacketType.CON) { /* The separate Response is CON (normally a Response is ACK or NON) */ response = new BasicCoapResponse(CoapPacketType.CON, responseCode, channelManager.getNewMessageID(), request.getToken()); /*send ack immediately */ sendMessage(new CoapEmptyMessage(CoapPacketType.ACK, request.getMessageID())); } else if (request.getPacketType() == CoapPacketType.NON){ /* Just a normal response*/ response = new BasicCoapResponse(CoapPacketType.NON, responseCode, request.getMessageID(), request.getToken()); } else { throw new IllegalStateException("Create Response failed, Request is neither a CON nor a NON packet"); } response.setChannel(this); return response; } @Override public void sendSeparateResponse(CoapResponse response) { sendMessage(response); } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber){ /*use the packet type of the request: if con than con otherwise non*/ if (request.getPacketType() == CoapPacketType.CON){ return createNotification(request, responseCode, sequenceNumber, true); } else { return createNotification(request, responseCode, sequenceNumber, false); } } @Override public CoapResponse createNotification(CoapRequest request, CoapResponseCode responseCode, int sequenceNumber, boolean reliable){ BasicCoapResponse response = null; CoapPacketType packetType; if (reliable){ packetType = CoapPacketType.CON; } else { packetType = CoapPacketType.NON; } response = new BasicCoapResponse(packetType, responseCode, channelManager.getNewMessageID(), request.getToken()); response.setChannel(this); response.setObserveOption(sequenceNumber); return response; } @Override public void sendNotification(CoapResponse response) { sendMessage(response); } }
1060413246zhaohong-
ws4d-jcoap/src/org/ws4d/coap/connection/BasicCoapServerChannel.java
Java
asf20
5,559