code
stringlengths
3
1.18M
language
stringclasses
1 value
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.formatting; public interface DistanceFormatter { public abstract CharSequence formatDistance(float distance); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.formatting; public class DistanceFormatterMetric implements DistanceFormatter { public CharSequence formatDistance(float distance) { if (distance == -1) { return ""; } if (distance >= 1000) { return String.format("%1$1.2fkm", distance / 1000.0); } return String.format("%1$dm", (int)distance); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.inject.Singleton; import android.util.Log; @Singleton public class Timing { private long mStartTime; public void lap(CharSequence msg) { long finishTime = System.currentTimeMillis(); Log.d("GeoBeagle", "****** " + msg + ": " + finishTime + ": " + (finishTime - mStartTime)); mStartTime = finishTime; } public void start() { mStartTime = System.currentTimeMillis(); } public long getTime() { return System.currentTimeMillis(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; public class Time { public long getCurrentTime() { return System.currentTimeMillis(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; public interface CacheListActivityStarter { public abstract void start(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.cacheloader; @SuppressWarnings("serial") public class CacheLoaderException extends Exception { private final int error; private final Object[] args; public CacheLoaderException(int resId, Object... args) { this.error = resId; this.args = args; } public int getError() { return error; } public Object[] getArgs() { return args; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.cacheloader; import com.google.code.geobeagle.R; import com.google.code.geobeagle.cachedetails.DetailsDatabaseReader; import org.xmlpull.v1.XmlPullParserException; import android.content.res.Resources; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class CacheLoader { private final DetailsDatabaseReader detailsDatabaseReader; private final DetailsXmlToString detailsXmlToString; private final Resources resources; CacheLoader(DetailsDatabaseReader detailsDatabaseReader, DetailsXmlToString detailsXmlToString, Resources resources) { this.detailsDatabaseReader = detailsDatabaseReader; this.detailsXmlToString = detailsXmlToString; this.resources = resources; } public String load(CharSequence cacheId) { Reader reader = createReader(cacheId); try { return detailsXmlToString.read(reader); } catch (XmlPullParserException e) { return resources.getString(R.string.error_reading_details_file, cacheId); } catch (IOException e) { return resources.getString(R.string.error_reading_details_file, cacheId); } } private Reader createReader(CharSequence cacheId) { return new StringReader(detailsDatabaseReader.read(cacheId)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.cacheloader; import com.google.code.geobeagle.xmlimport.EventDispatcher; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; class DetailsXmlToString { private final EventDispatcher eventDispatcher; DetailsXmlToString(EventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; } String read(Reader reader) throws XmlPullParserException, IOException { eventDispatcher.setInput(reader); eventDispatcher.open(); int eventType; for (eventType = eventDispatcher.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = eventDispatcher .next()) { eventDispatcher.handleEvent(eventType); } // Pick up END_DOCUMENT event as well. eventDispatcher.handleEvent(eventType); return eventDispatcher.getString(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import android.content.Context; import android.preference.DialogPreference; import android.provider.SearchRecentSuggestions; import android.util.AttributeSet; /** * The {@link ClearSuggestionHistoryPreference} is a preference to show a dialog * with Yes and No buttons. * <p> * This preference will store a boolean into the SharedPreferences. */ public class ClearSuggestionHistoryPreference extends DialogPreference { public ClearSuggestionHistoryPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onDialogClosed(boolean positiveResult) { super.onDialogClosed(positiveResult); if (callChangeListener(positiveResult) && positiveResult) { SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this.getContext(), SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); suggestions.clearHistory(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.code.geobeagle.activity.cachelist.CacheListActivity; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class CacheListActivityStarterPreHoneycomb implements CacheListActivityStarter { private Activity activity; @Inject CacheListActivityStarterPreHoneycomb(Activity activity) { this.activity = activity; } @Override public void start() { activity.startActivity(new Intent(activity, CacheListActivity.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; public interface IGpsLocation { public float distanceTo(IGpsLocation dest); float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceSortStrategy; import com.google.code.geobeagle.activity.cachelist.presenter.NullSortStrategy; import com.google.code.geobeagle.activity.cachelist.presenter.SortStrategy; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; @Singleton public class LocationControlBuffered implements LocationListener { private final DistanceSortStrategy mDistanceSortStrategy; private final GpsDisabledLocation mGpsDisabledLocation; private IGpsLocation mGpsLocation; private Location mLocation; private final NullSortStrategy mNullSortStrategy; private float mAzimuth; private final Provider<LocationManager> mLocationManagerProvider; @Inject public LocationControlBuffered(Provider<LocationManager> locationManagerProvider, DistanceSortStrategy distanceSortStrategy, NullSortStrategy nullSortStrategy, GpsDisabledLocation gpsDisabledLocation) { mLocationManagerProvider = locationManagerProvider; mDistanceSortStrategy = distanceSortStrategy; mNullSortStrategy = nullSortStrategy; mGpsDisabledLocation = gpsDisabledLocation; mGpsLocation = gpsDisabledLocation; mLocation = null; } public IGpsLocation getGpsLocation() { mLocation = mLocationManagerProvider.get().getLastKnownLocation( LocationManager.GPS_PROVIDER); if (mLocation == null) { mGpsLocation = mGpsDisabledLocation; } else { mGpsLocation = new GpsEnabledLocation((float)mLocation.getLatitude(), (float)mLocation.getLongitude()); } return mGpsLocation; } public Location getLocation() { getGpsLocation(); return mLocation; } public SortStrategy getSortStrategy() { getGpsLocation(); if (mLocation == null) return mNullSortStrategy; return mDistanceSortStrategy; } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } public void setAzimuth(float azimuth) { mAzimuth = azimuth; } public float getAzimuth() { return mAzimuth; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class OnClickListenerNOP implements OnClickListener { @Override public void onClick(DialogInterface dialog, int which) { } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; public class GpsDisabledLocation implements IGpsLocation { @Override public float distanceTo(IGpsLocation dest) { return Float.MAX_VALUE; } @Override public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) { return Float.MAX_VALUE; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.code.geobeagle.database.Tag; import com.google.code.geobeagle.database.TagReader; import com.google.inject.Inject; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class GraphicsGenerator { public static class AttributePainter { private final Paint mTempPaint; private final Rect mTempRect; @Inject public AttributePainter(Paint tempPaint, Rect tempRect) { mTempPaint = tempPaint; mTempRect = tempRect; } void paintAttribute(int position, int bottom, int imageHeight, int imageWidth, Canvas canvas, double attribute, int color) { final int diffWidth = (int)(imageWidth * (attribute / 10.0)); final int MARGIN = 1; final int THICKNESS = 3; final int base = imageHeight - bottom - MARGIN; final int attributeBottom = base - position * (THICKNESS + 1); final int attributeTop = attributeBottom - THICKNESS; mTempPaint.setColor(color); mTempRect.set(0, attributeTop, diffWidth, attributeBottom); canvas.drawRect(mTempRect, mTempPaint); } } public static class RatingsGenerator { Drawable createRating(Drawable unselected, Drawable halfSelected, Drawable selected, int rating) { int width = unselected.getIntrinsicWidth(); int height = unselected.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(5 * width, 16, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bitmap); int i = 0; while (i < rating / 2) { draw(width, height, c, i++, selected); } if (rating % 2 == 1) { draw(width, height, c, i++, halfSelected); } while (i < 5) { draw(width, height, c, i++, unselected); } return new BitmapDrawable(bitmap); } void draw(int width, int height, Canvas c, int i, Drawable drawable) { drawable.setBounds(width * i, 0, width * (i + 1) - 1, height - 1); drawable.draw(c); } } public static class RatingsArray { private final RatingsGenerator mRatingsGenerator; @Inject RatingsArray(RatingsGenerator ratingsGenerator) { mRatingsGenerator = ratingsGenerator; } public Drawable[] getRatings(Drawable[] drawables, int maxRatings) { Drawable[] ratings = new Drawable[maxRatings]; for (int i = 1; i <= maxRatings; i++) { ratings[i - 1] = mRatingsGenerator.createRating(drawables[0], drawables[1], drawables[2], i); } return ratings; } } public interface BitmapCopier { Bitmap copy(Bitmap source); int getBottom(); Drawable getDrawable(Bitmap icon); } public static class ListViewBitmapCopier implements BitmapCopier { @Override public Bitmap copy(Bitmap source) { int imageHeight = source.getHeight(); int imageWidth = source.getWidth(); Bitmap copy = Bitmap.createBitmap(imageWidth, imageHeight + 5, Bitmap.Config.ARGB_8888); int[] pixels = new int[imageWidth * imageHeight]; source.getPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight); copy.setPixels(pixels, 0, imageWidth, 0, 0, imageWidth, imageHeight); return copy; } @Override public int getBottom() { return 0; } @Override public Drawable getDrawable(Bitmap icon) { return new BitmapDrawable(icon); } } public static class MapViewBitmapCopier implements BitmapCopier { @Override public Bitmap copy(Bitmap source) { return source.copy(Bitmap.Config.ARGB_8888, true); } @Override public int getBottom() { return 3; } @Override public Drawable getDrawable(Bitmap icon) { Drawable iconMap = new BitmapDrawable(icon); int width = iconMap.getIntrinsicWidth(); int height = iconMap.getIntrinsicHeight(); iconMap.setBounds(-width / 2, -height, width / 2, 0); return iconMap; } } public static interface IconOverlay { void draw(Canvas canvas); } public static class IconOverlayImpl implements IconOverlay { private final Drawable mOverlayIcon; public IconOverlayImpl(Drawable overlayIcon) { mOverlayIcon = overlayIcon; } @Override public void draw(Canvas canvas) { if (mOverlayIcon != null) { mOverlayIcon.setBounds(0, 0, mOverlayIcon.getIntrinsicHeight() - 1, mOverlayIcon .getIntrinsicHeight() - 1); mOverlayIcon.draw(canvas); } } } public static class NullIconOverlay implements IconOverlay { @Override public void draw(Canvas canvas) { } } public static interface AttributesPainter { void paintAttributes(int difficulty, int terrain, Bitmap copy, Canvas canvas) ; } public static class DifficultyAndTerrainPainter implements AttributesPainter { private final AttributePainter mAttributePainter; @Inject public DifficultyAndTerrainPainter(AttributePainter attributePainter) { mAttributePainter = attributePainter; } @Override public void paintAttributes(int difficulty, int terrain, Bitmap copy, Canvas canvas) { int imageHeight = copy.getHeight(); int imageWidth = copy.getWidth(); mAttributePainter.paintAttribute(1, 0, imageHeight, imageWidth, canvas, difficulty, Color.rgb(0x20, 0x20, 0xFF)); mAttributePainter.paintAttribute(0, 0, imageHeight, imageWidth, canvas, terrain, Color .rgb(0xDB, 0xA1, 0x09)); } } public static class IconRenderer { private final Resources mResources; @Inject public IconRenderer(Resources resources) { mResources = resources; } public Drawable renderIcon(int difficulty, int terrain, int backdropId, IconOverlay iconOverlay, BitmapCopier bitmapCopier, AttributesPainter attributesPainter) { Bitmap bitmap = BitmapFactory.decodeResource(mResources, backdropId); Bitmap copy = bitmapCopier.copy(bitmap); Canvas canvas = new Canvas(copy); attributesPainter.paintAttributes(difficulty, terrain, copy, canvas); iconOverlay.draw(canvas); return bitmapCopier.getDrawable(copy); } } public static class IconOverlayFactory { private final TagReader mTagReader; private final Resources mResources; @Inject public IconOverlayFactory(TagReader tagReader, Resources resources) { mTagReader = tagReader; mResources = resources; } public IconOverlay create(Geocache geocache, boolean fBig) { if (mTagReader.hasTag(geocache.getId(), Tag.FOUND)) return new IconOverlayImpl( mResources.getDrawable(fBig ? R.drawable.overlay_found_big : R.drawable.overlay_found)); else if (mTagReader.hasTag(geocache.getId(), Tag.DNF)) return new IconOverlayImpl(mResources.getDrawable(fBig ? R.drawable.overlay_dnf_big : R.drawable.overlay_dnf)); return new NullIconOverlay(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import android.hardware.SensorListener; @SuppressWarnings("deprecation") @ContextScoped public class CompassListener implements SensorListener { private final Refresher mRefresher; private final LocationControlBuffered mLocationControlBuffered; private float mLastAzimuth; public float getLastAzimuth() { return mLastAzimuth; } @Inject public CompassListener(Refresher refresher, LocationControlBuffered locationControlBuffered) { mRefresher = refresher; mLocationControlBuffered = locationControlBuffered; mLastAzimuth = -1440f; } // public void onAccuracyChanged(Sensor sensor, int accuracy) { // } // public void onSensorChanged(SensorEvent event) { // onSensorChanged(SensorManager.SENSOR_ORIENTATION, event.values); // } @Override public void onAccuracyChanged(int sensor, int accuracy) { } @Override public void onSensorChanged(int sensor, float[] values) { final float currentAzimuth = values[0]; if (Math.abs(currentAzimuth - mLastAzimuth) > 5) { // Log.d("GeoBeagle", "azimuth now " + sensor + ", " + // currentAzimuth); mLocationControlBuffered.setAzimuth(((int)currentAzimuth / 5) * 5); mRefresher.refresh(); mLastAzimuth = currentAzimuth; } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class OnClickCancelListener implements OnClickListener { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.inject.Inject; import roboguice.inject.ContextScoped; @ContextScoped public class CacheListCompassListener extends CompassListener { @Inject public CacheListCompassListener(CacheListRefresh refresher, LocationControlBuffered locationControlBuffered) { super(refresher, locationControlBuffered); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.preferences; import com.google.code.geobeagle.activity.preferences.Preferences; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; public class PreferencesUpgrader { private final DependencyUpgrader dependencyUpgrader; @Inject PreferencesUpgrader(DependencyUpgrader dependencyUpgrader) { this.dependencyUpgrader = dependencyUpgrader; } public void upgrade(int oldVersion) { if (oldVersion <= 14) { dependencyUpgrader.upgrade(Preferences.BCACHING_ENABLED, Preferences.BCACHING_USERNAME); dependencyUpgrader.upgrade(Preferences.SDCARD_ENABLED, GeoBeagleEnvironment.IMPORT_FOLDER); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.preferences; import com.google.inject.Inject; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; class DependencyUpgrader { private final SharedPreferences sharedPreferences; @Inject DependencyUpgrader(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } void upgrade(String checkBoxKey, String stringKey) { String stringValue = sharedPreferences.getString(stringKey, ""); if (stringValue.length() > 0) { Editor editor = sharedPreferences.edit(); editor.putBoolean(checkBoxKey, true); editor.commit(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; public interface Refresher { public void refresh(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle; import com.google.code.geobeagle.activity.cachelist.CacheListActivityHoneycomb; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class CacheListActivityStarterHoneycomb implements CacheListActivityStarter { private Activity activity; @Inject CacheListActivityStarterHoneycomb(Activity activity) { this.activity = activity; } @Override public void start() { activity.startActivity(new Intent(activity, CacheListActivityHoneycomb.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.WhereFactoryFixedArea; import com.google.inject.Inject; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; class QueryManager { /** * We need to cache "needs loading" status because we might be zoomed out so * far we see no caches. In that situation, the compass will attempt to * refresh us every second, and we'll query the database over and over again * to learn that we have too many caches for the same set of points. */ static class CachedNeedsLoading { private GeoPoint mOldBottomRight; private GeoPoint mOldTopLeft; @Inject public CachedNeedsLoading() { mOldTopLeft = new GeoPoint(0, 0); mOldBottomRight = new GeoPoint(0, 0); } public CachedNeedsLoading(GeoPoint topLeft, GeoPoint bottomRight) { mOldTopLeft = topLeft; mOldBottomRight = bottomRight; } boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) { if (mOldTopLeft.equals(newTopLeft) && mOldBottomRight.equals(newBottomRight)) { Log.d("GeoBeagle", "CachedNeedsLoading.needsLoading: false"); return false; } mOldTopLeft = newTopLeft; mOldBottomRight = newBottomRight; Log.d("GeoBeagle", "CachedNeedsLoading.needsLoading: true"); return true; } } static interface Loader { ArrayList<Geocache> load(int latMin, int lonMin, int latMax, int lonMax, WhereFactoryFixedArea where, int[] newBounds); } static class LoaderImpl implements Loader { private final DbFrontend mDbFrontend; @Inject LoaderImpl(DbFrontend dbFrontend) { mDbFrontend = dbFrontend; } @Override public ArrayList<Geocache> load(int latMin, int lonMin, int latMax, int lonMax, WhereFactoryFixedArea where, int[] newBounds) { Log.d("GeoBeagle", "LoaderImpl.load: " + latMin + ", " + lonMin + ", " + latMax + ", " + lonMax); newBounds[0] = latMin; newBounds[1] = lonMin; newBounds[2] = latMax; newBounds[3] = lonMax; return mDbFrontend.loadCaches(0, 0, where); } } static class PeggedLoader implements Loader { private final DbFrontend mDbFrontend; private final LoaderImpl mLoader; private final ArrayList<Geocache> mNullList; private boolean mTooManyCaches; private final Toaster mToaster; @Inject PeggedLoader(DbFrontend dbFrontend, Toaster toaster, LoaderImpl loaderImpl) { mNullList = new ArrayList<Geocache>(); mDbFrontend = dbFrontend; mToaster = toaster; mTooManyCaches = false; mLoader = loaderImpl; } @Override public ArrayList<Geocache> load(int latMin, int lonMin, int latMax, int lonMax, WhereFactoryFixedArea where, int[] newBounds) { Log.d("GeoBeagle", "PeggedLoader.load: " + latMin + ", " + lonMin + ", " + latMax + ", " + lonMax); if (mDbFrontend.count(0, 0, where) > 1500) { latMin = latMax = lonMin = lonMax = 0; if (!mTooManyCaches) { Log.d("GeoBeagle", "QueryManager.load: too many caches"); mToaster.toast(R.string.too_many_caches, Toast.LENGTH_SHORT); mTooManyCaches = true; } return mNullList; } mTooManyCaches = false; return mLoader.load(latMin, lonMin, latMax, lonMax, where, newBounds); } } private final CachedNeedsLoading mCachedNeedsLoading; private final int[] mLatLonMinMax; // i.e. latmin, lonmin, latmax, lonmax private ArrayList<Geocache> mList; @Inject QueryManager(CachedNeedsLoading cachedNeedsLoading) { mLatLonMinMax = new int[] { 0, 0, 0, 0 }; mCachedNeedsLoading = cachedNeedsLoading; } // For testing QueryManager(CachedNeedsLoading cachedNeedsLoading, int[] latLonMinMax) { mCachedNeedsLoading = cachedNeedsLoading; mLatLonMinMax = latLonMinMax; } ArrayList<Geocache> load(GeoPoint newTopLeft, GeoPoint newBottomRight, Loader loader) { // Expand the area by the resolution so we get complete patches for the // density map. This isn't needed for the pins overlay, but it doesn't // hurt either. Log.d("GeoBeagle", "QueryManager.load: " + newTopLeft + ", " + newBottomRight); final int lonMin = newTopLeft.getLongitudeE6() - DensityPatchManager.RESOLUTION_LONGITUDE_E6; final int latMax = newTopLeft.getLatitudeE6() + DensityPatchManager.RESOLUTION_LATITUDE_E6; final int latMin = newBottomRight.getLatitudeE6() - DensityPatchManager.RESOLUTION_LATITUDE_E6; final int lonMax = newBottomRight.getLongitudeE6() + DensityPatchManager.RESOLUTION_LONGITUDE_E6; final WhereFactoryFixedArea where = new WhereFactoryFixedArea(latMin / 1E6, lonMin / 1E6, latMax / 1E6, lonMax / 1E6); mList = loader.load(latMin, lonMin, latMax, lonMax, where, mLatLonMinMax); return mList; } boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) { Log.d("GeoBeagle", "QueryManager.needsLoading new Points: " + newTopLeft + ", " + newBottomRight); Log.d("GeoBeagle", "QueryManager.needsLoading old Points: " + mLatLonMinMax[0] + ", " + mLatLonMinMax[1] + ", " + mLatLonMinMax[2] + ", " + mLatLonMinMax[3]); final boolean needsLoading = newTopLeft.getLatitudeE6() > mLatLonMinMax[2] || newTopLeft.getLongitudeE6() < mLatLonMinMax[1] || newBottomRight.getLatitudeE6() < mLatLonMinMax[0] || newBottomRight.getLongitudeE6() > mLatLonMinMax[3]; Log.d("GeoBeagle", "QueryManager.needsLoading: " + needsLoading); return mCachedNeedsLoading.needsLoading(newTopLeft, newBottomRight) && needsLoading; } }
Java
//http://www.spectrekking.com/download/FixedMyLocationOverlay.java package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Projection; import com.google.code.geobeagle.R; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.location.Location; public class FixedMyLocationOverlay extends MyLocationOverlay { private boolean bugged = false; private Paint accuracyPaint; private Point center; private Point left; private Drawable drawable; private int width; private int height; public FixedMyLocationOverlay(Context context, GeoMapView mapView) { super(context, mapView); } @Override protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) { if (!bugged) { try { super.drawMyLocation(canvas, mapView, lastFix, myLoc, when); } catch (Exception e) { bugged = true; } } if (bugged) { if (drawable == null) { accuracyPaint = new Paint(); accuracyPaint.setAntiAlias(true); accuracyPaint.setStrokeWidth(2.0f); drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation); width = drawable.getIntrinsicWidth(); height = drawable.getIntrinsicHeight(); center = new Point(); left = new Point(); } Projection projection = mapView.getProjection(); double latitude = lastFix.getLatitude(); double longitude = lastFix.getLongitude(); float accuracy = lastFix.getAccuracy(); float[] result = new float[1]; Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result); float longitudeLineDistance = result[0]; GeoPoint leftGeo = new GeoPoint((int)(latitude * 1e6), (int)((longitude - accuracy / longitudeLineDistance) * 1e6)); projection.toPixels(leftGeo, left); projection.toPixels(myLoc, center); int radius = center.x - left.x; accuracyPaint.setColor(0xff6666ff); accuracyPaint.setStyle(Style.STROKE); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); accuracyPaint.setColor(0x186666ff); accuracyPaint.setStyle(Style.FILL); canvas.drawCircle(center.x, center.y, radius, accuracyPaint); drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2); drawable.draw(canvas); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.MapView; import android.content.Context; import android.util.AttributeSet; import android.util.Log; public class GeoMapView extends MapView { private OverlayManager mOverlayManager; public GeoMapView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); Log.d("GeoBeagle", "~~~~~~~~~~onLayout " + changed + ", " + left + ", " + top + ", " + right + ", " + bottom); if (mOverlayManager != null) { mOverlayManager.selectOverlay(); } } public void setScrollListener(OverlayManager overlayManager) { mOverlayManager = overlayManager; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.OverlayItem; import com.google.code.geobeagle.Geocache; class CacheItem extends OverlayItem { private final Geocache mGeocache; CacheItem(GeoPoint geoPoint, String id, Geocache geocache) { super(geoPoint, id, ""); mGeocache = geocache; } Geocache getGeocache() { return mGeocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch; import com.google.code.geobeagle.activity.map.QueryManager.PeggedLoader; import com.google.inject.Inject; import java.util.ArrayList; import java.util.List; class DensityPatchManager { private List<DensityMatrix.DensityPatch> mDensityPatches; private final QueryManager mQueryManager; private final PeggedLoader mPeggedLoader; public static final double RESOLUTION_LATITUDE = 0.01; public static final double RESOLUTION_LONGITUDE = 0.02; public static final int RESOLUTION_LATITUDE_E6 = (int)(RESOLUTION_LATITUDE * 1E6); public static final int RESOLUTION_LONGITUDE_E6 = (int)(RESOLUTION_LONGITUDE * 1E6); @Inject DensityPatchManager(QueryManager queryManager, PeggedLoader peggedLoader) { mPeggedLoader = peggedLoader; mDensityPatches = new ArrayList<DensityPatch>(); mQueryManager = queryManager; } public List<DensityMatrix.DensityPatch> getDensityPatches(MapView mMapView) { Projection projection = mMapView.getProjection(); GeoPoint newTopLeft = projection.fromPixels(0, 0); GeoPoint newBottomRight = projection.fromPixels(mMapView.getRight(), mMapView.getBottom()); if (!mQueryManager.needsLoading(newTopLeft, newBottomRight)) { return mDensityPatches; } ArrayList<Geocache> list = mQueryManager.load(newTopLeft, newBottomRight, mPeggedLoader); DensityMatrix densityMatrix = new DensityMatrix(DensityPatchManager.RESOLUTION_LATITUDE, DensityPatchManager.RESOLUTION_LONGITUDE); densityMatrix.addCaches(list); mDensityPatches = densityMatrix.getDensityPatches(); // Log.d("GeoBeagle", "Density patches:" + mDensityPatches.size()); return mDensityPatches; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import java.util.HashMap; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.google.code.geobeagle.CacheType; class CacheDrawables { private static Drawable loadAndSizeDrawable(Resources resources, int res) { Drawable drawable = resources.getDrawable(res); int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); drawable.setBounds(-width/2, -height, width/2, 0); return drawable; } private final HashMap<CacheType, Drawable> mCacheDrawables; CacheDrawables(Resources resources) { final CacheType[] cacheTypes = CacheType.values(); mCacheDrawables = new HashMap<CacheType, Drawable>(cacheTypes.length); for (CacheType cacheType : cacheTypes) { final Drawable loadAndSizeDrawable = loadAndSizeDrawable(resources, cacheType .iconMap()); mCacheDrawables.put(cacheType, loadAndSizeDrawable); } } Drawable get(CacheType cacheType) { return mCacheDrawables.get(cacheType); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MyLocationOverlay; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.GeoUtils; import com.google.code.geobeagle.database.DbFrontend; import com.google.inject.Inject; import com.google.inject.Injector; import roboguice.activity.GuiceMapActivity; import roboguice.inject.ContextScoped; import roboguice.inject.InjectView; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class GeoMapActivity extends GuiceMapActivity { private static final int DEFAULT_ZOOM_LEVEL = 14; private static boolean fZoomed = false; @Inject @ContextScoped private DbFrontend mDbFrontend; private GeoMapActivityDelegate mGeoMapActivityDelegate; @InjectView(R.id.mapview) private GeoMapView mMapView; private FixedMyLocationOverlay mMyLocationOverlay; public MyLocationOverlay getMyLocationOverlay() { return mMyLocationOverlay; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // mMapView is built inside setContentView, therefore any objects which // depend on mapView must be created after setContentView. setContentView(R.layout.map); final Injector injector = getInjector(); mMyLocationOverlay = new FixedMyLocationOverlay(this, mMapView); mMapView.setBuiltInZoomControls(true); mMapView.setSatellite(false); mGeoMapActivityDelegate = injector.getInstance(GeoMapActivityDelegate.class); final Intent intent = getIntent(); final GeoPoint center = new GeoPoint( (int)(intent.getFloatExtra("latitude", 0) * GeoUtils.MILLION), (int)(intent.getFloatExtra("longitude", 0) * GeoUtils.MILLION)); final MapController mapController = mMapView.getController(); mapController.setCenter(center); final OverlayManager overlayManager = injector.getInstance(OverlayManager.class); mMapView.setScrollListener(overlayManager); if (!fZoomed) { mapController.setZoom(DEFAULT_ZOOM_LEVEL); fZoomed = true; } overlayManager.selectOverlay(); } @Override public boolean onCreateOptionsMenu(Menu menu) { return mGeoMapActivityDelegate.onCreateOptionsMenu(menu); } @Override public boolean onMenuOpened(int featureId, Menu menu) { return mGeoMapActivityDelegate.onMenuOpened(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mGeoMapActivityDelegate.onOptionsItemSelected(item); } @Override public void onPause() { mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); mDbFrontend.closeDatabase(); super.onPause(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); mMyLocationOverlay.enableCompass(); // Is this necessary? Or should we remove it and make openDatabase // private? mDbFrontend.openDatabase(); } @Override protected boolean isRouteDisplayed() { // This application doesn't use routes return false; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.Overlay; class NullOverlay extends Overlay { }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.Overlay; import com.google.code.geobeagle.R; import com.google.inject.Inject; import com.google.inject.Injector; import android.app.Activity; import android.util.Log; import java.util.List; public class OverlayManager { static final int DENSITY_MAP_ZOOM_THRESHOLD = 13; private final CachePinsOverlayFactory mCachePinsOverlayFactory; private final DensityOverlay mDensityOverlay; private boolean mUsesDensityMap; private final GeoMapActivity mActivity; public OverlayManager(Activity activity, DensityOverlay densityOverlay, CachePinsOverlayFactory cachePinsOverlayFactory, NullOverlay nullOverlay) { mActivity = (GeoMapActivity)activity; mDensityOverlay = densityOverlay; mCachePinsOverlayFactory = cachePinsOverlayFactory; init(nullOverlay); } @Inject public OverlayManager(Injector injector) { mActivity = (GeoMapActivity)injector.getInstance(Activity.class); mDensityOverlay = injector.getInstance(DensityOverlay.class); mCachePinsOverlayFactory = injector.getInstance(CachePinsOverlayFactory.class); NullOverlay nullOverlay = injector.getInstance(NullOverlay.class); init(nullOverlay); } void init(NullOverlay nullOverlay) { mUsesDensityMap = false; GeoMapView geoMapView = (GeoMapView)mActivity.findViewById(R.id.mapview); Overlay myLocationOverlay = mActivity.getMyLocationOverlay(); final List<Overlay> mapOverlays = geoMapView.getOverlays(); mapOverlays.add(nullOverlay); mapOverlays.add(myLocationOverlay); } public void selectOverlay() { GeoMapView geoMapView = (GeoMapView)mActivity.findViewById(R.id.mapview); final List<Overlay> mapOverlays = geoMapView.getOverlays(); final int zoomLevel = geoMapView.getZoomLevel(); Log.d("GeoBeagle", "Zoom: " + zoomLevel); boolean newZoomUsesDensityMap = zoomLevel < OverlayManager.DENSITY_MAP_ZOOM_THRESHOLD; if (newZoomUsesDensityMap && mUsesDensityMap) return; mUsesDensityMap = newZoomUsesDensityMap; mapOverlays.set(0, mUsesDensityMap ? mDensityOverlay : mCachePinsOverlayFactory .getCachePinsOverlay()); } public boolean usesDensityMap() { return mUsesDensityMap; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.inject.Inject; import android.graphics.Canvas; public class DensityOverlay extends Overlay { private DensityOverlayDelegate mDelegate; @Inject public DensityOverlay(DensityOverlayDelegate densityOverlayDelegate) { mDelegate = densityOverlayDelegate; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); mDelegate.draw(canvas, mapView, shadow); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.code.geobeagle.CacheListActivityStarter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.actions.MenuActionCacheList; import com.google.code.geobeagle.actions.MenuActions; import com.google.inject.Inject; import android.app.Activity; import android.content.res.Resources; import android.view.Menu; import android.view.MenuItem; public class GeoMapActivityDelegate { public static class MenuActionCenterLocation implements Action { private final MyLocationOverlay mMyLocationOverlay; private final MapController mMapController; public MenuActionCenterLocation(MapController mapController, MyLocationOverlay myLocationOverlay) { mMyLocationOverlay = myLocationOverlay; mMapController = mapController; } @Override public void act() { final GeoPoint myLocation = mMyLocationOverlay.getMyLocation(); if (myLocation == null) return; mMapController.animateTo(myLocation); } } public static class MenuActionToggleSatellite implements Action { private final MapView mMapView; public MenuActionToggleSatellite(MapView mapView) { mMapView = mapView; } @Override public void act() { mMapView.setSatellite(!mMapView.isSatellite()); } } private final GeoMapView mMapView; private final MenuActions mMenuActions; @Inject public GeoMapActivityDelegate(Resources resources, Activity activity, CacheListActivityStarter cacheListActivityStarter) { final MenuActions menuActions = new MenuActions(resources); final GeoMapView geoMapView = (GeoMapView)activity.findViewById(R.id.mapview); menuActions.add(new MenuActionBase(R.string.menu_toggle_satellite, new MenuActionToggleSatellite(geoMapView))); menuActions.add(new MenuActionBase(R.string.menu_cache_list, new MenuActionCacheList( cacheListActivityStarter))); final MyLocationOverlay fixedMyLocationOverlay = ((GeoMapActivity)activity) .getMyLocationOverlay(); menuActions.add(new MenuActionBase(R.string.menu_center_location, new MenuActionCenterLocation(geoMapView.getController(), fixedMyLocationOverlay))); mMapView = (GeoMapView)activity.findViewById(R.id.mapview); mMenuActions = menuActions; } // For testing. public GeoMapActivityDelegate(GeoMapView geoMapView, MenuActions menuActions) { this.mMapView = geoMapView; this.mMenuActions = menuActions; } public boolean onCreateOptionsMenu(Menu menu) { return mMenuActions.onCreateOptionsMenu(menu); } public boolean onMenuOpened(Menu menu) { menu.findItem(R.string.menu_toggle_satellite).setTitle( mMapView.isSatellite() ? R.string.map_view : R.string.satellite_view); return true; } public boolean onOptionsItemSelected(MenuItem item) { return mMenuActions.act(item.getItemId()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch; import com.google.inject.Inject; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import java.util.List; public class DensityOverlayDelegate { private static final double RESOLUTION_LATITUDE_E6 = (DensityPatchManager.RESOLUTION_LATITUDE * 1E6); private static final double RESOLUTION_LONGITUDE_E6 = (DensityPatchManager.RESOLUTION_LONGITUDE * 1E6); private final Paint mPaint; private final Rect mPatchRect; private final Point mScreenBottomRight; private final Point mScreenTopLeft; private final Timing mTiming; private final DensityPatchManager mDensityPatchManager; @Inject public DensityOverlayDelegate(Rect patchRect, Point screenLow, Point screenHigh, DensityPatchManager densityPatchManager, Paint paint, Timing timing) { mTiming = timing; mPatchRect = patchRect; mPaint = paint; paint.setARGB(128, 255, 0, 0); mScreenTopLeft = screenLow; mScreenBottomRight = screenHigh; mDensityPatchManager = densityPatchManager; } public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) return; // No shadow layer // Log.d("GeoBeagle", ">>>>>>>>>>Starting draw"); List<DensityMatrix.DensityPatch> densityPatches = mDensityPatchManager .getDensityPatches(mapView); mTiming.start(); final Projection projection = mapView.getProjection(); final GeoPoint newGeoTopLeft = projection.fromPixels(0, 0); final GeoPoint newGeoBottomRight = projection.fromPixels(mapView.getRight(), mapView .getBottom()); projection.toPixels(newGeoTopLeft, mScreenTopLeft); projection.toPixels(newGeoBottomRight, mScreenBottomRight); final int topLatitudeE6 = newGeoTopLeft.getLatitudeE6(); final int leftLongitudeE6 = newGeoTopLeft.getLongitudeE6(); final int bottomLatitudeE6 = newGeoBottomRight.getLatitudeE6(); final int rightLongitudeE6 = newGeoBottomRight.getLongitudeE6(); final double pixelsPerLatE6Degrees = (double)(mScreenBottomRight.y - mScreenTopLeft.y) / (double)(bottomLatitudeE6 - topLatitudeE6); final double pixelsPerLonE6Degrees = (double)(mScreenBottomRight.x - mScreenTopLeft.x) / (double)(rightLongitudeE6 - leftLongitudeE6); int patchCount = 0; for (DensityPatch patch : densityPatches) { final int patchLatLowE6 = patch.getLatLowE6(); final int patchLonLowE6 = patch.getLonLowE6(); int xOffset = (int)((patchLonLowE6 - leftLongitudeE6) * pixelsPerLonE6Degrees); int xEnd = (int)((patchLonLowE6 + RESOLUTION_LONGITUDE_E6 - leftLongitudeE6) * pixelsPerLonE6Degrees); int yOffset = (int)((patchLatLowE6 - topLatitudeE6) * pixelsPerLatE6Degrees); int yEnd = (int)((patchLatLowE6 + RESOLUTION_LATITUDE_E6 - topLatitudeE6) * pixelsPerLatE6Degrees); mPatchRect.set(xOffset, yEnd, xEnd, yOffset); // Log.d("GeoBeagle", "patchrect: " + mPatchRect.bottom + ", " + // mPatchRect.left // + ", " + mPatchRect.top + ", " + mPatchRect.right); mPaint.setAlpha(patch.getAlpha()); canvas.drawRect(mPatchRect, mPaint); patchCount++; } // mTiming.lap("Done drawing"); // Log.d("GeoBeagle", "patchcount: " + patchCount); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.map.CacheItemFactory; import com.google.code.geobeagle.activity.map.click.MapClickIntentFactory; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Canvas; import java.util.ArrayList; public class CachePinsOverlay extends ItemizedOverlay<CacheItem> { private final CacheItemFactory cacheItemFactory; private final Context context; private final ArrayList<Geocache> cacheList; private final MapClickIntentFactory mapClickIntentFactory; public CachePinsOverlay(Resources resources, CacheItemFactory cacheItemFactory, Context context, ArrayList<Geocache> cacheList, MapClickIntentFactory mapClickIntentFactory) { super(boundCenterBottom(resources.getDrawable(R.drawable.map_pin2_others))); this.context = context; this.cacheItemFactory = cacheItemFactory; this.cacheList = cacheList; this.mapClickIntentFactory = mapClickIntentFactory; populate(); } /* (non-Javadoc) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long) */ @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { return super.draw(canvas, mapView, shadow, when); } @Override protected boolean onTap(int i) { Geocache geocache = getItem(i).getGeocache(); if (geocache == null) return false; Intent intent = mapClickIntentFactory.createIntent(context, geocache); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return true; } @Override protected CacheItem createItem(int i) { return cacheItemFactory.createCacheItem(cacheList.get(i)); } @Override public int size() { return cacheList.size(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map; import com.google.code.geobeagle.Geocache; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class DensityMatrix { public static class DensityPatch { private int mCacheCount; private final int mLatLowE6; private final int mLonLowE6; public DensityPatch(double latLow, double lonLow) { mCacheCount = 0; mLatLowE6 = (int)(latLow * 1E6); mLonLowE6 = (int)(lonLow * 1E6); } public int getAlpha() { return Math.min(210, 10 + 32 * mCacheCount); } public int getCacheCount() { return mCacheCount; } public int getLatLowE6() { return mLatLowE6; } public int getLonLowE6() { return mLonLowE6; } public void setCacheCount(int count) { mCacheCount = count; } } /** Mapping lat -> (mapping lon -> cache count) */ private TreeMap<Integer, Map<Integer, DensityPatch>> mBuckets = new TreeMap<Integer, Map<Integer, DensityPatch>>(); private double mLatResolution; private double mLonResolution; public DensityMatrix(double latResolution, double lonResolution) { mLatResolution = latResolution; mLonResolution = lonResolution; } public void addCaches(ArrayList<Geocache> list) { for (Geocache cache : list) { incrementBucket(cache.getLatitude(), cache.getLongitude()); } } public List<DensityPatch> getDensityPatches() { ArrayList<DensityPatch> result = new ArrayList<DensityPatch>(); for (Integer latBucket : mBuckets.keySet()) { Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket); result.addAll(lonMap.values()); } return result; } private void incrementBucket(double lat, double lon) { Integer latBucket = (int)Math.floor(lat / mLatResolution); Integer lonBucket = (int)Math.floor(lon / mLonResolution); Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket); if (lonMap == null) { // Key didn't exist in map lonMap = new TreeMap<Integer, DensityPatch>(); mBuckets.put(latBucket, lonMap); } DensityPatch patch = lonMap.get(lonBucket); if (patch == null) { patch = new DensityPatch(latBucket * mLatResolution, lonBucket * mLonResolution); lonMap.put(lonBucket, patch); } patch.setCacheCount(patch.getCacheCount() + 1); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map.click; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.CacheListActivityHoneycomb; import android.app.SearchManager; import android.content.Context; import android.content.Intent; class MapClickIntentFactoryHoneycomb implements MapClickIntentFactory { @Override public Intent createIntent(Context context, Geocache geocache) { Intent intent = new Intent(context, CacheListActivityHoneycomb.class); intent.setAction(Intent.ACTION_SEARCH); intent.putExtra(SearchManager.QUERY, geocache.getId()); return intent; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map.click; import com.google.code.geobeagle.Geocache; import android.content.Context; import android.content.Intent; public interface MapClickIntentFactory { public abstract Intent createIntent(Context context, Geocache geocache); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.map.click; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.compass.CompassActivity; import android.content.Context; import android.content.Intent; class MapClickIntentFactoryPreHoneycomb implements MapClickIntentFactory { @Override public Intent createIntent(Context context, Geocache geocache) { Intent intent = new Intent(context, CompassActivity.class); intent.setAction(GeocacheListController.SELECT_CACHE); intent.putExtra("geocache", geocache); return intent; } }
Java
package com.google.code.geobeagle.activity.map; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.intents.IntentStarterGeo; import com.google.code.geobeagle.activity.compass.view.OnClickListenerIntentStarter; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; public class OnClickListenerMapPage implements OnClickListener { private final OnClickListenerIntentStarter onClickListenerIntentStarter; @Inject public OnClickListenerMapPage(Activity activity, HasGeocache hasGeocache, ErrorDisplayer errorDisplayer) { Intent geoMapActivityIntent = new Intent(activity, GeoMapActivity.class); IntentStarterGeo intentStarterGeo = new IntentStarterGeo(activity, geoMapActivityIntent, hasGeocache); onClickListenerIntentStarter = new OnClickListenerIntentStarter(intentStarterGeo, errorDisplayer); } @Override public void onClick(View v) { onClickListenerIntentStarter.onClick(v); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity; import com.google.code.geobeagle.Geocache; import com.google.inject.Inject; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class ActivitySaver { private final SharedPreferences sharedPreferences; static final String LAST_ACTIVITY = "lastActivity2"; @Inject ActivitySaver(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public void save(ActivityType activityType) { Editor editor = sharedPreferences.edit(); editor.putString(LAST_ACTIVITY, activityType.name()); editor.commit(); } public void save(ActivityType activityType, Geocache geocache) { Editor editor = sharedPreferences.edit(); editor.putString(LAST_ACTIVITY, activityType.name()); geocache.writeToPrefs(editor); editor.commit(); } }
Java
/* * Copyright (C) 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.code.geobeagle.activity.compass; /* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.code.geobeagle.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.hardware.SensorListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.TextView; @SuppressWarnings("deprecation") public class RadarView extends View implements SensorListener, LocationListener { private static final long RETAIN_GPS_MILLIS = 10000L; private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private double mMyLocationLat; private double mMyLocationLon; private int mLastScale = -1; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array * is used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_FEET = 0.0003048f; private static float KM_PER_MILES = 1.609344f; private static float FEET_PER_KM = 3280.8399f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array * is used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_FEET, 200 * KM_PER_FEET, 400 * KM_PER_FEET, 1000 * KM_PER_FEET, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #FEET_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, FEET_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fft", "%.0fft", "%.0fft", "%.0fft", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; private boolean mHaveLocation = false; // True when we have our location private TextView mDistanceView; private double mDistance; // Distance to target, in KM private double mBearing; // Bearing to target, in degrees // Ratio of the distance to the target to the radius of the outermost ring // on the radar screen private float mDistanceRatio; private Bitmap mBlip; // The bitmap used to draw the target // True if the display should use metric units; false if the display should // use standard units private boolean mUseMetric; // Time in millis for the last time GPS reported a location private long mLastGpsFixTime = 0L; // The last location reported by the network provider. Use this if we can't // get a location from GPS private Location mNetworkLocation; private boolean mGpsAvailable; // True if GPS is reporting a location // True if the network provider is reporting a location private boolean mNetworkAvailable; private TextView mBearingView; private float mMyLocationAccuracy; private TextView mAccuracyView; private final String mDegreesSymbol; private Path mCompassPath; private final Paint mCompassPaint; private final Paint mArrowPaint; private final Path mArrowPath; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mDegreesSymbol = context.getString(R.string.degrees_symbol); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); mCompassPaint = new Paint(); mCompassPaint.setColor(0xFF00FF00); mCompassPaint.setAntiAlias(true); mCompassPaint.setStyle(Style.STROKE); mCompassPaint.setStrokeWidth(1.0f); mCompassPaint.setTextSize(10.0f); mCompassPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behind the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Paint used for the arrow mArrowPaint = new Paint(); mArrowPaint.setColor(Color.WHITE); mArrowPaint.setAntiAlias(true); mArrowPaint.setStyle(Style.STROKE); mArrowPaint.setStrokeWidth(16); mArrowPaint.setAlpha(228); mArrowPath = new Path(); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); mCompassPath = new Path(); } /** * Sets the target to track on the radar * * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double)GeoUtils.MILLION; mTargetLon = lonE6 / (double)GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView d, TextView b, TextView a) { mDistanceView = d; mBearingView = b; mAccuracyView = a; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = Math.min(getHeight(), getWidth()) / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; gridPaint.setAlpha(100); canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int)(mDistanceRatio * radius); // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6, center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); if (mHaveLocation) { double northAngle = Math.toRadians(-mOrientation) - (Math.PI / 2); float northX = (float)Math.cos(northAngle); float northY = (float)Math.sin(northAngle); final int compassLength = radius >> 2; float tipX = northX * compassLength, tipY = northY * compassLength; float baseX = northY * 8, baseY = -northX * 8; double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float)Math.cos(drawingAngle); float sin = (float)Math.sin(drawingAngle); mArrowPath.reset(); mArrowPath.moveTo(center - cos * radius, center - sin * radius); mArrowPath.lineTo(center + cos * radius, center + sin * radius); final double arrowRight = drawingAngle + Math.PI / 2; final double arrowLeft = drawingAngle - Math.PI / 2; mArrowPath.moveTo(center + (float)Math.cos(arrowRight) * radius, center + (float)Math.sin(arrowRight) * radius); mArrowPath.lineTo(center + cos * radius, center + sin * radius); mArrowPath.lineTo(center + (float)Math.cos(arrowLeft) * radius, center + (float)Math.sin(arrowLeft) * radius); canvas.drawPath(mArrowPath, mArrowPaint); drawCompassArrow(canvas, center, mCompassPaint, tipX, tipY, baseX, baseY, Color.RED); drawCompassArrow(canvas, center, mCompassPaint, -tipX, -tipY, baseX, baseY, Color.GRAY); gridPaint.setAlpha(255); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8, center + (sin * blipRadius) - 8, gridPaint); } } private void drawCompassArrow(Canvas canvas, int center, final Paint gridPaint, float tipX, float tipY, float baseX, float baseY, int color) { gridPaint.setStyle(Paint.Style.FILL_AND_STROKE); gridPaint.setColor(color); gridPaint.setAlpha(255); mCompassPath.reset(); mCompassPath.moveTo(center + baseX, center + baseY); mCompassPath.lineTo(center + tipX, center + tipY); mCompassPath.lineTo(center - baseX, center - baseY); mCompassPath.close(); canvas.drawPath(mCompassPath, gridPaint); gridPaint.setStyle(Paint.Style.STROKE); } @Override public void onAccuracyChanged(int sensor, int accuracy) { } /** * Called when we get a new value from the compass * * @see android.hardware.SensorListener#onSensorChanged(int, float[]) */ @Override public void onSensorChanged(int sensor, float[] values) { mOrientation = values[0]; double bearingToTarget = mBearing - mOrientation; // Log.d("GeoBeagle", "bearing, newOrientation, orientation: " + mBearing + ", " // + newOrientation + ", " + mOrientation); updateBearing(bearingToTarget); postInvalidate(); } /** * Called when a location provider has a new location to report * * @see android.location.LocationListener#onLocationChanged(android.location.Location) */ @Override public void onLocationChanged(Location location) { // Log.d("GeoBeagle", "radarview::onLocationChanged"); if (!mHaveLocation) { mHaveLocation = true; } final long now = SystemClock.uptimeMillis(); boolean useLocation = false; final String provider = location.getProvider(); if (LocationManager.GPS_PROVIDER.equals(provider)) { // Use GPS if available mLastGpsFixTime = SystemClock.uptimeMillis(); useLocation = true; } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { // Use network provider if GPS is getting stale useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS; if (mNetworkLocation == null) { mNetworkLocation = new Location(location); } else { mNetworkLocation.set(location); } mLastGpsFixTime = 0L; } if (useLocation) { mMyLocationLat = location.getLatitude(); mMyLocationLon = location.getLongitude(); mMyLocationAccuracy = location.getAccuracy(); mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); updateDistance(mDistance); double bearingToTarget = mBearing - mOrientation; updateBearing(bearingToTarget); } } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } /** * Called when a location provider has changed its availability. * * @see android.location.LocationListener#onStatusChanged(java.lang.String, * int, android.os.Bundle) */ @Override public void onStatusChanged(String provider, int status, Bundle extras) { //Log.d("GeoBeagle", "onStatusChanged " + provider + ", " + status); if (LocationManager.GPS_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mGpsAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mGpsAvailable = false; if (mNetworkLocation != null && mNetworkAvailable) { // Fallback to network location mLastGpsFixTime = 0L; onLocationChanged(mNetworkLocation); } else { handleUnknownLocation(); } break; } } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mNetworkAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mNetworkAvailable = false; if (!mGpsAvailable) { handleUnknownLocation(); } break; } } } /** * Called when we no longer have a valid location. */ public void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(""); mAccuracyView.setText(""); mBearingView.setText(""); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseImperial(boolean useImperial) { mUseMetric = !useImperial; mLastScale = -1; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } private void updateBearing(double bearing) { double peggedBearing = (bearing + 720) % 360; if (mHaveLocation) { final String sBearing = ((int)peggedBearing / 5) * 5 + mDegreesSymbol; mBearingView.setText(sBearing); } } /** * Update our state to reflect a new distance to the target. This may * require choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target * @param bearing */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; String distanceStr = null; String accuracyStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; } final int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; if (mLastScale != i) { mLastScale = i; } mDistanceRatio = (float)(mDistance / scaleChoices[mLastScale]); distanceStr = String.format(format, distanceDisplay); break; } } if (mMyLocationAccuracy != 0.0) accuracyStr = formatDistance(scaleChoices, displayUnitsPerKm, displayFormats); mDistanceView.setText(distanceStr); mAccuracyView.setText("+/-" + accuracyStr); } private String formatDistance(final double[] scaleChoices, final float[] displayUnitsPerKm, final String[] displayFormats) { int count = scaleChoices.length; for (int i = 0; i < count; i++) { final float myLocationAccuracyKm = mMyLocationAccuracy / 1000; if (myLocationAccuracyKm < scaleChoices[i] || i == (count - 1)) { final String format = displayFormats[i]; return String.format(format, myLocationAccuracyKm * displayUnitsPerKm[i]); } } return ""; } }
Java
package com.google.code.geobeagle.activity.compass; import com.google.code.geobeagle.CompassListener; import com.google.code.geobeagle.shakewaker.ShakeWaker; import com.google.inject.Inject; import com.google.inject.Provider; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; class GeoBeagleSensors { private final SensorManager sensorManager; private final RadarView radarView; private final SharedPreferences sharedPreferences; private final CompassListener compassListener; private final ShakeWaker shakeWaker; private final Provider<LocationManager> locationManagerProvider; private final SatelliteCountListener satelliteCountListener; @Inject GeoBeagleSensors(SensorManager sensorManager, RadarView radarView, SharedPreferences sharedPreferences, CompassListener compassListener, ShakeWaker shakeWaker, Provider<LocationManager> locationManagerProvider, SatelliteCountListener satelliteCountListener) { this.sensorManager = sensorManager; this.radarView = radarView; this.sharedPreferences = sharedPreferences; this.compassListener = compassListener; this.shakeWaker = shakeWaker; this.locationManagerProvider = locationManagerProvider; this.satelliteCountListener = satelliteCountListener; } public void registerSensors() { radarView.handleUnknownLocation(); radarView.setUseImperial(sharedPreferences.getBoolean("imperial", false)); sensorManager.registerListener(radarView, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); sensorManager.registerListener(compassListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); locationManagerProvider.get().addGpsStatusListener(satelliteCountListener); shakeWaker.register(); } public void unregisterSensors() { sensorManager.unregisterListener(radarView); sensorManager.unregisterListener(compassListener); shakeWaker.unregister(); locationManagerProvider.get().removeGpsStatusListener(satelliteCountListener); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.LogFindDialogHelper; import com.google.code.geobeagle.activity.map.OnClickListenerMapPage; import com.google.inject.Inject; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; public class CompassActivity extends GuiceActivity { private CompassActivityDelegate compassActivityDelegate; private LogFindDialogHelper logFindDialogHelper; @Inject LocationControlBuffered locationControlBuffered; public Geocache getGeocache() { return compassActivityDelegate.getGeocache(); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "CompassActivity onCreate"); Injector injector = getInjector(); injector.getInstance(CompassFragtivityOnCreateHandler.class).onCreate(this); RadarView radarView = injector.getInstance(RadarView.class); locationControlBuffered.onLocationChanged(null); LocationManager locationManager = injector.getInstance(LocationManager.class); // Register for location updates locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, radarView); locationManager .requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, radarView); compassActivityDelegate = injector.getInstance(CompassActivityDelegate.class); // see http://www.androidguys.com/2008/11/07/rotational-forces-part-two/ if (getLastNonConfigurationInstance() != null) { setIntent((Intent)getLastNonConfigurationInstance()); } OnClickListenerMapPage onClickListenerMapPage = injector .getInstance(OnClickListenerMapPage.class); findViewById(R.id.maps).setOnClickListener(onClickListenerMapPage); injector.getInstance(CompassClickListenerSetter.class).setListeners( new ActivityViewContainer(this), this); logFindDialogHelper = injector.getInstance(LogFindDialogHelper.class); } @Override public boolean onCreateOptionsMenu(Menu menu) { return compassActivityDelegate.onCreateOptionsMenu(menu); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (compassActivityDelegate.onKeyDown(keyCode, event)) return true; return super.onKeyDown(keyCode, event); } @Override public boolean onOptionsItemSelected(MenuItem item) { return compassActivityDelegate.onOptionsItemSelected(item); } @Override public void onPause() { Log.d("GeoBeagle", "CompassActivity onPause"); compassActivityDelegate.onPause(); super.onPause(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); return compassActivityDelegate.onPrepareOptionsMenu(menu); } /* * (non-Javadoc) * @see android.app.Activity#onRetainNonConfigurationInstance() */ @Override public Object onRetainNonConfigurationInstance() { return getIntent(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == CompassActivityDelegate.ACTIVITY_REQUEST_TAKE_PICTURE) { Log.d("GeoBeagle", "camera intent has returned."); } else if (resultCode == Activity.RESULT_OK) setIntent(data); } @Override protected Dialog onCreateDialog(int id) { super.onCreateDialog(id); return logFindDialogHelper.onCreateDialog(this, id); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); logFindDialogHelper.onPrepareDialog(this, id, dialog); } /* * (non-Javadoc) * @see android.app.Activity#onRestoreInstanceState(android.os.Bundle) */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); compassActivityDelegate.onRestoreInstanceState(savedInstanceState); } @Override protected void onResume() { super.onResume(); Log.d("GeoBeagle", "CompassActivity onResume"); compassActivityDelegate.onResume(); } /* * (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); compassActivityDelegate.onSaveInstanceState(outState); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.app.AlertDialog; public class ChooseNavDialog { private final AlertDialog alertDialog; public ChooseNavDialog(AlertDialog alertDialog) { this.alertDialog = alertDialog; } public void show() { alertDialog.show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.compass.GeocacheFromParcelFactory; import com.google.code.geobeagle.activity.compass.view.CheckDetailsButton; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer; import com.google.code.geobeagle.activity.compass.view.WebPageMenuEnabler; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.LocationSaver; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import java.io.File; public class CompassActivityDelegate { static int ACTIVITY_REQUEST_TAKE_PICTURE = 1; private final ActivitySaver activitySaver; private final AppLifecycleManager appLifecycleManager; private final Provider<DbFrontend> dbFrontendProvider; private Geocache geocache; private final GeocacheFactory geocacheFactory; private final GeocacheFromParcelFactory geocacheFromParcelFactory; private final GeocacheViewer geocacheViewer; private final IncomingIntentHandler incomingIntentHandler; private final GeoBeagleActivityMenuActions menuActions; private final CompassActivity parent; private final CheckDetailsButton checkDetailsButton; private final GeoBeagleEnvironment geoBeagleEnvironment; private final WebPageMenuEnabler webPageMenuEnabler; private final LocationSaver locationSaver; private final GeoBeagleSensors geoBeagleSensors; public CompassActivityDelegate(ActivitySaver activitySaver, AppLifecycleManager appLifecycleManager, Activity parent, GeocacheFactory geocacheFactory, GeocacheViewer geocacheViewer, IncomingIntentHandler incomingIntentHandler, GeoBeagleActivityMenuActions menuActions, GeocacheFromParcelFactory geocacheFromParcelFactory, Provider<DbFrontend> dbFrontendProvider, CheckDetailsButton checkDetailsButton, WebPageMenuEnabler webPageMenuEnabler, GeoBeagleEnvironment geoBeagleEnvironment, LocationSaver locationSaver, GeoBeagleSensors geoBeagleSensors) { this.parent = (CompassActivity)parent; this.activitySaver = activitySaver; this.appLifecycleManager = appLifecycleManager; this.menuActions = menuActions; this.geocacheViewer = geocacheViewer; this.geocacheFactory = geocacheFactory; this.incomingIntentHandler = incomingIntentHandler; this.dbFrontendProvider = dbFrontendProvider; this.geocacheFromParcelFactory = geocacheFromParcelFactory; this.geoBeagleEnvironment = geoBeagleEnvironment; this.checkDetailsButton = checkDetailsButton; this.webPageMenuEnabler = webPageMenuEnabler; this.locationSaver = locationSaver; this.geoBeagleSensors = geoBeagleSensors; } @Inject public CompassActivityDelegate(Injector injector) { parent = (CompassActivity)injector.getInstance(Activity.class); activitySaver = injector.getInstance(ActivitySaver.class); appLifecycleManager = injector.getInstance(AppLifecycleManager.class); menuActions = injector.getInstance(GeoBeagleActivityMenuActions.class); geocacheViewer = injector.getInstance(GeocacheViewerFactory.class).create( new ActivityViewContainer(parent)); geocacheFactory = injector.getInstance(GeocacheFactory.class); incomingIntentHandler = injector.getInstance(IncomingIntentHandler.class); dbFrontendProvider = injector.getProvider(DbFrontend.class); geocacheFromParcelFactory = injector.getInstance(GeocacheFromParcelFactory.class); geoBeagleEnvironment = injector.getInstance(GeoBeagleEnvironment.class); checkDetailsButton = injector.getInstance(CheckDetailsButton.class); webPageMenuEnabler = injector.getInstance(WebPageMenuEnabler.class); locationSaver = injector.getInstance(LocationSaver.class); geoBeagleSensors = injector.getInstance(GeoBeagleSensors.class); } public Geocache getGeocache() { return geocache; } private void onCameraStart() { String filename = geoBeagleEnvironment.getExternalStorageDir() + "/GeoBeagle_" + geocache.getId() + DateFormat.format("_yyyy-MM-dd_kk.mm.ss.jpg", System.currentTimeMillis()); Log.d("GeoBeagle", "capturing image to " + filename); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename))); parent.startActivityForResult(intent, CompassActivityDelegate.ACTIVITY_REQUEST_TAKE_PICTURE); } public boolean onCreateOptionsMenu(Menu menu) { return menuActions.onCreateOptionsMenu(menu); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA && event.getRepeatCount() == 0) { onCameraStart(); return true; } return false; } public boolean onOptionsItemSelected(MenuItem item) { return menuActions.act(item.getItemId()); } public void onPause() { appLifecycleManager.onPause(); geoBeagleSensors.unregisterSensors(); activitySaver.save(ActivityType.VIEW_CACHE, geocache); dbFrontendProvider.get().closeDatabase(); } public void onRestoreInstanceState(Bundle savedInstanceState) { geocache = geocacheFromParcelFactory.createFromBundle(savedInstanceState); } public void onResume() { appLifecycleManager.onResume(); geoBeagleSensors.registerSensors(); geocache = incomingIntentHandler.maybeGetGeocacheFromIntent(parent.getIntent(), geocache, locationSaver); // Possible fix for issue 53. if (geocache == null) { geocache = geocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "", CacheType.NULL, 0, 0, 0, true, false); } geocacheViewer.set(geocache); checkDetailsButton.check(geocache); } public void onSaveInstanceState(Bundle outState) { // apparently there are cases where getGeocache returns null, causing // crashes with 0.7.7/0.7.8. if (geocache != null) geocache.saveToBundle(outState); } public void setGeocache(Geocache geocache) { this.geocache = geocache; } public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.string.web_page); item.setVisible(webPageMenuEnabler.shouldEnable(getGeocache())); return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.app.Activity; import android.view.View; public class ActivityViewContainer implements HasViewById { private Activity activity; ActivityViewContainer(Activity activity) { this.activity = activity; } @Override public View findViewById(int id) { return activity.findViewById(id); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.app.Activity; public interface CompassFragtivityOnCreateHandler { public void onCreate(Activity activity); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.view.View; public class ViewViewContainer implements HasViewById { private View view; ViewViewContainer(View view) { this.view = view; } @Override public View findViewById(int id) { return view.findViewById(id); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.compass.GeocacheFromIntentFactory; import com.google.code.geobeagle.database.LocationSaver; import com.google.inject.Inject; import android.content.Intent; public class IncomingIntentHandler { private GeocacheFactory mGeocacheFactory; private GeocacheFromIntentFactory mGeocacheFromIntentFactory; @Inject IncomingIntentHandler(GeocacheFactory geocacheFactory, GeocacheFromIntentFactory geocacheFromIntentFactory) { mGeocacheFactory = geocacheFactory; mGeocacheFromIntentFactory = geocacheFromIntentFactory; } Geocache maybeGetGeocacheFromIntent(Intent intent, Geocache defaultGeocache, LocationSaver locationSaver) { if (intent != null) { final String action = intent.getAction(); if (action != null) { if (action.equals(Intent.ACTION_VIEW) && intent.getType() == null) { return mGeocacheFromIntentFactory.viewCacheFromMapsIntent(intent, locationSaver, defaultGeocache); } else if (action.equals(GeocacheListController.SELECT_CACHE)) { Geocache geocache = intent.<Geocache> getParcelableExtra("geocache"); if (geocache == null) geocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "", CacheType.NULL, 0, 0, 0, true, false); return geocache; } } } return defaultGeocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.actions.MenuActionCacheList; import com.google.code.geobeagle.actions.MenuActionEditGeocache; import com.google.code.geobeagle.actions.MenuActionSettings; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.compass.menuactions.MenuActionWebPage; import com.google.inject.Inject; import com.google.inject.Injector; import android.content.res.Resources; class GeoBeagleActivityMenuActions extends MenuActions { @Inject public GeoBeagleActivityMenuActions(Injector injector) { super(injector.getInstance(Resources.class)); add(new MenuActionBase(R.string.menu_cache_list, injector.getInstance(MenuActionCacheList.class))); add(new MenuActionBase(R.string.menu_edit_geocache, injector.getInstance(MenuActionEditGeocache.class))); add(new MenuActionBase(R.string.menu_settings, injector.getInstance(MenuActionSettings.class))); add(new MenuActionBase(R.string.web_page, injector.getInstance(MenuActionWebPage.class))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.CompassListener; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.CacheListActivityHoneycomb; import com.google.code.geobeagle.activity.compass.view.GeocacheViewer; import com.google.code.geobeagle.shakewaker.ShakeWaker; import com.google.inject.Injector; import android.app.Fragment; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class CompassFragment extends Fragment { private Geocache geocache; private GeoBeagleSensors geoBeagleSensors; public Geocache getGeocache() { return geocache; } public GeoBeagleSensors getGeoBeagleSensors() { return geoBeagleSensors; } @Override public void onResume() { super.onResume(); geoBeagleSensors.registerSensors(); } @Override public void onPause() { super.onPause(); geoBeagleSensors.unregisterSensors(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View inflatedView = inflater.inflate(R.layout.compass, container, false); Bundle arguments = getArguments(); CacheListActivityHoneycomb cacheListActivity = (CacheListActivityHoneycomb)getActivity(); Injector injector = cacheListActivity.getInjector(); GeocacheViewerFactory geocacheViewerFactory = injector .getInstance(GeocacheViewerFactory.class); GeocacheViewer geocacheViewer = geocacheViewerFactory.create(new ViewViewContainer( inflatedView)); GeocacheFromParcelFactory geocacheFromParcelFactory = injector .getInstance(GeocacheFromParcelFactory.class); geocache = geocacheFromParcelFactory.createFromBundle(arguments); geocacheViewer.set(geocache); injector.getInstance(CompassClickListenerSetter.class).setListeners( new ViewViewContainer(inflatedView), cacheListActivity); RadarView radarView = (RadarView)inflatedView.findViewById(R.id.radarview); geoBeagleSensors = new GeoBeagleSensors(injector.getInstance(SensorManager.class), radarView, injector.getInstance(SharedPreferences.class), injector.getInstance(CompassListener.class), injector.getInstance(ShakeWaker.class), injector.getProvider(LocationManager.class), injector.getInstance(SatelliteCountListener.class)); LocationManager locationManager = injector.getInstance(LocationManager.class); // Register for location updates locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, radarView); locationManager .requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, radarView); return inflatedView; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.net.UrlQuerySanitizer; import android.net.UrlQuerySanitizer.ValueSanitizer; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Util { public static final String[] geocachingQueryParam = new String[] { "q" }; // #Wildwood Park, Saratoga, CA(The Nut Case #89882) private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)"); private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)"); private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.,]+)[^\\d]*"); private static final Pattern PAT_LATLON = Pattern .compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)"); private static final Pattern PAT_LATLONDEC = Pattern.compile("([\\d.]+)\\s+([\\d.]+)"); private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]"); private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*"); private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]"); public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) { final double fAbsDegrees = Math.abs(fDegrees); final int dAbsDegrees = (int)fAbsDegrees; return String.format(Locale.US, (fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees, 60.0 * (fAbsDegrees - dAbsDegrees)); } public static double parseCoordinate(CharSequence string) { int sign = 1; Matcher negsignMatcher = PAT_NEGSIGN.matcher(string); if (negsignMatcher.find()) { sign = -1; } Matcher signMatcher = PAT_SIGN.matcher(string); String noSigns = signMatcher.replaceAll(""); Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(noSigns); double degrees = 0.0; for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) { String coordinate = dmsMatcher.group(1); String nocommas = coordinate.replace(',', '.'); degrees += Double.parseDouble(nocommas) / scale; } return sign * degrees; } public static CharSequence[] parseDescription(CharSequence string) { Matcher matcher = PAT_ATLASQUEST.matcher(string); if (matcher.matches()) return new CharSequence[] { "LB" + matcher.group(2).trim(), matcher.group(1).trim() }; return new CharSequence[] { string, "" }; } public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer, ValueSanitizer valueSanitizer) { sanitizer.registerParameters(geocachingQueryParam, valueSanitizer); sanitizer.parseQuery(query); return sanitizer.getValue("q"); } public static CharSequence[] splitCoordsAndDescription(CharSequence location) { Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location); if (matcher.matches()) { return new CharSequence[] { matcher.group(2).trim(), matcher.group(1).trim() }; } matcher = PAT_PAREN_FORMAT.matcher(location); if (matcher.matches()) { return new CharSequence[] { matcher.group(1).trim(), matcher.group(2).trim() }; } // No description. return new CharSequence[] { location, "" }; } public static CharSequence[] splitLatLon(CharSequence string) { Matcher matcherDecimal = PAT_LATLONDEC.matcher(string); if (matcherDecimal.matches()) { return new String[] { matcherDecimal.group(1).trim(), matcherDecimal.group(2).trim() }; } Matcher matcher = PAT_LATLON.matcher(string); if (matcher.matches()) return new String[] { matcher.group(1).trim(), matcher.group(2).trim() }; return null; } public static CharSequence[] splitLatLonDescription(CharSequence location) { CharSequence coordsAndDescription[] = splitCoordsAndDescription(location); CharSequence latLon[] = splitLatLon(coordsAndDescription[0]); CharSequence[] parseDescription = parseDescription(coordsAndDescription[1]); return new CharSequence[] { latLon[0], latLon[1], parseDescription[0], parseDescription[1] }; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.R; import android.app.Activity; class CompassFragmentOnCreateHandler implements CompassFragtivityOnCreateHandler { @Override public void onCreate(Activity activity) { activity.setContentView(R.layout.compass_fragment); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.details.DetailsActivity; import com.google.inject.Inject; import com.google.inject.Injector; import android.app.Activity; import android.content.Intent; import android.view.View; public class OnClickListenerCacheDetails implements View.OnClickListener { private final Activity activity; private final HasGeocache hasGeocache; // For testing. public OnClickListenerCacheDetails(Activity geoBeagle, HasGeocache hasGeocache) { this.activity = geoBeagle; this.hasGeocache = hasGeocache; } @Inject public OnClickListenerCacheDetails(Injector injector) { activity = injector.getInstance(Activity.class); hasGeocache = injector.getInstance(HasGeocache.class); } @Override public void onClick(View v) { Intent intent = new Intent(activity, DetailsActivity.class); Geocache geocache = hasGeocache.get(activity); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_SOURCE, geocache.getSourceName()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID, geocache.getId().toString()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME, geocache.getName().toString()); activity.startActivity(intent); } }
Java
package com.google.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory.Provider; public class WebPageMenuEnabler { public boolean shouldEnable(Geocache geocache) { final Provider contentProvider = geocache.getContentProvider(); return contentProvider == Provider.GROUNDSPEAK || contentProvider == Provider.ATLAS_QUEST || contentProvider == Provider.OPENCACHING; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.database.LocationSaver; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; public class SetButtonOnClickListener implements OnClickListener { private final Activity activity; private final EditCache editCache; private final LocationSaver locationSaver; public SetButtonOnClickListener(Activity activity, EditCache editCache, LocationSaver locationSaver) { this.activity = activity; this.editCache = editCache; this.locationSaver = locationSaver; } @Override public void onClick(View v) { final Geocache geocache = editCache.get(); locationSaver.saveLocation(geocache); final Intent i = new Intent(); i.setAction(GeocacheListController.SELECT_CACHE); i.putExtra("geocache", geocache); activity.setResult(Activity.RESULT_OK, i); activity.finish(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.inject.Inject; import android.app.Activity; import android.view.View; public class CheckDetailsButton { private final View detailsButton; @Inject public CheckDetailsButton(Activity activity) { detailsButton = activity.findViewById(R.id.cache_details); } public void check(Geocache geocache) { detailsButton.setEnabled(geocache.getSourceType() == Source.GPX); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view.install_radar; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; class InstallRadarOnClickListenerPositive implements android.content.DialogInterface.OnClickListener { private final Activity mActivity; @Inject public InstallRadarOnClickListenerPositive(Activity activity) { mActivity = activity; } @Override public void onClick(DialogInterface dialog, int which) { mActivity.startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mActivity .getString(R.string.install_radar_uri)))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view.install_radar; import com.google.code.geobeagle.OnClickListenerNOP; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.app.AlertDialog; import android.app.AlertDialog.Builder; public class InstallRadarAppDialog { private final Builder dialogBuilder; private final OnClickListenerNOP onClickListenerNOP; private final InstallRadarOnClickListenerPositive onClickListenerPositive; @Inject InstallRadarAppDialog(AlertDialog.Builder dialogBuilder, InstallRadarOnClickListenerPositive onClickListenerPositive, OnClickListenerNOP onClickListenerNOP) { this.dialogBuilder = dialogBuilder; this.onClickListenerPositive = onClickListenerPositive; this.onClickListenerNOP = onClickListenerNOP; } public void showInstallRadarDialog() { dialogBuilder.setMessage(R.string.ask_install_radar_app); dialogBuilder.setPositiveButton(R.string.install_radar, onClickListenerPositive); dialogBuilder.setNegativeButton(R.string.cancel, onClickListenerNOP); dialogBuilder.create().show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.database.LocationSaver; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; import android.widget.Button; import android.widget.EditText; public class EditCacheActivityDelegate { private final CancelButtonOnClickListener cancelButtonOnClickListener; private final GeocacheFactory geocacheFactory; private final LocationSaver locationSaver; private final Activity parent; @Inject public EditCacheActivityDelegate(Activity parent, CancelButtonOnClickListener cancelButtonOnClickListener, GeocacheFactory geocacheFactory, LocationSaver locationSaver) { this.parent = parent; this.cancelButtonOnClickListener = cancelButtonOnClickListener; this.geocacheFactory = geocacheFactory; this.locationSaver = locationSaver; } public void onCreate() { parent.setContentView(R.layout.cache_edit); } public void onPause() { } public void onResume() { final Intent intent = parent.getIntent(); final Geocache geocache = intent.<Geocache> getParcelableExtra("geocache"); final EditCache editCache = new EditCache(geocacheFactory, (EditText)parent .findViewById(R.id.edit_id), (EditText)parent.findViewById(R.id.edit_name), (EditText)parent.findViewById(R.id.edit_latitude), (EditText)parent .findViewById(R.id.edit_longitude)); editCache.set(geocache); final SetButtonOnClickListener setButtonOnClickListener = new SetButtonOnClickListener( parent, editCache, locationSaver); ((Button)parent.findViewById(R.id.edit_set)).setOnClickListener(setButtonOnClickListener); ((Button)parent.findViewById(R.id.edit_cancel)) .setOnClickListener(cancelButtonOnClickListener); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.activity.compass.Util; import android.widget.EditText; public class EditCache { private final GeocacheFactory geocacheFactory; private final EditText id; private final EditText latitude; private final EditText longitude; private final EditText name; private Geocache mOriginalGeocache; public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name, EditText latitude, EditText longitude) { this.geocacheFactory = geocacheFactory; this.id = id; this.name = name; this.latitude = latitude; this.longitude = longitude; } Geocache get() { return geocacheFactory.create(id.getText(), name.getText(), Util.parseCoordinate(latitude.getText()), Util.parseCoordinate(longitude.getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache.getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache.getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache.getContainer(), mOriginalGeocache.getAvailable(), mOriginalGeocache.getArchived()); } void set(Geocache geocache) { mOriginalGeocache = geocache; id.setText(geocache.getId()); name.setText(geocache.getName()); latitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude())); longitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude())); latitude.requestFocus(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.activity.compass.IntentStarterRadar; import com.google.code.geobeagle.activity.compass.view.install_radar.InstallRadarAppDialog; import com.google.inject.Inject; import android.content.ActivityNotFoundException; import android.view.View; import android.view.View.OnClickListener; public class OnClickListenerRadar implements OnClickListener { private final IntentStarterRadar intentStarterRadar; private final InstallRadarAppDialog installRadarAppDialog; @Inject OnClickListenerRadar(IntentStarterRadar intentStarterRadar, InstallRadarAppDialog installRadarAppDialog) { this.intentStarterRadar = intentStarterRadar; this.installRadarAppDialog = installRadarAppDialog; } @Override public void onClick(View arg0) { try { intentStarterRadar.startIntent(); } catch (final ActivityNotFoundException e) { installRadarAppDialog.showInstallRadarDialog(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.intents.IntentStarter; import android.content.ActivityNotFoundException; import android.view.View; import android.view.View.OnClickListener; public class OnClickListenerIntentStarter implements OnClickListener { private final IntentStarter mIntentStarter; private final ErrorDisplayer mErrorDisplayer; public OnClickListenerIntentStarter(IntentStarter intentStarter, ErrorDisplayer errorDisplayer) { mIntentStarter = intentStarter; mErrorDisplayer = errorDisplayer; } @Override public void onClick(View view) { try { mIntentStarter.startIntent(); } catch (final ActivityNotFoundException e) { mErrorDisplayer.displayError(R.string.error1, e.getMessage()); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlay; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.MapViewBitmapCopier; import com.google.code.geobeagle.activity.cachelist.view.NameFormatter; import com.google.code.geobeagle.activity.compass.GeoUtils; import com.google.code.geobeagle.activity.compass.RadarView; import com.google.inject.Inject; import com.google.inject.name.Named; import android.app.Activity; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class GeocacheViewer { public interface AttributeViewer { void setImage(int attributeValue); } public static class LabelledAttributeViewer implements AttributeViewer { private final AttributeViewer unlabelledAttributeViewer; private final TextView label; public LabelledAttributeViewer(TextView label, AttributeViewer unlabelledAttributeViewer) { this.unlabelledAttributeViewer = unlabelledAttributeViewer; this.label = label; } @Override public void setImage(int attributeValue) { unlabelledAttributeViewer.setImage(attributeValue); label.setVisibility(attributeValue == 0 ? View.GONE : View.VISIBLE); } } public static class UnlabelledAttributeViewer implements AttributeViewer { private final Drawable[] drawables; private final ImageView imageView; public UnlabelledAttributeViewer(ImageView imageView, Drawable[] drawables) { this.imageView = imageView; this.drawables = drawables; } @Override public void setImage(int attributeValue) { if (attributeValue == 0) { imageView.setVisibility(View.GONE); return; } imageView.setImageDrawable(drawables[attributeValue-1]); imageView.setVisibility(View.VISIBLE); } } public static class ResourceImages implements AttributeViewer { private final List<Integer> resources; private final ImageView imageView; private final TextView label; public ResourceImages(TextView label, ImageView imageView, List<Integer> resources) { this.label = label; this.imageView = imageView; this.resources = resources; } @Override public void setImage(int attributeValue) { imageView.setImageResource(resources.get(attributeValue)); } public void setVisibility(int visibility) { imageView.setVisibility(visibility); label.setVisibility(visibility); } } public static class NameViewer { private final TextView name; private final NameFormatter nameFormatter; @Inject public NameViewer(@Named("GeocacheName") TextView name, NameFormatter nameFormatter) { this.name = name; this.nameFormatter = nameFormatter; } void set(CharSequence name, boolean available, boolean archived) { if (name.length() == 0) { this.name.setVisibility(View.GONE); return; } this.name.setText(name); this.name.setVisibility(View.VISIBLE); nameFormatter.format(this.name, available, archived); } } public static final Integer CONTAINER_IMAGES[] = { R.drawable.size_0, R.drawable.size_1, R.drawable.size_2, R.drawable.size_3, R.drawable.size_4, R.drawable.size_5 }; private final ImageView cacheTypeImageView; private final ResourceImages container; private final AttributeViewer difficulty; private final NameViewer name; private final RadarView radarView; private final AttributeViewer terrain; private final IconOverlayFactory iconOverlayFactory; private final MapViewBitmapCopier mapViewBitmapCopier; private final IconRenderer iconRenderer; private final Activity activity; private final DifficultyAndTerrainPainter difficultyAndTerrainPainter; public GeocacheViewer(RadarView radarView, Activity activity, NameViewer gcName, ImageView cacheTypeImageView, AttributeViewer gcDifficulty, AttributeViewer gcTerrain, ResourceImages gcContainer, IconOverlayFactory iconOverlayFactory, MapViewBitmapCopier mapViewBitmapCopier, IconRenderer iconRenderer, DifficultyAndTerrainPainter difficultyAndTerrainPainter) { this.radarView = radarView; this.activity = activity; this.name = gcName; this.cacheTypeImageView = cacheTypeImageView; this.difficulty = gcDifficulty; this.terrain = gcTerrain; this.container = gcContainer; this.iconOverlayFactory = iconOverlayFactory; this.mapViewBitmapCopier = mapViewBitmapCopier; this.iconRenderer = iconRenderer; this.difficultyAndTerrainPainter = difficultyAndTerrainPainter; } public void set(Geocache geocache) { double latitude = geocache.getLatitude(); double longitude = geocache.getLongitude(); radarView.setTarget((int)(latitude * GeoUtils.MILLION), (int)(longitude * GeoUtils.MILLION)); activity.setTitle("GeoBeagle: " + geocache.getId()); IconOverlay iconOverlay = iconOverlayFactory.create(geocache, true); int iconBig = geocache.getCacheType().iconBig(); Drawable icon = iconRenderer.renderIcon(0, 0, iconBig, iconOverlay, mapViewBitmapCopier, difficultyAndTerrainPainter); cacheTypeImageView.setImageDrawable(icon); int container = geocache.getContainer(); this.container.setVisibility(container == 0 ? View.GONE : View.VISIBLE); this.container.setImage(container); difficulty.setImage(geocache.getDifficulty()); terrain.setImage(geocache.getTerrain()); name.set(geocache.getName(), geocache.getAvailable(), geocache.getArchived()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.view; import com.google.inject.Inject; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; public class CancelButtonOnClickListener implements OnClickListener { private final Activity activity; @Inject public CancelButtonOnClickListener(Activity activity) { this.activity = activity; } @Override public void onClick(View v) { activity.setResult(Activity.RESULT_CANCELED, null); activity.finish(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.intents.IntentStarterGeo; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class IntentStarterRadar extends IntentStarterGeo { @Inject IntentStarterRadar(Activity geoBeagle, HasGeocache hasGeocache) { super(geoBeagle, new Intent("com.google.android.radar.SHOW_RADAR"), hasGeocache); } }
Java
/* * Copyright (C) 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.code.geobeagle.activity.compass; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ // // public static double distanceKm(GeoPoint p1, GeoPoint p2) { // double lat1 = p1.getLatitudeE6() / (double)MILLION; // double lon1 = p1.getLongitudeE6() / (double)MILLION; // double lat2 = p2.getLatitudeE6() / (double)MILLION; // double lon2 = p2.getLongitudeE6() / (double)MILLION; // // return distanceKm(lat1, lon1, lat2, lon2); // } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ // public static double bearing(GeoPoint p1, GeoPoint p2) { // double lat1 = p1.getLatitudeE6() / (double) MILLION; // double lon1 = p1.getLongitudeE6() / (double) MILLION; // double lat2 = p2.getLatitudeE6() / (double) MILLION; // double lon2 = p2.getLongitudeE6() / (double) MILLION; // // return bearing(lat1, lon1, lat2, lon2); // } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.intents.GeocacheToCachePage; import com.google.code.geobeagle.activity.compass.intents.IntentStarterViewUri; import com.google.inject.Inject; import com.google.inject.Injector; import android.app.Activity; public class IntentStarterViewCachePage extends IntentStarterViewUri { @Inject public IntentStarterViewCachePage(Injector injector) { super(injector.getInstance(Activity.class), injector.getInstance(GeocacheToCachePage.class), injector .getInstance(ErrorDisplayer.class), injector.getInstance(HasGeocache.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.cacheloader.CacheLoaderException; public interface GeocacheToUri { public String convert(Geocache geocache) throws CacheLoaderException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.cacheloader.CacheLoaderException; import com.google.inject.Inject; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; public class IntentStarterViewUri implements IntentStarter { private final Activity activity; private final GeocacheToUri geocacheToUri; private final ErrorDisplayer errorDisplayer; private final HasGeocache hasGeocache; @Inject public IntentStarterViewUri(Activity geoBeagle, GeocacheToUri geocacheToUri, ErrorDisplayer errorDisplayer, HasGeocache hasGeocache) { this.activity = geoBeagle; this.geocacheToUri = geocacheToUri; this.errorDisplayer = errorDisplayer; this.hasGeocache = hasGeocache; } @Override public void startIntent() { try { String uri = geocacheToUri.convert(hasGeocache.get(activity)); try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri))); } catch (ActivityNotFoundException e) { errorDisplayer.displayError(R.string.no_intent_handler, uri); } } catch (CacheLoaderException e) { errorDisplayer.displayError(e.getError(), e.getArgs()); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; import com.google.code.geobeagle.Geocache; import com.google.inject.Provider; import android.content.res.Resources; import java.net.URLEncoder; import java.util.Locale; public class GeocacheToGoogleGeo implements GeocacheToUri { private final Provider<Resources> mResourcesProvider; private final int mIntent; public GeocacheToGoogleGeo(Provider<Resources> contextProvider, int intent) { mResourcesProvider = contextProvider; mIntent = intent; } /* * (non-Javadoc) * @see * com.google.code.geobeagle.activity.main.intents.GeocacheToUri#convert * (com.google.code.geobeagle.Geocache) */ public String convert(Geocache geocache) { // "geo:%1$.5f,%2$.5f?name=cachename" String idAndName = geocache.getIdAndName().toString(); idAndName = idAndName.replace("(", "["); idAndName = idAndName.replace(")", "]"); idAndName = URLEncoder.encode(idAndName); final String format = String.format(Locale.US, mResourcesProvider.get().getString(mIntent), geocache.getLatitude(), geocache.getLongitude(), idAndName); return format; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import android.app.Activity; import android.content.Intent; public class IntentStarterGeo implements IntentStarter { private final Activity geoBeagle; private final Intent intent; private final HasGeocache hasGeocache; public IntentStarterGeo(Activity geoBeagle, Intent intent, HasGeocache hasGeocache) { this.geoBeagle = geoBeagle; this.intent = intent; this.hasGeocache = hasGeocache; } @Override public void startIntent() { Geocache geocache = hasGeocache.get(geoBeagle); intent.putExtra("latitude", (float)geocache.getLatitude()); intent.putExtra("longitude", (float)geocache.getLongitude()); geoBeagle.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.R; import com.google.code.geobeagle.cacheloader.CacheLoader; import com.google.code.geobeagle.cacheloader.CacheLoaderException; import com.google.code.geobeagle.cacheloader.CacheLoaderFactory; import com.google.code.geobeagle.xmlimport.CacheXmlTagsToUrl; import com.google.inject.Inject; import android.content.res.Resources; /* * Convert a Geocache to the cache page url. */ public class GeocacheToCachePage implements GeocacheToUri { private final CacheLoader cacheLoader; private final Resources resources; // for testing public GeocacheToCachePage(CacheLoader cacheLoader, Resources resources) { this.cacheLoader = cacheLoader; this.resources = resources; } @Inject public GeocacheToCachePage(Resources resources, CacheXmlTagsToUrl cacheXmlTagsToUrl, CacheLoaderFactory cacheLoaderFactory) { cacheLoader = cacheLoaderFactory.create(cacheXmlTagsToUrl); this.resources = resources; } @Override public String convert(Geocache geocache) throws CacheLoaderException { if (geocache.getSourceType() == Source.GPX) { return cacheLoader.load(geocache.getId()); } return String.format(resources.getStringArray(R.array.cache_page_url)[geocache .getContentProvider().toInt()], geocache.getShortId()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.intents; public interface IntentStarter { public abstract void startIntent(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.R; import com.google.code.geobeagle.R.id; import com.google.code.geobeagle.activity.compass.view.OnClickListenerCacheDetails; import com.google.code.geobeagle.activity.map.OnClickListenerMapPage; import com.google.inject.Inject; import android.app.Activity; class CompassClickListenerSetter { private final OnClickListenerCacheDetails onClickListenerCacheDetails; private final OnClickListenerNavigate onClickListenerNavigate; private final OnClickListenerMapPage onClickListenerMapPage; @Inject public CompassClickListenerSetter(OnClickListenerCacheDetails onClickListenerCacheDetails, OnClickListenerNavigate onClickListenerNavigate, OnClickListenerMapPage onClickListenerMapPage) { this.onClickListenerCacheDetails = onClickListenerCacheDetails; this.onClickListenerNavigate = onClickListenerNavigate; this.onClickListenerMapPage = onClickListenerMapPage; } void setListeners(HasViewById hasViewById, Activity activity) { hasViewById.findViewById(R.id.cache_details) .setOnClickListener(onClickListenerCacheDetails); hasViewById.findViewById(id.navigate).setOnClickListener(onClickListenerNavigate); hasViewById.findViewById(id.menu_log_find).setOnClickListener( new LogFindClickListener(activity, id.menu_log_find)); hasViewById.findViewById(id.menu_log_dnf).setOnClickListener( new LogFindClickListener(activity, id.menu_log_dnf)); hasViewById.findViewById(R.id.maps).setOnClickListener(onClickListenerMapPage); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.R; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.ProvisionException; import android.app.Activity; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationManager; import android.util.Log; import android.widget.TextView; class SatelliteCountListener implements GpsStatus.Listener { private final Provider<LocationManager> locationManagerProvider; private final Provider<Activity> activityProvider; @Inject SatelliteCountListener(Provider<Activity> activityProvider, Provider<LocationManager> locationManagerProvider) { this.locationManagerProvider = locationManagerProvider; this.activityProvider = activityProvider; } @Override public void onGpsStatusChanged(int event) { try { GpsStatus gpsStatus = locationManagerProvider.get().getGpsStatus(null); int satelliteCount = 0; for (@SuppressWarnings("unused") GpsSatellite gpsSatellite : gpsStatus.getSatellites()) { satelliteCount++; } ((TextView)activityProvider.get().findViewById(R.id.satellite_count)) .setText(satelliteCount + " SATs"); } catch (ProvisionException e) { Log.d("GeoBeagle", "ignoring provision exception in satellite count listener"); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; public class LogFindClickListener implements OnClickListener { private final Activity activity; private final int idDialog; LogFindClickListener(Activity activity, int idDialog) { this.activity = activity; this.idDialog = idDialog; } @Override public void onClick(View v) { activity.showDialog(idDialog); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.inject.Inject; import android.content.res.Resources; public class FieldnoteStringsFVsDnf { private final Resources mResources; @Inject public FieldnoteStringsFVsDnf(Resources resources) { mResources = resources; } String getString(int id, boolean dnf) { return mResources.getStringArray(id)[dnf ? 0 : 1]; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.database.Tag; import com.google.code.geobeagle.database.TagWriter; import com.google.inject.Inject; public class DatabaseLogger { private final TagWriter mTagWriter; @Inject DatabaseLogger(TagWriter tagWriter) { mTagWriter = tagWriter; } public void log(CharSequence geocacheId, boolean dnf) { if (dnf) mTagWriter.add(geocacheId, Tag.DNF, true); else mTagWriter.add(geocacheId, Tag.FOUND, true); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.inject.Inject; import android.content.Context; import android.widget.Toast; public class Toaster { private final Context context; @Inject Toaster(Context context) { this.context = context; } public void toast(int resource, int duration) { Toast.makeText(context, resource, duration).show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; import android.widget.Toast; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Date; /** * Writes lines formatted like: * * <pre> * GC1FX1A,2008-09-27T21:04Z, Found it,&quot;log text&quot; * </pre> */ public class FileLogger implements ICacheLogger { private final Toaster mToaster; private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; private final DateFormatter mSimpleDateFormat; private final GeoBeagleEnvironment mGeoBeagleEnvironment; @Inject public FileLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, DateFormatter simpleDateFormat, Toaster toaster, GeoBeagleEnvironment geoBeagleEnvironment) { mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; mSimpleDateFormat = simpleDateFormat; mToaster = toaster; mGeoBeagleEnvironment = geoBeagleEnvironment; } @Override public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { try { OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream( mGeoBeagleEnvironment.getFieldNotesFilename(), true), "UTF-16"); final Date date = new Date(); final String formattedDate = mSimpleDateFormat.format(date); final String logLine = String.format("%1$s,%2$s,%3$s,\"%4$s\"\n", geocacheId, formattedDate, mFieldnoteStringsFVsDnf.getString(R.array.fieldnote_file_code, dnf), logText.toString()); writer.write(logLine); writer.close(); } catch (IOException e) { mToaster.toast(R.string.error_writing_cache_log, Toast.LENGTH_LONG); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; public class SmsLogger implements ICacheLogger { private final Context context; private final ErrorDisplayer errorDisplayer; private final FieldnoteStringsFVsDnf fieldNoteStringsFoundVsDnf; @Inject public SmsLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, Context context, ErrorDisplayer errorDisplayer) { this.fieldNoteStringsFoundVsDnf = fieldnoteStringsFVsDnf; this.context = context; this.errorDisplayer = errorDisplayer; } @Override public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("address", "41411"); sendIntent.putExtra("sms_body", fieldNoteStringsFoundVsDnf.getString(R.array.fieldnote_code, dnf) + geocacheId + " " + logText); sendIntent.setType("vnd.android-dir/mms-sms"); try { context.startActivity(sendIntent); } catch (ActivityNotFoundException e) { errorDisplayer.displayError(R.string.sms_fail); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import android.app.Dialog; import android.widget.EditText; import android.widget.TextView; public interface DialogHelper { public abstract void configureEditor(EditText fieldNote); public abstract void configureDialogText(Dialog dialog, TextView fieldnoteCaveat); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.text.util.Linkify; import android.widget.EditText; import android.widget.TextView; public class DialogHelperCommon { private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; @Inject public DialogHelperCommon(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf) { mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; } public void configureDialogText(TextView fieldNoteCaveat) { Linkify.addLinks(fieldNoteCaveat, Linkify.WEB_URLS); } public void configureEditor(EditText editText, String localDate, boolean dnf) { final String defaultMessage = mFieldnoteStringsFVsDnf.getString(R.array.default_msg, dnf); final String msg = String.format("(%1$s/%2$s) %3$s", localDate, mFieldnoteStringsFVsDnf .getString(R.array.geobeagle_sig, dnf), defaultMessage); editText.setText(msg); final int len = msg.length(); editText.setSelection(len - defaultMessage.length(), len); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.R; import android.app.Dialog; import android.text.InputFilter; import android.text.InputFilter.LengthFilter; import android.widget.EditText; import android.widget.TextView; public class DialogHelperSms implements DialogHelper { private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; private final int mGeocacheIdLength; private final boolean mFDnf; public DialogHelperSms(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, int geocacheIdLength, boolean fDnf) { mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; mGeocacheIdLength = geocacheIdLength; mFDnf = fDnf; } @Override public void configureEditor(EditText fieldNote) { final LengthFilter lengthFilter = new LengthFilter( 160 - (mGeocacheIdLength + 1 + mFieldnoteStringsFVsDnf.getString( R.array.fieldnote_code, mFDnf).length())); fieldNote.setFilters(new InputFilter[] { lengthFilter }); } @Override public void configureDialogText(Dialog dialog, TextView fieldnoteCaveat) { fieldnoteCaveat.setText(R.string.sms_caveat); dialog.setTitle(R.string.log_cache_with_sms); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.R; import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.SharedPreferences; import android.widget.EditText; import android.widget.TextView; public class FieldnoteLogger { public static class OnClickOk implements OnClickListener { private final CacheLogger mCacheLogger; private final boolean mDnf; private final EditText mEditText; private final CharSequence mGeocacheId; public OnClickOk(CharSequence geocacheId, EditText editText, CacheLogger cacheLogger, boolean dnf) { mGeocacheId = geocacheId; mEditText = editText; mCacheLogger = cacheLogger; mDnf = dnf; } @Override public void onClick(DialogInterface arg0, int arg1) { mCacheLogger.log(mGeocacheId, mEditText.getText(), mDnf); } } private final DialogHelperCommon mDialogHelperCommon; private final DialogHelperFile mDialogHelperFile; private final DialogHelperSms mDialogHelperSms; private final SharedPreferences mSharedPreferences; @Inject public FieldnoteLogger(DialogHelperCommon dialogHelperCommon, DialogHelperFile dialogHelperFile, @Assisted DialogHelperSms dialogHelperSms, SharedPreferences sharedPreferences) { mDialogHelperSms = dialogHelperSms; mDialogHelperFile = dialogHelperFile; mDialogHelperCommon = dialogHelperCommon; mSharedPreferences = sharedPreferences; } public void onPrepareDialog(Dialog dialog, String localDate, boolean dnf) { final boolean fieldNoteTextFile = mSharedPreferences.getBoolean("field-note-text-file", false); DialogHelper dialogHelper = fieldNoteTextFile ? mDialogHelperFile : mDialogHelperSms; TextView fieldnoteCaveat = ((TextView)dialog.findViewById(R.id.fieldnote_caveat)); dialogHelper.configureDialogText(dialog, fieldnoteCaveat); EditText editText = ((EditText)dialog.findViewById(R.id.fieldnote)); mDialogHelperCommon.configureDialogText(fieldnoteCaveat); dialogHelper.configureEditor(editText); mDialogHelperCommon.configureEditor(editText, localDate, dnf); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatter { private static DateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); String format(Date date) { return mDateFormat.format(date); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; interface ICacheLogger { public void log(CharSequence geocacheId, CharSequence logText, boolean dnf); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.CompassFragment; import android.app.Activity; public class FragmentWithGeocache implements HasGeocache { @Override public Geocache get(Activity activity) { CompassFragment fragment = (CompassFragment)activity.getFragmentManager().findFragmentById( R.id.compass_frame); return fragment.getGeocache(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.inject.Inject; import android.content.SharedPreferences; public class CacheLogger implements ICacheLogger { private final FileLogger mFileLogger; private final SharedPreferences mSharedPreferences; private final SmsLogger mSmsLogger; private final DatabaseLogger mDatabaseLogger; @Inject public CacheLogger(SharedPreferences sharedPreferences, FileLogger fileLogger, SmsLogger smsLogger, DatabaseLogger databaseLogger) { mSharedPreferences = sharedPreferences; mFileLogger = fileLogger; mSmsLogger = smsLogger; mDatabaseLogger = databaseLogger; } @Override public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { final boolean fFieldNoteTextFile = mSharedPreferences.getBoolean( "field-note-text-file", false); mDatabaseLogger.log(geocacheId, dnf); if (fFieldNoteTextFile) mFileLogger.log(geocacheId, logText, dnf); else mSmsLogger.log(geocacheId, logText, dnf); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.inject.Inject; import android.app.Dialog; import android.content.Context; import android.widget.EditText; import android.widget.TextView; public class DialogHelperFile implements DialogHelper { private final Context mContext; private final GeoBeagleEnvironment mGeoBeagleEnvironment; @Inject public DialogHelperFile(Context context, GeoBeagleEnvironment geoBeagleEnvironment) { mContext = context; mGeoBeagleEnvironment = geoBeagleEnvironment; } @Override public void configureEditor(EditText fieldNote) { } @Override public void configureDialogText(Dialog dialog, TextView fieldnoteCaveat) { fieldnoteCaveat.setText(String.format(mContext.getString(R.string.field_note_file_caveat), mGeoBeagleEnvironment.getFieldNotesFilename())); dialog.setTitle(R.string.log_cache_to_file); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.compass.CompassActivity; import android.app.Activity; public class ActivityWithGeocache implements HasGeocache { @Override public Geocache get(Activity activity) { return ((CompassActivity)activity).getGeocache(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.fieldnotes; import com.google.code.geobeagle.Geocache; import android.app.Activity; public interface HasGeocache { Geocache get(Activity activity); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.location.LocationLifecycleManager; import com.google.inject.Inject; import android.content.SharedPreferences; import android.location.LocationManager; public class AppLifecycleManager { private final LifecycleManager[] lifecycleManagers; private final SharedPreferences sharedPreferences; @Inject AppLifecycleManager(SharedPreferences preferences, LocationControlBuffered locationControlBuffered, LocationManager locationManager, RadarView radarView) { this.lifecycleManagers = new LifecycleManager[] { new LocationLifecycleManager(locationControlBuffered, locationManager), new LocationLifecycleManager(radarView, locationManager) }; sharedPreferences = preferences; } AppLifecycleManager(SharedPreferences sharedPreferences, LifecycleManager[] lifecycleManagers) { this.sharedPreferences = sharedPreferences; this.lifecycleManagers = lifecycleManagers; } public void onPause() { final SharedPreferences.Editor editor = sharedPreferences.edit(); for (LifecycleManager lifecycleManager : lifecycleManagers) { lifecycleManager.onPause(editor); } editor.commit(); } public void onResume() { for (LifecycleManager lifecycleManager : lifecycleManagers) { lifecycleManager.onResume(sharedPreferences); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.inject.Inject; import android.view.View; import android.view.View.OnClickListener; class OnClickListenerNavigate implements OnClickListener { private final ChooseNavDialog chooseNavDialog; @Inject OnClickListenerNavigate(ChooseNavDialog chooseNavDialog) { this.chooseNavDialog = chooseNavDialog; } @Override public void onClick(View v) { chooseNavDialog.show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import com.google.code.geobeagle.Refresher; public class NullRefresher implements Refresher { @Override public void refresh() { } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.view.View; public interface HasViewById { View findViewById(int id); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public interface LifecycleManager { public abstract void onPause(Editor editor); public abstract void onResume(SharedPreferences preferences); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR 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.code.geobeagle.activity.compass.menuactions; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.activity.compass.IntentStarterViewCachePage; import com.google.inject.Inject; import com.google.inject.Injector; public class MenuActionWebPage implements Action { private final IntentStarterViewCachePage intentStarterViewCachePage; @Inject public MenuActionWebPage(Injector injector) { this.intentStarterViewCachePage = injector.getInstance(IntentStarterViewCachePage.class); } @Override public void act() { intentStarterViewCachePage.startIntent(); } }
Java