Cleaned up code

This commit is contained in:
2012-07-22 09:36:54 -04:00
parent 6fcc65a605
commit fee38864a7
29 changed files with 984 additions and 703 deletions

View File

@@ -22,12 +22,14 @@ import com.skyhookwireless.wps.WPSReturnCode;
import com.skyhookwireless.wps.XPS; import com.skyhookwireless.wps.XPS;
/** /**
* this calls will be used to create skyhook object that uses an listener interface to interact with the rest of location ringer * this calls will be used to create skyhook object that uses an listener
* interface to interact with the rest of location ringer
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHook implements GeoPointLocationListener{ public class SkyHook implements GeoPointLocationListener {
private class XPScallback implements WPSPeriodicLocationCallback { private class XPScallback implements WPSPeriodicLocationCallback {
@Override @Override
public void done() { public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE)); mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
@@ -45,6 +47,7 @@ public class SkyHook implements GeoPointLocationListener{
return WPSContinuation.WPS_CONTINUE; return WPSContinuation.WPS_CONTINUE;
} }
} }
public static final String TAG = "Skyhook"; public static final String TAG = "Skyhook";
public static final String USERNAME = "cjyh95q32gsc"; public static final String USERNAME = "cjyh95q32gsc";
public static final String USERNAME_FOR_TESTING = "twentycodes"; public static final String USERNAME_FOR_TESTING = "twentycodes";
@@ -56,7 +59,7 @@ public class SkyHook implements GeoPointLocationListener{
private final XPS mXps; private final XPS mXps;
private final Context mContext; private final Context mContext;
private GeoPointLocationListener mListener; private GeoPointLocationListener mListener;
private long mPeriod = 0l; //period is in milliseconds for periodic updates private long mPeriod = 0l; // period is in milliseconds for periodic updates
private final int mIterations = 0; private final int mIterations = 0;
private WPSAuthentication mWPSAuthentication; private WPSAuthentication mWPSAuthentication;
private static Handler mHandler; private static Handler mHandler;
@@ -71,29 +74,29 @@ public class SkyHook implements GeoPointLocationListener{
private boolean isFirstFix; private boolean isFirstFix;
/* /*
* this runnable will be used to check if we have location from skyhook, * this runnable will be used to check if we have location from skyhook, if
* if we dont, then we will us android's location services to fall back on. * we dont, then we will us android's location services to fall back on.
*/ */
private final Runnable mFallBack = new Runnable() { private final Runnable mFallBack = new Runnable() {
@Override @Override
public void run() { public void run() {
mHandler.removeCallbacks(mFallBack); mHandler.removeCallbacks(mFallBack);
Log.d(TAG,"skyhook, "+ (hasLocation ? "is" : "isn't") +" working!"); Log.d(TAG, "skyhook, " + (hasLocation ? "is" : "isn't") + " working!");
if(! hasLocation && mSkyHookFallback == null && isEnabled){ if (!hasLocation && mSkyHookFallback == null && isEnabled) {
Log.d(TAG,"falling back on android"); Log.d(TAG, "falling back on android");
mSkyHookFallback = new AndroidGPS(mContext); mSkyHookFallback = new AndroidGPS(mContext);
mSkyHookFallback.enableLocationUpdates(SkyHook.this); mSkyHookFallback.enableLocationUpdates(SkyHook.this);
/* /*
* Schedule another check, if skyhook is still enabled * Schedule another check, if skyhook is still enabled
*/ */
if(mXps != null) if (mXps != null)
mHandler.postDelayed(mFallBack, mFallBackDelay ); mHandler.postDelayed(mFallBack, mFallBackDelay);
} else { } else {
Log.d(TAG,"already fell back on android"); Log.d(TAG, "already fell back on android");
if(mSkyHookFallback != null) { if (mSkyHookFallback != null) {
Log.d(TAG,"got location, picking up the slack"); Log.d(TAG, "got location, picking up the slack");
mSkyHookFallback.disableLocationUpdates(); mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null; mSkyHookFallback = null;
} }
@@ -108,14 +111,15 @@ public class SkyHook implements GeoPointLocationListener{
private final Runnable mPeriodicUpdates = new Runnable() { private final Runnable mPeriodicUpdates = new Runnable() {
@Override @Override
public void run() { public void run() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"geting location"); Log.d(TAG, "geting location");
mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback); mXps.getXPSLocation(mWPSAuthentication, mIterations, XPS.EXACT_ACCURACY, mXPScallback);
} }
}; };
/** /**
* Constructors a new skyhook object * Constructors a new skyhook object
*
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
@@ -131,8 +135,10 @@ public class SkyHook implements GeoPointLocationListener{
/** /**
* Constructors a new skyhook object * Constructors a new skyhook object
*
* @param context * @param context
* @param period between location updates in milliseconds * @param period
* between location updates in milliseconds
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHook(final Context context, final long period) { public SkyHook(final Context context, final long period) {
@@ -141,13 +147,15 @@ public class SkyHook implements GeoPointLocationListener{
} }
/** /**
* request current user location, note that the listeners onLocationChanged() will be call multiple times. * request current user location, note that the listeners
* updates will stop once an accurate location is determined. * onLocationChanged() will be call multiple times. updates will stop once
* an accurate location is determined.
*
* @author Ricky Barrette * @author Ricky Barrette
*/ */
public void getLoctaion(){ public void getLoctaion() {
Log.d(TAG,"getLocation()"); Log.d(TAG, "getLocation()");
if (mListener != null){ if (mListener != null) {
mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM); mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM);
mHandler.post(mPeriodicUpdates); mHandler.post(mPeriodicUpdates);
} }
@@ -155,13 +163,14 @@ public class SkyHook implements GeoPointLocationListener{
/** /**
* Attempts to register the the listener for periodic updates * Attempts to register the the listener for periodic updates
*
* @author Ricky Barrette * @author Ricky Barrette
*/ */
public void getUpdates(){ public void getUpdates() {
Log.d(TAG,"getUpdates()"); Log.d(TAG, "getUpdates()");
if (mListener != null) { if (mListener != null) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.i(TAG, "username: " + SkyHookRegistration.getUserName(mContext)); Log.i(TAG, "username: " + SkyHookRegistration.getUserName(mContext));
mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM); mWPSAuthentication = new WPSAuthentication(SkyHookRegistration.getUserName(mContext), REALM);
@@ -175,45 +184,47 @@ public class SkyHook implements GeoPointLocationListener{
* @return true is skyhook is enabled * @return true is skyhook is enabled
* @author ricky barrette * @author ricky barrette
*/ */
public boolean isEnabled(){ public boolean isEnabled() {
return isEnabled; return isEnabled;
} }
@Override @Override
public void onFirstFix(final boolean firstFix) { public void onFirstFix(final boolean firstFix) {
if(mListener != null) if (mListener != null)
mListener.onFirstFix(firstFix); mListener.onFirstFix(firstFix);
} }
/** /**
* called from our skyhook to android fall back class * called from our skyhook to android fall back class (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int) * @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint,
* int)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(final GeoPoint point, final int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(! hasLocation) if (!hasLocation)
if(mListener != null) if (mListener != null)
mListener.onLocationChanged(point, accuracy); mListener.onLocationChanged(point, accuracy);
} }
/** /**
* Removes any current registration for location updates of the current activity * Removes any current registration for location updates of the current
* with the given LocationListener. Following this call, updates will no longer * activity with the given LocationListener. Following this call, updates
* occur for this listener. * will no longer occur for this listener.
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void removeUpdates() { public void removeUpdates() {
Log.d(TAG,"removeUpdates()"); Log.d(TAG, "removeUpdates()");
mHandler.removeCallbacks(mFallBack); mHandler.removeCallbacks(mFallBack);
mListener = null; mListener = null;
isPeriodicEnabled = false; isPeriodicEnabled = false;
if(mXps != null) if (mXps != null)
mXps.abort(); mXps.abort();
if(mSkyHookFallback != null) { if (mSkyHookFallback != null) {
Log.d(TAG,"disabling fallback"); Log.d(TAG, "disabling fallback");
mSkyHookFallback.disableLocationUpdates(); mSkyHookFallback.disableLocationUpdates();
mSkyHookFallback = null; mSkyHookFallback = null;
isEnabled = false; isEnabled = false;
@@ -222,14 +233,15 @@ public class SkyHook implements GeoPointLocationListener{
} }
/** /**
* Used for receiving notifications from SkyHook when * Used for receiving notifications from SkyHook when the location has
* the location has changed. These methods are called if the * changed. These methods are called if the LocationListener has been
* LocationListener has been registered with the location manager service using the method. * registered with the location manager service using the method.
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocationListener(final GeoPointLocationListener listener){ public void setLocationListener(final GeoPointLocationListener listener) {
Log.d(TAG,"setLocationListener()"); Log.d(TAG, "setLocationListener()");
if (mListener == null) if (mListener == null)
mListener = listener; mListener = listener;
} }
@@ -240,63 +252,65 @@ public class SkyHook implements GeoPointLocationListener{
@Override @Override
public void handleMessage(final Message msg) { public void handleMessage(final Message msg) {
switch (msg.what) { switch (msg.what) {
case LOCATION_MESSAGE: case LOCATION_MESSAGE:
if (msg.obj instanceof WPSLocation) { if (msg.obj instanceof WPSLocation) {
final WPSLocation location = (WPSLocation) msg.obj; final WPSLocation location = (WPSLocation) msg.obj;
if (mListener != null && location != null) { if (mListener != null && location != null) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"got location "+ location.getLatitude() +", "+ location.getLongitude()+" +- "+ location.getHPE() +"m"); Log.d(TAG, "got location " + location.getLatitude() + ", " + location.getLongitude() + " +- " + location.getHPE() + "m");
mListener.onLocationChanged(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), location.getHPE()); mListener.onLocationChanged(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), location.getHPE());
mListener.onFirstFix(isFirstFix); mListener.onFirstFix(isFirstFix);
hasLocation = true; hasLocation = true;
isFirstFix = false; isFirstFix = false;
}
} }
return; }
return;
case ERROR_MESSAGE: case ERROR_MESSAGE:
if( msg.obj instanceof WPSReturnCode) { if (msg.obj instanceof WPSReturnCode) {
final WPSReturnCode code = (WPSReturnCode) msg.obj; final WPSReturnCode code = (WPSReturnCode) msg.obj;
if ( code != null) if (code != null)
Log.w(TAG, code.toString()); Log.w(TAG, code.toString());
hasLocation = false; hasLocation = false;
/* /*
* check to see if the error returned is an WPS_ERROR_UNAUTHORIZED * check to see if the error returned is an
* then check to see if this is the second occurrence of WPS_ERROR_UNAUTHORIZED, * WPS_ERROR_UNAUTHORIZED then check to see if this is
* if so we will stop skyhook's services to cut down the work load * the second occurrence of WPS_ERROR_UNAUTHORIZED, if
*/ * so we will stop skyhook's services to cut down the
if(code == WPSReturnCode.WPS_ERROR_UNAUTHORIZED){ * work load
if (isUnauthorized){ */
isPeriodicEnabled = false; if (code == WPSReturnCode.WPS_ERROR_UNAUTHORIZED) {
mXps.abort(); if (isUnauthorized) {
// mXps = null; isPeriodicEnabled = false;
} mXps.abort();
isUnauthorized = true; // mXps = null;
}
/*
* check to see if we already have a fall back Scheduled
* if we dont, and there is not fallback already in place, then schedule one
*/
if(! isFallBackScheduled && mSkyHookFallback == null && isEnabled) {
Log.d(TAG, "scheduling fallback");
postDelayed(mFallBack, mFallBackDelay);
isFallBackScheduled = true;
} }
isUnauthorized = true;
} }
return;
case DONE_MESSAGE: /*
if (isPeriodicEnabled) { * check to see if we already have a fall back Scheduled
postDelayed(mPeriodicUpdates, mPeriod); * if we dont, and there is not fallback already in
Log.d(TAG,"done getting location"); * place, then schedule one
*/
if (!isFallBackScheduled && mSkyHookFallback == null && isEnabled) {
Log.d(TAG, "scheduling fallback");
postDelayed(mFallBack, mFallBackDelay);
isFallBackScheduled = true;
} }
return; }
return;
case DONE_MESSAGE:
if (isPeriodicEnabled) {
postDelayed(mPeriodicUpdates, mPeriod);
Log.d(TAG, "done getting location");
}
return;
} }
} }
}; };

View File

@@ -17,39 +17,42 @@ import com.skyhookwireless.wps.XPS;
/** /**
* this class will be used to register new users with skyhook * this class will be used to register new users with skyhook
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHookRegistration{ public class SkyHookRegistration {
/** /**
* returns the users username * returns the users username
*
* @param context * @param context
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public static String getUserName(final Context context){ public static String getUserName(final Context context) {
switch(LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR){ switch (LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR) {
case NORMAL: case NORMAL:
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null) if (tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null"); Log.v(SkyHook.TAG, "TelephonyManager is null");
return tm.getLine1Number(); return tm.getLine1Number();
case RETURN_NULL: case RETURN_NULL:
return null; return null;
case USE_TESTING_USERNAME: case USE_TESTING_USERNAME:
return SkyHook.USERNAME_FOR_TESTING; return SkyHook.USERNAME_FOR_TESTING;
} }
return null; return null;
} }
private final XPS mXps; private final XPS mXps;
private final Context mContext; private final Context mContext;
public SkyHookRegistration(final Context context){ public SkyHookRegistration(final Context context) {
mContext = context; mContext = context;
mXps = new XPS(context); mXps = new XPS(context);
} }
@@ -58,21 +61,23 @@ public class SkyHookRegistration{
* attempts to register the user by their cell # * attempts to register the user by their cell #
* *
* TODO hash cell number for privacy * TODO hash cell number for privacy
* @param listener for call back methods *
* @param listener
* for call back methods
* @author ricky barrette * @author ricky barrette
*/ */
public void registerNewUser(final RegistrationCallback listener){ public void registerNewUser(final RegistrationCallback listener) {
if(mXps != null){ if (mXps != null) {
final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null) if (tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null"); Log.v(SkyHook.TAG, "TelephonyManager is null");
final String newUser = tm.getLine1Number(); final String newUser = tm.getLine1Number();
if(Debug.DEBUG) if (Debug.DEBUG)
Log.v(SkyHook.TAG, "newUser = " + newUser); Log.v(SkyHook.TAG, "newUser = " + newUser);
if(newUser == null) if (newUser == null)
Log.e(SkyHook.TAG,"users number is null"); Log.e(SkyHook.TAG, "users number is null");
mXps.registerUser(new WPSAuthentication(SkyHook.USERNAME, SkyHook.REALM), new WPSAuthentication(newUser, SkyHook.REALM), listener); mXps.registerUser(new WPSAuthentication(SkyHook.USERNAME, SkyHook.REALM), new WPSAuthentication(newUser, SkyHook.REALM), listener);
} }
} }

View File

@@ -26,44 +26,56 @@ import com.skyhookwireless.wps.WPSContinuation;
import com.skyhookwireless.wps.WPSReturnCode; import com.skyhookwireless.wps.WPSReturnCode;
/** /**
* This service class will be used broadcast the users location either one time, or periodically. * This service class will be used broadcast the users location either one time,
* To use as a one shot location service: * or periodically. To use as a one shot location service: <blockquote>
* <blockquote><pre>PendingIntent pendingIntent = PendingIntent.getService(context, 0, SkyHookService.startService(context), 0); *
* <pre>
* PendingIntent pendingIntent = PendingIntent.getService(context, 0, SkyHookService.startService(context), 0);
* or * or
* Intent service = new Intent(context, SkyHookService.class); * Intent service = new Intent(context, SkyHookService.class);
* context.startService(service);<pre></bloackquote> * context.startService(service);
*
* <pre>
* </bloackquote>
* To use as a recurring service: * To use as a recurring service:
* <blockquote>SkyHookService.startService(this, (60000 * Integer.parseInt(ringer.getString(UPDATE_INTVERVAL , "5")))).run();</bloackquote> * <blockquote>SkyHookService.startService(this, (60000 * Integer.parseInt(ringer.getString(UPDATE_INTVERVAL , "5")))).run();</bloackquote>
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHookService extends Service implements GeoPointLocationListener, RegistrationCallback{ public class SkyHookService extends Service implements GeoPointLocationListener, RegistrationCallback {
public static final String TAG = "SkyHookService"; public static final String TAG = "SkyHookService";
public static final int REQUEST_CODE = 32741942; public static final int REQUEST_CODE = 32741942;
/** /**
* a convince method for getting an intent to start the service * a convince method for getting an intent to start the service
*
* @param context * @param context
* @return a intent that will be used to start the service * @return a intent that will be used to start the service
* @author ricky barrette * @author ricky barrette
*/ */
public static Intent getStartServiceIntent(final Context context){ public static Intent getStartServiceIntent(final Context context) {
return new Intent(context, SkyHookService.class); return new Intent(context, SkyHookService.class);
} }
/** /**
* a convince method for stopping the service and removing its que from the alarm manager * a convince method for stopping the service and removing its que from the
* alarm manager
*
* @param context * @param context
* @return a runnable that will stop the service * @return a runnable that will stop the service
* @author ricky barrette * @author ricky barrette
*/ */
public static Runnable stopService(final Context context){ public static Runnable stopService(final Context context) {
return new Runnable(){ return new Runnable() {
@Override @Override
public void run(){ public void run() {
context.stopService(new Intent(context, SkyHookService.class)); context.stopService(new Intent(context, SkyHookService.class));
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, SkyHookService.class), 0)); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context,
SkyHookService.class), 0));
} }
}; };
} }
private SkyHook mSkyhook; private SkyHook mSkyhook;
protected long mPeriod = -1; protected long mPeriod = -1;
private GeoPoint mLocation; private GeoPoint mLocation;
@@ -82,7 +94,7 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
private void braodcastLocation() { private void braodcastLocation() {
if (mLocation != null) { if (mLocation != null) {
final Intent locationUpdate = new Intent(); final Intent locationUpdate = new Intent();
if(mIntent.getAction() != null) if (mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction()); locationUpdate.setAction(mIntent.getAction());
else else
locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE); locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE);
@@ -93,13 +105,14 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
/** /**
* converts skyhook's location object into android's location object * converts skyhook's location object into android's location object
*
* @return converted location * @return converted location
* @author ricky barrette * @author ricky barrette
*/ */
public Location convertLocation(){ public Location convertLocation() {
final Location location = new Location("location"); final Location location = new Location("location");
location.setLatitude(mLocation.getLatitudeE6() /1e6); location.setLatitude(mLocation.getLatitudeE6() / 1e6);
location.setLongitude(mLocation.getLongitudeE6() /1e6); location.setLongitude(mLocation.getLongitudeE6() / 1e6);
location.setAccuracy(mAccuracy); location.setAccuracy(mAccuracy);
return location; return location;
} }
@@ -111,18 +124,21 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
} }
/* /*
* I believe that this method is no longer needed as we are not supporting pre 2.1 * I believe that this method is no longer needed as we are not supporting
* pre 2.1
*/ */
// /** // /**
// * To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x // * To keep backwards compatibility we override onStart which is the
// * @author ricky barrette // equivalent of onStartCommand in pre android 2.x
// */ // * @author ricky barrette
// @Override // */
// public void onStart(Intent intent, int startId) { // @Override
// Log.i(SkyHook.TAG, "onStart.Service started with start id of: " + startId); // public void onStart(Intent intent, int startId) {
// parseIntent(intent); // Log.i(SkyHook.TAG, "onStart.Service started with start id of: " +
// this.mSkyhook.getUpdates(); // startId);
// } // parseIntent(intent);
// this.mSkyhook.getUpdates();
// }
@Override @Override
public WPSContinuation handleError(final WPSReturnCode arg0) { public WPSContinuation handleError(final WPSReturnCode arg0) {
@@ -138,6 +154,7 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent) * @see android.app.Service#onBind(android.content.Intent)
* @param arg0 * @param arg0
* @return * @return
@@ -149,35 +166,35 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
} }
@Override @Override
public void onCreate(){ public void onCreate() {
super.onCreate(); super.onCreate();
mSkyhook = new SkyHook(this); mSkyhook = new SkyHook(this);
mSkyhook.setLocationListener(this); mSkyhook.setLocationListener(this);
/* /*
* fail safe * fail safe this will stop the service after the maximum running time,
* this will stop the service after the maximum running time, if location has not been reported * if location has not been reported
*/ */
new Handler().postDelayed(new Runnable(){ new Handler().postDelayed(new Runnable() {
@Override @Override
public void run(){ public void run() {
stopSelfResult(mStartID); stopSelfResult(mStartID);
} }
}, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME); }, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME);
} }
/** /**
* aborts location services * aborts location services (non-Javadoc)
* (non-Javadoc) *
* @see android.app.Service#onDestroy() * @see android.app.Service#onDestroy()
* @author Ricky Barrette * @author Ricky Barrette
*/ */
@Override @Override
public void onDestroy(){ public void onDestroy() {
mSkyhook.removeUpdates(); mSkyhook.removeUpdates();
braodcastLocation(); braodcastLocation();
//ask android to restart service if mPeriod is set // ask android to restart service if mPeriod is set
if(mPeriod > -1) if (mPeriod > -1)
registerWakeUp(); registerWakeUp();
super.onDestroy(); super.onDestroy();
} }
@@ -193,23 +210,24 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
mLocation = point; mLocation = point;
mAccuracy = accuracy; mAccuracy = accuracy;
/* /*
* fail safe * fail safe if the accuracy is greater than the minimum required
* if the accuracy is greater than the minimum required accuracy * accuracy then continue else stop to report location
* then continue
* else stop to report location
*/ */
if(accuracy < (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION) if (accuracy < (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY)
|| LocationLibraryConstants.REPORT_FIRST_LOCATION)
this.stopSelf(mStartID); this.stopSelf(mStartID);
} }
/** /**
* This method is called when startService is called. only used in 2.x android. * This method is called when startService is called. only used in 2.x
* android.
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(final Intent intent, final int flags, final int startId) { public int onStartCommand(final Intent intent, final int flags, final int startId) {
Log.i(SkyHook.TAG , "onStartCommand.Service started with start id of: " + startId); Log.i(SkyHook.TAG, "onStartCommand.Service started with start id of: " + startId);
mStartID = startId; mStartID = startId;
parseIntent(intent); parseIntent(intent);
mSkyhook.getUpdates(); mSkyhook.getUpdates();
@@ -221,11 +239,11 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
* *
* @author ricky barrette * @author ricky barrette
*/ */
private void parseIntent(final Intent intent){ private void parseIntent(final Intent intent) {
mIntent = intent; mIntent = intent;
if(intent != null){ if (intent != null) {
if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES)) if (intent.hasExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES))
mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL); mPeriod = intent.getLongExtra(LocationLibraryConstants.INTENT_EXTRA_PERIOD_BETWEEN_UPDATES, LocationLibraryConstants.FAIL_SAFE_UPDATE_INVERVAL);
@@ -236,9 +254,10 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
/** /**
* registers our Receiver the starts the service with the alarm manager * registers our Receiver the starts the service with the alarm manager
*
* @author ricky barrette * @author ricky barrette
*/ */
private void registerWakeUp(){ private void registerWakeUp() {
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0)); am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));
} }

View File

@@ -8,12 +8,14 @@ package com.TwentyCodes.android.debug;
/** /**
* This class will be used to enable and disable debugging features * This class will be used to enable and disable debugging features
*
* @author ricky barrette * @author ricky barrette
*/ */
public class Debug { public class Debug {
/** /**
* Sets the logging level for this library * Sets the logging level for this library
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final boolean DEBUG = false; public static final boolean DEBUG = false;

View File

@@ -12,42 +12,49 @@ import android.location.LocationManager;
/** /**
* This class will be used to set the Location Library Constants * This class will be used to set the Location Library Constants
*
* @author ricky barrette * @author ricky barrette
*/ */
public final class LocationLibraryConstants { public final class LocationLibraryConstants {
static{ static {
SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO; SUPPORTS_FROYO = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO;
SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; SUPPORTS_GINGERBREAD = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD;
} }
/** /**
* Sets the default SkyHook Registration Behavior used by SkyHookRegistration.getUserName() * Sets the default SkyHook Registration Behavior used by
* SkyHookRegistration.getUserName()
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final SkyHookRegistrationBehavior DEFAULT_REGISTRATION_BEHAVIOR = SkyHookRegistrationBehavior.NORMAL; public static final SkyHookRegistrationBehavior DEFAULT_REGISTRATION_BEHAVIOR = SkyHookRegistrationBehavior.NORMAL;
/** /**
* Sets the default compass sensor update interval * Sets the default compass sensor update interval
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final int COMPASS_UPDATE_INTERVAL = SensorManager.SENSOR_DELAY_NORMAL; public static final int COMPASS_UPDATE_INTERVAL = SensorManager.SENSOR_DELAY_NORMAL;
/** /**
* The maximum running time for a single shot location service * The maximum running time for a single shot location service
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final long MAX_LOCATION_SERVICE_RUN_TIME = 60000l; public static final long MAX_LOCATION_SERVICE_RUN_TIME = 60000l;
/** /**
* Forces single shot location services to return the first location * Forces single shot location services to return the first location
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final boolean REPORT_FIRST_LOCATION = false; public static final boolean REPORT_FIRST_LOCATION = false;
/** /**
* Minimum Required accuracy to report * Minimum Required accuracy to report
*
* @author ricky barrette * @author ricky barrette
*/ */
public static final int MINIMUM_REQUIRED_ACCURACY = 100; public static final int MINIMUM_REQUIRED_ACCURACY = 100;
@@ -61,7 +68,8 @@ public final class LocationLibraryConstants {
public static final String INTENT_EXTRA_LOCATION_CHANGED = LocationManager.KEY_LOCATION_CHANGED; public static final String INTENT_EXTRA_LOCATION_CHANGED = LocationManager.KEY_LOCATION_CHANGED;
/** /**
* Used to tell the service how frequently it needs to run. This is required if you want a multishot service * Used to tell the service how frequently it needs to run. This is required
* if you want a multishot service
*/ */
public static final String INTENT_EXTRA_PERIOD_BETWEEN_UPDATES = "period_beween_updates"; public static final String INTENT_EXTRA_PERIOD_BETWEEN_UPDATES = "period_beween_updates";
@@ -71,7 +79,8 @@ public final class LocationLibraryConstants {
public static final String INTENT_EXTRA_REQUIRED_ACCURACY = "required_accuracy"; public static final String INTENT_EXTRA_REQUIRED_ACCURACY = "required_accuracy";
/** /**
* used if the INTENT_EXTRA_PERIOD_BETWEEN_UPDATES is present, but contains no data * used if the INTENT_EXTRA_PERIOD_BETWEEN_UPDATES is present, but contains
* no data
*/ */
public static final long FAIL_SAFE_UPDATE_INVERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES; public static final long FAIL_SAFE_UPDATE_INVERVAL = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
} }

View File

@@ -8,6 +8,7 @@ package com.TwentyCodes.android.debug;
/** /**
* This enum will be used to select the testing level * This enum will be used to select the testing level
*
* @author ricky barrette * @author ricky barrette
*/ */
public enum SkyHookRegistrationBehavior { public enum SkyHookRegistrationBehavior {
@@ -18,7 +19,8 @@ public enum SkyHookRegistrationBehavior {
NORMAL, NORMAL,
/** /**
* Used to force SkyHookRegistration.getUserName to return the testing user name * Used to force SkyHookRegistration.getUserName to return the testing user
* name
*/ */
USE_TESTING_USERNAME, USE_TESTING_USERNAME,

View File

@@ -31,18 +31,20 @@ public abstract class BaseMapFragment extends Fragment {
/** /**
* Creates a new MapFragment * Creates a new MapFragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public BaseMapFragment() { public BaseMapFragment() {
super(); super();
} }
public void addOverlay(final Overlay overlay){ public void addOverlay(final Overlay overlay) {
mMapView.getOverlays().add(overlay); mMapView.getOverlays().add(overlay);
} }
/** /**
* changes the map mode * changes the map mode
*
* @author ricky barrette * @author ricky barrette
*/ */
public void changeMapMode() { public void changeMapMode() {
@@ -51,9 +53,10 @@ public abstract class BaseMapFragment extends Fragment {
/** /**
* Disables the Acquiring GPS dialog * Disables the Acquiring GPS dialog
*
* @author ricky barrette * @author ricky barrette
*/ */
public void disableGPSProgess(){ public void disableGPSProgess() {
isGPSDialogEnabled = false; isGPSDialogEnabled = false;
mProgress.setVisibility(View.GONE); mProgress.setVisibility(View.GONE);
} }
@@ -63,7 +66,7 @@ public abstract class BaseMapFragment extends Fragment {
* *
* @author ricky barrette * @author ricky barrette
*/ */
public void enableGPSProgess(){ public void enableGPSProgess() {
isGPSDialogEnabled = true; isGPSDialogEnabled = true;
mProgress.setVisibility(View.VISIBLE); mProgress.setVisibility(View.VISIBLE);
} }
@@ -72,15 +75,16 @@ public abstract class BaseMapFragment extends Fragment {
* @return mapview * @return mapview
* @author ricky barrette * @author ricky barrette
*/ */
public MapView getMap(){ public MapView getMap() {
return mMapView; return mMapView;
} }
/** /**
* Forces the map to redraw * Forces the map to redraw
*
* @author ricky barrette * @author ricky barrette
*/ */
public void invalidate(){ public void invalidate() {
mMapView.invalidate(); mMapView.invalidate();
} }
@@ -88,7 +92,7 @@ public abstract class BaseMapFragment extends Fragment {
* @return true if the GPS progress is showing * @return true if the GPS progress is showing
* @author ricky barrette * @author ricky barrette
*/ */
public boolean isGPSProgessShowing(){ public boolean isGPSProgessShowing() {
return isGPSDialogEnabled; return isGPSDialogEnabled;
} }
@@ -96,14 +100,15 @@ public abstract class BaseMapFragment extends Fragment {
* @return true if the map is in satellite mode * @return true if the map is in satellite mode
* @author ricky barrette * @author ricky barrette
*/ */
public boolean isSatellite(){ public boolean isSatellite() {
return mMapView.isSatellite(); return mMapView.isSatellite();
} }
/** /**
* Called when the fragment view is first created * Called when the fragment view is first created (non-Javadoc)
* (non-Javadoc) *
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle) * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/ */
@Override @Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
@@ -120,7 +125,9 @@ public abstract class BaseMapFragment extends Fragment {
} }
/** /**
* Called when the mapview has been initialized. here you want to init and add your custom overlays * Called when the mapview has been initialized. here you want to init and
* add your custom overlays
*
* @param map * @param map
* @author ricky barrette * @author ricky barrette
*/ */
@@ -128,47 +135,52 @@ public abstract class BaseMapFragment extends Fragment {
/** /**
* Removes an overlay from the mapview * Removes an overlay from the mapview
*
* @param overlay * @param overlay
* @author ricky barrette * @author ricky barrette
*/ */
public void removeOverlay(final Object overlay){ public void removeOverlay(final Object overlay) {
mMapView.getOverlays().remove(overlay); mMapView.getOverlays().remove(overlay);
} }
/** /**
* Enables or disables the built in zoom controls * Enables or disables the built in zoom controls
*
* @param isShowing * @param isShowing
* @author ricky barrette * @author ricky barrette
*/ */
public void setBuiltInZoomControls(final boolean isShowing){ public void setBuiltInZoomControls(final boolean isShowing) {
mMapView.setBuiltInZoomControls(isShowing); mMapView.setBuiltInZoomControls(isShowing);
} }
/** /**
* Sets where or not the map view is interactive * Sets where or not the map view is interactive
*
* @param isClickable * @param isClickable
* @author ricky barrette * @author ricky barrette
*/ */
public void setClickable(final boolean isClickable){ public void setClickable(final boolean isClickable) {
mMapView.setClickable(isClickable); mMapView.setClickable(isClickable);
} }
/** /**
* Sets double tap zoom * Sets double tap zoom
*
* @param isDoubleTapZoonEnabled * @param isDoubleTapZoonEnabled
* @author ricky barrette * @author ricky barrette
*/ */
public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled){ public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled) {
mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled); mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled);
} }
/** /**
* Sets the center of the map to the provided point * Sets the center of the map to the provided point
*
* @param point * @param point
* @author ricky barrette * @author ricky barrette
*/ */
public boolean setMapCenter(final GeoPoint point){ public boolean setMapCenter(final GeoPoint point) {
if(point == null) if (point == null)
return false; return false;
mMapView.getController().setCenter(point); mMapView.getController().setCenter(point);
return true; return true;
@@ -176,19 +188,21 @@ public abstract class BaseMapFragment extends Fragment {
/** /**
* Sets the view of the map. true is sat, false is map * Sets the view of the map. true is sat, false is map
*
* @param isSat * @param isSat
* @author ricky barrette * @author ricky barrette
*/ */
public void setSatellite(final boolean isSat){ public void setSatellite(final boolean isSat) {
mMapView.setSatellite(isSat); mMapView.setSatellite(isSat);
} }
/** /**
* Sets the zoom level of the map * Sets the zoom level of the map
*
* @param zoom * @param zoom
* @author ricky barrette * @author ricky barrette
*/ */
public void setZoom(final int zoom){ public void setZoom(final int zoom) {
mMapView.getController().setZoom(zoom); mMapView.getController().setZoom(zoom);
} }
} }

View File

@@ -17,26 +17,30 @@ import com.TwentyCodes.android.location.R;
import com.TwentyCodes.android.overlays.DirectionsOverlay; import com.TwentyCodes.android.overlays.DirectionsOverlay;
/** /**
* this is a custom listview adaptor that wills a listview that has 2 textviews in each row. * this is a custom listview adaptor that wills a listview that has 2 textviews
* in each row.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsAdapter extends BaseAdapter { public class DirectionsAdapter extends BaseAdapter {
/** /**
* this class will hold the TextViews * this class will hold the TextViews
*
* @author ricky barrette * @author ricky barrette
*/ */
class ViewHolder { class ViewHolder {
TextView text; TextView text;
TextView text2; TextView text2;
} }
private final LayoutInflater mInflater;
private final LayoutInflater mInflater;
private final DirectionsOverlay mDirections; private final DirectionsOverlay mDirections;
/** /**
* Creates a new DirectionsAdapter * Creates a new DirectionsAdapter
*
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsAdapter(final Context context, final DirectionsOverlay directions) { public DirectionsAdapter(final Context context, final DirectionsOverlay directions) {
@@ -46,6 +50,7 @@ public class DirectionsAdapter extends BaseAdapter {
/** /**
* returns the size of the main list * returns the size of the main list
*
* @see android.widget.Adapter#getCount() * @see android.widget.Adapter#getCount()
* @return * @return
* @author ricky barrette * @author ricky barrette
@@ -57,6 +62,7 @@ public class DirectionsAdapter extends BaseAdapter {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int) * @see android.widget.Adapter#getItem(int)
* @param position * @param position
* @return * @return
@@ -69,6 +75,7 @@ public class DirectionsAdapter extends BaseAdapter {
/** /**
* returns the current position in the list * returns the current position in the list
*
* @see android.widget.Adapter#getItemId(int) * @see android.widget.Adapter#getItemId(int)
* @param position * @param position
* @return * @return
@@ -81,7 +88,9 @@ public class DirectionsAdapter extends BaseAdapter {
/** /**
* inflates the row from xml, and sets the textviews to their intended vales * inflates the row from xml, and sets the textviews to their intended vales
* @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) *
* @see android.widget.Adapter#getView(int, android.view.View,
* android.view.ViewGroup)
* @param position * @param position
* @param convertView * @param convertView
* @param parent * @param parent
@@ -104,12 +113,12 @@ public class DirectionsAdapter extends BaseAdapter {
/** /**
* Display the copyrights on the bottom of the directions list * Display the copyrights on the bottom of the directions list
*/ */
if (position == mDirections.getDirections().size()){ if (position == mDirections.getDirections().size()) {
holder.text.setText(mDirections.getCopyrights()); holder.text.setText(mDirections.getCopyrights());
holder.text2.setText(""); holder.text2.setText("");
} else { } else {
holder.text.setText(Html.fromHtml(mDirections.getDirections().get(position))); holder.text.setText(Html.fromHtml(mDirections.getDirections().get(position)));
holder.text2.setText(mDirections.getDurations().get(position) +" : "+ mDirections.getDistances().get(position)); holder.text2.setText(mDirections.getDurations().get(position) + " : " + mDirections.getDistances().get(position));
} }
return convertView; return convertView;
} }

View File

@@ -17,20 +17,23 @@ import com.TwentyCodes.android.overlays.DirectionsOverlay;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This fragment will be used to display directions to the user. * This fragment will be used to display directions to the user. When a specific
* When a specific direction is clicked, the corrispoding geopoint is returned via listener * direction is clicked, the corrispoding geopoint is returned via listener
*
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsListFragment extends ListFragment { public class DirectionsListFragment extends ListFragment {
/** /**
* A simple interfrace for a directions list fragment * A simple interfrace for a directions list fragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface OnDirectionSelectedListener { public interface OnDirectionSelectedListener {
/** /**
* Called when the user selects a direction from a directions list * Called when the user selects a direction from a directions list
*
* @param point * @param point
* @author ricky barrette * @author ricky barrette
*/ */
@@ -43,6 +46,7 @@ public class DirectionsListFragment extends ListFragment {
/** /**
* Creates a new Directions List Fragment * Creates a new Directions List Fragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsListFragment() { public DirectionsListFragment() {
@@ -51,6 +55,7 @@ public class DirectionsListFragment extends ListFragment {
/** /**
* Creates a new Directions List Fragment * Creates a new Directions List Fragment
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
@@ -61,6 +66,7 @@ public class DirectionsListFragment extends ListFragment {
/** /**
* Deletes all content in the listview * Deletes all content in the listview
*
* @author ricky barrette * @author ricky barrette
*/ */
public void clear() { public void clear() {
@@ -68,20 +74,23 @@ public class DirectionsListFragment extends ListFragment {
} }
/** /**
* Called when a list item is clicked. * Called when a list item is clicked. Checks to see if the list item is a
* Checks to see if the list item is a direction, if to it reports the selected direction's geopoint to the listener * direction, if to it reports the selected direction's geopoint to the
* (non-Javadoc) * listener (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long) *
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView,
* android.view.View, int, long)
*/ */
@Override @Override
public void onListItemClick(final ListView l, final View w, final int position, final long id) { public void onListItemClick(final ListView l, final View w, final int position, final long id) {
if(position < mPoints.size()) if (position < mPoints.size())
if(mListener != null) if (mListener != null)
mListener.onDirectionSelected(mPoints.get(position)); mListener.onDirectionSelected(mPoints.get(position));
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onStart() * @see android.support.v4.app.Fragment#onStart()
*/ */
@Override @Override
@@ -92,6 +101,7 @@ public class DirectionsListFragment extends ListFragment {
/** /**
* Displays the directions from the provided DirectionsOverlay object * Displays the directions from the provided DirectionsOverlay object
*
* @param directions * @param directions
* @author ricky barrette * @author ricky barrette
*/ */
@@ -102,10 +112,11 @@ public class DirectionsListFragment extends ListFragment {
/** /**
* Sets the text to be displayed while the list is empty * Sets the text to be displayed while the list is empty
*
* @param text * @param text
* @author ricky barrette * @author ricky barrette
*/ */
public void SetEmptyText(final String text){ public void SetEmptyText(final String text) {
setEmptyText(text); setEmptyText(text);
} }
} }

View File

@@ -16,9 +16,10 @@ import com.google.android.maps.GeoPoint;
* This is a MapFragment that maintains the SkyHookUserOverlay * This is a MapFragment that maintains the SkyHookUserOverlay
* *
* TODO acquiring gps dialog * TODO acquiring gps dialog
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements GeoPointLocationListener, CompassListener{ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements GeoPointLocationListener, CompassListener {
private SkyHookUserOverlay mUserOverlay; private SkyHookUserOverlay mUserOverlay;
private GeoPointLocationListener mGeoPointLocationListener; private GeoPointLocationListener mGeoPointLocationListener;
@@ -26,6 +27,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
/** /**
* Creates a new UserOverlayMapFragment * Creates a new UserOverlayMapFragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHoookUserOverlayMapFragment() { public SkyHoookUserOverlayMapFragment() {
@@ -34,10 +36,11 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
/** /**
* Tells the useroverlay to pan the map to follow the user * Tells the useroverlay to pan the map to follow the user
*
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(final boolean followUser){ public void followUser(final boolean followUser) {
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
@@ -45,7 +48,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getDestination(){ public GeoPoint getDestination() {
return mUserOverlay.getDestination(); return mUserOverlay.getDestination();
} }
@@ -58,34 +61,36 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
} }
/** /**
* Called when the compass is updated * Called when the compass is updated (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(final float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if (mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
} }
@Override @Override
public void onFirstFix(final boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if (mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
/** /**
* Called when has a location to report * Called when has a location to report
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(final GeoPoint point, final int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mGeoPointLocationListener != null) if (mGeoPointLocationListener != null)
mGeoPointLocationListener.onLocationChanged(point, accuracy); mGeoPointLocationListener.onLocationChanged(point, accuracy);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView) * @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView)
*/ */
@Override @Override
@@ -101,6 +106,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause()
*/ */
@Override @Override
@@ -112,12 +118,13 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume()
*/ */
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if(mUserOverlay != null) { if (mUserOverlay != null) {
mUserOverlay.enableMyLocation(); mUserOverlay.enableMyLocation();
addOverlay(mUserOverlay); addOverlay(mUserOverlay);
} }
@@ -125,6 +132,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
/** /**
* reorders the overlays to the UserOverlay always on top * reorders the overlays to the UserOverlay always on top
*
* @author ricky barrette * @author ricky barrette
*/ */
public void reorderOverlays() { public void reorderOverlays() {
@@ -139,7 +147,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y){ public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y) {
mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y); mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y);
} }
@@ -147,16 +155,17 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(final CompassListener listener){ public void setCompassListener(final CompassListener listener) {
mCompassListener = listener; mCompassListener = listener;
} }
/** /**
* Sets the destination for the compass to point to * Sets the destination for the compass to point to
*
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(final GeoPoint destination){ public void setDestination(final GeoPoint destination) {
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +173,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(final GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener) {
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -16,9 +16,10 @@ import com.google.android.maps.GeoPoint;
* This is a MapFragment that maintains the UserOverlay * This is a MapFragment that maintains the UserOverlay
* *
* TODO acquiring gps dialog * TODO acquiring gps dialog
*
* @author ricky barrette * @author ricky barrette
*/ */
public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointLocationListener, CompassListener{ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointLocationListener, CompassListener {
private UserOverlay mUserOverlay; private UserOverlay mUserOverlay;
private GeoPointLocationListener mGeoPointLocationListener; private GeoPointLocationListener mGeoPointLocationListener;
@@ -26,6 +27,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
/** /**
* Creates a new UserOverlayMapFragment * Creates a new UserOverlayMapFragment
*
* @author ricky barrette * @author ricky barrette
*/ */
public UserOverlayMapFragment() { public UserOverlayMapFragment() {
@@ -34,10 +36,11 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
/** /**
* Tells the useroverlay to pan the map to follow the user * Tells the useroverlay to pan the map to follow the user
*
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(final boolean followUser){ public void followUser(final boolean followUser) {
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
@@ -45,7 +48,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getDestination(){ public GeoPoint getDestination() {
return mUserOverlay.getDestination(); return mUserOverlay.getDestination();
} }
@@ -58,34 +61,36 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
} }
/** /**
* Called when the compass is updated * Called when the compass is updated (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(final float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if (mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
} }
@Override @Override
public void onFirstFix(final boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if (mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
/** /**
* Called when skyhook has a location to report * Called when skyhook has a location to report
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(final GeoPoint point, final int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mGeoPointLocationListener != null) if (mGeoPointLocationListener != null)
mGeoPointLocationListener.onLocationChanged(point, accuracy); mGeoPointLocationListener.onLocationChanged(point, accuracy);
} }
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView) * @see com.TwentyCodes.android.fragments.BaseMapFragment#onMapViewCreate(com.TwentyCodes.android.location.MapView)
*/ */
@Override @Override
@@ -101,6 +106,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onPause()
*/ */
@Override @Override
@@ -112,12 +118,13 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume() * @see com.TwentyCodes.android.fragments.BaseMapFragment#onResume()
*/ */
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if(mUserOverlay != null) { if (mUserOverlay != null) {
mUserOverlay.enableMyLocation(); mUserOverlay.enableMyLocation();
addOverlay(mUserOverlay); addOverlay(mUserOverlay);
} }
@@ -125,6 +132,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
/** /**
* reorders the overlays to the UserOverlay always on top * reorders the overlays to the UserOverlay always on top
*
* @author ricky barrette * @author ricky barrette
*/ */
public void reorderOverlays() { public void reorderOverlays() {
@@ -139,7 +147,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y){ public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y) {
mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y); mUserOverlay.setCompassDrawables(needleResId, backgroundResId, x, y);
} }
@@ -147,16 +155,17 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(final CompassListener listener){ public void setCompassListener(final CompassListener listener) {
mCompassListener = listener; mCompassListener = listener;
} }
/** /**
* Sets the destination for the compass to point to * Sets the destination for the compass to point to
*
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(final GeoPoint destination){ public void setDestination(final GeoPoint destination) {
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +173,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(final GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener) {
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -18,7 +18,9 @@ import com.TwentyCodes.android.debug.Debug;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This class will be used for gathering location using android's location services * This class will be used for gathering location using android's location
* services
*
* @author ricky barrette * @author ricky barrette
*/ */
public class AndroidGPS implements LocationListener { public class AndroidGPS implements LocationListener {
@@ -31,6 +33,7 @@ public class AndroidGPS implements LocationListener {
/** /**
* Creates a new SkyHookFallback * Creates a new SkyHookFallback
*
* @author ricky barrette * @author ricky barrette
*/ */
public AndroidGPS(final Context context) { public AndroidGPS(final Context context) {
@@ -40,10 +43,11 @@ public class AndroidGPS implements LocationListener {
/** /**
* Remove updates from androids location services * Remove updates from androids location services
*
* @author ricky barrette * @author ricky barrette
*/ */
public void disableLocationUpdates(){ public void disableLocationUpdates() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "disableLocationUpdates()"); Log.d(TAG, "disableLocationUpdates()");
mListener = null; mListener = null;
mLocationManager.removeUpdates(this); mLocationManager.removeUpdates(this);
@@ -52,10 +56,11 @@ public class AndroidGPS implements LocationListener {
/** /**
* request periodic location updates from androids location services * request periodic location updates from androids location services
*
* @author ricky barrette * @author ricky barrette
*/ */
public void enableLocationUpdates(final GeoPointLocationListener listener) { public void enableLocationUpdates(final GeoPointLocationListener listener) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()"); Log.d(SkyHook.TAG, "enableLocationUpdates()");
if (mListener == null) { if (mListener == null) {
mListener = listener; mListener = listener;
@@ -65,13 +70,14 @@ public class AndroidGPS implements LocationListener {
/** /**
* Attempts to enable periodic location updates * Attempts to enable periodic location updates
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enableLocationUpdates(final LocationListener listener) { public void enableLocationUpdates(final LocationListener listener) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()"); Log.d(SkyHook.TAG, "enableLocationUpdates()");
if(mLocationListener == null){ if (mLocationListener == null) {
mLocationListener = listener; mLocationListener = listener;
requestUpdates(); requestUpdates();
} }
@@ -79,18 +85,19 @@ public class AndroidGPS implements LocationListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.location.LocationListener#onLocationChanged(android.location.Location) * @see android.location.LocationListener#onLocationChanged(android.location.Location)
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(final Location location) { public void onLocationChanged(final Location location) {
if(mListener != null) { if (mListener != null) {
mListener.onLocationChanged(new GeoPoint( (int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), (int) location.getAccuracy()); mListener.onLocationChanged(new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)), (int) location.getAccuracy());
mListener.onFirstFix(isFirstFix); mListener.onFirstFix(isFirstFix);
} }
if(mLocationListener != null) if (mLocationListener != null)
mLocationListener.onLocationChanged(location); mLocationListener.onLocationChanged(location);
isFirstFix = false; isFirstFix = false;
@@ -98,6 +105,7 @@ public class AndroidGPS implements LocationListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.location.LocationListener#onProviderDisabled(java.lang.String) * @see android.location.LocationListener#onProviderDisabled(java.lang.String)
* @param arg0 * @param arg0
* @author ricky barrette * @author ricky barrette
@@ -110,6 +118,7 @@ public class AndroidGPS implements LocationListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.location.LocationListener#onProviderEnabled(java.lang.String) * @see android.location.LocationListener#onProviderEnabled(java.lang.String)
* @param arg0 * @param arg0
* @author ricky barrette * @author ricky barrette
@@ -121,7 +130,9 @@ public class AndroidGPS implements LocationListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) *
* @see android.location.LocationListener#onStatusChanged(java.lang.String,
* int, android.os.Bundle)
* @param arg0 * @param arg0
* @param arg1 * @param arg1
* @param arg2 * @param arg2
@@ -134,6 +145,7 @@ public class AndroidGPS implements LocationListener {
/** /**
* Request updates from android location services * Request updates from android location services
*
* @author ricky barrette * @author ricky barrette
*/ */
private void requestUpdates() { private void requestUpdates() {

View File

@@ -12,7 +12,9 @@ import android.location.Location;
import android.location.LocationManager; import android.location.LocationManager;
/** /**
* this abstract class will be used as a for classes wishing to be a receiver of location updates from the location services * this abstract class will be used as a for classes wishing to be a receiver of
* location updates from the location services
*
* @author ricky barrette * @author ricky barrette
*/ */
public abstract class BaseLocationReceiver extends BroadcastReceiver { public abstract class BaseLocationReceiver extends BroadcastReceiver {
@@ -21,6 +23,7 @@ public abstract class BaseLocationReceiver extends BroadcastReceiver {
/** /**
* called when a location update is received * called when a location update is received
*
* @param parcelableExtra * @param parcelableExtra
* @author ricky barrette * @author ricky barrette
*/ */
@@ -28,13 +31,15 @@ public abstract class BaseLocationReceiver extends BroadcastReceiver {
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) *
* @see android.content.BroadcastReceiver#onReceive(android.content.Context,
* android.content.Intent)
*/ */
@Override @Override
public void onReceive(final Context context, final Intent intent) { public void onReceive(final Context context, final Intent intent) {
mContext = context; mContext = context;
final String key = LocationManager.KEY_LOCATION_CHANGED; final String key = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(key)) if (intent.hasExtra(key))
onLocationUpdate((Location)intent.getExtras().get(key)); onLocationUpdate((Location) intent.getExtras().get(key));
} }
} }

View File

@@ -25,18 +25,21 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
/** /**
* A simple convince class that accesses the compass sensor on another thread * A simple convince class that accesses the compass sensor on another thread
*
* @author ricky barrette * @author ricky barrette
*/ */
public class CompassSensor{ public class CompassSensor {
/** /**
* A simple listener interface to get updates from CompassSensor * A simple listener interface to get updates from CompassSensor
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface CompassListener { public interface CompassListener {
/** /**
* Called when there is an update from the Compass Sensor * Called when there is an update from the Compass Sensor
*
* @param bearing * @param bearing
* @author ricky barrette * @author ricky barrette
*/ */
@@ -52,12 +55,12 @@ public class CompassSensor{
private static CompassListener mListener; private static CompassListener mListener;
private float mDelination = 0; private float mDelination = 0;
static{ static {
mHandler = new Handler(){ mHandler = new Handler() {
@Override @Override
public void handleMessage(final Message msg){ public void handleMessage(final Message msg) {
if(mListener != null) if (mListener != null)
if(msg.what == BEARING) if (msg.what == BEARING)
mListener.onCompassUpdate((Float) msg.obj); mListener.onCompassUpdate((Float) msg.obj);
} }
}; };
@@ -66,16 +69,17 @@ public class CompassSensor{
private final SensorEventListener mCallBack = new SensorEventListener() { private final SensorEventListener mCallBack = new SensorEventListener() {
private final float[] mRotationMatrix = new float[16]; private final float[] mRotationMatrix = new float[16];
// private float[] mRemapedRotationMatrix = new float[16]; // private float[] mRemapedRotationMatrix = new float[16];
private final float[] mI = new float[16]; private final float[] mI = new float[16];
private float[] mGravity = new float[3]; private float[] mGravity = new float[3];
private float[] mGeomag = new float[3]; private float[] mGeomag = new float[3];
private final float[] mOrientVals = new float[3]; private final float[] mOrientVals = new float[3];
private double mAzimuth = 0; private double mAzimuth = 0;
// double mPitch = 0;
// double mRoll = 0; // double mPitch = 0;
// private float mInclination; // double mRoll = 0;
// private float mInclination;
@Override @Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) { public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
@@ -83,20 +87,20 @@ public class CompassSensor{
@Override @Override
public void onSensorChanged(final SensorEvent sensorEvent) { public void onSensorChanged(final SensorEvent sensorEvent) {
if(Debug.DEBUG) if (Debug.DEBUG)
switch (sensorEvent.accuracy){ switch (sensorEvent.accuracy) {
case SensorManager.SENSOR_STATUS_UNRELIABLE: case SensorManager.SENSOR_STATUS_UNRELIABLE:
Log.v(TAG , "UNRELIABLE"); Log.v(TAG, "UNRELIABLE");
break; break;
case SensorManager.SENSOR_STATUS_ACCURACY_LOW: case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
Log.v(TAG , "LOW"); Log.v(TAG, "LOW");
break; break;
case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM: case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
Log.v(TAG , "MEDIUM"); Log.v(TAG, "MEDIUM");
break; break;
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH: case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
Log.v(TAG , "HIGH"); Log.v(TAG, "HIGH");
break; break;
} }
@@ -106,12 +110,12 @@ public class CompassSensor{
// Gets the value of the sensor that has been changed // Gets the value of the sensor that has been changed
switch (sensorEvent.sensor.getType()) { switch (sensorEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER: case Sensor.TYPE_ACCELEROMETER:
mGravity = sensorEvent.values.clone(); mGravity = sensorEvent.values.clone();
break; break;
case Sensor.TYPE_MAGNETIC_FIELD: case Sensor.TYPE_MAGNETIC_FIELD:
mGeomag = sensorEvent.values.clone(); mGeomag = sensorEvent.values.clone();
break; break;
} }
// If gravity and geomag have values then find rotation matrix // If gravity and geomag have values then find rotation matrix
@@ -121,33 +125,41 @@ public class CompassSensor{
final boolean success = SensorManager.getRotationMatrix(mRotationMatrix, mI, mGravity, mGeomag); final boolean success = SensorManager.getRotationMatrix(mRotationMatrix, mI, mGravity, mGeomag);
if (success) { if (success) {
// switch (mDisplay.getOrientation()){ // switch (mDisplay.getOrientation()){
// case Surface.ROTATION_0: // case Surface.ROTATION_0:
// Log.v(TAG , "0"); // Log.v(TAG , "0");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix); // // SensorManager.remapCoordinateSystem(mRotationMatrix,
// break; // SensorManager.AXIS_X, SensorManager.AXIS_Y,
// case Surface.ROTATION_90: // mRemapedRotationMatrix);
// Log.v(TAG , "90"); // break;
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix); // case Surface.ROTATION_90:
// break; // Log.v(TAG , "90");
// case Surface.ROTATION_180: // // SensorManager.remapCoordinateSystem(mRotationMatrix,
// Log.v(TAG , "180"); // SensorManager.AXIS_X, SensorManager.AXIS_Y,
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y, mRemapedRotationMatrix); // mRemapedRotationMatrix);
// break; // break;
// case Surface.ROTATION_270: // case Surface.ROTATION_180:
// Log.v(TAG , "270"); // Log.v(TAG , "180");
// // SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_MINUS_X, SensorManager.AXIS_Y, mRemapedRotationMatrix); // // SensorManager.remapCoordinateSystem(mRotationMatrix,
// break; // SensorManager.AXIS_MINUS_X, SensorManager.AXIS_MINUS_Y,
// } // mRemapedRotationMatrix);
// break;
// case Surface.ROTATION_270:
// Log.v(TAG , "270");
// // SensorManager.remapCoordinateSystem(mRotationMatrix,
// SensorManager.AXIS_MINUS_X, SensorManager.AXIS_Y,
// mRemapedRotationMatrix);
// break;
// }
/* /*
* remap cords due to Display.getRotation() * remap cords due to Display.getRotation()
*/ */
SensorManager.getOrientation(mRotationMatrix, mOrientVals); SensorManager.getOrientation(mRotationMatrix, mOrientVals);
// mInclination = SensorManager.getInclination(mI); // mInclination = SensorManager.getInclination(mI);
mAzimuth = Math.toDegrees(mOrientVals[0]); mAzimuth = Math.toDegrees(mOrientVals[0]);
// mPitch = Math.toDegrees(mOrientVals[1]); // mPitch = Math.toDegrees(mOrientVals[1]);
// mRoll = Math.toDegrees(mOrientVals[2]); // mRoll = Math.toDegrees(mOrientVals[2]);
/* /*
* compensate for magentic delination * compensate for magentic delination
@@ -157,18 +169,18 @@ public class CompassSensor{
/* /*
* compensate for device orentation * compensate for device orentation
*/ */
switch (mDisplay.getRotation()){ switch (mDisplay.getRotation()) {
case Surface.ROTATION_0: case Surface.ROTATION_0:
break; break;
case Surface.ROTATION_90: case Surface.ROTATION_90:
mAzimuth = mAzimuth + 90; mAzimuth = mAzimuth + 90;
break; break;
case Surface.ROTATION_180: case Surface.ROTATION_180:
mAzimuth = mAzimuth +180; mAzimuth = mAzimuth + 180;
break; break;
case Surface.ROTATION_270: case Surface.ROTATION_270:
mAzimuth = mAzimuth - 90; mAzimuth = mAzimuth - 90;
break; break;
} }
} }
} }
@@ -179,6 +191,7 @@ public class CompassSensor{
/** /**
* Creates a new CompassSensor * Creates a new CompassSensor
*
* @author ricky barrette * @author ricky barrette
*/ */
public CompassSensor(final Context context) { public CompassSensor(final Context context) {
@@ -189,45 +202,51 @@ public class CompassSensor{
/** /**
* Disables compass updates * Disables compass updates
*
* @author ricky barrette * @author ricky barrette
*/ */
public void disable(){ public void disable() {
mListener = null; mListener = null;
mSensorManager.unregisterListener(mCallBack); mSensorManager.unregisterListener(mCallBack);
} }
/** /**
* Attempts to register the listener for compass updates * Attempts to register the listener for compass updates
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(final CompassListener listener){ public void enable(final CompassListener listener) {
if(mListener == null) { if (mListener == null) {
mListener = listener; mListener = listener;
if(mSensorManager != null) if (mSensorManager != null)
new Thread(new Runnable(){ new Thread(new Runnable() {
@Override @Override
public void run() { public void run() {
// Register this class as a listener for the accelerometer sensor // Register this class as a listener for the
mSensorManager.registerListener(mCallBack, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), LocationLibraryConstants.COMPASS_UPDATE_INTERVAL); // accelerometer sensor
mSensorManager.registerListener(mCallBack, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
LocationLibraryConstants.COMPASS_UPDATE_INTERVAL);
// ...and the orientation sensor // ...and the orientation sensor
mSensorManager.registerListener(mCallBack, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), LocationLibraryConstants.COMPASS_UPDATE_INTERVAL); mSensorManager.registerListener(mCallBack, mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
LocationLibraryConstants.COMPASS_UPDATE_INTERVAL);
} }
}).start(); }).start();
} }
} }
/** /**
* Updates the Geomagnetic Field Declination based off of the provided location * Updates the Geomagnetic Field Declination based off of the provided
* @param location last known (lat,lon,altitude), null will reset * location
*
* @param location
* last known (lat,lon,altitude), null will reset
* @author ricky barrette * @author ricky barrette
*/ */
public void setDeclination(final Location location){ public void setDeclination(final Location location) {
if (location != null) { if (location != null) {
final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(), final GeomagneticField geomagneticField = new GeomagneticField(Double.valueOf(location.getLatitude()).floatValue(), Double.valueOf(location.getLongitude())
Double.valueOf(location.getLongitude()).floatValue(), .floatValue(), Double.valueOf(location.getAltitude()).floatValue(), System.currentTimeMillis());
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis());
mDelination = geomagneticField.getDeclination(); mDelination = geomagneticField.getDeclination();
} else } else
mDelination = 0; mDelination = 0;

View File

@@ -8,13 +8,16 @@ package com.TwentyCodes.android.location;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* this interface will be used to interface with skyhook sdk with the rest of the application * this interface will be used to interface with skyhook sdk with the rest of
* the application
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface GeoPointLocationListener { public interface GeoPointLocationListener {
/** /**
* Called when first fix is aquired * Called when first fix is aquired
*
* @param isFirstFix * @param isFirstFix
* @author ricky barrette * @author ricky barrette
*/ */
@@ -22,6 +25,7 @@ public interface GeoPointLocationListener {
/** /**
* Called when the location has changed * Called when the location has changed
*
* @param point * @param point
* @param accuracy * @param accuracy
* @author ricky barrette * @author ricky barrette

View File

@@ -31,6 +31,7 @@ import com.google.android.maps.MapView;
/** /**
* This class contains common tools for computing common geological problems * This class contains common tools for computing common geological problems
*
* @author ricky barrette * @author ricky barrette
* @author Google Inc. * @author Google Inc.
*/ */
@@ -40,12 +41,19 @@ public class GeoUtils {
public static final double MILLION = 1000000; public static final double MILLION = 1000000;
/** /**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East * computes the bearing of lat2/lon2 in relationship from lat1/lon1 in
* @param lat1 source lat * degrees East
* @param lon1 source lon *
* @param lat2 destination lat * @param lat1
* @param lon2 destination lon * source lat
* @return the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north * @param lon1
* source lon
* @param lat2
* destination lat
* @param lon2
* destination lon
* @return the bearing of lat2/lon2 in relationship from lat1/lon1 in
* degrees East of true north
* @author Google Inc. * @author Google Inc.
*/ */
public static double bearing(final double lat1, final double lon1, final double lat2, final double lon2) { public static double bearing(final double lat1, final double lon1, final double lat2, final double lon2) {
@@ -58,9 +66,13 @@ public class GeoUtils {
} }
/** /**
* computes the bearing of lat2/lon2 in relationship from lat1/lon1 in degrees East of true north * computes the bearing of lat2/lon2 in relationship from lat1/lon1 in
* @param p1 source geopoint * degrees East of true north
* @param p2 destination geopoint *
* @param p1
* source geopoint
* @param p2
* destination geopoint
* @return the bearing of p2 in relationship from p1 in degrees East * @return the bearing of p2 in relationship from p1 in degrees East
* @author Google Inc. * @author Google Inc.
*/ */
@@ -73,22 +85,28 @@ public class GeoUtils {
} }
/** /**
* Calculates the bearing from the user location to the destination location, or returns the bearing for north if there is no destination. * Calculates the bearing from the user location to the destination
* This method is awesome for making a compass point toward the destination rather than North. * location, or returns the bearing for north if there is no destination.
* @param user location * This method is awesome for making a compass point toward the destination
* @param dest location * rather than North.
* @param bearing Degrees East from compass *
* @param user
* location
* @param dest
* location
* @param bearing
* Degrees East from compass
* @return Degrees East of dest location * @return Degrees East of dest location
* @author ricky barrette * @author ricky barrette
*/ */
public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) { public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) {
if( user == null || dest == null ) if (user == null || dest == null)
return bearing; return bearing;
final float heading = bearing(user, dest).floatValue(); final float heading = bearing(user, dest).floatValue();
bearing = 360 - heading + bearing; bearing = 360 - heading + bearing;
if (bearing > 360) if (bearing > 360)
return bearing - 360; return bearing - 360;
@@ -97,16 +115,19 @@ public class GeoUtils {
} }
/** /**
* Calculates a geopoint x meters away of the geopoint supplied. The new geopoint * Calculates a geopoint x meters away of the geopoint supplied. The new
* shares the same latitude as geopoint point, this way they are on the same latitude arc. * geopoint shares the same latitude as geopoint point, this way they are on
* the same latitude arc.
* *
* @param point central geopoint * @param point
* @param distance in meters from the geopoint * central geopoint
* @param distance
* in meters from the geopoint
* @return geopoint that is x meters away from the geopoint supplied * @return geopoint that is x meters away from the geopoint supplied
* @author ricky barrette * @author ricky barrette
*/ */
public static GeoPoint distanceFrom(final GeoPoint point, double distance){ public static GeoPoint distanceFrom(final GeoPoint point, double distance) {
//convert meters into kilometers // convert meters into kilometers
distance = distance / 1000; distance = distance / 1000;
// convert lat and lon of geopoint to radians // convert lat and lon of geopoint to radians
@@ -114,34 +135,45 @@ public class GeoUtils {
final double lon1Rad = Math.toRadians(point.getLongitudeE6() / 1e6); final double lon1Rad = Math.toRadians(point.getLongitudeE6() / 1e6);
/* /*
* kilometers = acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371 * kilometers =
* acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos
* (lon2Rad-lon1Rad)6371
* *
* we are solving this equation for lon2Rad * we are solving this equation for lon2Rad
* *
* lon2Rad = lon1Rad+acos(cos(meters/6371)sec(lat1Rad)sec(lat2Rad)-tan(lat1Rad)tan(lat2Rad)) * lon2Rad =
* lon1Rad+acos(cos(meters/6371)sec(lat1Rad)sec(lat2Rad)-tan(lat1Rad
* )tan(lat2Rad))
* *
* NOTE: sec(x) = 1/cos(x) * NOTE: sec(x) = 1/cos(x)
* *
* NOTE: that lat2Rad is = lat1Rad because we want to keep the new geopoint on the same lat arc * NOTE: that lat2Rad is = lat1Rad because we want to keep the new
* therefore i saw no need to create a new variable for lat2Rad, * geopoint on the same lat arc therefore i saw no need to create a new
* and simply inputed lat1Rad in place of lat2Rad in the equation * variable for lat2Rad, and simply inputed lat1Rad in place of lat2Rad
* in the equation
* *
* NOTE: this equation has be tested in the field against another gps device, and the distanceKm() from google * NOTE: this equation has be tested in the field against another gps
* and has been proven to be damn close * device, and the distanceKm() from google and has been proven to be
* damn close
*/ */
final double lon2Rad = lon1Rad + Math.acos( Math.cos(distance/6371) * (1 / Math.cos(lat1Rad)) final double lon2Rad = lon1Rad + Math.acos(Math.cos(distance / 6371) * (1 / Math.cos(lat1Rad)) * (1 / Math.cos(lat1Rad)) - Math.tan(lat1Rad) * Math.tan(lat1Rad));
* (1 / Math.cos(lat1Rad)) - Math.tan(lat1Rad) * Math.tan(lat1Rad));
//return a geopoint that is x meters away from the geopoint supplied // return a geopoint that is x meters away from the geopoint supplied
return new GeoPoint(point.getLatitudeE6(), (int) (Math.toDegrees(lon2Rad) * 1e6)); return new GeoPoint(point.getLatitudeE6(), (int) (Math.toDegrees(lon2Rad) * 1e6));
} }
/** /**
* computes the distance between to lat1/lon1 and lat2/lon2 based on the curve of the earth * computes the distance between to lat1/lon1 and lat2/lon2 based on the
* @param lat1 source lat * curve of the earth
* @param lon1 source lon *
* @param lat2 destination lat * @param lat1
* @param lon2 destination lon * source lat
* @param lon1
* source lon
* @param lat2
* destination lat
* @param lon2
* destination lon
* @return the distance between to lat1/lon1 and lat2/lon2 * @return the distance between to lat1/lon1 and lat2/lon2
* @author Google Inc. * @author Google Inc.
*/ */
@@ -153,15 +185,17 @@ public class GeoUtils {
} }
/** /**
* computes the distance between to p1 and p2 based on the curve of the earth * computes the distance between to p1 and p2 based on the curve of the
* earth
*
* @param p1 * @param p1
* @param p2 * @param p2
* @return the distance between to p1 and p2 * @return the distance between to p1 and p2
* @author Google Inc. * @author Google Inc.
*/ */
public static double distanceKm(final GeoPoint p1, final GeoPoint p2) { public static double distanceKm(final GeoPoint p1, final GeoPoint p2) {
//if we are handed a null, return -1 so we don't break // if we are handed a null, return -1 so we don't break
if(p1 == null || p2 == null) if (p1 == null || p2 == null)
return -1; return -1;
final double lat1 = p1.getLatitudeE6() / MILLION; final double lat1 = p1.getLatitudeE6() / MILLION;
@@ -173,8 +207,11 @@ public class GeoUtils {
/** /**
* Converts distance into a human readbale string * Converts distance into a human readbale string
* @param distance in kilometers *
* @param returnMetric true if metric, false for US * @param distance
* in kilometers
* @param returnMetric
* true if metric, false for US
* @return string distance * @return string distance
* @author ricky barrette * @author ricky barrette
*/ */
@@ -198,31 +235,40 @@ public class GeoUtils {
} }
/** /**
* a convince method for testing if 2 circles on the the surface of the earth intersect. * a convince method for testing if 2 circles on the the surface of the
* we will use this method to test if the users accuracy circle intersects a marked locaton's radius * earth intersect. we will use this method to test if the users accuracy
* if ( (accuracyCircleRadius + locationRadius) - fudgeFactor) > acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad)cos(lat2Rad)cos(lon2Rad-lon1Rad)6371 * circle intersects a marked locaton's radius if ( (accuracyCircleRadius +
* locationRadius) - fudgeFactor) >
* acos(sin(lat1Rad)sin(lat2Rad)+cos(lat1Rad
* )cos(lat2Rad)cos(lon2Rad-lon1Rad)6371
*
* @param userPoint * @param userPoint
* @param accuracyRadius in KM * @param accuracyRadius
* in KM
* @param locationPoint * @param locationPoint
* @param locationRadius in KM * @param locationRadius
* @param fudgeFactor how many KM the circles have to intersect * in KM
* @param fudgeFactor
* how many KM the circles have to intersect
* @return true if the circles intersect * @return true if the circles intersect
* @author ricky barrette * @author ricky barrette
*/ */
public static boolean isIntersecting(final GeoPoint userPoint, final float accuracyRadius, final GeoPoint locationPoint, final float locationRadius, final float fudgeFactor){ public static boolean isIntersecting(final GeoPoint userPoint, final float accuracyRadius, final GeoPoint locationPoint, final float locationRadius,
if(accuracyRadius + locationRadius - fudgeFactor > distanceKm(locationPoint, userPoint)) final float fudgeFactor) {
if (accuracyRadius + locationRadius - fudgeFactor > distanceKm(locationPoint, userPoint))
return true; return true;
return false; return false;
} }
/** /**
* determines when the specified point is off the map * determines when the specified point is off the map
*
* @param point * @param point
* @return true is the point is off the map * @return true is the point is off the map
* @author ricky barrette * @author ricky barrette
*/ */
public static boolean isPointOffMap(final MapView map , final GeoPoint point){ public static boolean isPointOffMap(final MapView map, final GeoPoint point) {
if(map == null) if (map == null)
return false; return false;
if (point == null) if (point == null)
return false; return false;
@@ -230,27 +276,30 @@ public class GeoUtils {
final double distance = GeoUtils.distanceKm(center, point); final double distance = GeoUtils.distanceKm(center, point);
final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + map.getLatitudeSpan() / 2, center.getLongitudeE6())); final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + map.getLatitudeSpan() / 2, center.getLongitudeE6()));
final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + map.getLongitudeSpan() / 2)); final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + map.getLongitudeSpan() / 2));
if (distance > distanceLat || distance > distanceLon) if (distance > distanceLat || distance > distanceLon)
return true; return true;
return false; return false;
} }
/** /**
* computes a geopoint the is the central geopoint between p1 and p1 * computes a geopoint the is the central geopoint between p1 and p1
* @param p1 first geopoint *
* @param p2 second geopoint * @param p1
* first geopoint
* @param p2
* second geopoint
* @return a MidPoint object * @return a MidPoint object
* @author ricky barrette * @author ricky barrette
*/ */
public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) { public static MidPoint midPoint(final GeoPoint p1, final GeoPoint p2) {
int minLatitude = (int)(+81 * 1E6); int minLatitude = (int) (+81 * 1E6);
int maxLatitude = (int)(-81 * 1E6); int maxLatitude = (int) (-81 * 1E6);
int minLongitude = (int)(+181 * 1E6); int minLongitude = (int) (+181 * 1E6);
int maxLongitude = (int)(-181 * 1E6); int maxLongitude = (int) (-181 * 1E6);
final List<Point> mPoints = new ArrayList<Point>(); final List<Point> mPoints = new ArrayList<Point>();
int latitude = p1.getLatitudeE6(); int latitude = p1.getLatitudeE6();
int longitude = p1.getLongitudeE6(); int longitude = p1.getLongitudeE6();
if (latitude != 0 && longitude !=0) { if (latitude != 0 && longitude != 0) {
minLatitude = minLatitude > latitude ? latitude : minLatitude; minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = maxLatitude < latitude ? latitude : maxLatitude; maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = minLongitude > longitude ? longitude : minLongitude; minLongitude = minLongitude > longitude ? longitude : minLongitude;
@@ -260,18 +309,19 @@ public class GeoUtils {
latitude = p2.getLatitudeE6(); latitude = p2.getLatitudeE6();
longitude = p2.getLongitudeE6(); longitude = p2.getLongitudeE6();
if (latitude != 0 && longitude !=0) { if (latitude != 0 && longitude != 0) {
minLatitude = minLatitude > latitude ? latitude : minLatitude; minLatitude = minLatitude > latitude ? latitude : minLatitude;
maxLatitude = maxLatitude < latitude ? latitude : maxLatitude; maxLatitude = maxLatitude < latitude ? latitude : maxLatitude;
minLongitude = minLongitude > longitude ? longitude : minLongitude; minLongitude = minLongitude > longitude ? longitude : minLongitude;
maxLongitude = maxLongitude < longitude ? longitude : maxLongitude; maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude)); mPoints.add(new Point(latitude, longitude));
} }
return new MidPoint(new GeoPoint((maxLatitude + minLatitude)/2, (maxLongitude + minLongitude)/2 ), minLatitude, minLongitude, maxLatitude, maxLongitude); return new MidPoint(new GeoPoint((maxLatitude + minLatitude) / 2, (maxLongitude + minLongitude) / 2), minLatitude, minLongitude, maxLatitude, maxLongitude);
} }
/** /**
* converts radians to bearing * converts radians to bearing
*
* @param rad * @param rad
* @return bearing * @return bearing
* @author Google Inc. * @author Google Inc.

View File

@@ -25,37 +25,45 @@ import com.TwentyCodes.android.debug.Debug;
import com.TwentyCodes.android.debug.LocationLibraryConstants; import com.TwentyCodes.android.debug.LocationLibraryConstants;
/** /**
* This service class will be used broadcast the users location either one time, or periodically. * This service class will be used broadcast the users location either one time,
* or periodically.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class LocationService extends Service implements LocationListener { public class LocationService extends Service implements LocationListener {
public static final String TAG = "LocationService"; public static final String TAG = "LocationService";
private static final int REQUEST_CODE = 7893749; private static final int REQUEST_CODE = 7893749;
/** /**
*a convince method for getting an intent to start the service * a convince method for getting an intent to start the service
*
* @param context * @param context
* @return a intent that will start the service * @return a intent that will start the service
* @author ricky barrette * @author ricky barrette
*/ */
public static Intent getStartServiceIntent(final Context context){ public static Intent getStartServiceIntent(final Context context) {
return new Intent(context, LocationService.class); return new Intent(context, LocationService.class);
} }
/** /**
* a convince method for stopping the service and removing it's alarm * a convince method for stopping the service and removing it's alarm
*
* @param context * @param context
* @return a runnable that will stop the service * @return a runnable that will stop the service
* @author ricky barrette * @author ricky barrette
*/ */
public static Runnable stopService(final Context context){ public static Runnable stopService(final Context context) {
return new Runnable(){ return new Runnable() {
@Override @Override
public void run(){ public void run() {
context.stopService(new Intent(context, LocationService.class)); context.stopService(new Intent(context, LocationService.class));
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context, LocationService.class), 0)); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(PendingIntent.getService(context, REQUEST_CODE, new Intent(context,
LocationService.class), 0));
} }
}; };
} }
private WakeLock mWakeLock; private WakeLock mWakeLock;
protected long mPeriod = -1; protected long mPeriod = -1;
private Location mLocation; private Location mLocation;
@@ -63,29 +71,30 @@ public class LocationService extends Service implements LocationListener {
private AndroidGPS mLocationManager; private AndroidGPS mLocationManager;
private int mRequiredAccuracy; private int mRequiredAccuracy;
private Intent mIntent; private Intent mIntent;
/* /*
* this runnable will be qued when the service is created. this will be used as a fail safe * this runnable will be qued when the service is created. this will be used
* as a fail safe
*/ */
private final Runnable failSafe = new Runnable() { private final Runnable failSafe = new Runnable() {
@Override @Override
public void run(){ public void run() {
stopSelf(mStartId); stopSelf(mStartId);
} }
}; };
/** /**
* broadcasts location to anything listening for updates, * broadcasts location to anything listening for updates, since this is the
* since this is the last function of the service, we call finish()u * last function of the service, we call finish()u
*
* @author ricky barrette * @author ricky barrette
*/ */
private void broadcastLocation() { private void broadcastLocation() {
Log.d(TAG, "broadcastLocation()"); Log.d(TAG, "broadcastLocation()");
if (mLocation != null) { if (mLocation != null) {
final Intent locationUpdate = new Intent(); final Intent locationUpdate = new Intent();
if(mIntent.getAction() != null) if (mIntent.getAction() != null)
locationUpdate.setAction(mIntent.getAction()); locationUpdate.setAction(mIntent.getAction());
else else
locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE); locationUpdate.setAction(LocationLibraryConstants.INTENT_ACTION_UPDATE);
@@ -97,6 +106,7 @@ public class LocationService extends Service implements LocationListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
*
* @see android.app.Service#onBind(android.content.Intent) * @see android.app.Service#onBind(android.content.Intent)
* @param arg0 * @param arg0
* @return * @return
@@ -109,48 +119,51 @@ public class LocationService extends Service implements LocationListener {
} }
/** /**
* called when the service is created. this will initialize the location manager, and acquire a wakelock * called when the service is created. this will initialize the location
* (non-Javadoc) * manager, and acquire a wakelock (non-Javadoc)
*
* @see android.app.Service#onCreate() * @see android.app.Service#onCreate()
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCreate(){ public void onCreate() {
mLocationManager = new AndroidGPS(this); mLocationManager = new AndroidGPS(this);
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire(); mWakeLock.acquire();
/* /*
* que the fail safe runnable to kill the report location and kill it self after the MAX_RUN_TIME has been meet * que the fail safe runnable to kill the report location and kill it
* self after the MAX_RUN_TIME has been meet
*/ */
new Handler().postDelayed(failSafe, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME); new Handler().postDelayed(failSafe, LocationLibraryConstants.MAX_LOCATION_SERVICE_RUN_TIME);
super.onCreate(); super.onCreate();
} }
/** /**
* called when the service is destroyed. * called when the service is destroyed. this will remove any wakelock or
* this will remove any wakelock or location service running, and register to be waken back up * location service running, and register to be waken back up (non-Javadoc)
* (non-Javadoc) *
* @see android.app.Service#onDestroy() * @see android.app.Service#onDestroy()
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onDestroy(){ public void onDestroy() {
broadcastLocation(); broadcastLocation();
mLocationManager.disableLocationUpdates(); mLocationManager.disableLocationUpdates();
if(mWakeLock.isHeld()) if (mWakeLock.isHeld())
mWakeLock.release(); mWakeLock.release();
if(mPeriod > -1) if (mPeriod > -1)
registerwakeUp(); registerwakeUp();
} }
@Override @Override
public void onLocationChanged(final Location location) { public void onLocationChanged(final Location location) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "got location +- "+ location.getAccuracy() +"m"); Log.d(TAG, "got location +- " + location.getAccuracy() + "m");
mLocation = location; mLocation = location;
if(location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION) if (location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY)
|| LocationLibraryConstants.REPORT_FIRST_LOCATION)
stopSelf(mStartId); stopSelf(mStartId);
} }
@@ -167,13 +180,15 @@ public class LocationService extends Service implements LocationListener {
} }
/** /**
* This method is called when startService is called. only used in 2.x android. * This method is called when startService is called. only used in 2.x
* android.
*
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(final Intent intent, final int flags, final int startId) { public int onStartCommand(final Intent intent, final int flags, final int startId) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.i(TAG , "onStartCommand.Service started with start id of: " + startId); Log.i(TAG, "onStartCommand.Service started with start id of: " + startId);
mStartId = startId; mStartId = startId;
parseIntent(intent); parseIntent(intent);
@@ -192,7 +207,7 @@ public class LocationService extends Service implements LocationListener {
* *
* @author ricky barrette * @author ricky barrette
*/ */
private void parseIntent(final Intent intent){ private void parseIntent(final Intent intent) {
mIntent = intent; mIntent = intent;
@@ -205,9 +220,10 @@ public class LocationService extends Service implements LocationListener {
/** /**
* registers this service to be waken up by android's alarm manager * registers this service to be waken up by android's alarm manager
*
* @author ricky barrette * @author ricky barrette
*/ */
private void registerwakeUp(){ private void registerwakeUp() {
Log.d(TAG, "registerwakeUp()"); Log.d(TAG, "registerwakeUp()");
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0)); am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));

View File

@@ -14,7 +14,9 @@ import android.view.MotionEvent;
import com.TwentyCodes.android.debug.Debug; import com.TwentyCodes.android.debug.Debug;
/** /**
* We use this MapView Because it has double tap zoom capability and exception handling * We use this MapView Because it has double tap zoom capability and exception
* handling
*
* @author ricky barrette * @author ricky barrette
*/ */
public class MapView extends com.google.android.maps.MapView { public class MapView extends com.google.android.maps.MapView {
@@ -52,22 +54,21 @@ public class MapView extends com.google.android.maps.MapView {
} }
/** /**
* We will override the draw method to help prevent issues * We will override the draw method to help prevent issues (non-Javadoc)
* (non-Javadoc) *
* @see android.view.View#draw(android.graphics.Canvas) * @see android.view.View#draw(android.graphics.Canvas)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(final Canvas canvas) { public void draw(final Canvas canvas) {
try { try {
if(getZoomLevel() >= 21) if (getZoomLevel() >= 21)
getController().setZoom(20); getController().setZoom(20);
super.draw(canvas); super.draw(canvas);
} } catch (final Exception ex) {
catch(final Exception ex) { // getController().setCenter(this.getMapCenter());
// getController().setCenter(this.getMapCenter()); // getController().setZoom(this.getZoomLevel() - 2);
// getController().setZoom(this.getZoomLevel() - 2); if (Debug.DEBUG)
if(Debug.DEBUG)
Log.d(TAG, "Internal error in MapView:" + Log.getStackTraceString(ex)); Log.d(TAG, "Internal error in MapView:" + Log.getStackTraceString(ex));
} }
} }
@@ -99,7 +100,8 @@ public class MapView extends com.google.android.maps.MapView {
} }
/** /**
* @param isDoubleTapZoonEnabled the isDoubleTapZoonEnabled to set * @param isDoubleTapZoonEnabled
* the isDoubleTapZoonEnabled to set
* @author ricky barrette * @author ricky barrette
*/ */
public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled) { public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled) {

View File

@@ -8,7 +8,9 @@ package com.TwentyCodes.android.location;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This MidPoint object will hold the information form the calculations performed by GeoUtils.midPoint(). * This MidPoint object will hold the information form the calculations
* performed by GeoUtils.midPoint().
*
* @author ricky barrette * @author ricky barrette
*/ */
public class MidPoint { public class MidPoint {
@@ -21,6 +23,7 @@ public class MidPoint {
/** /**
* Creates a new MidPoint * Creates a new MidPoint
*
* @author ricky barrette * @author ricky barrette
*/ */
public MidPoint(final GeoPoint midPoint, final int minLatitude, final int minLongitude, final int maxLatitude, final int maxLongitude) { public MidPoint(final GeoPoint midPoint, final int minLatitude, final int minLongitude, final int maxLatitude, final int maxLongitude) {
@@ -33,19 +36,21 @@ public class MidPoint {
/** /**
* returns the calculated midpoint * returns the calculated midpoint
*
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getMidPoint(){ public GeoPoint getMidPoint() {
return mMidPoint; return mMidPoint;
} }
/** /**
* zooms the provided map view to the span of this mid point * zooms the provided map view to the span of this mid point
*
* @param mMapView * @param mMapView
* @author ricky barrette * @author ricky barrette
*/ */
public void zoomToSpan(final com.google.android.maps.MapView mMapView){ public void zoomToSpan(final com.google.android.maps.MapView mMapView) {
mMapView.getController().zoomToSpan(mMaxLatitude - mMinLatitude, mMaxLongitude - mMinLongitude); mMapView.getController().zoomToSpan(mMaxLatitude - mMinLatitude, mMaxLongitude - mMinLongitude);
} }
} }

View File

@@ -3,7 +3,9 @@ package com.TwentyCodes.android.location;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This interface will be used to pass the selected location from the dialogs to the listening instance * This interface will be used to pass the selected location from the dialogs to
* the listening instance
*
* @author ricky barrette * @author ricky barrette
*/ */
public interface OnLocationSelectedListener { public interface OnLocationSelectedListener {

View File

@@ -15,17 +15,19 @@ import com.TwentyCodes.android.debug.LocationLibraryConstants;
/** /**
* A convenience class for requesting passive location updates * A convenience class for requesting passive location updates
*
* @author ricky barrette * @author ricky barrette
*/ */
public class PassiveLocationListener { public class PassiveLocationListener {
/** /**
* A convenience method for requesting passive location updates * A convenience method for requesting passive location updates
*
* @param context * @param context
* @param receiverIntent * @param receiverIntent
* @author ricky barrette * @author ricky barrette
*/ */
public static final void requestPassiveLocationUpdates(final Context context, final Intent receiverIntent){ public static final void requestPassiveLocationUpdates(final Context context, final Intent receiverIntent) {
if (LocationLibraryConstants.SUPPORTS_FROYO) { if (LocationLibraryConstants.SUPPORTS_FROYO) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT); final PendingIntent locationListenerPassivePendingIntent = PendingIntent.getBroadcast(context, 0, receiverIntent, PendingIntent.FLAG_UPDATE_CURRENT);

View File

@@ -26,8 +26,9 @@ import android.util.Log;
import com.TwentyCodes.android.debug.Debug; import com.TwentyCodes.android.debug.Debug;
/** /**
* Due to this bug http://code.google.com/p/android/issues/detail?id=8816 google's Geocoder class does not function in android 2.2+. * Due to this bug http://code.google.com/p/android/issues/detail?id=8816
* I found this source in one of the comments mentioning that it is a work around. * google's Geocoder class does not function in android 2.2+. I found this
* source in one of the comments mentioning that it is a work around.
* *
* @author ricky barrette * @author ricky barrette
*/ */
@@ -37,7 +38,9 @@ public class ReverseGeocoder {
/** /**
* Performs a google maps search for the address * Performs a google maps search for the address
* @param address to search *
* @param address
* to search
* @return JSON Array of google place marks * @return JSON Array of google place marks
* @throws IOException * @throws IOException
* @throws JSONException * @throws JSONException
@@ -49,7 +52,7 @@ public class ReverseGeocoder {
final StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
final HttpClient client = new DefaultHttpClient(); final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
final HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
final HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
@@ -60,7 +63,7 @@ public class ReverseGeocoder {
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
return new JSONObject(response.toString()).getJSONArray("Placemark"); return new JSONObject(response.toString()).getJSONArray("Placemark");
@@ -68,17 +71,18 @@ public class ReverseGeocoder {
/** /**
* Performs a google maps search for the closest address to the location * Performs a google maps search for the closest address to the location
*
* @param lat * @param lat
* @param lon * @param lon
* @return string address, or lat, lon if search fails * @return string address, or lat, lon if search fails
* @author ricky barrette * @author ricky barrette
*/ */
public static String getAddressFromLocation(final Location location) { public static String getAddressFromLocation(final Location location) {
final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false"; final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false";
final StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
final HttpClient client = new DefaultHttpClient(); final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
try { try {
final HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
@@ -93,19 +97,18 @@ public class ReverseGeocoder {
e.printStackTrace(); e.printStackTrace();
} }
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
JSONArray responseArray = null; JSONArray responseArray = null;
try { try {
responseArray = new JSONObject(response.toString()).getJSONArray("Placemark"); responseArray = new JSONObject(response.toString()).getJSONArray("Placemark");
} catch (final JSONException e) { } catch (final JSONException e) {
return location.getLatitude() +", "+ location.getLongitude() +" +/- "+ location.getAccuracy()+"m"; return location.getLatitude() + ", " + location.getLongitude() + " +/- " + location.getAccuracy() + "m";
} }
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,responseArray.length() + " result(s)"); Log.d(TAG, responseArray.length() + " result(s)");
try { try {
final JSONObject jsl = responseArray.getJSONObject(0); final JSONObject jsl = responseArray.getJSONObject(0);
@@ -114,23 +117,24 @@ public class ReverseGeocoder {
e.printStackTrace(); e.printStackTrace();
} }
return location.getLatitude() +", "+ location.getLongitude() +" +/- "+ location.getAccuracy()+"m"; return location.getLatitude() + ", " + location.getLongitude() + " +/- " + location.getAccuracy() + "m";
} }
/** /**
* Performs a google maps search for the address * Performs a google maps search for the address
*
* @param location * @param location
* @return JSON Array on google place marks nearby * @return JSON Array on google place marks nearby
* @author ricky barrette * @author ricky barrette
* @throws IOException * @throws IOException
* @throws JSONException * @throws JSONException
*/ */
public static JSONArray getFromLocation(final Location location) throws IOException, JSONException { public static JSONArray getFromLocation(final Location location) throws IOException, JSONException {
final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false"; final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false";
final StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
final HttpClient client = new DefaultHttpClient(); final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
final HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
final HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
@@ -141,7 +145,7 @@ public class ReverseGeocoder {
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, response.toString()); Log.d(TAG, response.toString());
return new JSONObject(response.toString()).getJSONArray("Placemark"); return new JSONObject(response.toString()).getJSONArray("Placemark");

View File

@@ -30,29 +30,31 @@ import com.google.android.maps.Projection;
/** /**
* This class will be used to build user overlays * This class will be used to build user overlays
*
* @author ricky barrette * @author ricky barrette
*/ */
public abstract class BaseUserOverlay extends Overlay implements GeoPointLocationListener, CompassListener { public abstract class BaseUserOverlay extends Overlay implements GeoPointLocationListener, CompassListener {
/** /**
* This thread is responsible for animating the user icon * This thread is responsible for animating the user icon
*
* @author ricky barrette * @author ricky barrette
*/ */
public class AnimationThread extends Thread { public class AnimationThread extends Thread {
private boolean isAborted; private boolean isAborted;
public void abort(){ public void abort() {
isAborted = true; isAborted = true;
} }
/** /**
* Main method of this animation thread * Main method of this animation thread (non-Javadoc)
* (non-Javadoc) *
* @see java.lang.Thread#run() * @see java.lang.Thread#run()
*/ */
@Override @Override
public void run(){ public void run() {
super.run(); super.run();
int index = 0; int index = 0;
boolean isCountingDown = false; boolean isCountingDown = false;
@@ -61,41 +63,41 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
if (isAborted) if (isAborted)
break; break;
switch(index){ switch (index) {
case 1: case 1:
mUserArrow = R.drawable.user_arrow_animation_2; mUserArrow = R.drawable.user_arrow_animation_2;
if(isCountingDown) if (isCountingDown)
index--;
else
index++;
try {
sleep(100l);
} catch (final InterruptedException e) {
e.printStackTrace();
}
break;
case 2:
mUserArrow = R.drawable.user_arrow_animation_3;
index--; index--;
isCountingDown = true; else
try {
sleep(200l);
} catch (final InterruptedException e) {
e.printStackTrace();
}
break;
default:
mUserArrow = R.drawable.user_arrow_animation_1;
index++; index++;
isCountingDown = false;
try { try {
sleep(2000l); sleep(100l);
} catch (final InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
return; }
} break;
break; case 2:
mUserArrow = R.drawable.user_arrow_animation_3;
index--;
isCountingDown = true;
try {
sleep(200l);
} catch (final InterruptedException e) {
e.printStackTrace();
}
break;
default:
mUserArrow = R.drawable.user_arrow_animation_1;
index++;
isCountingDown = false;
try {
sleep(2000l);
} catch (final InterruptedException e) {
e.printStackTrace();
return;
}
break;
} }
} }
@@ -121,6 +123,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
/** /**
* Construct a new UserOverlay * Construct a new UserOverlay
*
* @param mapView * @param mapView
* @param context * @param context
* @author ricky barrette * @author ricky barrette
@@ -135,6 +138,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
/** /**
* Construct a new UserOverlayTODO Auto-generated method stub * Construct a new UserOverlayTODO Auto-generated method stub
*
* @param mapView * @param mapView
* @param context * @param context
* @param followUser * @param followUser
@@ -147,38 +151,42 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
/** /**
* Disables the compass * Disables the compass
*
* @author ricky barrette * @author ricky barrette
*/ */
public final void disableCompass(){ public final void disableCompass() {
isCompassEnabled = false; isCompassEnabled = false;
mMapView.getOverlays().remove(mCompass); mMapView.getOverlays().remove(mCompass);
} }
/** /**
* Stops location updates and removes the overlay from view * Stops location updates and removes the overlay from view
*
* @author ricky barrette * @author ricky barrette
*/ */
public final void disableMyLocation(){ public final void disableMyLocation() {
Log.d(TAG,"disableMyLocation()"); Log.d(TAG, "disableMyLocation()");
onMyLocationDisabled(); onMyLocationDisabled();
isEnabled = false; isEnabled = false;
mCompass.disable(); mCompass.disable();
if(mListener != null) if (mListener != null)
mListener.onFirstFix(false); mListener.onFirstFix(false);
mAnimationThread.abort(); mAnimationThread.abort();
} }
/** /**
* we override this methods so we can provide a drawable and a location to draw on the canvas. * we override this methods so we can provide a drawable and a location to
* (non-Javadoc) * draw on the canvas. (non-Javadoc)
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean) *
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas,
* com.google.android.maps.MapView, boolean)
* @param canvas * @param canvas
* @param mapView * @param mapView
* @param shadow * @param shadow
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(Canvas canvas, final MapView mapView, final boolean shadow){ public void draw(Canvas canvas, final MapView mapView, final boolean shadow) {
if (isEnabled && mPoint != null) { if (isEnabled && mPoint != null) {
final Point center = new Point(); final Point center = new Point();
final Point left = new Point(); final Point left = new Point();
@@ -189,19 +197,24 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
canvas = drawAccuracyCircle(center, left, canvas); canvas = drawAccuracyCircle(center, left, canvas);
canvas = drawUser(center, mBearing, canvas); canvas = drawUser(center, mBearing, canvas);
/* /*
* the following log is used to demonstrate if the leftGeo point is the correct * the following log is used to demonstrate if the leftGeo point is
* the correct
*/ */
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, GeoUtils.distanceKm(mPoint, leftGeo) * 1000+"m"); Log.d(TAG, GeoUtils.distanceKm(mPoint, leftGeo) * 1000 + "m");
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
} }
/** /**
* draws an accuracy circle onto the canvas supplied * draws an accuracy circle onto the canvas supplied
* @param center point of the circle *
* @param left point of the circle * @param center
* @param canvas to be drawn on * point of the circle
* @param left
* point of the circle
* @param canvas
* to be drawn on
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
@@ -212,7 +225,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* get radius of the circle being drawn by * get radius of the circle being drawn by
*/ */
int circleRadius = center.x - left.x; int circleRadius = center.x - left.x;
if(circleRadius <= 0) if (circleRadius <= 0)
circleRadius = left.x - center.x; circleRadius = left.x - center.x;
/* /*
* paint a blue circle on the map * paint a blue circle on the map
@@ -230,10 +243,9 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
canvas.drawCircle(center.x, center.y, circleRadius, paint); canvas.drawCircle(center.x, center.y, circleRadius, paint);
/* /*
* for testing * for testing draw a dot over the left geopoint
* draw a dot over the left geopoint
*/ */
if(Debug.DEBUG){ if (Debug.DEBUG) {
paint.setColor(Color.RED); paint.setColor(Color.RED);
final RectF oval = new RectF(left.x - 1, left.y - 1, left.x + 1, left.y + 1); final RectF oval = new RectF(left.x - 1, left.y - 1, left.x + 1, left.y + 1);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
@@ -243,40 +255,34 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
} }
/** /**
* draws user arrow that points north based on bearing onto the supplied canvas * draws user arrow that points north based on bearing onto the supplied
* @param point to draw user arrow on * canvas
* @param bearing of the device *
* @param canvas to draw on * @param point
* to draw user arrow on
* @param bearing
* of the device
* @param canvas
* to draw on
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
private Canvas drawUser(final Point point, final float bearing, final Canvas canvas){ private Canvas drawUser(final Point point, final float bearing, final Canvas canvas) {
final Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow); final Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow);
final Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(bearing); matrix.postRotate(bearing);
final Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(user, 0, 0, user.getWidth(), user.getHeight(), matrix, true);
user, canvas.drawBitmap(rotatedBmp, point.x - rotatedBmp.getWidth() / 2, point.y - rotatedBmp.getHeight() / 2, null);
0, 0,
user.getWidth(),
user.getHeight(),
matrix,
true
);
canvas.drawBitmap(
rotatedBmp,
point.x - rotatedBmp.getWidth() / 2,
point.y - rotatedBmp.getHeight() / 2,
null
);
return canvas; return canvas;
} }
/** /**
* Enables the compass * Enables the compass
*
* @author ricky barrette * @author ricky barrette
*/ */
public void enableCompass(){ public void enableCompass() {
if(! isCompassEnabled){ if (!isCompassEnabled) {
mMapView.getOverlays().add(mCompass); mMapView.getOverlays().add(mCompass);
isCompassEnabled = true; isCompassEnabled = true;
} }
@@ -284,12 +290,13 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
/** /**
* Attempts to enable MyLocation, registering for updates from provider * Attempts to enable MyLocation, registering for updates from provider
*
* @author ricky barrette * @author ricky barrette
*/ */
public void enableMyLocation(){ public void enableMyLocation() {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"enableMyLocation()"); Log.d(TAG, "enableMyLocation()");
if (! isEnabled) { if (!isEnabled) {
mAnimationThread = new AnimationThread(); mAnimationThread = new AnimationThread();
mAnimationThread.start(); mAnimationThread.start();
@@ -298,19 +305,20 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
isEnabled = true; isEnabled = true;
mCompass.enable(this); mCompass.enable(this);
isFistFix = true; isFistFix = true;
if(mListener != null) if (mListener != null)
mListener.onFirstFix(false); mListener.onFirstFix(false);
} }
} }
/** /**
* Allows the map to follow the user * Allows the map to follow the user
*
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(final boolean followUser){ public void followUser(final boolean followUser) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG,"followUser()"); Log.d(TAG, "followUser()");
isFollowingUser = followUser; isFollowingUser = followUser;
} }
@@ -318,40 +326,44 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getDestination(){ public GeoPoint getDestination() {
return mCompass.getDestination(); return mCompass.getDestination();
} }
/** /**
* returns the users current bearing * returns the users current bearing
*
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public float getUserBearing(){ public float getUserBearing() {
return mBearing; return mBearing;
} }
/** /**
* returns the users current location * returns the users current location
*
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getUserLocation(){ public GeoPoint getUserLocation() {
return mPoint; return mPoint;
} }
@Override @Override
public void onCompassUpdate(final float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if (mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
mBearing = bearing; mBearing = bearing;
mMapView.invalidate(); mMapView.invalidate();
} }
/** /**
* called when the SkyHook location changes, this mthod is resposiable for updating the overlay location and accuracy circle. * called when the SkyHook location changes, this mthod is resposiable for
* (non-Javadoc) * updating the overlay location and accuracy circle. (non-Javadoc)
* @see com.TwentyCodes.android.SkyHook.GeoPointLocationListener.location.LocationListener#onLocationChanged(com.google.android.maps.GeoPoint, float) *
* @see com.TwentyCodes.android.SkyHook.GeoPointLocationListener.location.LocationListener#onLocationChanged(com.google.android.maps.GeoPoint,
* float)
* @param point * @param point
* @param accuracy * @param accuracy
* @author ricky barrette * @author ricky barrette
@@ -359,26 +371,26 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
@Override @Override
public void onLocationChanged(final GeoPoint point, final int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mCompass != null) if (mCompass != null)
mCompass.setLocation(point); mCompass.setLocation(point);
/* /*
* if this is the first fix * if this is the first fix set map center the users location, and zoom
* set map center the users location, and zoom to the max zoom level * to the max zoom level
*/ */
if(point != null && isFistFix){ if (point != null && isFistFix) {
mMapView.getController().setCenter(point); mMapView.getController().setCenter(point);
mMapView.getController().setZoom( mMapView.getMaxZoomLevel() - 2 ); mMapView.getController().setZoom(mMapView.getMaxZoomLevel() - 2);
if(mListener != null) if (mListener != null)
mListener.onFirstFix(true); mListener.onFirstFix(true);
isFistFix = false; isFistFix = false;
} }
//update the users point, and accuracy for the UI // update the users point, and accuracy for the UI
mPoint = point; mPoint = point;
mAccuracy = accuracy; mAccuracy = accuracy;
mMapView.invalidate(); mMapView.invalidate();
if(mListener != null) if (mListener != null)
mListener.onLocationChanged(point, accuracy); mListener.onLocationChanged(point, accuracy);
if (isFollowingUser) if (isFollowingUser)
@@ -386,19 +398,24 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
} }
/** /**
* Called when disableMyLocation is called. This is where you want to disable any location updates from your provider * Called when disableMyLocation is called. This is where you want to
* disable any location updates from your provider
*
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onMyLocationDisabled(); public abstract void onMyLocationDisabled();
/** /**
* Called when the enableMyLocation() is called. This is where you want to ask your location provider for updates * Called when the enableMyLocation() is called. This is where you want to
* ask your location provider for updates
*
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onMyLocationEnabled(); public abstract void onMyLocationEnabled();
/** /**
* pans the map view if the user is off screen. * pans the map view if the user is off screen.
*
* @author ricky barrette * @author ricky barrette
*/ */
private void panToUserIfOffMap(final GeoPoint user) { private void panToUserIfOffMap(final GeoPoint user) {
@@ -410,27 +427,29 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
final double whichIsGreater = distanceLat > distanceLon ? distanceLat : distanceLon; final double whichIsGreater = distanceLat > distanceLon ? distanceLat : distanceLon;
/** /**
* if the user is one the map, keep them their * if the user is one the map, keep them their else don't pan to user
* else don't pan to user unless they pan pack to them * unless they pan pack to them
*/ */
if( ! (distance > whichIsGreater) ) if (!(distance > whichIsGreater))
if (distance > distanceLat || distance > distanceLon) if (distance > distanceLat || distance > distanceLon)
mMapView.getController().animateTo(user); mMapView.getController().animateTo(user);
} }
/** /**
* Attempts to register the listener for location updates * Attempts to register the listener for location updates
*
* @param listener * @param listener
* @author Ricky Barrette * @author Ricky Barrette
*/ */
public void registerListener(final GeoPointLocationListener listener){ public void registerListener(final GeoPointLocationListener listener) {
Log.d(TAG,"registerListener()"); Log.d(TAG, "registerListener()");
if (mListener == null) if (mListener == null)
mListener = listener; mListener = listener;
} }
/** /**
* Set the compass drawables and location * Set the compass drawables and location
*
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
* @param x * @param x
@@ -443,27 +462,31 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
/** /**
* Sets the CompassListener * Sets the CompassListener
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(final CompassListener listener){ public void setCompassListener(final CompassListener listener) {
mCompassListener = listener; mCompassListener = listener;
} }
/** /**
* Sets the destination for the compass * Sets the destination for the compass
*
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(final GeoPoint destination){ public void setDestination(final GeoPoint destination) {
if(mCompass != null) if (mCompass != null)
mCompass.setDestination(destination); mCompass.setDestination(destination);
} }
/** /**
* UnResgisters the listener. after this call you will no longer get location updates * UnResgisters the listener. after this call you will no longer get
* location updates
*
* @author Ricky Barrette * @author Ricky Barrette
*/ */
public void unRegisterListener(){ public void unRegisterListener() {
mListener = null; mListener = null;
} }
} }

View File

@@ -24,7 +24,9 @@ import com.google.android.maps.MapView;
import com.google.android.maps.Overlay; import com.google.android.maps.Overlay;
/** /**
* A Simple compass overlay that will be used to point towards a destination or north * A Simple compass overlay that will be used to point towards a destination or
* north
*
* @author ricky barrette * @author ricky barrette
*/ */
public class CompasOverlay extends Overlay implements CompassListener { public class CompasOverlay extends Overlay implements CompassListener {
@@ -43,6 +45,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
*
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(final Context context) { public CompasOverlay(final Context context) {
@@ -54,26 +57,30 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
*
* @param context * @param context
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(final Context context, final GeoPoint destination){ public CompasOverlay(final Context context, final GeoPoint destination) {
this(context); this(context);
mDestination = destination; mDestination = destination;
} }
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
*
* @param context * @param context
* @param destination * @param destination
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
* @param x dip * @param x
* @param y dip * dip
* @param y
* dip
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(final Context context, final GeoPoint destination, final int needleResId, final int backgroundResId, final int x, final int y){ public CompasOverlay(final Context context, final GeoPoint destination, final int needleResId, final int backgroundResId, final int x, final int y) {
this(context, destination); this(context, destination);
mX = convertDipToPx(x); mX = convertDipToPx(x);
mY = convertDipToPx(y); mY = convertDipToPx(y);
@@ -83,6 +90,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Creates a new CompasOverlay * Creates a new CompasOverlay
*
* @param context * @param context
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
@@ -90,12 +98,13 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(final Context context, final int needleResId, final int backgroundResId, final int x, final int y){ public CompasOverlay(final Context context, final int needleResId, final int backgroundResId, final int x, final int y) {
this(context, null, needleResId, backgroundResId, x, y); this(context, null, needleResId, backgroundResId, x, y);
} }
/** /**
* Converts dip to px * Converts dip to px
*
* @param dip * @param dip
* @return px * @return px
* @author ricky barrette * @author ricky barrette
@@ -107,9 +116,10 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Disables the compass overlay * Disables the compass overlay
*
* @author ricky barrette * @author ricky barrette
*/ */
public void disable(){ public void disable() {
isEnabled = false; isEnabled = false;
mCompassSensor.disable(); mCompassSensor.disable();
mListener = null; mListener = null;
@@ -117,43 +127,30 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean) *
* @see com.google.android.maps.Overlay#draw(android.graphics.Canvas,
* com.google.android.maps.MapView, boolean)
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) { public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
if(isEnabled){ if (isEnabled) {
//set the center of the compass in the top left corner of the screen // set the center of the compass in the top left corner of the
// screen
final Point point = new Point(); final Point point = new Point();
point.set(mX, mY); point.set(mX, mY);
//draw compass background // draw compass background
final Bitmap compass = BitmapFactory.decodeResource( mContext.getResources(), mBackgroundResId); final Bitmap compass = BitmapFactory.decodeResource(mContext.getResources(), mBackgroundResId);
canvas.drawBitmap(compass, canvas.drawBitmap(compass, point.x - compass.getWidth() / 2, point.y - compass.getHeight() / 2, null);
point.x - compass.getWidth() / 2,
point.y - compass.getHeight() / 2,
null
);
//draw the compass needle // draw the compass needle
final Bitmap arrowBitmap = BitmapFactory.decodeResource( mContext.getResources(), mNeedleResId); final Bitmap arrowBitmap = BitmapFactory.decodeResource(mContext.getResources(), mNeedleResId);
final Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing)); matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing));
final Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(arrowBitmap, 0, 0, arrowBitmap.getWidth(), arrowBitmap.getHeight(), matrix, true);
arrowBitmap, canvas.drawBitmap(rotatedBmp, point.x - rotatedBmp.getWidth() / 2, point.y - rotatedBmp.getHeight() / 2, null);
0, 0,
arrowBitmap.getWidth(),
arrowBitmap.getHeight(),
matrix,
true
);
canvas.drawBitmap(
rotatedBmp,
point.x - rotatedBmp.getWidth() / 2,
point.y - rotatedBmp.getHeight() / 2,
null
);
mapView.invalidate(); mapView.invalidate();
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
@@ -161,10 +158,11 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Enables the compass overlay * Enables the compass overlay
*
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(){ public void enable() {
if(! isEnabled){ if (!isEnabled) {
isEnabled = true; isEnabled = true;
mCompassSensor.enable(this); mCompassSensor.enable(this);
} }
@@ -172,10 +170,11 @@ public class CompasOverlay extends Overlay implements CompassListener {
/** /**
* Enables the compass overlay * Enables the compass overlay
*
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(final CompassListener listener){ public void enable(final CompassListener listener) {
mListener = listener; mListener = listener;
enable(); enable();
} }
@@ -184,7 +183,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @return the current bearing * @return the current bearing
* @author ricky barrette * @author ricky barrette
*/ */
public float getBearing(){ public float getBearing() {
return mBearing; return mBearing;
} }
@@ -192,13 +191,14 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @return return the current destination * @return return the current destination
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getDestination(){ public GeoPoint getDestination() {
return mDestination; return mDestination;
} }
/** /**
* Called from the compass Sensor to update the current bearing * Called from the compass Sensor to update the current bearing
* (non-Javadoc) * (non-Javadoc)
*
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
* @author ricky barrette * @author ricky barrette
*/ */
@@ -209,7 +209,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
/* /*
* pass it down the chain * pass it down the chain
*/ */
if(mListener != null) if (mListener != null)
mListener.onCompassUpdate(bearing); mListener.onCompassUpdate(bearing);
} }
@@ -217,18 +217,20 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(final GeoPoint destination){ public void setDestination(final GeoPoint destination) {
mDestination = destination; mDestination = destination;
} }
/** /**
* @param needleResId * @param needleResId
* @param backgroundResId * @param backgroundResId
* @param x dip * @param x
* @param y dip * dip
* @param y
* dip
* @author ricky barrette * @author ricky barrette
*/ */
public void setDrawables(final int needleResId, final int backgroundResId, final int x, final int y){ public void setDrawables(final int needleResId, final int backgroundResId, final int x, final int y) {
mX = convertDipToPx(x); mX = convertDipToPx(x);
mY = convertDipToPx(y); mY = convertDipToPx(y);
mNeedleResId = needleResId; mNeedleResId = needleResId;
@@ -239,7 +241,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(final GeoPoint location){ public void setLocation(final GeoPoint location) {
mLocation = location; mLocation = location;
} }

View File

@@ -26,7 +26,9 @@ import com.TwentyCodes.android.location.MapView;
import com.google.android.maps.GeoPoint; import com.google.android.maps.GeoPoint;
/** /**
* This Overlay class will be used to display provided by the Google Directions API on a map * This Overlay class will be used to display provided by the Google Directions
* API on a map
*
* @author ricky barrette * @author ricky barrette
*/ */
public class DirectionsOverlay { public class DirectionsOverlay {
@@ -34,7 +36,7 @@ public class DirectionsOverlay {
/** /**
* @author ricky barrette * @author ricky barrette
*/ */
public interface OnDirectionsCompleteListener{ public interface OnDirectionsCompleteListener {
public void onDirectionsComplete(DirectionsOverlay directionsOverlay); public void onDirectionsComplete(DirectionsOverlay directionsOverlay);
} }
@@ -51,15 +53,19 @@ public class DirectionsOverlay {
/** /**
* Downloads and Creates a new DirectionsOverlay from the provided points * Downloads and Creates a new DirectionsOverlay from the provided points
* @param origin point *
* @param destination point * @param origin
* point
* @param destination
* point
* @author ricky barrette * @author ricky barrette
* @throws IOException * @throws IOException
* @throws ClientProtocolException * @throws ClientProtocolException
* @throws IllegalStateException * @throws IllegalStateException
* @throws JSONException * @throws JSONException
*/ */
public DirectionsOverlay(final MapView map, final GeoPoint origin, final GeoPoint destination, final OnDirectionsCompleteListener listener) throws IllegalStateException, ClientProtocolException, IOException, JSONException { public DirectionsOverlay(final MapView map, final GeoPoint origin, final GeoPoint destination, final OnDirectionsCompleteListener listener)
throws IllegalStateException, ClientProtocolException, IOException, JSONException {
mMapView = map; mMapView = map;
mListener = listener; mListener = listener;
final String json = downloadJSON(generateUrl(origin, destination)); final String json = downloadJSON(generateUrl(origin, destination));
@@ -68,11 +74,12 @@ public class DirectionsOverlay {
/** /**
* Creates a new DirectionsOverlay from the provided String JSON * Creates a new DirectionsOverlay from the provided String JSON
*
* @param json * @param json
* @throws JSONException * @throws JSONException
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsOverlay(final MapView map, final String json, final OnDirectionsCompleteListener listener) throws JSONException{ public DirectionsOverlay(final MapView map, final String json, final OnDirectionsCompleteListener listener) throws JSONException {
mListener = listener; mListener = listener;
mMapView = map; mMapView = map;
drawPath(json); drawPath(json);
@@ -80,14 +87,16 @@ public class DirectionsOverlay {
/** /**
* Deocodes googles polyline * Deocodes googles polyline
*
* @param encoded * @param encoded
* @return a list of geopoints representing the path * @return a list of geopoints representing the path
* @author Mark McClure http://facstaff.unca.edu/mcmcclur/googlemaps/encodepolyline/ * @author Mark McClure
* http://facstaff.unca.edu/mcmcclur/googlemaps/encodepolyline/
* @author ricky barrette * @author ricky barrette
* @throws JSONException * @throws JSONException
*/ */
private void decodePoly(final JSONObject step) throws JSONException { private void decodePoly(final JSONObject step) throws JSONException {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "decodePoly"); Log.d(TAG, "decodePoly");
final String encoded = step.getJSONObject("polyline").getString("points"); final String encoded = step.getJSONObject("polyline").getString("points");
@@ -118,17 +127,16 @@ public class DirectionsOverlay {
final GeoPoint p = new GeoPoint((int) (lat / 1E5 * 1E6), (int) (lng / 1E5 * 1E6)); final GeoPoint p = new GeoPoint((int) (lat / 1E5 * 1E6), (int) (lng / 1E5 * 1E6));
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.d(TAG, "current = "+ p.toString()); Log.d(TAG, "current = " + p.toString());
if(last != null) if (last != null)
Log.d(TAG, "last = "+ last.toString()); Log.d(TAG, "last = " + last.toString());
} }
if (last != null)
if(last != null)
mPath.add(new PathOverlay(last, p, Color.RED)); mPath.add(new PathOverlay(last, p, Color.RED));
// else // else
// mPath.add(new PathOverlay(p, 5, Color.GREEN)); // mPath.add(new PathOverlay(p, 5, Color.GREEN));
last = p; last = p;
} }
@@ -137,6 +145,7 @@ public class DirectionsOverlay {
/** /**
* Downloads Google Directions JSON from the Internet * Downloads Google Directions JSON from the Internet
*
* @param url * @param url
* @return * @return
* @throws IllegalStateException * @throws IllegalStateException
@@ -145,9 +154,9 @@ public class DirectionsOverlay {
* @author ricky barrette * @author ricky barrette
*/ */
private String downloadJSON(final String url) throws IllegalStateException, ClientProtocolException, IOException { private String downloadJSON(final String url) throws IllegalStateException, ClientProtocolException, IOException {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, url); Log.d(TAG, url);
if(url == null) if (url == null)
throw new NullPointerException(); throw new NullPointerException();
final StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
final BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(new DefaultHttpClient().execute(new HttpGet(url)).getEntity().getContent()));
@@ -157,16 +166,17 @@ public class DirectionsOverlay {
return response.toString(); return response.toString();
} }
/** /**
* Creates a new DirectionsOverlay from the json provided * Creates a new DirectionsOverlay from the json provided
* @param json of Google Directions API *
* @param json
* of Google Directions API
* @author ricky barrette * @author ricky barrette
* @return * @return
* @throws JSONException * @throws JSONException
*/ */
public void drawPath(final String json) throws JSONException{ public void drawPath(final String json) throws JSONException {
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.d(TAG, "drawPath"); Log.d(TAG, "drawPath");
Log.d(TAG, json); Log.d(TAG, json);
} }
@@ -176,46 +186,52 @@ public class DirectionsOverlay {
mDistance = new ArrayList<String>(); mDistance = new ArrayList<String>();
mDuration = new ArrayList<String>(); mDuration = new ArrayList<String>();
//get first route // get first route
final JSONObject route = new JSONObject(json).getJSONArray("routes").getJSONObject(0); final JSONObject route = new JSONObject(json).getJSONArray("routes").getJSONObject(0);
mCopyRights = route.getString("copyrights"); mCopyRights = route.getString("copyrights");
//route.getString("status"); // route.getString("status");
final JSONObject leg = route.getJSONArray("legs").getJSONObject(0); final JSONObject leg = route.getJSONArray("legs").getJSONObject(0);
getDistance(leg); getDistance(leg);
getDuration(leg); getDuration(leg);
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("start_location")), 12, Color.GREEN)); // mMapView.getOverlays().add(new
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(leg.getJSONObject("end_location")), 12, Color.RED)); // PathOverlay(getGeoPoint(leg.getJSONObject("start_location")), 12,
// Color.GREEN));
// mMapView.getOverlays().add(new
// PathOverlay(getGeoPoint(leg.getJSONObject("end_location")), 12,
// Color.RED));
leg.getString("start_address"); leg.getString("start_address");
leg.getString("end_address"); leg.getString("end_address");
// JSONArray warnings = leg.getJSONArray("warnings"); // JSONArray warnings = leg.getJSONArray("warnings");
// for(int i = 0; i < warnings.length(); i++){ // for(int i = 0; i < warnings.length(); i++){
// mWarnings.add(warnings.get)w // mWarnings.add(warnings.get)w
// }w // }w
/* /*
* here we will parse the steps of the directions * here we will parse the steps of the directions
*/ */
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "processing steps"); Log.d(TAG, "processing steps");
final JSONArray steps = leg.getJSONArray("steps"); final JSONArray steps = leg.getJSONArray("steps");
JSONObject step = null; JSONObject step = null;
for(int i = 0; i < steps.length(); i++){ for (int i = 0; i < steps.length(); i++) {
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "step "+i); Log.d(TAG, "step " + i);
step = steps.getJSONObject(i); step = steps.getJSONObject(i);
if(Debug.DEBUG){ if (Debug.DEBUG) {
Log.d(TAG, "start "+getGeoPoint(step.getJSONObject("start_location")).toString()); Log.d(TAG, "start " + getGeoPoint(step.getJSONObject("start_location")).toString());
Log.d(TAG, "end "+getGeoPoint(step.getJSONObject("end_location")).toString()); Log.d(TAG, "end " + getGeoPoint(step.getJSONObject("end_location")).toString());
} }
// if(Debug.DEBUG) // if(Debug.DEBUG)
// mMapView.getOverlays().add(new PathOverlay(getGeoPoint(step.getJSONObject("start_location")), getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA)); // mMapView.getOverlays().add(new
// PathOverlay(getGeoPoint(step.getJSONObject("start_location")),
// getGeoPoint(step.getJSONObject("end_location")), Color.MAGENTA));
decodePoly(step); decodePoly(step);
@@ -224,19 +240,19 @@ public class DirectionsOverlay {
mDistance.add(getDistance(step)); mDistance.add(getDistance(step));
mDirections.add(step.getString("html_instructions")); mDirections.add(step.getString("html_instructions"));
// Log.d("TEST", step.getString("html_instructions")); // Log.d("TEST", step.getString("html_instructions"));
mPoints.add(getGeoPoint(step.getJSONObject("start_location"))); mPoints.add(getGeoPoint(step.getJSONObject("start_location")));
} }
if(Debug.DEBUG) if (Debug.DEBUG)
Log.d(TAG, "finished parsing"); Log.d(TAG, "finished parsing");
if(mMapView != null){ if (mMapView != null) {
mMapView.getOverlays().addAll(mPath); mMapView.getOverlays().addAll(mPath);
mMapView.postInvalidate(); mMapView.postInvalidate();
} }
if(mListener != null) if (mListener != null)
mListener.onDirectionsComplete(DirectionsOverlay.this); mListener.onDirectionsComplete(DirectionsOverlay.this);
} }
@@ -246,23 +262,17 @@ public class DirectionsOverlay {
* @return The Google API url for our directions * @return The Google API url for our directions
* @author ricky barrette * @author ricky barrette
*/ */
private String generateUrl(final GeoPoint origin, final GeoPoint destination){ private String generateUrl(final GeoPoint origin, final GeoPoint destination) {
return "http://maps.googleapis.com/maps/api/directions/json?&origin="+ return "http://maps.googleapis.com/maps/api/directions/json?&origin=" + Double.toString(origin.getLatitudeE6() / 1.0E6) + ","
Double.toString(origin.getLatitudeE6() / 1.0E6)+ + Double.toString(origin.getLongitudeE6() / 1.0E6) + "&destination=" + Double.toString(destination.getLatitudeE6() / 1.0E6) + ","
","+ + Double.toString(destination.getLongitudeE6() / 1.0E6) + "&sensor=true&mode=walking";
Double.toString(origin.getLongitudeE6() / 1.0E6)+
"&destination="+
Double.toString(destination.getLatitudeE6() / 1.0E6)+
","+
Double.toString(destination.getLongitudeE6() / 1.0E6)+
"&sensor=true&mode=walking";
} }
/** /**
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public String getCopyrights(){ public String getCopyrights() {
return mCopyRights; return mCopyRights;
} }
@@ -280,7 +290,7 @@ public class DirectionsOverlay {
* @throws JSONException * @throws JSONException
* @author ricky barrette * @author ricky barrette
*/ */
private String getDistance(final JSONObject step) throws JSONException{ private String getDistance(final JSONObject step) throws JSONException {
return step.getJSONObject("distance").getString("text"); return step.getJSONObject("distance").getString("text");
} }
@@ -288,7 +298,7 @@ public class DirectionsOverlay {
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public ArrayList<String> getDistances(){ public ArrayList<String> getDistances() {
return mDistance; return mDistance;
} }
@@ -298,7 +308,7 @@ public class DirectionsOverlay {
* @throws JSONException * @throws JSONException
* @author ricky barrette * @author ricky barrette
*/ */
private String getDuration(final JSONObject step) throws JSONException{ private String getDuration(final JSONObject step) throws JSONException {
return step.getJSONObject("duration").getString("text"); return step.getJSONObject("duration").getString("text");
} }
@@ -306,26 +316,27 @@ public class DirectionsOverlay {
* @return * @return
* @author ricky barrette * @author ricky barrette
*/ */
public ArrayList<String> getDurations(){ public ArrayList<String> getDurations() {
return mDuration; return mDuration;
} }
/** /**
* Converts a JSON location object into a GeoPoint * Converts a JSON location object into a GeoPoint
*
* @param point * @param point
* @return Geopoint parsed from the provided JSON Object * @return Geopoint parsed from the provided JSON Object
* @throws JSONException * @throws JSONException
* @author ricky barrette * @author ricky barrette
*/ */
private GeoPoint getGeoPoint(final JSONObject point) throws JSONException{ private GeoPoint getGeoPoint(final JSONObject point) throws JSONException {
return new GeoPoint((int) (point.getDouble("lat")*1E6), (int) (point.getDouble("lng")*1E6)); return new GeoPoint((int) (point.getDouble("lat") * 1E6), (int) (point.getDouble("lng") * 1E6));
} }
/** /**
* @return the array of PathOverlays * @return the array of PathOverlays
* @author ricky barrette * @author ricky barrette
*/ */
public ArrayList<PathOverlay> getPath(){ public ArrayList<PathOverlay> getPath() {
return mPath; return mPath;
} }
@@ -347,9 +358,11 @@ public class DirectionsOverlay {
/** /**
* Removes the directions overlay from the map view * Removes the directions overlay from the map view
*
* @author ricky barrette * @author ricky barrette
*/ */
public void removePath() { public void removePath() {
if(mMapView.getOverlays().removeAll(mPath)); if (mMapView.getOverlays().removeAll(mPath))
;
} }
} }

View File

@@ -18,6 +18,7 @@ import com.google.android.maps.Projection;
/** /**
* This imutable overlay class is used to draw a path and points on a map * This imutable overlay class is used to draw a path and points on a map
*
* @author ricky barrette * @author ricky barrette
*/ */
public final class PathOverlay extends Overlay { public final class PathOverlay extends Overlay {
@@ -32,6 +33,7 @@ public final class PathOverlay extends Overlay {
/** /**
* Creates a new PathOverlay in path mode * Creates a new PathOverlay in path mode
*
* @author ricky barrette * @author ricky barrette
*/ */
public PathOverlay(final GeoPoint start, final GeoPoint end, final int color) { public PathOverlay(final GeoPoint start, final GeoPoint end, final int color) {
@@ -44,12 +46,13 @@ public final class PathOverlay extends Overlay {
/** /**
* Creates a new PathOverlay in point mode. This is used to draw end points. * Creates a new PathOverlay in point mode. This is used to draw end points.
*
* @param point * @param point
* @param radius * @param radius
* @param color * @param color
* @author ricky barrette * @author ricky barrette
*/ */
public PathOverlay(final GeoPoint point, final int radius, final int color){ public PathOverlay(final GeoPoint point, final int radius, final int color) {
mMode = POINT; mMode = POINT;
mRadius = radius; mRadius = radius;
mStart = point; mStart = point;
@@ -59,7 +62,8 @@ public final class PathOverlay extends Overlay {
/** /**
* *
* @param canvas canvas to be drawn on * @param canvas
* canvas to be drawn on
* @param mapView * @param mapView
* @param shadow * @param shadow
* @param when * @param when
@@ -73,16 +77,16 @@ public final class PathOverlay extends Overlay {
final Point point = new Point(); final Point point = new Point();
projection.toPixels(mStart, point); projection.toPixels(mStart, point);
switch (mMode){ switch (mMode) {
case POINT: case POINT:
final RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); final RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
case PATH: case PATH:
final Point point2 = new Point(); final Point point2 = new Point();
projection.toPixels(mEnd, point2); projection.toPixels(mEnd, point2);
paint.setStrokeWidth(5); paint.setStrokeWidth(5);
paint.setAlpha(120); paint.setAlpha(120);
canvas.drawLine(point.x, point.y, point2.x, point2.y, paint); canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);
} }
super.draw(canvas, mapView, shadow); super.draw(canvas, mapView, shadow);
} }
@@ -91,7 +95,7 @@ public final class PathOverlay extends Overlay {
* @return the end point of this path * @return the end point of this path
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getEndPoint(){ public GeoPoint getEndPoint() {
return mEnd; return mEnd;
} }
@@ -99,7 +103,7 @@ public final class PathOverlay extends Overlay {
* @return the start point of this path * @return the start point of this path
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getStartPoint(){ public GeoPoint getStartPoint() {
return mStart; return mStart;
} }
} }

View File

@@ -21,11 +21,12 @@ import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection; import com.google.android.maps.Projection;
/** /**
* This class will used to draw a radius of a specified size in a specified location, then inserted into * This class will used to draw a radius of a specified size in a specified
* an overlay list to be displayed a map * location, then inserted into an overlay list to be displayed a map
*
* @author ricky barrette * @author ricky barrette
*/ */
public class RadiusOverlay extends Overlay{ public class RadiusOverlay extends Overlay {
public OverlayItem mOverlayItem; public OverlayItem mOverlayItem;
private GeoPoint mPoint; private GeoPoint mPoint;
@@ -36,16 +37,22 @@ public class RadiusOverlay extends Overlay{
/** /**
* Creates a new RadiusOverlay * Creates a new RadiusOverlay
*
* @author ricky barrette * @author ricky barrette
*/ */
public RadiusOverlay(){ public RadiusOverlay() {
} }
/** /**
* Creates a new RadiusOverlay object that can be inserted into an overlay list. * Creates a new RadiusOverlay object that can be inserted into an overlay
* @param point center of radius geopoint * list.
* @param radius radius in meters *
* @param color desired color of the radius from Color API * @param point
* center of radius geopoint
* @param radius
* radius in meters
* @param color
* desired color of the radius from Color API
* @author ricky barrette * @author ricky barrette
*/ */
public RadiusOverlay(final GeoPoint point, final float radius, final int color) { public RadiusOverlay(final GeoPoint point, final float radius, final int color) {
@@ -56,25 +63,28 @@ public class RadiusOverlay extends Overlay{
/** /**
* draws a specific radius on the mapview that is handed to it * draws a specific radius on the mapview that is handed to it
* @param canvas canvas to be drawn on *
* @param canvas
* canvas to be drawn on
* @param mapView * @param mapView
* @param shadow * @param shadow
* @param when * @param when
*/ */
@Override @Override
public void draw(final Canvas canvas, final MapView mapView, final boolean shadow){ public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
if(mPoint != null){ if (mPoint != null) {
final Paint paint = new Paint(); final Paint paint = new Paint();
final Point center = new Point(); final Point center = new Point();
final Point left = new Point(); final Point left = new Point();
final Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
/* /*
* Calculate a geopoint that is "radius" meters away from geopoint point and * Calculate a geopoint that is "radius" meters away from geopoint
* convert the given GeoPoint and leftGeo to onscreen pixel coordinates, * point and convert the given GeoPoint and leftGeo to onscreen
* relative to the top-left of the MapView that provided this Projection. * pixel coordinates, relative to the top-left of the MapView that
* provided this Projection.
*/ */
mRadiusPoint = GeoUtils.distanceFrom(mPoint , mRadius); mRadiusPoint = GeoUtils.distanceFrom(mPoint, mRadius);
projection.toPixels(mRadiusPoint, left); projection.toPixels(mRadiusPoint, left);
projection.toPixels(mPoint, center); projection.toPixels(mPoint, center);
@@ -82,7 +92,7 @@ public class RadiusOverlay extends Overlay{
* get radius of the circle being drawn by * get radius of the circle being drawn by
*/ */
int circleRadius = center.x - left.x; int circleRadius = center.x - left.x;
if(circleRadius <= 0) if (circleRadius <= 0)
circleRadius = left.x - center.x; circleRadius = left.x - center.x;
/* /*
@@ -94,11 +104,11 @@ public class RadiusOverlay extends Overlay{
paint.setStyle(Style.STROKE); paint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, circleRadius, paint); canvas.drawCircle(center.x, center.y, circleRadius, paint);
//draw a dot over the geopoint // draw a dot over the geopoint
final RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2); final RectF oval = new RectF(center.x - 2, center.y - 2, center.x + 2, center.y + 2);
canvas.drawOval(oval, paint); canvas.drawOval(oval, paint);
//fill the radius with a nice green // fill the radius with a nice green
paint.setAlpha(25); paint.setAlpha(25);
paint.setStyle(Style.FILL); paint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, circleRadius, paint); canvas.drawCircle(center.x, center.y, circleRadius, paint);
@@ -109,19 +119,19 @@ public class RadiusOverlay extends Overlay{
* @return the selected location * @return the selected location
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getLocation(){ public GeoPoint getLocation() {
return mPoint; return mPoint;
} }
public int getZoomLevel() { public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius) // GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0; return 0;
} }
@Override @Override
public boolean onTap(final GeoPoint p, final MapView mapView) { public boolean onTap(final GeoPoint p, final MapView mapView) {
mPoint = p; mPoint = p;
if(mListener != null) if (mListener != null)
mListener.onLocationSelected(p); mListener.onLocationSelected(p);
return super.onTap(p, mapView); return super.onTap(p, mapView);
} }
@@ -130,7 +140,7 @@ public class RadiusOverlay extends Overlay{
* @param color * @param color
* @author ricky barrette * @author ricky barrette
*/ */
public void setColor(final int color){ public void setColor(final int color) {
mColor = color; mColor = color;
} }
@@ -138,7 +148,7 @@ public class RadiusOverlay extends Overlay{
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(final GeoPoint location){ public void setLocation(final GeoPoint location) {
mPoint = location; mPoint = location;
} }
@@ -147,11 +157,12 @@ public class RadiusOverlay extends Overlay{
} }
/** /**
* @param radius in meters * @param radius
* in meters
* @author ricky barrette * @author ricky barrette
* @param radius * @param radius
*/ */
public void setRadius(final int radius){ public void setRadius(final int radius) {
mRadius = radius; mRadius = radius;
} }
} }

View File

@@ -11,10 +11,12 @@ import com.TwentyCodes.android.SkyHook.SkyHook;
import com.google.android.maps.MapView; import com.google.android.maps.MapView;
/** /**
* this class will be used to display the users location on the map using skyhook's call back methods * this class will be used to display the users location on the map using
* skyhook's call back methods
*
* @author ricky barrette * @author ricky barrette
*/ */
public class SkyHookUserOverlay extends BaseUserOverlay{ public class SkyHookUserOverlay extends BaseUserOverlay {
private final SkyHook mSkyHook; private final SkyHook mSkyHook;
@@ -25,6 +27,7 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
/** /**
* Construct a new SkyHookUserOverlay * Construct a new SkyHookUserOverlay
*
* @param mapView * @param mapView
* @param context * @param context
* @param followUser * @param followUser
@@ -41,8 +44,8 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
} }
/** /**
* Called when the location provider needs to be disabled * Called when the location provider needs to be disabled (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.overlays.BaseUserOverlay#onMyLocationDisabled() * @see com.TwentyCodes.android.overlays.BaseUserOverlay#onMyLocationDisabled()
*/ */
@Override @Override
@@ -51,8 +54,8 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
} }
/** /**
* Called when the location provider needs to be enabled * Called when the location provider needs to be enabled (non-Javadoc)
* (non-Javadoc) *
* @see com.TwentyCodes.android.overlays.BaseUserOverlay#onMyLocationEnabled() * @see com.TwentyCodes.android.overlays.BaseUserOverlay#onMyLocationEnabled()
*/ */
@Override @Override

View File

@@ -12,9 +12,10 @@ import com.google.android.maps.MapView;
/** /**
* This is the standard version of the UserOverlay. * This is the standard version of the UserOverlay.
*
* @author ricky barrette * @author ricky barrette
*/ */
public class UserOverlay extends BaseUserOverlay{ public class UserOverlay extends BaseUserOverlay {
private final AndroidGPS mAndroidGPS; private final AndroidGPS mAndroidGPS;