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.activity.compass.menuactions; import com.google.code.geobeagle.activity.compass.intents.IntentStarter; import com.google.code.geobeagle.activity.compass.view.install_radar.InstallRadarAppDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; public class NavigateOnClickListener implements DialogInterface.OnClickListener { private final IntentStarter[] intentStarters; private final InstallRadarAppDialog installRadarAppDialog; public NavigateOnClickListener(IntentStarter[] intentStarters, InstallRadarAppDialog installRadarAppDialog) { this.intentStarters = intentStarters; this.installRadarAppDialog = installRadarAppDialog; } @Override public void onClick(DialogInterface dialog, int which) { try { intentStarters[which].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; import com.google.code.geobeagle.R; import android.app.Activity; class CompassActivityOnCreateHandler implements CompassFragtivityOnCreateHandler { @Override public void onCreate(Activity activity) { activity.setContentView(R.layout.compass); } }
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.details; import com.google.code.geobeagle.R; import com.google.code.geobeagle.shakewaker.ShakeWaker; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.os.Bundle; import android.webkit.WebView; public class DetailsActivity extends GuiceActivity { private DetailsWebView detailsWebView; private ShakeWaker shakeWaker; public static final String INTENT_EXTRA_GEOCACHE_SOURCE = "geocache_source"; public static final String INTENT_EXTRA_GEOCACHE_ID = "geocache_id"; public static final String INTENT_EXTRA_GEOCACHE_NAME = "geocache_name"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.details); Injector injector = getInjector(); shakeWaker = injector.getInstance(ShakeWaker.class); detailsWebView = injector.getInstance(DetailsWebView.class); setTitle(detailsWebView.loadDetails((WebView)findViewById(R.id.cache_details), getIntent())); } @Override public void onPause() { super.onPause(); shakeWaker.unregister(); } @Override public void onResume() { super.onResume(); shakeWaker.register(); } }
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.details; import com.google.code.geobeagle.cacheloader.CacheLoader; import com.google.code.geobeagle.cacheloader.CacheLoaderFactory; import com.google.code.geobeagle.xmlimport.CacheXmlTagsToDetails; import com.google.inject.Inject; import com.google.inject.Injector; import android.content.Intent; import android.webkit.WebView; class DetailsWebView { private final CacheLoader cacheLoader; DetailsWebView(CacheLoader cacheLoader) { this.cacheLoader = cacheLoader; } @Inject DetailsWebView(Injector injector) { CacheLoaderFactory cacheLoaderFactory = injector.getInstance(CacheLoaderFactory.class); CacheXmlTagsToDetails cacheXmlTagsToDetails = injector.getInstance(CacheXmlTagsToDetails.class); cacheLoader = cacheLoaderFactory.create(cacheXmlTagsToDetails); } String loadDetails(WebView webView, Intent intent) { webView.getSettings().setJavaScriptEnabled(true); String id = intent.getStringExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID); webView.loadDataWithBaseURL(null, cacheLoader.load(id), "text/html", "utf-8", null); return id + ": " + intent.getStringExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME); } }
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.searchonline; import com.google.code.geobeagle.CacheListActivityStarter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class SearchOnlineActivity extends GuiceActivity { private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate; private UpdateGpsWidgetRunnable mUpdateGpsWidgetRunnable; private CacheListActivityStarter mCacheListActivityStarter; SearchOnlineActivityDelegate getMSearchOnlineActivityDelegate() { return mSearchOnlineActivityDelegate; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); Log.d("GeoBeagle", "SearchOnlineActivity onCreate"); Injector injector = this.getInjector(); final InflatedGpsStatusWidget mInflatedGpsStatusWidget = injector .getInstance(InflatedGpsStatusWidget.class); GpsStatusWidgetDelegate gpsStatusWidgetDelegate = injector .getInstance(GpsStatusWidgetDelegate.class); mUpdateGpsWidgetRunnable = injector.getInstance(UpdateGpsWidgetRunnable.class); mInflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate); mInflatedGpsStatusWidget.setBackgroundColor(Color.BLACK); mSearchOnlineActivityDelegate = injector.getInstance(SearchOnlineActivityDelegate.class); mSearchOnlineActivityDelegate.configureWebView(); mCacheListActivityStarter = injector.getInstance(CacheListActivityStarter.class); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_online_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); mCacheListActivityStarter.start(); return true; } @Override protected void onPause() { Log.d("GeoBeagle", "SearchOnlineActivity onPause"); mSearchOnlineActivityDelegate.onPause(); // Must call super so that context scope is cleared only after listeners // are removed. super.onPause(); } @Override protected void onResume() { super.onResume(); Log.d("GeoBeagle", "SearchOnlineActivity onResume"); mSearchOnlineActivityDelegate.onResume(); mUpdateGpsWidgetRunnable.run(); } }
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.searchonline; import com.google.code.geobeagle.CompassListener; import com.google.code.geobeagle.LocationControlBuffered; 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.cachelist.ActivityVisible; import com.google.code.geobeagle.location.CombinedLocationListener; import com.google.code.geobeagle.location.CombinedLocationManager; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.Activity; import android.graphics.Color; import android.hardware.SensorManager; import android.webkit.WebSettings; import android.webkit.WebView; public class SearchOnlineActivityDelegate { private final ActivitySaver mActivitySaver; private final CombinedLocationListener mCombinedLocationListener; private final CombinedLocationManager mCombinedLocationManager; private final Provider<CompassListener> mCompassListenerProvider; private final LocationControlBuffered mLocationControlBuffered; private final SensorManager mSensorManager; private final WebView mWebView; private final ActivityVisible mActivityVisible; private final JsInterface mJsInterface; @Inject public SearchOnlineActivityDelegate(Activity activity, SensorManager sensorManager, Provider<CompassListener> compassListenerProvider, CombinedLocationManager combinedLocationManager, CombinedLocationListener combinedLocationListener, LocationControlBuffered locationControlBuffered, ActivitySaver activitySaver, ActivityVisible activityVisible, JsInterface jsInterface) { mSensorManager = sensorManager; mCompassListenerProvider = compassListenerProvider; mCombinedLocationListener = combinedLocationListener; mCombinedLocationManager = combinedLocationManager; mLocationControlBuffered = locationControlBuffered; mWebView = (WebView)activity.findViewById(R.id.help_contents); mActivitySaver = activitySaver; mActivityVisible = activityVisible; mJsInterface = jsInterface; } public void configureWebView() { mWebView.loadUrl("file:///android_asset/search.html"); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setBackgroundColor(Color.BLACK); mWebView.addJavascriptInterface(mJsInterface, "gb"); } public void onPause() { mCombinedLocationManager.removeUpdates(); mSensorManager.unregisterListener(mCompassListenerProvider.get()); mActivityVisible.setVisible(false); mActivitySaver.save(ActivityType.SEARCH_ONLINE); } public void onResume() { mCombinedLocationManager.requestLocationUpdates(1000, 0, mLocationControlBuffered); mCombinedLocationManager.requestLocationUpdates(1000, 0, mCombinedLocationListener); mSensorManager.registerListener(mCompassListenerProvider.get(), SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); mActivityVisible.setVisible(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.searchonline; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.widget.Toast; import java.util.Locale; class JsInterface { private final JsInterfaceHelper mHelper; private final Toaster mToaster; private final LocationManager mLocationManager; static class JsInterfaceHelper { private final Activity mActivity; @Inject public JsInterfaceHelper(Activity activity) { mActivity = activity; } public void launch(String uri) { mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri))); } public String getTemplate(int ix) { return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix]; } public String getNS(double latitude) { return latitude > 0 ? "N" : "S"; } public String getEW(double longitude) { return longitude > 0 ? "E" : "W"; } } @Inject public JsInterface(JsInterfaceHelper jsInterfaceHelper, Toaster toaster, LocationManager locationManager) { mHelper = jsInterfaceHelper; mToaster = toaster; mLocationManager = locationManager; } public int atlasQuestOrGroundspeak(int ix) { Location location = getLocation(); if (location == null) return 0; final String uriTemplate = mHelper.getTemplate(ix); mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location.getLongitude())); return 0; } private Location getLocation() { Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { mToaster.toast(R.string.current_location_null, Toast.LENGTH_LONG); } return location; } public int openCaching(int ix) { Location location = getLocation(); if (location == null) return 0; final String uriTemplate = mHelper.getTemplate(ix); final double latitude = location.getLatitude(); final double longitude = location.getLongitude(); final String NS = mHelper.getNS(latitude); final String EW = mHelper.getEW(longitude); final double abs_latitude = Math.abs(latitude); final double abs_longitude = Math.abs(longitude); final int lat_h = (int)abs_latitude; final double lat_m = 60 * (abs_latitude - lat_h); final int lon_h = (int)abs_longitude; final double lon_m = 60 * (abs_longitude - lon_h); mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m)); return 0; } }
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.activity.compass.view.EditCacheActivityDelegate; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.os.Bundle; public class EditCacheActivity extends GuiceActivity { private EditCacheActivityDelegate editCacheActivityDelegate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Injector injector = getInjector(); editCacheActivityDelegate = injector.getInstance(EditCacheActivityDelegate.class); editCacheActivityDelegate.onCreate(); } @Override protected void onPause() { editCacheActivityDelegate.onPause(); super.onPause(); } @Override protected void onResume() { super.onResume(); editCacheActivityDelegate.onResume(); } }
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.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.compass.CompassActivity; import com.google.code.geobeagle.activity.compass.GeocacheFromPreferencesFactory; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; class ViewCacheRestorer implements Restorer { private final Activity activity; private final GeocacheFromPreferencesFactory geocacheFromPreferencesFactory; private final SharedPreferences sharedPreferences; public ViewCacheRestorer(GeocacheFromPreferencesFactory geocacheFromPreferencesFactory, SharedPreferences sharedPreferences, Activity activity) { this.geocacheFromPreferencesFactory = geocacheFromPreferencesFactory; this.sharedPreferences = sharedPreferences; this.activity = activity; } @Override public void restore() { final Geocache geocache = geocacheFromPreferencesFactory.create(sharedPreferences); final Intent intent = new Intent(activity, CompassActivity.class); intent.putExtra("geocache", geocache).setAction(GeocacheListController.SELECT_CACHE); activity.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; public enum ActivityType { // These constants are persisted to the database. They are also used as // indices in ActivityRestorer. CACHE_LIST(1), NONE(0), SEARCH_ONLINE(2), VIEW_CACHE(3); private final int mIx; ActivityType(int i) { mIx = i; } int toInt() { return mIx; } }
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.CacheListActivityStarter; import com.google.inject.Inject; import android.app.Activity; class CacheListRestorer implements Restorer { private final Activity activity; private final CacheListActivityStarter cacheListActivityStarter; @Inject public CacheListRestorer(Activity activity, CacheListActivityStarter cacheListActivityStarter) { this.activity = activity; this.cacheListActivityStarter = cacheListActivityStarter; } @Override public void restore() { cacheListActivityStarter.start(); 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; interface Restorer { void restore(); }
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.cachelist; import android.view.ContextMenu; public interface ViewMenuAdder { abstract void addViewMenu(ContextMenu menu); }
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.cachelist; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.app.Dialog; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class CacheListActivityHoneycomb extends GuiceActivity { private CacheListDelegate cacheListDelegate; public CacheListDelegate getCacheListDelegate() { return cacheListDelegate; } @Override public Dialog onCreateDialog(int idDialog) { super.onCreateDialog(idDialog); return cacheListDelegate.onCreateDialog(this, idDialog); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return cacheListDelegate.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return cacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "CacheListActivityHoneycomb onCreate"); requestWindowFeature(Window.FEATURE_PROGRESS); Injector injector = getInjector(); cacheListDelegate = injector.getInstance(CacheListDelegate.class); cacheListDelegate.onCreate(injector); Log.d("GeoBeagle", "Done creating CacheListActivityHoneycomb"); } @Override protected void onPause() { Log.d("GeoBeagle", "CacheListActivity onPause"); /* * cacheListDelegate closes the database, it must be called before * super.onPause because the guice activity onPause nukes the database * object from the guice map. */ cacheListDelegate.onPause(); super.onPause(); Log.d("GeoBeagle", "CacheListActivityHoneycomb onPauseComplete"); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); cacheListDelegate.onPrepareDialog(id, dialog); } @Override protected void onResume() { super.onResume(); SearchTarget searchTarget = getInjector().getInstance(SearchTarget.class); Log.d("GeoBeagle", "CacheListActivityHoneycomb onResume"); cacheListDelegate.onResume(searchTarget); } }
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.cachelist; import com.google.code.geobeagle.R; import android.view.ContextMenu; public class ViewMenuAdderPreHoneycomb implements ViewMenuAdder { @Override public void addViewMenu(ContextMenu menu) { menu.add(0, GeocacheListController.MENU_VIEW, 0, R.string.context_menu_view); } }
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.cachelist; import com.google.inject.Injector; import roboguice.activity.GuiceListActivity; import android.app.Dialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ListView; public class CacheListActivity extends GuiceListActivity { private CacheListDelegate cacheListDelegate; public CacheListDelegate getCacheListDelegate() { return cacheListDelegate; } @Override public boolean onContextItemSelected(MenuItem item) { return cacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item); } @Override public Dialog onCreateDialog(int idDialog) { super.onCreateDialog(idDialog); return cacheListDelegate.onCreateDialog(this, idDialog); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return cacheListDelegate.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return cacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "CacheListActivity onCreate"); requestWindowFeature(Window.FEATURE_PROGRESS); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) { startActivity(new Intent(this, CacheListActivityHoneycomb.class)); finish(); return; } Injector injector = this.getInjector(); cacheListDelegate = injector.getInstance(CacheListDelegate.class); cacheListDelegate.onCreate(injector); Log.d("GeoBeagle", "Done creating CacheListActivity"); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); cacheListDelegate.onListItemClick(position); } @Override protected void onPause() { Log.d("GeoBeagle", "CacheListActivity onPause"); /* * cacheListDelegate closes the database, it must be called before * super.onPause because the guice activity onPause nukes the database * object from the guice map. */ cacheListDelegate.onPause(); super.onPause(); Log.d("GeoBeagle", "CacheListActivity onPauseComplete"); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); cacheListDelegate.onPrepareDialog(id, dialog); } @Override protected void onResume() { super.onResume(); SearchTarget searchTarget = getInjector().getInstance(SearchTarget.class); Log.d("GeoBeagle", "CacheListActivity onResume"); cacheListDelegate.onResume(searchTarget); } }
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.cachelist; import com.google.code.geobeagle.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSms; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSmsFactory; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger.OnClickOk; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLoggerFactory; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.fieldnotes.OnClickOkFactory; import com.google.inject.Inject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import java.text.DateFormat; import java.util.Date; public class LogFindDialogHelper { private static final DateFormat mLocalDateFormat = DateFormat .getTimeInstance(DateFormat.MEDIUM); private final DialogHelperSmsFactory dialogHelperSmsFactory; private final FieldnoteLoggerFactory fieldnoteLoggerFactory; private final OnClickOkFactory onClickOkFactory; private final OnClickCancelListener onClickCancelListener; private final HasGeocache hasGeocache; @Inject LogFindDialogHelper(DialogHelperSmsFactory dialogHelperSmsFactory, FieldnoteLoggerFactory fieldnoteLoggerFactory, OnClickOkFactory onClickOkFactory, OnClickCancelListener onClickCancelListener, HasGeocache hasGeocache) { this.dialogHelperSmsFactory = dialogHelperSmsFactory; this.fieldnoteLoggerFactory = fieldnoteLoggerFactory; this.onClickOkFactory = onClickOkFactory; this.onClickCancelListener = onClickCancelListener; this.hasGeocache = hasGeocache; } public void onPrepareDialog(Activity activity, int id, Dialog dialog) { CharSequence cacheId = hasGeocache.get(activity).getId(); boolean fDnf = id == R.id.menu_log_dnf; DialogHelperSms dialogHelperSms = dialogHelperSmsFactory.create(cacheId.length(), fDnf); FieldnoteLogger fieldnoteLogger = fieldnoteLoggerFactory.create(dialogHelperSms); fieldnoteLogger.onPrepareDialog(dialog, mLocalDateFormat.format(new Date()), fDnf); } public Dialog onCreateDialog(Activity activity, int id) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); View fieldnoteDialogView = LayoutInflater.from(activity).inflate(R.layout.fieldnote, null); boolean fDnf = id == R.id.menu_log_dnf; OnClickOk onClickOk = onClickOkFactory.create( (EditText)fieldnoteDialogView.findViewById(R.id.fieldnote), fDnf); builder.setTitle(R.string.field_note_title); builder.setView(fieldnoteDialogView); builder.setNegativeButton(R.string.cancel, onClickCancelListener); builder.setPositiveButton(R.string.log_cache, onClickOk); AlertDialog alertDialog = builder.create(); return alertDialog; } }
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.cachelist.presenter; public class AbsoluteBearingFormatter implements BearingFormatter { private static final String[] LETTERS = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; @Override public String formatBearing(float absBearing, float myHeading) { return LETTERS[((((int)(absBearing) + 22 + 720) % 360) / 45)]; } }
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.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.Timing; import com.google.inject.Inject; import com.google.inject.ProvisionException; import com.google.inject.Singleton; import roboguice.inject.ContextScoped; import android.util.Log; @ContextScoped public class CacheListRefresh implements Refresher { public static class ActionManager { private final ActionAndTolerance mActionAndTolerances[]; public ActionManager(ActionAndTolerance actionAndTolerances[]) { mActionAndTolerances = actionAndTolerances; } public int getMinActionExceedingTolerance(IGpsLocation here, float azimuth, long now) { int i; for (i = 0; i < mActionAndTolerances.length; i++) { if (mActionAndTolerances[i].exceedsTolerance(here, azimuth, now)) break; } return i; } public void performActions(IGpsLocation here, float azimuth, int startingAction, long now) { for (int i = startingAction; i < mActionAndTolerances.length; i++) { mActionAndTolerances[i].refresh(); mActionAndTolerances[i].updateLastRefreshed(here, azimuth, now); } } } @Singleton public static class UpdateFlag { private boolean mUpdateFlag = true; public void setUpdatesEnabled(boolean enabled) { Log.d("GeoBeagle", "Update enabled: " + enabled); mUpdateFlag = enabled; } boolean updatesEnabled() { return mUpdateFlag; } } private final ActionManager mActionManager; private final LocationControlBuffered mLocationControlBuffered; private final Timing mTiming; private final UpdateFlag mUpdateFlag; @Inject public CacheListRefresh(ActionManager actionManager, Timing timing, LocationControlBuffered locationControlBuffered, UpdateFlag updateFlag) { mLocationControlBuffered = locationControlBuffered; mTiming = timing; mActionManager = actionManager; mUpdateFlag = updateFlag; } public void forceRefresh() { mTiming.start(); if (!mUpdateFlag.updatesEnabled()) return; final long now = mTiming.getTime(); mActionManager.performActions(mLocationControlBuffered.getGpsLocation(), mLocationControlBuffered.getAzimuth(), 0, now); } @Override public void refresh() { if (!mUpdateFlag.updatesEnabled()) return; mTiming.start(); try { // Log.d("GeoBeagle", "REFRESH"); final long now = mTiming.getTime(); final IGpsLocation here = mLocationControlBuffered.getGpsLocation(); final float azimuth = mLocationControlBuffered.getAzimuth(); final int minActionExceedingTolerance = mActionManager.getMinActionExceedingTolerance( here, azimuth, now); mActionManager.performActions(here, azimuth, minActionExceedingTolerance, now); } catch (ProvisionException e) { Log.d("GeoBeagle", "Ignoring provision exception during refresh: " + e); } } }
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.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.ActivityVisible; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater; import com.google.inject.Inject; import com.google.inject.Injector; import roboguice.inject.ContextScoped; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; @ContextScoped public class GeocacheListAdapter extends BaseAdapter { //TODO(sng): Rename to CacheListAdapter. private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater; private final GeocacheVectors mGeocacheVectors; private final ActivityVisible mActivityVisible; private CharSequence mSelected; public GeocacheListAdapter(GeocacheVectors geocacheVectors, GeocacheSummaryRowInflater geocacheSummaryRowInflater, ActivityVisible activityVisible) { mGeocacheVectors = geocacheVectors; mGeocacheSummaryRowInflater = geocacheSummaryRowInflater; mActivityVisible = activityVisible; } @Inject public GeocacheListAdapter(Injector injector) { mGeocacheVectors = injector.getInstance(GeocacheVectors.class); mGeocacheSummaryRowInflater = injector.getInstance(GeocacheSummaryRowInflater.class); mActivityVisible = injector.getInstance(ActivityVisible.class); } @Override public int getCount() { return mGeocacheVectors.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = mGeocacheSummaryRowInflater.inflate(convertView); if (!mActivityVisible.getVisible()) { // Log.d("GeoBeagle", // "Not visible, punting any real work on getView"); return view; } mGeocacheSummaryRowInflater.setData(view, mGeocacheVectors.get(position)); // ListView listView = (ListView)parent; // boolean isChecked = listView.isItemChecked(position + 1); boolean isChecked = mGeocacheVectors.get(position).getId().equals(mSelected); view.setBackgroundColor(isChecked ? Color.DKGRAY : Color.TRANSPARENT); return view; } public void setSelected(int position) { mSelected = mGeocacheVectors.get(position).getId(); } }
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.cachelist.presenter; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import com.google.code.geobeagle.database.filter.FilterNearestCaches; import com.google.inject.Inject; import android.app.Activity; public class TitleUpdater { private final FilterNearestCaches mFilterNearestCaches; private final Activity mActivity; private final Timing mTiming; private final SearchTarget mSearchTarget; @Inject public TitleUpdater(Activity activity, FilterNearestCaches filterNearestCaches, Timing timing, SearchTarget searchTarget) { mActivity = activity; mFilterNearestCaches = filterNearestCaches; mTiming = timing; mSearchTarget = searchTarget; } public void update(int sqlCount, int nearestCachesCount) { mActivity.setTitle(mSearchTarget.getTitle() + mActivity.getString(mFilterNearestCaches.getTitleText(), nearestCachesCount, sqlCount)); mTiming.lap("update title time"); } }
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.cachelist.presenter; import com.google.code.geobeagle.CacheListCompassListener; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.activity.cachelist.CacheListViewScrollListener; import com.google.code.geobeagle.activity.cachelist.GeocacheListController.CacheListOnCreateContextMenuListener; import com.google.code.geobeagle.activity.cachelist.Pausable; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import com.google.code.geobeagle.activity.cachelist.ViewMenuAdder; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.filter.UpdateFilterMediator; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.code.geobeagle.database.filter.UpdateFilterWorker; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable; import com.google.code.geobeagle.location.CombinedLocationListener; import com.google.code.geobeagle.location.CombinedLocationManager; import com.google.code.geobeagle.shakewaker.ShakeWaker; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.app.Activity; import android.hardware.SensorManager; import android.location.LocationListener; import android.util.Log; import android.view.View; import android.widget.ListView; public class CacheListPresenter implements Pausable { static final int UPDATE_DELAY = 1000; private final LocationListener combinedLocationListener; private final CombinedLocationManager combinedLocationManager; private final Provider<CacheListCompassListener> cacheListCompassListenerProvider; private final GeocacheVectors geocacheVectors; private final InflatedGpsStatusWidget inflatedGpsStatusWidget; private final Activity activity; private final LocationControlBuffered locationControlBuffered; private final SensorManagerWrapper sensorManagerWrapper; private final UpdateGpsWidgetRunnable updateGpsWidgetRunnable; private final CacheListViewScrollListener scrollListener; private final GpsStatusListener gpsStatusListener; private final UpdateFilterWorker updateFilterWorker; private final FilterCleanliness filterCleanliness; private final ShakeWaker shakeWaker; private final UpdateFilterMediator updateFilterMediator; private final SearchTarget searchTarget; private final ListFragtivityOnCreateHandler listFragtivityOnCreateHandler; private final ViewMenuAdder viewMenuAdder; public CacheListPresenter(CombinedLocationListener combinedLocationListener, CombinedLocationManager combinedLocationManager, ListFragtivityOnCreateHandler listFragtivityOnCreateHandler, Provider<CacheListCompassListener> cacheListCompassListenerProvider, GeocacheVectors geocacheVectors, InflatedGpsStatusWidget inflatedGpsStatusWidget, Activity listActivity, LocationControlBuffered locationControlBuffered, SensorManagerWrapper sensorManagerWrapper, UpdateGpsWidgetRunnable updateGpsWidgetRunnable, CacheListViewScrollListener cacheListViewScrollListener, GpsStatusListener gpsStatusListener, UpdateFilterWorker updateFilterWorker, FilterCleanliness filterCleanliness, ShakeWaker shakeWaker, UpdateFilterMediator updateFilterMediator, SearchTarget searchTarget, ViewMenuAdder viewMenuAdder) { this.combinedLocationListener = combinedLocationListener; this.combinedLocationManager = combinedLocationManager; this.cacheListCompassListenerProvider = cacheListCompassListenerProvider; this.geocacheVectors = geocacheVectors; this.inflatedGpsStatusWidget = inflatedGpsStatusWidget; this.shakeWaker = shakeWaker; this.activity = listActivity; this.locationControlBuffered = locationControlBuffered; this.updateGpsWidgetRunnable = updateGpsWidgetRunnable; this.sensorManagerWrapper = sensorManagerWrapper; this.scrollListener = cacheListViewScrollListener; this.gpsStatusListener = gpsStatusListener; this.updateFilterWorker = updateFilterWorker; this.filterCleanliness = filterCleanliness; this.updateFilterMediator = updateFilterMediator; this.searchTarget = searchTarget; this.listFragtivityOnCreateHandler = listFragtivityOnCreateHandler; this.viewMenuAdder = viewMenuAdder; } @Inject public CacheListPresenter(Injector injector) { this.combinedLocationListener = injector.getInstance(CombinedLocationListener.class); this.combinedLocationManager = injector.getInstance(CombinedLocationManager.class); this.cacheListCompassListenerProvider = injector .getProvider(CacheListCompassListener.class); this.geocacheVectors = injector.getInstance(GeocacheVectors.class); this.inflatedGpsStatusWidget = injector.getInstance(InflatedGpsStatusWidget.class); this.shakeWaker = injector.getInstance(ShakeWaker.class); this.activity = injector.getInstance(Activity.class); this.locationControlBuffered = injector.getInstance(LocationControlBuffered.class); this.updateGpsWidgetRunnable = injector.getInstance(UpdateGpsWidgetRunnable.class); this.sensorManagerWrapper = injector.getInstance(SensorManagerWrapper.class); this.scrollListener = injector.getInstance(CacheListViewScrollListener.class); this.gpsStatusListener = injector.getInstance(GpsStatusListener.class); this.updateFilterWorker = injector.getInstance(UpdateFilterWorker.class); this.filterCleanliness = injector.getInstance(FilterCleanliness.class); this.updateFilterMediator = injector.getInstance(UpdateFilterMediator.class); this.searchTarget = injector.getInstance(SearchTarget.class); this.listFragtivityOnCreateHandler = injector .getInstance(ListFragtivityOnCreateHandler.class); this.viewMenuAdder = injector.getInstance(ViewMenuAdder.class); } public void onCreate() { listFragtivityOnCreateHandler.onCreateActivity(activity, this); } void setupListView(ListView listView) { NoCachesView noCachesView = (NoCachesView)listView.getEmptyView(); noCachesView.setSearchTarget(searchTarget); listView.addHeaderView((View)inflatedGpsStatusWidget.getTag()); listView.setOnCreateContextMenuListener(new CacheListOnCreateContextMenuListener( geocacheVectors, viewMenuAdder)); listView.setOnScrollListener(scrollListener); } public void onCreateFragment(Object listFragment) { listFragtivityOnCreateHandler.onCreateFragment(this, listFragment); } @Override public void onPause() { combinedLocationManager.removeUpdates(); sensorManagerWrapper.unregisterListener(); shakeWaker.unregister(); } public void onResume(CacheListRefresh cacheListRefresh) { if (filterCleanliness.isDirty()) { updateFilterMediator.startFiltering("Resetting filter"); updateFilterWorker.start(); } CacheListRefreshLocationListener cacheListRefreshLocationListener = new CacheListRefreshLocationListener( cacheListRefresh); CacheListCompassListener compassListener = cacheListCompassListenerProvider.get(); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, locationControlBuffered); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, combinedLocationListener); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, cacheListRefreshLocationListener); combinedLocationManager.addGpsStatusListener(gpsStatusListener); updateGpsWidgetRunnable.run(); sensorManagerWrapper.registerListener(compassListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); shakeWaker.register(); Log.d("GeoBeagle", "GeocacheListPresenter onResume done"); } }
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.cachelist.presenter; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.cachelist.ActivityVisible; import com.google.code.geobeagle.activity.cachelist.model.CacheListData; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.filter.FilterNearestCaches; import com.google.inject.Inject; import com.google.inject.Provider; import android.location.Location; import java.util.ArrayList; public class SqlCacheLoader implements RefreshAction { private final CacheListData cacheListData; private final FilterNearestCaches filterNearestCaches; private final Provider<DbFrontend> dbFrontendProvider; private final LocationControlBuffered locationControlBuffered; private final Timing timing; private final TitleUpdater titleUpdater; private final ActivityVisible activityVisible; @Inject public SqlCacheLoader(Provider<DbFrontend> dbFrontendProvider, FilterNearestCaches filterNearestCaches, CacheListData cacheListData, LocationControlBuffered locationControlBuffered, TitleUpdater titleUpdater, Timing timing, ActivityVisible activityVisible) { this.dbFrontendProvider = dbFrontendProvider; this.filterNearestCaches = filterNearestCaches; this.cacheListData = cacheListData; this.locationControlBuffered = locationControlBuffered; this.timing = timing; this.titleUpdater = titleUpdater; this.activityVisible = activityVisible; } @Override public void refresh() { if (!activityVisible.getVisible()) return; Location location = locationControlBuffered.getLocation(); double latitude = 0; double longitude = 0; if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } // Log.d("GeoBeagle", "Location: " + location); DbFrontend dbFrontend = dbFrontendProvider.get(); ArrayList<Geocache> geocaches = dbFrontend.loadCaches(latitude, longitude, filterNearestCaches.getWhereFactory()); timing.lap("SQL time"); cacheListData.add(geocaches, locationControlBuffered); timing.lap("add to list time"); int nearestCachesCount = cacheListData.size(); titleUpdater.update(dbFrontend.countAll(), nearestCachesCount); } }
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.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector.LocationComparator; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collections; public class DistanceSortStrategy implements SortStrategy { private final LocationComparator mLocationComparator; @Inject public DistanceSortStrategy(LocationComparator locationComparator) { mLocationComparator = locationComparator; } @Override public void sort(ArrayList<GeocacheVector> geocacheVectors) { for (GeocacheVector geocacheVector : geocacheVectors) { geocacheVector.setDistance(geocacheVector.getDistanceFast()); } Collections.sort(geocacheVectors, mLocationComparator); } }
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.cachelist.presenter; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.app.Activity; import android.app.ListActivity; import android.widget.ListView; public class ListActivityOnCreateHandler implements ListFragtivityOnCreateHandler { private final GeocacheListAdapter geocacheListAdapter; @Inject public ListActivityOnCreateHandler(GeocacheListAdapter geocacheListAdapter) { this.geocacheListAdapter = geocacheListAdapter; } @Override public void onCreateActivity(Activity activity, CacheListPresenter cacheListPresenter) { ListActivity listActivity = (ListActivity)activity; listActivity.setContentView(R.layout.cache_list); ListView listView = listActivity.getListView(); cacheListPresenter.setupListView(listView); listActivity.setListAdapter(geocacheListAdapter); } @Override public void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam) { } }
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.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.webkit.WebSettings; import android.webkit.WebView; public class NoCachesView extends WebView { private static final String NO_CACHES_FOUND_HTML = "file:///android_asset/no_caches_found.html"; private static final String NO_CACHES = "file:///android_asset/no_caches.html"; private SearchTarget searchTarget; public NoCachesView(Context context) { super(context); setup(); } public NoCachesView(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public NoCachesView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); } @Override public void onDraw(Canvas canvas) { // Log.d("GeoBeagle", "getUrl: " + getUrl()); if (searchTarget == null || searchTarget.getTarget() == null) { if (getUrl() == null || 0 != getUrl().compareTo(NO_CACHES)) loadUrl(NO_CACHES); } else if (getUrl() == null || 0 != getUrl().compareTo(NO_CACHES_FOUND_HTML)) { loadUrl(NO_CACHES_FOUND_HTML); } super.onDraw(canvas); } public void setSearchTarget(SearchTarget searchTarget) { this.searchTarget = searchTarget; } private void setup() { WebSettings webSettings = getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setSupportZoom(false); setBackgroundColor(Color.BLACK); } }
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.cachelist.presenter; import com.google.code.geobeagle.formatting.DistanceFormatter; public interface HasDistanceFormatter { public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter); }
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.cachelist.presenter; public class RelativeBearingFormatter implements BearingFormatter { private static final String[] ARROWS = { "^", ">", "v", "<", }; @Override public String formatBearing(float absBearing, float myHeading) { return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)]; } }
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.cachelist.presenter; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.ProvisionException; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationManager; import android.util.Log; class GpsStatusListener implements GpsStatus.Listener { private final InflatedGpsStatusWidget inflatedGpsStatusWidget; private final Provider<LocationManager> locationManagerProvider; @Inject public GpsStatusListener(InflatedGpsStatusWidget inflatedGpsStatusWidget, Provider<LocationManager> locationManagerProvider) { this.inflatedGpsStatusWidget = inflatedGpsStatusWidget; this.locationManagerProvider = locationManagerProvider; } @Override public void onGpsStatusChanged(int event) { try { GpsStatus gpsStatus = locationManagerProvider.get().getGpsStatus(null); int satelliteCount = 0; for (@SuppressWarnings("unused") GpsSatellite gpsSatellite : gpsStatus.getSatellites()) { satelliteCount++; } inflatedGpsStatusWidget.getDelegate().setProvider("SAT: " + satelliteCount); } catch (ProvisionException e) { Log.d("GeoBeagle", "Ignoring provision exception during onGpsStatusChanged: " + e); } } }
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.cachelist.presenter; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; public class CacheListRefreshLocationListener implements LocationListener { private final CacheListRefresh mCacheListRefresh; public CacheListRefreshLocationListener(CacheListRefresh cacheListRefresh) { mCacheListRefresh = cacheListRefresh; } @Override public void onLocationChanged(Location location) { // Log.d("GeoBeagle", "location changed"); mCacheListRefresh.refresh(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }
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.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import java.util.ArrayList; public interface SortStrategy { public void sort(ArrayList<GeocacheVector> arrayList); }
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.cachelist.presenter; interface RefreshAction { 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.cachelist.presenter.filter; import com.google.inject.Inject; import android.os.Handler; import android.os.Message; public class UpdateFilterHandler extends Handler { private final UpdateFilterMediator updateFilterMediator; @Inject UpdateFilterHandler(UpdateFilterMediator updateFilterMediator) { this.updateFilterMediator = updateFilterMediator; } @Override public void handleMessage(Message msg) { UpdateFilterMessages updateFilterMessage = UpdateFilterMessages.fromOrd(msg.what); updateFilterMessage.handleMessage(updateFilterMediator, msg.obj); } private void sendMessage(UpdateFilterMessages updateFilterMessage) { sendMessage(updateFilterMessage, null); } private void sendMessage(UpdateFilterMessages updateFilterMessage, String prompt) { sendMessage(obtainMessage(updateFilterMessage.ordinal(), prompt)); } public void endFiltering() { sendMessage(UpdateFilterMessages.END_FILTERING); } public void setProgressMessage(String string) { sendMessage(UpdateFilterMessages.SET_PROGRESS_MESSAGE, string); } }
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.cachelist.presenter.filter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.database.filter.FilterProgressDialog; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.ProgressDialog; public class UpdateFilterMediator { private final CacheListRefresh cacheListRefresh; private final Provider<FilterProgressDialog> clearFilterProgressDialogProvider; private final UpdateFlag updateFlag; private final FilterCleanliness filterCleanliness; @Inject public UpdateFilterMediator(CacheListRefresh cacheListRefresh, UpdateFlag updateFlag, Provider<FilterProgressDialog> clearFilterProgressDialogProvider, FilterCleanliness filterCleanliness) { this.cacheListRefresh = cacheListRefresh; this.updateFlag = updateFlag; this.clearFilterProgressDialogProvider = clearFilterProgressDialogProvider; this.filterCleanliness = filterCleanliness; } public void startFiltering(String string) { updateFlag.setUpdatesEnabled(false); ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.setMessage(string); progressDialog.show(); } public void endFiltering() { filterCleanliness.markDirty(false); updateFlag.setUpdatesEnabled(true); cacheListRefresh.forceRefresh(); ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.dismiss(); } public void setProgressMessage(String message) { ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.setMessage(message); } }
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.cachelist.presenter.filter; public enum UpdateFilterMessages { END_FILTERING { @Override void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj) { updateFilterMediator.endFiltering(); } }, SET_PROGRESS_MESSAGE { @Override void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj) { updateFilterMediator.setProgressMessage((String)obj); } }; public static UpdateFilterMessages fromOrd(int i) { return UpdateFilterMessages.values()[i]; } abstract void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj); }
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.cachelist.presenter; import android.app.Activity; import android.app.ListActivity; public interface ListFragtivityOnCreateHandler { void onCreateActivity(Activity listActivity, CacheListPresenter cacheListPresenter); void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam); }
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.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; public interface ToleranceStrategy { public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now); public void updateLastRefreshed(IGpsLocation here, float azimuth, long now); }
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.cachelist.presenter; import com.google.code.geobeagle.CompassListener; import com.google.inject.Inject; import android.hardware.SensorManager; public class SensorManagerWrapper { private CompassListener mCompassListener; private final SensorManager mSensorManager; @Inject public SensorManagerWrapper(SensorManager sensorManager) { mSensorManager = sensorManager; } public void unregisterListener() { mSensorManager.unregisterListener(mCompassListener); } public void registerListener(CompassListener compassListener, int sensorOrientation, int sensorDelayUi) { mCompassListener = compassListener; mSensorManager.registerListener(compassListener, sensorOrientation, sensorDelayUi); } }
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.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; public class LocationAndAzimuthTolerance implements ToleranceStrategy { private float mLastAzimuth; private final LocationTolerance mLocationTolerance; public LocationAndAzimuthTolerance(LocationTolerance locationTolerance, float lastAzimuth) { mLocationTolerance = locationTolerance; mLastAzimuth = lastAzimuth; } @Override public boolean exceedsTolerance(IGpsLocation here, float currentAzimuth, long now) { if (mLastAzimuth != currentAzimuth) { // Log.d("GeoBeagle", "new azimuth: " + currentAzimuth); mLastAzimuth = currentAzimuth; return true; } return mLocationTolerance.exceedsTolerance(here, currentAzimuth, now); } @Override public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { mLocationTolerance.updateLastRefreshed(here, azimuth, now); mLastAzimuth = azimuth; } }
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.cachelist.presenter; public interface BearingFormatter { public abstract String formatBearing(float absBearing, float myHeading); }
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.cachelist.presenter; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.app.Activity; import android.app.ListFragment; import android.widget.ListView; public class ListFragmentOnCreateHandler implements ListFragtivityOnCreateHandler { private final GeocacheListAdapter geocacheListAdapter; @Inject public ListFragmentOnCreateHandler(GeocacheListAdapter geocacheListAdapter) { this.geocacheListAdapter = geocacheListAdapter; } @Override public void onCreateActivity(Activity listActivity, CacheListPresenter cacheListPresenter) { listActivity.setContentView(R.layout.cache_list_fragment); } @Override public void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam) { ListFragment listFragment = (ListFragment)listFragmentParam; ListView listView = listFragment.getListView(); cacheListPresenter.setupListView(listView); listFragment.setListAdapter(geocacheListAdapter); } }
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.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import java.util.ArrayList; public class NullSortStrategy implements SortStrategy { public void sort(ArrayList<GeocacheVector> arrayList) { return; } }
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.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; public class ActionAndTolerance { private final RefreshAction mRefreshAction; private final ToleranceStrategy mToleranceStrategy; public ActionAndTolerance(RefreshAction refreshAction, ToleranceStrategy toleranceStrategy) { mRefreshAction = refreshAction; mToleranceStrategy = toleranceStrategy; } public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { return mToleranceStrategy.exceedsTolerance(here, azimuth, now); } public void refresh() { mRefreshAction.refresh(); } public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { mToleranceStrategy.updateLastRefreshed(here, azimuth, now); } }
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.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; public class LocationTolerance implements ToleranceStrategy { private IGpsLocation mLastRefreshLocation; private final float mLocationTolerance; private final int mMinTimeBetweenRefresh; private long mLastRefreshTime; public LocationTolerance(float locationTolerance, IGpsLocation lastRefreshed, int minTimeBetweenRefresh) { mLocationTolerance = locationTolerance; mLastRefreshLocation = lastRefreshed; mMinTimeBetweenRefresh = minTimeBetweenRefresh; mLastRefreshTime = 0; } @Override public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { if (now < mLastRefreshTime + mMinTimeBetweenRefresh) return false; final float distanceTo = here.distanceTo(mLastRefreshLocation); // Log.d("GeoBeagle", "distance, tolerance: " + distanceTo + ", " + // mLocationTolerance); final boolean fExceedsTolerance = distanceTo >= mLocationTolerance; return fExceedsTolerance; } @Override public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { // Log.d("GeoBeagle", "updateLastRefreshed here: " + here); mLastRefreshLocation = here; mLastRefreshTime = now; } }
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.cachelist.presenter; import com.google.inject.Inject; import com.google.inject.Injector; public class DistanceUpdater implements RefreshAction { private final GeocacheListAdapter mGeocacheListAdapter; @Inject public DistanceUpdater(Injector injector) { mGeocacheListAdapter = injector.getInstance(GeocacheListAdapter.class); } public DistanceUpdater(GeocacheListAdapter geocacheListAdapter) { mGeocacheListAdapter = geocacheListAdapter; } @Override public void refresh() { mGeocacheListAdapter.notifyDataSetChanged(); } }
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.cachelist.presenter; import com.google.code.geobeagle.GeoBeagleApplication; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.cachelist.model.CacheListData; import com.google.inject.Inject; public class AdapterCachesSorter implements RefreshAction { private final CacheListData mCacheListData; private final LocationControlBuffered mLocationControlBuffered; private final Timing mTiming; @Inject public AdapterCachesSorter(CacheListData cacheListData, Timing timing, LocationControlBuffered locationControlBuffered) { mCacheListData = cacheListData; mTiming = timing; mLocationControlBuffered = locationControlBuffered; } @Override public void refresh() { mLocationControlBuffered.getSortStrategy().sort(mCacheListData.get()); mTiming.lap("sort time"); GeoBeagleApplication.timing.lap("START TIME TO FIRST REFRESH"); // Debug.stopMethodTracing(); } }
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.cachelist; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.ContextActions; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView.AdapterContextMenuInfo; public class GeocacheListController { public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener { private final GeocacheVectors mGeocacheVectors; private final ViewMenuAdder mViewMenuAdder; public CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors, ViewMenuAdder viewMenuAdder) { mGeocacheVectors = geocacheVectors; mViewMenuAdder = viewMenuAdder; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; if (acmi.position > 0) { menu.setHeaderTitle(mGeocacheVectors.get(acmi.position - 1).getId()); mViewMenuAdder.addViewMenu(menu); menu.add(0, MENU_EDIT, 1, R.string.context_menu_edit); menu.add(0, MENU_DELETE, 2, R.string.context_menu_delete); } } } static final int MENU_EDIT = 0; static final int MENU_DELETE = 1; static final int MENU_VIEW = 2; public static final String SELECT_CACHE = "SELECT_CACHE"; private final CacheListRefresh mCacheListRefresh; private final AbortState mAborter; private final Provider<MenuActionSyncGpx> mMenuActionSyncGpxProvider; private final Provider<CacheListMenuActions> mCacheListMenuActionsProvider; private final Provider<ContextActions> mContextActionsProvider; @Inject public GeocacheListController(Injector injector) { mCacheListRefresh = injector.getInstance(CacheListRefresh.class); mAborter = injector.getInstance(AbortState.class); mMenuActionSyncGpxProvider = injector.getProvider(MenuActionSyncGpx.class); mCacheListMenuActionsProvider = injector.getProvider(CacheListMenuActions.class); mContextActionsProvider = injector.getProvider(ContextActions.class); } public GeocacheListController(CacheListRefresh cacheListRefresh, AbortState abortState, Provider<MenuActionSyncGpx> menuActionSyncProvider, Provider<CacheListMenuActions> cacheListMenuActionsProvider, Provider<ContextActions> contextActionsProvider) { mCacheListRefresh = cacheListRefresh; mAborter = abortState; mMenuActionSyncGpxProvider = menuActionSyncProvider; mCacheListMenuActionsProvider = cacheListMenuActionsProvider; mContextActionsProvider = contextActionsProvider; } public boolean onContextItemSelected(MenuItem menuItem) { AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem .getMenuInfo(); mContextActionsProvider.get() .act(menuItem.getItemId(), adapterContextMenuInfo.position - 1); return true; } public boolean onCreateOptionsMenu(Menu menu) { return mCacheListMenuActionsProvider.get().onCreateOptionsMenu(menu); } public void onListItemClick(int position) { if (position > 0) mContextActionsProvider.get().act(MENU_VIEW, position - 1); else mCacheListRefresh.forceRefresh(); } public boolean onOptionsItemSelected(MenuItem item) { return mCacheListMenuActionsProvider.get().act(item.getItemId()); } public void onPause() { Log.d("GeoBeagle", "onPause aborting"); mAborter.abort(); mMenuActionSyncGpxProvider.get().abort(); } public void onResume(boolean fImport) { mCacheListRefresh.forceRefresh(); if (fImport) mMenuActionSyncGpxProvider.get().act(); } }
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.cachelist.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.GraphicsGenerator.AttributesPainter; 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.ListViewBitmapCopier; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.graphics.drawable.Drawable; import android.widget.ImageView; import android.widget.TextView; class RowViews { private final TextView mAttributes; private final TextView mCacheName; private final TextView mDistance; private final ImageView mIcon; private final GraphicsGenerator.IconOverlayFactory mIconOverlayFactory; private final TextView mId; private final NameFormatter mNameFormatter; RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon, TextView id, IconOverlayFactory iconOverlayFactory, NameFormatter nameFormatter) { mAttributes = attributes; mCacheName = cacheName; mDistance = distance; mIcon = icon; mId = id; mIconOverlayFactory = iconOverlayFactory; mNameFormatter = nameFormatter; } void set(GeocacheVector geocacheVector, BearingFormatter relativeBearingFormatter, DistanceFormatter distanceFormatter, ListViewBitmapCopier listViewBitmapCopier, IconRenderer iconRenderer, AttributesPainter attributesPainter) { Geocache geocache = geocacheVector.getGeocache(); IconOverlay iconOverlay = mIconOverlayFactory.create(geocache, false); mNameFormatter.format(mCacheName, geocache.getAvailable(), geocache.getArchived()); final Drawable icon = iconRenderer.renderIcon(geocache.getDifficulty(), geocache .getTerrain(), geocache.getCacheType().icon(), iconOverlay, listViewBitmapCopier, attributesPainter); mIcon.setImageDrawable(icon); mId.setText(geocacheVector.getId()); mAttributes.setText(geocacheVector.getFormattedAttributes()); mCacheName.setText(geocacheVector.getName()); mDistance.setText(geocacheVector.getFormattedDistance(distanceFormatter, relativeBearingFormatter)); } }
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.cachelist.view; import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.ListViewBitmapCopier; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class GeocacheSummaryRowInflater { private final Provider<BearingFormatter> mBearingFormatterProvider; private final Provider<DistanceFormatter> mDistanceFormatterProvider; private final IconOverlayFactory mIconOverlayFactory; private final IconRenderer mIconRenderer; private final LayoutInflater mLayoutInflater; private final ListViewBitmapCopier mListViewBitmapCopier; private final NameFormatter mNameFormatter; private final DifficultyAndTerrainPainter mDifficultyAndTerrainPainter; public GeocacheSummaryRowInflater(LayoutInflater layoutInflater, Provider<DistanceFormatter> distanceFormatterProvider, Provider<BearingFormatter> bearingFormatterProvider, IconRenderer iconRenderer, ListViewBitmapCopier listViewBitmapCopier, IconOverlayFactory iconOverlayFactory, NameFormatter nameFormatter, DifficultyAndTerrainPainter difficultyAndTerrainPainter) { mLayoutInflater = layoutInflater; mDistanceFormatterProvider = distanceFormatterProvider; mBearingFormatterProvider = bearingFormatterProvider; mIconRenderer = iconRenderer; mListViewBitmapCopier = listViewBitmapCopier; mIconOverlayFactory = iconOverlayFactory; mNameFormatter = nameFormatter; mDifficultyAndTerrainPainter = difficultyAndTerrainPainter; } @Inject public GeocacheSummaryRowInflater(Injector injector) { mLayoutInflater = injector.getInstance(LayoutInflater.class); mDistanceFormatterProvider = injector.getProvider(DistanceFormatter.class); mBearingFormatterProvider = injector.getProvider(BearingFormatter.class); mIconRenderer = injector.getInstance(IconRenderer.class); mListViewBitmapCopier = injector.getInstance(ListViewBitmapCopier.class); mIconOverlayFactory = injector.getInstance(IconOverlayFactory.class); mNameFormatter = injector.getInstance(NameFormatter.class); mDifficultyAndTerrainPainter = injector.getInstance(DifficultyAndTerrainPainter.class); } public View inflate(View convertView) { if (convertView != null) return convertView; // Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")"); View view = mLayoutInflater.inflate(R.layout.cache_row, null); RowViews rowViews = new RowViews((TextView)view.findViewById(R.id.txt_gcattributes), ((TextView)view.findViewById(R.id.txt_cache)), ((TextView)view .findViewById(R.id.distance)), ((ImageView)view .findViewById(R.id.gc_row_icon)), ((TextView)view .findViewById(R.id.txt_gcid)), mIconOverlayFactory, mNameFormatter); view.setTag(rowViews); return view; } public void setData(View view, GeocacheVector geocacheVector) { ((RowViews)view.getTag()).set(geocacheVector, mBearingFormatterProvider.get(), mDistanceFormatterProvider.get(), mListViewBitmapCopier, mIconRenderer, mDifficultyAndTerrainPainter); } }
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.cachelist.view; import android.graphics.Color; import android.graphics.Paint; import android.widget.TextView; public class NameFormatter { public void format(TextView name, boolean available, boolean archived) { if (archived) { name.setTextColor(Color.rgb(200, 0, 0)); name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); return; } if (!available) { name.setTextColor(Color.WHITE); name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); return; } name.setTextColor(Color.WHITE); name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); } }
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.cachelist; public interface Pausable { void onPause(); }
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.cachelist.actions.menu; import com.google.code.geobeagle.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; public class MenuActionDeleteAllCaches implements Action { private final Activity activity; private final Builder builder; private final CacheListRefresh cacheListRefresh; private final Provider<DbFrontend> cbFrontendProvider; private final BCachingStartTime bcachingLastUpdated; private final CompassFrameHider compassFrameHider; @Inject public MenuActionDeleteAllCaches(CacheListRefresh cacheListRefresh, Activity activity, Provider<DbFrontend> dbFrontendProvider, AlertDialog.Builder builder, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { this.cbFrontendProvider = dbFrontendProvider; this.builder = builder; this.activity = activity; this.cacheListRefresh = cacheListRefresh; this.bcachingLastUpdated = bcachingLastUpdated; this.compassFrameHider = compassFrameHider; } @Override public void act() { buildAlertDialog(cbFrontendProvider, cacheListRefresh, bcachingLastUpdated, compassFrameHider).show(); } private AlertDialog buildAlertDialog(Provider<DbFrontend> dbFrontendProvider, CacheListRefresh cacheListRefresh, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { builder.setTitle(R.string.delete_all_title); final OnClickOkayListener onClickOkayListener = new OnClickOkayListener(activity, dbFrontendProvider, cacheListRefresh, bcachingLastUpdated, compassFrameHider); final DialogInterface.OnClickListener onClickCancelListener = new OnClickCancelListener(); builder.setMessage(R.string.confirm_delete_all) .setPositiveButton(R.string.delete_all_title, onClickOkayListener) .setNegativeButton(R.string.cancel, onClickCancelListener); AlertDialog alertDialog = builder.create(); alertDialog.setOwnerActivity(activity); return alertDialog; } }
Java
package com.google.code.geobeagle.activity.cachelist.actions.menu; import android.app.Activity; public interface CompassFrameHider { public void hideCompassFrame(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.cachelist.actions.menu; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.inject.Provider; import android.app.Activity; import android.content.DialogInterface; class OnClickOkayListener implements DialogInterface.OnClickListener { private final CacheListRefresh cacheListRefresh; private final Provider<DbFrontend> dbFrontendProvider; private final BCachingStartTime bcachingLastUpdated; private final Activity activity; private final CompassFrameHider compassFrameHider; OnClickOkayListener(Activity activity, Provider<DbFrontend> dbFrontendProvider, CacheListRefresh cacheListRefresh, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { this.activity = activity; this.dbFrontendProvider = dbFrontendProvider; this.cacheListRefresh = cacheListRefresh; this.bcachingLastUpdated = bcachingLastUpdated; this.compassFrameHider = compassFrameHider; } void hideCompassFrame() { } @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); dbFrontendProvider.get().deleteAll(); bcachingLastUpdated.clearStartTime(); cacheListRefresh.forceRefresh(); compassFrameHider.hideCompassFrame(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.cachelist.actions.menu; import android.app.Activity; public class NullCompassFrameHider implements CompassFrameHider { @Override public void hideCompassFrame(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.cachelist.actions.menu; import com.google.code.geobeagle.R; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ListActivity; public class HoneycombCompassFrameHider implements CompassFrameHider { @Override public void hideCompassFrame(Activity activity) { ListActivity listActivity = (ListActivity)activity; FragmentManager fragmentManager = listActivity.getFragmentManager(); Fragment compassFragment = fragmentManager.findFragmentById(R.id.compass_frame); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.hide(compassFragment); transaction.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.activity.cachelist.actions.menu; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.xmlimport.CacheSyncer; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Singleton; import android.util.Log; @Singleton public class MenuActionSyncGpx implements Action { private CacheSyncer cacheSyncer; private final Provider<CacheSyncer> cacheSyncerProvider; private boolean syncInProgress; @Inject public MenuActionSyncGpx(Injector injector) { cacheSyncerProvider = injector.getProvider(CacheSyncer.class); syncInProgress = false; } // For testing. public MenuActionSyncGpx(Provider<CacheSyncer> gpxImporterProvider) { cacheSyncerProvider = gpxImporterProvider; syncInProgress = false; } public void abort() { Log.d("GeoBeagle", "MenuActionSyncGpx aborting: " + syncInProgress); if (!syncInProgress) return; cacheSyncer.abort(); syncInProgress = false; } @Override public void act() { Log.d("GeoBeagle", "MenuActionSync importing"); cacheSyncer = cacheSyncerProvider.get(); cacheSyncer.syncGpxs(); syncInProgress = 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.cachelist.actions.menu; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.activity.EditCacheActivity; import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory; import com.google.code.geobeagle.database.LocationSaver; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class MenuActionMyLocation implements Action { private final ErrorDisplayer mErrorDisplayer; private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory; private final LocationSaver mLocationSaver; private final Activity mActivity; @Inject public MenuActionMyLocation(Activity activity, ErrorDisplayer errorDisplayer, GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) { mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory; mErrorDisplayer = errorDisplayer; mLocationSaver = locationSaver; mActivity = activity; } @Override public void act() { final Geocache myLocation = mGeocacheFromMyLocationFactory.create(); if (myLocation == null) { mErrorDisplayer.displayError(R.string.current_location_null); return; } mLocationSaver.saveLocation(myLocation); final Intent intent = new Intent(mActivity, EditCacheActivity.class); intent.putExtra("geocache", myLocation); mActivity.startActivityForResult(intent, 0); } }
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.cachelist.actions.context; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.EditCacheActivity; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.inject.Inject; import android.content.Context; import android.content.Intent; public class ContextActionEdit implements ContextAction { private final Context mContext; private final GeocacheVectors mGeocacheVectors; @Inject public ContextActionEdit(GeocacheVectors geocacheVectors, Context context) { mGeocacheVectors = geocacheVectors; mContext = context; } public void act(int position) { Geocache selected = mGeocacheVectors.get(position).getGeocache(); Intent intent = new Intent(mContext, EditCacheActivity.class); intent.putExtra("geocache", selected); mContext.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.cachelist.actions.context; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.inject.Inject; import android.content.Context; import android.content.Intent; public class ContextActionView implements ContextAction { private final Context context; private final GeocacheVectors geocacheVectors; @Inject public ContextActionView(GeocacheVectors geocacheVectors, Context context) { this.geocacheVectors = geocacheVectors; this.context = context; } @Override public void act(int position) { Intent intent = new Intent(context, com.google.code.geobeagle.activity.compass.CompassActivity.class); intent.putExtra("geocache", geocacheVectors.get(position).getGeocache()).setAction( GeocacheListController.SELECT_CACHE); context.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.cachelist.actions.context; public interface ContextAction { public void act(int position); }
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.cachelist.actions.context; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.actions.context.delete.ContextActionDeleteStore; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.database.CacheSqlWriter; import com.google.inject.Inject; import com.google.inject.Provider; import roboguice.inject.ContextScoped; import android.app.Activity; @ContextScoped public class ContextActionDelete implements ContextAction { private final Activity activity; private final Provider<CacheSqlWriter> cacheWriterProvider; private final GeocacheVectors geocacheVectors; private final CacheListRefresh cacheListRefresh; private final ContextActionDeleteStore contextActionDeleteStore; @Inject public ContextActionDelete(GeocacheVectors geocacheVectors, Provider<CacheSqlWriter> cacheWriterProvider, Activity activity, ContextActionDeleteStore contextActionDeleteStore, CacheListRefresh cacheListRefresh) { this.geocacheVectors = geocacheVectors; this.cacheWriterProvider = cacheWriterProvider; this.activity = activity; this.contextActionDeleteStore = contextActionDeleteStore; this.cacheListRefresh = cacheListRefresh; } @Override public void act(int position) { GeocacheVector geocacheVector = geocacheVectors.get(position); String cacheName = geocacheVector.getName().toString(); String cacheId = geocacheVector.getId().toString(); contextActionDeleteStore.saveCacheToDelete(cacheId, cacheName); activity.showDialog(R.id.delete_cache); } public void delete() { String cacheId = contextActionDeleteStore.getCacheId(); cacheWriterProvider.get().deleteCache(cacheId); cacheListRefresh.forceRefresh(); } public CharSequence getConfirmDeleteBodyText() { return String.format(activity.getString(R.string.confirm_delete_body_text), contextActionDeleteStore.getCacheId(), contextActionDeleteStore.getCacheName()); } public CharSequence getConfirmDeleteTitle() { return String.format(activity.getString(R.string.confirm_delete_title), contextActionDeleteStore.getCacheId()); } }
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.cachelist.actions.context.delete; import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete; import com.google.inject.Inject; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class OnClickOk implements OnClickListener { private final ContextActionDelete contextActionDelete; @Inject public OnClickOk(ContextActionDelete contextActionDelete) { this.contextActionDelete = contextActionDelete; } @Override public void onClick(DialogInterface dialog, int whichButton) { contextActionDelete.delete(); dialog.dismiss(); } }
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.cachelist.actions.context.delete; import com.google.inject.Inject; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class ContextActionDeleteStore { private final SharedPreferences sharedPreferences; static final String CACHE_TO_DELETE_NAME = "cache-to-delete-name"; static final String CACHE_TO_DELETE_ID = "cache-to-delete-id"; @Inject public ContextActionDeleteStore(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public void saveCacheToDelete(String cacheId, String cacheName) { Editor editor = sharedPreferences.edit(); editor.putString(CACHE_TO_DELETE_ID, cacheId); editor.putString(CACHE_TO_DELETE_NAME, cacheName); editor.commit(); } public String getCacheId() { return sharedPreferences.getString(CACHE_TO_DELETE_ID, null); } public String getCacheName() { return sharedPreferences.getString(CACHE_TO_DELETE_NAME, null); } }
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.cachelist.actions.context.delete; import com.google.code.geobeagle.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete; import com.google.inject.Inject; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class ContextActionDeleteDialogHelper { private final ContextActionDelete contextActionDelete; private final OnClickOk onClickOk; private final Builder builder; private final LayoutInflater layoutInflater; private final OnClickCancelListener onClickCancelListener; @Inject public ContextActionDeleteDialogHelper(ContextActionDelete contextActionDelete, OnClickOk onClickOk, AlertDialog.Builder builder, LayoutInflater layoutInflater, OnClickCancelListener onClickCancelListener) { this.contextActionDelete = contextActionDelete; this.onClickOk = onClickOk; this.builder = builder; this.layoutInflater = layoutInflater; this.onClickCancelListener = onClickCancelListener; } public Dialog onCreateDialog() { View confirmDeleteCacheView = layoutInflater.inflate(R.layout.confirm_delete_cache, null); builder.setNegativeButton(R.string.confirm_delete_negative, onClickCancelListener); builder.setView(confirmDeleteCacheView); builder.setPositiveButton(R.string.delete_cache, onClickOk); return builder.create(); } public void onPrepareDialog(Dialog dialog) { CharSequence confirmDeleteTitle = contextActionDelete.getConfirmDeleteTitle(); dialog.setTitle(confirmDeleteTitle); TextView textView = (TextView)dialog.findViewById(R.id.delete_cache); textView.setText(contextActionDelete.getConfirmDeleteBodyText()); } }
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.cachelist; import com.google.inject.Singleton; @Singleton public class SearchTarget { private String target; public void setTarget(String target) { this.target = target; } public String getTarget() { return target; } public String getTitle() { if (target == null) { return ""; } return "Searching: '" + target + "'; "; } }
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.cachelist; import com.google.code.geobeagle.R; import com.google.code.geobeagle.R.id; import com.google.code.geobeagle.SuggestionProvider; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.cachelist.actions.context.delete.ContextActionDeleteDialogHelper; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListPresenter; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.app.Activity; import android.app.Dialog; import android.app.SearchManager; import android.content.Intent; import android.provider.SearchRecentSuggestions; import android.view.Menu; import android.view.MenuItem; public class CacheListDelegate { private final ActivitySaver activitySaver; private final ActivityVisible activityVisible; private final CacheListRefresh cacheListRefresh; private final GeocacheListController controller; private final Provider<DbFrontend> dbFrontendProvider; private final ImportIntentManager importIntentManager; private final CacheListPresenter presenter; private final LogFindDialogHelper logFindDialogHelper; private final ContextActionDeleteDialogHelper contextActionDeleteDialogHelper; private final Activity activity; public CacheListDelegate(ImportIntentManager importIntentManager, ActivitySaver activitySaver, CacheListRefresh cacheListRefresh, GeocacheListController geocacheListController, CacheListPresenter cacheListPresenter, Provider<DbFrontend> dbFrontendProvider, ActivityVisible activityVisible, LogFindDialogHelper logFindDialogHelper, ContextActionDeleteDialogHelper contextActionDeleteDialogHelper, Activity activity) { this.activitySaver = activitySaver; this.cacheListRefresh = cacheListRefresh; this.controller = geocacheListController; this.presenter = cacheListPresenter; this.importIntentManager = importIntentManager; this.dbFrontendProvider = dbFrontendProvider; this.activityVisible = activityVisible; this.logFindDialogHelper = logFindDialogHelper; this.contextActionDeleteDialogHelper = contextActionDeleteDialogHelper; this.activity = activity; } @Inject public CacheListDelegate(Injector injector) { this.activitySaver = injector.getInstance(ActivitySaver.class); this.cacheListRefresh = injector.getInstance(CacheListRefresh.class); this.controller = injector.getInstance(GeocacheListController.class); this.presenter = injector.getInstance(CacheListPresenter.class); this.importIntentManager = injector.getInstance(ImportIntentManager.class); this.dbFrontendProvider = injector.getProvider(DbFrontend.class); this.activityVisible = injector.getInstance(ActivityVisible.class); this.logFindDialogHelper = injector.getInstance(LogFindDialogHelper.class); this.contextActionDeleteDialogHelper = injector .getInstance(ContextActionDeleteDialogHelper.class); this.activity = injector.getInstance(Activity.class); } public boolean onContextItemSelected(MenuItem menuItem) { return controller.onContextItemSelected(menuItem); } public void onCreate(Injector injector) { InflatedGpsStatusWidget inflatedGpsStatusWidget = injector .getInstance(InflatedGpsStatusWidget.class); GpsStatusWidgetDelegate gpsStatusWidgetDelegate = injector .getInstance(GpsStatusWidgetDelegate.class); presenter.onCreate(); inflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate); } public void onCreateFragment(Object cacheListFragment) { presenter.onCreateFragment(cacheListFragment); } public boolean onCreateOptionsMenu(Menu menu) { return controller.onCreateOptionsMenu(menu); } public void onListItemClick(int position) { controller.onListItemClick(position); } public boolean onOptionsItemSelected(MenuItem item) { return controller.onOptionsItemSelected(item); } public void onPause() { activityVisible.setVisible(false); presenter.onPause(); controller.onPause(); activitySaver.save(ActivityType.CACHE_LIST); dbFrontendProvider.get().closeDatabase(); } public void onResume(SearchTarget searchTarget) { search(activity, searchTarget); activityVisible.setVisible(true); presenter.onResume(cacheListRefresh); controller.onResume(importIntentManager.isImport()); } Dialog onCreateDialog(Activity activity, int idDialog) { if (idDialog == id.menu_log_dnf || idDialog == id.menu_log_find) { return logFindDialogHelper.onCreateDialog(activity, idDialog); } return contextActionDeleteDialogHelper.onCreateDialog(); } public void onPrepareDialog(int id, Dialog dialog) { if (id == R.id.delete_cache) contextActionDeleteDialogHelper.onPrepareDialog(dialog); else logFindDialogHelper.onPrepareDialog(activity, id, dialog); } void search(Activity activity, SearchTarget searchTarget) { Intent intent = activity.getIntent(); if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); searchTarget.setTarget(query); SearchRecentSuggestions suggestions = new SearchRecentSuggestions(activity, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); suggestions.saveRecentQuery(query, null); } else { searchTarget.setTarget(null); } } }
Java
package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.inject.Inject; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; public class CacheListViewScrollListener implements OnScrollListener { private final UpdateFlag mUpdateFlag; @Inject public CacheListViewScrollListener(UpdateFlag updateFlag) { mUpdateFlag = updateFlag; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mUpdateFlag.setUpdatesEnabled(scrollState == SCROLL_STATE_IDLE); } }
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.cachelist; import com.google.inject.Singleton; @Singleton public class ActivityVisible { private boolean isVisible; public void setVisible(boolean isVisible) { this.isVisible = isVisible; } public boolean getVisible() { return isVisible; } }
Java
package com.google.code.geobeagle.activity.cachelist; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; class ImportIntentManager { static final String INTENT_EXTRA_IMPORT_TRIGGERED = "com.google.code.geabeagle.import_triggered"; private final Activity mActivity; @Inject ImportIntentManager(Activity activity) { this.mActivity = activity; } boolean isImport() { Intent intent = mActivity.getIntent(); if (intent == null) return false; String action = intent.getAction(); if (action == null) return false; if (!action.equals("android.intent.action.VIEW")) return false; if (intent.getBooleanExtra(INTENT_EXTRA_IMPORT_TRIGGERED, false)) return false; // Need to alter the intent so that the import isn't retriggered if // pause/resume is a result of the phone going to sleep and then // waking up again. intent.putExtra(INTENT_EXTRA_IMPORT_TRIGGERED, true); 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. */ /* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS 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.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.inject.Singleton; import java.util.ArrayList; @Singleton public class GeocacheVectors { private final ArrayList<GeocacheVector> mGeocacheVectorsList; public GeocacheVectors() { mGeocacheVectorsList = new ArrayList<GeocacheVector>(10); } public void add(GeocacheVector destinationVector) { mGeocacheVectorsList.add(0, destinationVector); } public void addLocations(ArrayList<Geocache> geocaches, LocationControlBuffered locationControlBuffered) { for (Geocache geocache : geocaches) { add(new GeocacheVector(geocache, locationControlBuffered)); } } public GeocacheVector get(int position) { return mGeocacheVectorsList.get(position); } public ArrayList<GeocacheVector> getGeocacheVectorsList() { return mGeocacheVectorsList; } public void remove(int position) { mGeocacheVectorsList.remove(position); } public void reset(int size) { mGeocacheVectorsList.clear(); mGeocacheVectorsList.ensureCapacity(size); } public int size() { return mGeocacheVectorsList.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.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.location.Location; import android.util.FloatMath; import java.util.Comparator; public class GeocacheVector { public static class LocationComparator implements Comparator<GeocacheVector> { @Override public int compare(GeocacheVector geocacheVector1, GeocacheVector geocacheVector2) { final float d1 = geocacheVector1.getDistance(); final float d2 = geocacheVector2.getDistance(); if (d1 < d2) return -1; if (d1 > d2) return 1; return 0; } } // From http://www.anddev.org/viewtopic.php?p=20195. public static float calculateDistanceFast(float lat1, float lon1, float lat2, float lon2) { double dLat = Math.toRadians(lat2 - lat1); double dLon = Math.toRadians(lon2 - lon1); final float sinDLat = FloatMath.sin((float)(dLat / 2)); final float sinDLon = FloatMath.sin((float)(dLon / 2)); float a = sinDLat * sinDLat + FloatMath.cos((float)Math.toRadians(lat1)) * FloatMath.cos((float)Math.toRadians(lat2)) * sinDLon * sinDLon; float c = (float)(2 * Math.atan2(FloatMath.sqrt(a), FloatMath.sqrt(1 - a))); return 6371000 * c; } // TODO: distance formatter shouldn't be in every object. private final Geocache mGeocache; private float mDistance; private final LocationControlBuffered mLocationControlBuffered; float getDistance() { return mDistance; } public void setDistance(float f) { mDistance = f; } public GeocacheVector(Geocache geocache, LocationControlBuffered locationControlBuffered) { mGeocache = geocache; mLocationControlBuffered = locationControlBuffered; } public float getDistanceFast() { Location here = mLocationControlBuffered.getLocation(); return calculateDistanceFast((float)here.getLatitude(), (float)here.getLongitude(), (float)mGeocache.getLatitude(), (float)mGeocache.getLongitude()); } public CharSequence getFormattedDistance(DistanceFormatter distanceFormatter, BearingFormatter relativeBearingFormatter) { // Use the slower, more accurate distance for display. final float[] distanceAndBearing = mGeocache .calculateDistanceAndBearing(mLocationControlBuffered.getLocation()); if (distanceAndBearing[0] == -1) { return ""; } final float azimuth = mLocationControlBuffered.getAzimuth(); final CharSequence formattedDistance = distanceFormatter .formatDistance(distanceAndBearing[0]); final String formattedBearing = relativeBearingFormatter.formatBearing( distanceAndBearing[1], azimuth); return formattedDistance + " " + formattedBearing; } public Geocache getGeocache() { return mGeocache; } public CharSequence getId() { return mGeocache.getId(); } public CharSequence getName() { return mGeocache.getName(); } public CharSequence getFormattedAttributes() { return mGeocache.getFormattedAttributes(); } }
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.cachelist.model; import roboguice.config.AbstractAndroidModule; public class ModelModule extends AbstractAndroidModule { @Override protected void configure() { } }
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.cachelist.model; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import java.util.ArrayList; @ContextScoped public class CacheListData { private final GeocacheVectors mGeocacheVectors; @Inject public CacheListData(GeocacheVectors geocacheVectors) { mGeocacheVectors = geocacheVectors; } public void add(ArrayList<Geocache> geocaches, LocationControlBuffered locationControlBuffered) { mGeocacheVectors.reset(geocaches.size()); mGeocacheVectors.addLocations(geocaches, locationControlBuffered); } public ArrayList<GeocacheVector> get() { return mGeocacheVectors.getGeocacheVectorsList(); } public int size() { return mGeocacheVectors.size(); } }
Java
package com.google.code.geobeagle.activity.cachelist; import android.view.ContextMenu; // TODO(sng): Rename to CacheListController. public class ViewMenuAdderHoneycomb implements ViewMenuAdder { @Override public void addViewMenu(ContextMenu menu) { } }
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.cachelist; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListAdapter; import com.google.code.geobeagle.activity.compass.CompassFragment; import com.google.inject.Injector; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ListFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.HeaderViewListAdapter; import android.widget.ListView; public class CacheListFragment extends ListFragment { private GeocacheVectors geocacheVectors; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getCacheListDelegate().onCreateFragment(this); } @Override public boolean onContextItemSelected(MenuItem item) { return getCacheListDelegate().onContextItemSelected(item) || super.onContextItemSelected(item); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Injector injector = ((CacheListActivityHoneycomb)getActivity()).getInjector(); geocacheVectors = injector.getInstance(GeocacheVectors.class); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.cache_list, container, false); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); HeaderViewListAdapter adapter = (HeaderViewListAdapter)l.getAdapter(); GeocacheListAdapter wrappedAdapter = (GeocacheListAdapter)adapter.getWrappedAdapter(); wrappedAdapter.setSelected(position-1); showDetails(position - 1); } void showDetails(int position) { int positionToShow = position; int cacheCount = geocacheVectors.size(); if (cacheCount == 0) return; if (positionToShow >= cacheCount) positionToShow = cacheCount - 1; CompassFragment compassFragment = new CompassFragment(); Bundle bundle = new Bundle(); geocacheVectors.get(position).getGeocache().saveToBundle(bundle); compassFragment.setArguments(bundle); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.compass_frame, compassFragment); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { return getCacheListDelegate().onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } private CacheListDelegate getCacheListDelegate() { return ((CacheListActivityHoneycomb)getActivity()).getCacheListDelegate(); } }
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.cachelist; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.actions.MenuActionMap; import com.google.code.geobeagle.actions.MenuActionSearchOnline; import com.google.code.geobeagle.actions.MenuActionSettings; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionDeleteAllCaches; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionMyLocation; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx; import com.google.inject.Inject; import com.google.inject.Injector; import android.content.res.Resources; public class CacheListMenuActions extends MenuActions { @Inject public CacheListMenuActions(Injector injector, Resources resources) { super(resources); add(new MenuActionBase(R.string.menu_sync, injector.getInstance(MenuActionSyncGpx.class))); add(new MenuActionBase(R.string.menu_delete_all_caches, injector.getInstance(MenuActionDeleteAllCaches.class))); add(new MenuActionBase(R.string.menu_add_my_location, injector.getInstance(MenuActionMyLocation.class))); add(new MenuActionBase(R.string.menu_search_online, injector.getInstance(MenuActionSearchOnline.class))); add(new MenuActionBase(R.string.menu_map, injector.getInstance(MenuActionMap.class))); add(new MenuActionBase(R.string.menu_settings, injector.getInstance(MenuActionSettings.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; import com.google.code.geobeagle.activity.compass.GeocacheFromPreferencesFactory; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; public class ActivityRestorer { private final Restorer[] restorers; private final SharedPreferences sharedPreferences; public SharedPreferences getSharedPreferences() { return sharedPreferences; } @Inject public ActivityRestorer(Activity activity, GeocacheFromPreferencesFactory geocacheFromPreferencesFactory, SharedPreferences sharedPreferences, CacheListRestorer cacheListRestorer) { this.sharedPreferences = sharedPreferences; this.restorers = new Restorer[] { cacheListRestorer, cacheListRestorer, cacheListRestorer, new ViewCacheRestorer(geocacheFromPreferencesFactory, sharedPreferences, activity) }; } public boolean restore(int flags, ActivityType currentActivityType) { if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { return false; } final String lastActivity = sharedPreferences.getString(ActivitySaver.LAST_ACTIVITY, ActivityType.NONE.name()); final ActivityType activityType = ActivityType.valueOf(lastActivity); if (currentActivityType != activityType) { Log.d("GeoBeagle", "restoring: " + activityType); restorers[activityType.toInt()].restore(); return true; } 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.preferences; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.inject.Inject; import roboguice.activity.GuicePreferenceActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.widget.Toast; public class EditPreferences extends GuicePreferenceActivity { static class SyncPreferencesChangeListener implements OnPreferenceChangeListener { private final SharedPreferences sharedPreferences; private final Toaster toaster; @Inject public SyncPreferencesChangeListener(SharedPreferences sharedPreferences, Toaster toaster) { this.sharedPreferences = sharedPreferences; this.toaster = toaster; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String otherKey = preference.getKey().equals(Preferences.BCACHING_ENABLED) ? Preferences.SDCARD_ENABLED : Preferences.BCACHING_ENABLED; if (newValue == Boolean.FALSE && !sharedPreferences.getBoolean(otherKey, false)) { toaster.toast(R.string.must_have_a_sync_method, Toast.LENGTH_SHORT); return false; } return true; } } private FilterCleanliness filterCleanliness; private FilterSettingsChangeListener onPreferenceChangeListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference showFoundCachesPreference = findPreference(Preferences.SHOW_FOUND_CACHES); Preference showDnfCachesPreference = findPreference(Preferences.SHOW_DNF_CACHES); Preference showUnavailableCachesPreference = findPreference(Preferences.SHOW_UNAVAILABLE_CACHES); Preference showWaypointsPreference = findPreference(Preferences.SHOW_WAYPOINTS); onPreferenceChangeListener = getInjector().getInstance(FilterSettingsChangeListener.class); SyncPreferencesChangeListener syncPreferencesChangeListener = getInjector().getInstance( SyncPreferencesChangeListener.class); showWaypointsPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showFoundCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showDnfCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showUnavailableCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); Preference sdCardEnabledPreference = findPreference(Preferences.SDCARD_ENABLED); Preference bcachingEnabledPreference = findPreference(Preferences.BCACHING_ENABLED); sdCardEnabledPreference.setOnPreferenceChangeListener(syncPreferencesChangeListener); bcachingEnabledPreference.setOnPreferenceChangeListener(syncPreferencesChangeListener); filterCleanliness = getInjector().getInstance(FilterCleanliness.class); } @Override public void onPause() { super.onPause(); filterCleanliness.markDirty(onPreferenceChangeListener.hasChanged()); } @Override public void onResume() { super.onResume(); // Defensively set dirty bit in case we crash before onPause. This is // better than setting the dirty bit every time the preferences change // because it doesn't slow down clicking/unclicking the checkbox. filterCleanliness.markDirty(true); onPreferenceChangeListener.resetHasChanged(); } }
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.preferences; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; class FilterSettingsChangeListener implements OnPreferenceChangeListener { private boolean hasChanged = false; @Override public boolean onPreferenceChange(Preference preference, Object newValue) { hasChanged = true; return true; } public void resetHasChanged() { hasChanged = false; } public boolean hasChanged() { return hasChanged; } }
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.preferences; public class Preferences { public static final String BCACHING_ENABLED = "bcaching-enabled"; public static final String BCACHING_HOSTNAME = "bcaching-hostname"; public static final String BCACHING_PASSWORD = "bcaching-password"; public static final String BCACHING_USERNAME = "bcaching-username"; public static final String SDCARD_ENABLED = "sdcard-enabled"; public static final String SHOW_DNF_CACHES = "show-dnf-caches"; public static final String SHOW_FOUND_CACHES = "show-found-caches"; public static final String SHOW_UNAVAILABLE_CACHES = "show-unavailable-caches"; public static final String SHOW_WAYPOINTS = "show-waypoints"; }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; /** * This {@code WakefulBroadcastReceiver} takes care of creating and managing a * partial wake lock for your app. It passes off the work of processing the GCM * message to an {@code IntentService}, while ensuring that the device does not * go back to sleep in the transition. The {@code IntentService} calls * {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to * release the wake lock. */ public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.util.Log; /** * This {@code IntentService} does the actual handling of the GCM message. * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a * partial wake lock for this service while the service does its work. When the * service is finished, it calls {@code completeWakefulIntent()} to release the * wake lock. */ public class GcmIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GcmIntentService() { super("GcmIntentService"); } public static final String TAG = "GCM Demo"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. sendNotification("Received: " + extras.toString()); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(String msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, DemoActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_gcm) .setContentTitle("GCM Notification") .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** * Substitute you own sender ID here. This is the project number you got * from the API Console, as described in "Getting Started." */ String SENDER_ID = "Your-Sender-ID"; /** * Tag used on log messages. */ static final String TAG = "GCM Demo"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); Context context; String regid; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); context = getApplicationContext(); // Check device for Play Services APK. If check succeeds, proceed with GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } @Override protected void onResume() { super.onResume(); // Check device for Play Services APK. checkPlayServices(); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * Stores the registration ID and the app versionCode in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } /** * Gets the current registration ID for application on GCM service, if there is one. * <p> * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing * registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } // Send an upstream message. public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } } @Override protected void onDestroy() { super.onDestroy(); } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(DemoActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send * messages to your app. Not needed for this demo since the device sends upstream messages * to a server that echoes back the message using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { // Your implementation here. } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is thread-safe but not persistent (it will lost the data when the * app is restarted) - it is meant just as an example. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); synchronized (regIds) { regIds.add(regId); } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); synchronized (regIds) { regIds.remove(regId); } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); synchronized (regIds) { regIds.remove(oldId); regIds.add(newId); } } /** * Gets all registered devices. */ public static List<String> getDevices() { synchronized (regIds) { return new ArrayList<String>(regIds); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private static final int MULTICAST_SIZE = 1000; private Sender sender; private static final Executor threadPool = Executors.newFixedThreadPool(5); @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); status = "Sent message to one device: " + result; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == MULTICAST_SIZE || counter == total) { asyncSend(partialDevices); partialDevices.clear(); tasks++; } } status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } private void asyncSend(List<String> partialDevices) { // make a copy final List<String> devices = new ArrayList<String>(partialDevices); threadPool.execute(new Runnable() { public void run() { Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.send(message, devices, 5); } catch (IOException e) { logger.log(Level.SEVERE, "Error posting messages", e); return; } List<Result> results = multicastResult.getResults(); // analyze the results for (int i = 0; i < devices.size(); i++) { String regId = devices.get(i); Result result = results.get(i); String messageId = result.getMessageId(); if (messageId != null) { logger.fine("Succesfully sent message to device: " + regId + "; messageId = " + messageId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.info("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it logger.info("Unregistered device: " + regId); Datastore.unregister(regId); } else { logger.severe("Error sending message to " + regId + ": " + error); } } } }}); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private Message createMessage() { Message message = new Message.Builder().build(); return message; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = createMessage(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String multicastKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(multicastKey); Message message = createMessage(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, multicastKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, multicastKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/send").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); tasks++; } } status = "Queued tasks to send " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java