Updated Compat library and cleaned up code

Signed-off-by: Ricky Barrette <rickbarrette@gmail.com>
This commit is contained in:
2012-07-01 11:19:46 -04:00
parent 2abc43c3bf
commit 39cc29a4c5
33 changed files with 1532 additions and 1548 deletions

View File

@@ -15,8 +15,8 @@
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-sdk <uses-sdk
android:minSdkVersion="4" android:minSdkVersion="8"
android:targetSdkVersion="11" /> android:targetSdkVersion="15" />
<uses-feature <uses-feature
android:name="android.hardware.location" android:name="android.hardware.location"

Binary file not shown.

Binary file not shown.

View File

@@ -1,22 +1,23 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical" > android:orientation="vertical" >
<TextView <TextView
android:id="@+id/TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="20dip" android:textColor="#000000"
android:textColor="#000000"/> android:textSize="20dip" />
<TextView <TextView
android:id="@+id/TextView02" android:id="@+id/TextView02"
android:layout_width="wrap_content" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:textSize="20dip"
android:textColor="#000000"
android:layout_gravity="right" android:layout_gravity="right"
android:paddingRight="10dip" android:paddingRight="10dip"
/> android:textColor="#000000"
android:textSize="20dip" />
</LinearLayout> </LinearLayout>

View File

@@ -4,7 +4,7 @@
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_height="fill_parent"
android:background="#ffffff" android:background="#ffffff"
tools:ignore="ContentDescription" > tools:ignore="ContentDescription,Overdraw" >
<ImageView <ImageView
android:id="@+id/skyhook_img" android:id="@+id/skyhook_img"

View File

@@ -27,6 +27,24 @@ import com.skyhookwireless.wps.XPS;
*/ */
public class SkyHook implements GeoPointLocationListener{ public class SkyHook implements GeoPointLocationListener{
private class XPScallback implements WPSPeriodicLocationCallback {
@Override
public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
}
@Override
public WPSContinuation handleError(final WPSReturnCode error) {
mHandler.sendMessage(mHandler.obtainMessage(ERROR_MESSAGE, error));
return WPSContinuation.WPS_CONTINUE;
}
@Override
public WPSContinuation handleWPSPeriodicLocation(final WPSLocation location) {
mHandler.sendMessage(mHandler.obtainMessage(LOCATION_MESSAGE, location));
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";
@@ -39,9 +57,9 @@ public class SkyHook implements GeoPointLocationListener{
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 int mIterations = 0; private final int mIterations = 0;
private WPSAuthentication mWPSAuthentication; private WPSAuthentication mWPSAuthentication;
private Handler mHandler; private static Handler mHandler;
private boolean isPeriodicEnabled; private boolean isPeriodicEnabled;
private boolean hasLocation; private boolean hasLocation;
protected AndroidGPS mSkyHookFallback = null; protected AndroidGPS mSkyHookFallback = null;
@@ -49,6 +67,7 @@ public class SkyHook implements GeoPointLocationListener{
private boolean isFallBackScheduled = false; private boolean isFallBackScheduled = false;
private boolean isEnabled = false; private boolean isEnabled = false;
private boolean isUnauthorized = false; private boolean isUnauthorized = false;
private boolean isFirstFix; private boolean isFirstFix;
/* /*
@@ -56,11 +75,12 @@ public class SkyHook implements GeoPointLocationListener{
* if we dont, then we will us android's location services to fall back on. * if 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
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);
@@ -86,6 +106,7 @@ public class SkyHook implements GeoPointLocationListener{
* this runnable keeps skyhook working! * this runnable keeps skyhook working!
*/ */
private final Runnable mPeriodicUpdates = new Runnable() { private final Runnable mPeriodicUpdates = new Runnable() {
@Override
public void run() { public void run() {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG,"geting location"); Log.d(TAG,"geting location");
@@ -93,31 +114,12 @@ public class SkyHook implements GeoPointLocationListener{
} }
}; };
private class XPScallback implements WPSPeriodicLocationCallback {
@Override
public void done() {
mHandler.sendMessage(mHandler.obtainMessage(DONE_MESSAGE));
}
@Override
public WPSContinuation handleError(WPSReturnCode error) {
mHandler.sendMessage(mHandler.obtainMessage(ERROR_MESSAGE, error));
return WPSContinuation.WPS_CONTINUE;
}
@Override
public WPSContinuation handleWPSPeriodicLocation(WPSLocation location) {
mHandler.sendMessage(mHandler.obtainMessage(LOCATION_MESSAGE, location));
return WPSContinuation.WPS_CONTINUE;
}
}
/** /**
* Constructors a new skyhook object * Constructors a new skyhook object
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHook(Context context) { public SkyHook(final Context context) {
mXps = new XPS(context); mXps = new XPS(context);
mContext = context; mContext = context;
// initialize the Handler which will display location data // initialize the Handler which will display location data
@@ -133,7 +135,7 @@ public class SkyHook implements GeoPointLocationListener{
* @param period between location updates in milliseconds * @param period between location updates in milliseconds
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHook(Context context, long period) { public SkyHook(final Context context, final long period) {
this(context); this(context);
mPeriod = period; mPeriod = period;
} }
@@ -177,6 +179,25 @@ public class SkyHook implements GeoPointLocationListener{
return isEnabled; return isEnabled;
} }
@Override
public void onFirstFix(final boolean firstFix) {
if(mListener != null)
mListener.onFirstFix(firstFix);
}
/**
* called from our skyhook to android fall back class
* (non-Javadoc)
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int)
* @author ricky barrette
*/
@Override
public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(! hasLocation)
if(mListener != null)
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 activity
* with the given LocationListener. Following this call, updates will no longer * with the given LocationListener. Following this call, updates will no longer
@@ -207,12 +228,11 @@ public class SkyHook implements GeoPointLocationListener{
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocationListener(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;
} }
}
private void setUIHandler() { private void setUIHandler() {
mHandler = new Handler() { mHandler = new Handler() {
@@ -222,7 +242,7 @@ public class SkyHook implements GeoPointLocationListener{
switch (msg.what) { switch (msg.what) {
case LOCATION_MESSAGE: case LOCATION_MESSAGE:
if (msg.obj instanceof WPSLocation) { if (msg.obj instanceof WPSLocation) {
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)
@@ -239,10 +259,9 @@ public class SkyHook implements GeoPointLocationListener{
case ERROR_MESSAGE: case ERROR_MESSAGE:
if( msg.obj instanceof WPSReturnCode) { if( msg.obj instanceof WPSReturnCode) {
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;
/* /*
@@ -264,9 +283,9 @@ public class SkyHook implements GeoPointLocationListener{
* check to see if we already have a fall back Scheduled * 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 we dont, and there is not fallback already in place, then schedule one
*/ */
if((! isFallBackScheduled) && ( mSkyHookFallback == null) && isEnabled) { if(! isFallBackScheduled && mSkyHookFallback == null && isEnabled) {
Log.d(TAG, "scheduling fallback"); Log.d(TAG, "scheduling fallback");
mHandler.postDelayed(mFallBack, mFallBackDelay); postDelayed(mFallBack, mFallBackDelay);
isFallBackScheduled = true; isFallBackScheduled = true;
} }
} }
@@ -274,7 +293,7 @@ public class SkyHook implements GeoPointLocationListener{
case DONE_MESSAGE: case DONE_MESSAGE:
if (isPeriodicEnabled) { if (isPeriodicEnabled) {
mHandler.postDelayed(mPeriodicUpdates, mPeriod); postDelayed(mPeriodicUpdates, mPeriod);
Log.d(TAG,"done getting location"); Log.d(TAG,"done getting location");
} }
return; return;
@@ -282,23 +301,4 @@ public class SkyHook implements GeoPointLocationListener{
} }
}; };
} }
/**
* called from our skyhook to android fall back class
* (non-Javadoc)
* @see com.TwentyCodes.android.location.GeoPointLocationListener#onLocationChanged(com.google.android.maps.GeoPoint, int)
* @author ricky barrette
*/
@Override
public void onLocationChanged(GeoPoint point, int accuracy) {
if(! hasLocation)
if(mListener != null)
mListener.onLocationChanged(point, accuracy);
}
@Override
public void onFirstFix(boolean firstFix) {
if(mListener != null)
mListener.onFirstFix(firstFix);
}
} }

View File

@@ -21,10 +21,35 @@ import com.skyhookwireless.wps.XPS;
*/ */
public class SkyHookRegistration{ public class SkyHookRegistration{
/**
* returns the users username
* @param context
* @return
* @author ricky barrette
*/
public static String getUserName(final Context context){
switch(LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR){
case NORMAL:
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null");
return tm.getLine1Number();
case RETURN_NULL:
return null;
case USE_TESTING_USERNAME:
return SkyHook.USERNAME_FOR_TESTING;
}
return null;
}
private final XPS mXps; private final XPS mXps;
private final Context mContext; private final Context mContext;
public SkyHookRegistration(Context context){ public SkyHookRegistration(final Context context){
mContext = context; mContext = context;
mXps = new XPS(context); mXps = new XPS(context);
} }
@@ -41,40 +66,14 @@ public class SkyHookRegistration{
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");
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);
} }
} }
/**
* returns the users username
* @param context
* @return
* @author ricky barrette
*/
public static String getUserName(final Context context){
switch(LocationLibraryConstants.DEFAULT_REGISTRATION_BEHAVIOR){
case NORMAL:
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm == null)
Log.v(SkyHook.TAG, "TelephonyManager is null");
return tm.getLine1Number();
case RETURN_NULL:
return null;
case USE_TESTING_USERNAME:
return SkyHook.USERNAME_FOR_TESTING;
}
return null;
}
} }

View File

@@ -40,12 +40,38 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
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
* @param context
* @return a intent that will be used to start the service
* @author ricky barrette
*/
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, SkyHookService.class);
}
/**
* a convince method for stopping the service and removing its que from the alarm manager
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
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));
}
};
}
private SkyHook mSkyhook; private SkyHook mSkyhook;
protected long mPeriod = -1; protected long mPeriod = -1;
private GeoPoint mLocation; private GeoPoint mLocation;
private int mStartID; private int mStartID;
private int mRequiredAccuracy; private int mRequiredAccuracy;
private Intent mIntent; private Intent mIntent;
private int mAccuracy; private int mAccuracy;
/** /**
@@ -55,7 +81,7 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
*/ */
private void braodcastLocation() { private void braodcastLocation() {
if (mLocation != null) { if (mLocation != null) {
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
@@ -71,13 +97,45 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
* @author ricky barrette * @author ricky barrette
*/ */
public Location convertLocation(){ public Location convertLocation(){
Location location = new Location("location"); final Location location = new Location("location");
location.setLatitude(this.mLocation.getLatitudeE6() /1e6); location.setLatitude(mLocation.getLatitudeE6() /1e6);
location.setLongitude(this.mLocation.getLongitudeE6() /1e6); location.setLongitude(mLocation.getLongitudeE6() /1e6);
location.setAccuracy(this.mAccuracy); location.setAccuracy(mAccuracy);
return location; return location;
} }
@Override
public void done() {
// unused
}
/*
* 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
// * @author ricky barrette
// */
// @Override
// public void onStart(Intent intent, int startId) {
// Log.i(SkyHook.TAG, "onStart.Service started with start id of: " + startId);
// parseIntent(intent);
// this.mSkyhook.getUpdates();
// }
@Override
public WPSContinuation handleError(final WPSReturnCode arg0) {
// unused
return null;
}
@Override
public void handleSuccess() {
// unused
}
/** /**
* (non-Javadoc) * (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent) * @see android.app.Service#onBind(android.content.Intent)
@@ -86,15 +144,15 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
* @author Ricky Barrette barrette * @author Ricky Barrette barrette
*/ */
@Override @Override
public IBinder onBind(Intent arg0) { public IBinder onBind(final Intent arg0) {
return null; return null;
} }
@Override @Override
public void onCreate(){ public void onCreate(){
super.onCreate(); super.onCreate();
this.mSkyhook = new SkyHook(this); mSkyhook = new SkyHook(this);
this.mSkyhook.setLocationListener(this); mSkyhook.setLocationListener(this);
/* /*
* fail safe * fail safe
@@ -124,30 +182,37 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
super.onDestroy(); super.onDestroy();
} }
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
@Override
public void onLocationChanged(final GeoPoint point, final int accuracy) {
mLocation = point;
mAccuracy = accuracy;
/* /*
* I believe that this method is no longer needed as we are not supporting pre 2.1 * fail safe
* if the accuracy is greater than the minimum required accuracy
* then continue
* else stop to report location
*/ */
// /** if(accuracy < (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
// * To keep backwards compatibility we override onStart which is the equivalent of onStartCommand in pre android 2.x this.stopSelf(mStartID);
// * @author ricky barrette
// */ }
// @Override
// public void onStart(Intent intent, int startId) {
// Log.i(SkyHook.TAG, "onStart.Service started with start id of: " + startId);
// parseIntent(intent);
// this.mSkyhook.getUpdates();
// }
/** /**
* 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(Intent intent, int flags, 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);
this.mSkyhook.getUpdates(); mSkyhook.getUpdates();
return START_STICKY; return START_STICKY;
} }
@@ -156,9 +221,9 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
* *
* @author ricky barrette * @author ricky barrette
*/ */
private void parseIntent(Intent intent){ private void parseIntent(final Intent intent){
this.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))
@@ -174,72 +239,7 @@ public class SkyHookService extends Service implements GeoPointLocationListener,
* @author ricky barrette * @author ricky barrette
*/ */
private void registerWakeUp(){ private void registerWakeUp(){
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + this.mPeriod, PendingIntent.getService(this, REQUEST_CODE, this.mIntent, 0)); am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));
}
/**
* a convince method for getting an intent to start the service
* @param context
* @return a intent that will be used to start the service
* @author ricky barrette
*/
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, SkyHookService.class);
}
/**
* a convince method for stopping the service and removing its que from the alarm manager
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
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));
}
};
}
@Override
public void onLocationChanged(GeoPoint point, int accuracy) {
this.mLocation = point;
this.mAccuracy = accuracy;
/*
* fail safe
* if the accuracy is greater than the minimum required accuracy
* then continue
* else stop to report location
*/
if(accuracy < (this.mRequiredAccuracy > -1 ? this.mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
this.stopSelf(this.mStartID);
}
@Override
public void done() {
// unused
}
@Override
public WPSContinuation handleError(WPSReturnCode arg0) {
// unused
return null;
}
@Override
public void handleSuccess() {
// unused
}
@Override
public void onFirstFix(boolean isFistFix) {
// unused
} }
} }

View File

@@ -6,8 +6,6 @@
*/ */
package com.TwentyCodes.android.debug; package com.TwentyCodes.android.debug;
import com.TwentyCodes.android.location.BaseLocationReceiver;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.location.LocationManager; import android.location.LocationManager;

View File

@@ -37,7 +37,7 @@ public abstract class BaseMapFragment extends Fragment {
super(); super();
} }
public void addOverlay(Overlay overlay){ public void addOverlay(final Overlay overlay){
mMapView.getOverlays().add(overlay); mMapView.getOverlays().add(overlay);
} }
@@ -106,8 +106,8 @@ public abstract class BaseMapFragment extends Fragment {
* @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(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.base_map_fragment, container, false); final View view = inflater.inflate(R.layout.base_map_fragment, container, false);
mMapView = (MapView) view.findViewById(R.id.mapview); mMapView = (MapView) view.findViewById(R.id.mapview);
mMapView.setClickable(true); mMapView.setClickable(true);
@@ -131,7 +131,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param overlay * @param overlay
* @author ricky barrette * @author ricky barrette
*/ */
public void removeOverlay(Object overlay){ public void removeOverlay(final Object overlay){
mMapView.getOverlays().remove(overlay); mMapView.getOverlays().remove(overlay);
} }
@@ -140,7 +140,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param isShowing * @param isShowing
* @author ricky barrette * @author ricky barrette
*/ */
public void setBuiltInZoomControls(boolean isShowing){ public void setBuiltInZoomControls(final boolean isShowing){
mMapView.setBuiltInZoomControls(isShowing); mMapView.setBuiltInZoomControls(isShowing);
} }
@@ -149,7 +149,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param isClickable * @param isClickable
* @author ricky barrette * @author ricky barrette
*/ */
public void setClickable(boolean isClickable){ public void setClickable(final boolean isClickable){
mMapView.setClickable(isClickable); mMapView.setClickable(isClickable);
} }
@@ -158,7 +158,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param isDoubleTapZoonEnabled * @param isDoubleTapZoonEnabled
* @author ricky barrette * @author ricky barrette
*/ */
public void setDoubleTapZoonEnabled(boolean isDoubleTapZoonEnabled){ public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled){
mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled); mMapView.setDoubleTapZoonEnabled(isDoubleTapZoonEnabled);
} }
@@ -167,7 +167,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param point * @param point
* @author ricky barrette * @author ricky barrette
*/ */
public boolean setMapCenter(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);
@@ -179,7 +179,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param isSat * @param isSat
* @author ricky barrette * @author ricky barrette
*/ */
public void setSatellite(boolean isSat){ public void setSatellite(final boolean isSat){
mMapView.setSatellite(isSat); mMapView.setSatellite(isSat);
} }
@@ -188,7 +188,7 @@ public abstract class BaseMapFragment extends Fragment {
* @param zoom * @param zoom
* @author ricky barrette * @author ricky barrette
*/ */
public void setZoom(int zoom){ public void setZoom(final int zoom){
mMapView.getController().setZoom(zoom); mMapView.getController().setZoom(zoom);
} }
} }

View File

@@ -22,15 +22,24 @@ import com.TwentyCodes.android.overlays.DirectionsOverlay;
*/ */
public class DirectionsAdapter extends BaseAdapter { public class DirectionsAdapter extends BaseAdapter {
/**
* this class will hold the TextViews
* @author ricky barrette
*/
class ViewHolder {
TextView text;
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(Context context, DirectionsOverlay directions) { public DirectionsAdapter(final Context context, final DirectionsOverlay directions) {
mInflater = LayoutInflater.from(context); mInflater = LayoutInflater.from(context);
mDirections = directions; mDirections = directions;
} }
@@ -54,7 +63,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public Object getItem(int position) { public Object getItem(final int position) {
return position; return position;
} }
@@ -66,7 +75,7 @@ public class DirectionsAdapter extends BaseAdapter {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public long getItemId(int position) { public long getItemId(final int position) {
return position; return position;
} }
@@ -89,9 +98,8 @@ public class DirectionsAdapter extends BaseAdapter {
holder.text2 = (TextView) convertView.findViewById(R.id.TextView02); holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);
convertView.setTag(holder); convertView.setTag(holder);
} else { } else
holder = (ViewHolder) convertView.getTag(); holder = (ViewHolder) convertView.getTag();
}
/** /**
* Display the copyrights on the bottom of the directions list * Display the copyrights on the bottom of the directions list
@@ -106,13 +114,4 @@ public class DirectionsAdapter extends BaseAdapter {
return convertView; return convertView;
} }
/**
* this class will hold the TextViews
* @author ricky barrette
*/
class ViewHolder {
TextView text;
TextView text2;
}
} }

View File

@@ -54,7 +54,7 @@ public class DirectionsListFragment extends ListFragment {
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public DirectionsListFragment(OnDirectionSelectedListener listener) { public DirectionsListFragment(final OnDirectionSelectedListener listener) {
this(); this();
mListener = listener; mListener = listener;
} }
@@ -64,7 +64,7 @@ public class DirectionsListFragment extends ListFragment {
* @author ricky barrette * @author ricky barrette
*/ */
public void clear() { public void clear() {
this.setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new ArrayList<String>())); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, new ArrayList<String>()));
} }
/** /**
@@ -74,7 +74,7 @@ public class DirectionsListFragment extends ListFragment {
* @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(ListView l, View w, int position, 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));
@@ -86,7 +86,7 @@ public class DirectionsListFragment extends ListFragment {
*/ */
@Override @Override
public void onStart() { public void onStart() {
this.setListShown(true); setListShown(true);
super.onStart(); super.onStart();
} }
@@ -97,7 +97,7 @@ public class DirectionsListFragment extends ListFragment {
*/ */
public void setDirections(final DirectionsOverlay directions) { public void setDirections(final DirectionsOverlay directions) {
mPoints = directions.getPoints(); mPoints = directions.getPoints();
this.setListAdapter(new DirectionsAdapter(getActivity(), directions)); setListAdapter(new DirectionsAdapter(getActivity(), directions));
} }
/** /**
@@ -105,7 +105,7 @@ public class DirectionsListFragment extends ListFragment {
* @param text * @param text
* @author ricky barrette * @author ricky barrette
*/ */
public void SetEmptyText(String text){ public void SetEmptyText(final String text){
this.setEmptyText(text); setEmptyText(text);
} }
} }

View File

@@ -37,7 +37,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(boolean followUser){ public void followUser(final boolean followUser){
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
@@ -63,13 +63,13 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(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(boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
@@ -79,7 +79,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, 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);
} }
@@ -89,8 +89,8 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @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
public void onMapViewCreate(MapView map) { public void onMapViewCreate(final MapView map) {
mUserOverlay = new SkyHookUserOverlay(map, this.getActivity().getApplicationContext()); mUserOverlay = new SkyHookUserOverlay(map, getActivity().getApplicationContext());
mUserOverlay.registerListener(this); mUserOverlay.registerListener(this);
mUserOverlay.setCompassListener(this); mUserOverlay.setCompassListener(this);
mUserOverlay.enableCompass(); mUserOverlay.enableCompass();
@@ -139,7 +139,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, 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,7 +147,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
@@ -156,7 +156,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +164,7 @@ public class SkyHoookUserOverlayMapFragment extends BaseMapFragment implements G
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener){
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -37,7 +37,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(boolean followUser){ public void followUser(final boolean followUser){
mUserOverlay.followUser(followUser); mUserOverlay.followUser(followUser);
} }
@@ -63,13 +63,13 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float) * @see com.TwentyCodes.android.location.CompassListener#onCompassUpdate(float)
*/ */
@Override @Override
public void onCompassUpdate(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(boolean isFistFix) { public void onFirstFix(final boolean isFistFix) {
if(mGeoPointLocationListener != null) if(mGeoPointLocationListener != null)
mGeoPointLocationListener.onFirstFix(isFistFix); mGeoPointLocationListener.onFirstFix(isFistFix);
} }
@@ -79,7 +79,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, 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);
} }
@@ -89,8 +89,8 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @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
public void onMapViewCreate(MapView map) { public void onMapViewCreate(final MapView map) {
mUserOverlay = new UserOverlay(map, this.getActivity().getApplicationContext()); mUserOverlay = new UserOverlay(map, getActivity().getApplicationContext());
mUserOverlay.registerListener(this); mUserOverlay.registerListener(this);
mUserOverlay.setCompassListener(this); mUserOverlay.setCompassListener(this);
mUserOverlay.enableCompass(); mUserOverlay.enableCompass();
@@ -139,7 +139,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, 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,7 +147,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
@@ -156,7 +156,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mUserOverlay.setDestination(destination); mUserOverlay.setDestination(destination);
} }
@@ -164,7 +164,7 @@ public class UserOverlayMapFragment extends BaseMapFragment implements GeoPointL
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setGeoPointLocationListener(GeoPointLocationListener listener){ public void setGeoPointLocationListener(final GeoPointLocationListener listener){
mGeoPointLocationListener = listener; mGeoPointLocationListener = listener;
} }
} }

View File

@@ -33,7 +33,7 @@ public class AndroidGPS implements LocationListener {
* Creates a new SkyHookFallback * Creates a new SkyHookFallback
* @author ricky barrette * @author ricky barrette
*/ */
public AndroidGPS(Context context) { public AndroidGPS(final Context context) {
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
isFirstFix = true; isFirstFix = true;
} }
@@ -51,28 +51,28 @@ public class AndroidGPS implements LocationListener {
} }
/** /**
* Attempts to enable periodic location updates * request periodic location updates from androids location services
* @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enableLocationUpdates(LocationListener listener) { public void enableLocationUpdates(final GeoPointLocationListener listener) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()"); Log.d(SkyHook.TAG, "enableLocationUpdates()");
if(mLocationListener == null){ if (mListener == null) {
mLocationListener = listener; mListener = listener;
requestUpdates(); requestUpdates();
} }
} }
/** /**
* request periodic location updates from androids location services * Attempts to enable periodic location updates
* @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enableLocationUpdates(GeoPointLocationListener listener) { public void enableLocationUpdates(final LocationListener listener) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(SkyHook.TAG, "enableLocationUpdates()"); Log.d(SkyHook.TAG, "enableLocationUpdates()");
if (mListener == null) { if(mLocationListener == null){
mListener = listener; mLocationListener = listener;
requestUpdates(); requestUpdates();
} }
} }
@@ -84,15 +84,14 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(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;
} }
@@ -104,7 +103,7 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onProviderDisabled(String arg0) { public void onProviderDisabled(final String arg0) {
// UNUSED // UNUSED
} }
@@ -116,7 +115,7 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onProviderEnabled(String arg0) { public void onProviderEnabled(final String arg0) {
// UNUSED // UNUSED
} }
@@ -129,7 +128,7 @@ public class AndroidGPS implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) { public void onStatusChanged(final String arg0, final int arg1, final Bundle arg2) {
// UNUSED // UNUSED
} }
@@ -140,7 +139,7 @@ public class AndroidGPS implements LocationListener {
private void requestUpdates() { private void requestUpdates() {
try { try {
mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this); mLocationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, this);
} catch (IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
/* We do no handle this exception as it is caused if the android version is < 1.6. since the PASSIVE_PROVIDER call is not required /* We do no handle this exception as it is caused if the android version is < 1.6. since the PASSIVE_PROVIDER call is not required
* to function we can ignore it. * to function we can ignore it.

View File

@@ -19,22 +19,22 @@ public abstract class BaseLocationReceiver extends BroadcastReceiver {
public Context mContext; public Context mContext;
/**
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
final String key = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(key))
onLocationUpdate((Location)intent.getExtras().get(key));
}
/** /**
* called when a location update is received * called when a location update is received
* @param parcelableExtra * @param parcelableExtra
* @author ricky barrette * @author ricky barrette
*/ */
public abstract void onLocationUpdate(Location location); public abstract void onLocationUpdate(Location location);
/**
* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(final Context context, final Intent intent) {
mContext = context;
final String key = LocationManager.KEY_LOCATION_CHANGED;
if (intent.hasExtra(key))
onLocationUpdate((Location)intent.getExtras().get(key));
}
} }

View File

@@ -55,7 +55,7 @@ public class CompassSensor{
static{ static{
mHandler = new Handler(){ mHandler = new Handler(){
@Override @Override
public void handleMessage(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);
@@ -65,20 +65,25 @@ public class CompassSensor{
private final SensorEventListener mCallBack = new SensorEventListener() { private final SensorEventListener mCallBack = new SensorEventListener() {
private 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 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 float[] mOrientVals = new float[3]; private final float[] mOrientVals = new float[3];
private double mAzimuth = 0; private double mAzimuth = 0;
// double mPitch = 0; // double mPitch = 0;
// double mRoll = 0; // double mRoll = 0;
// private float mInclination; // private float mInclination;
@Override
public void onAccuracyChanged(final Sensor sensor, final int accuracy) {
}
@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");
@@ -94,7 +99,6 @@ public class CompassSensor{
break; break;
} }
}
// If the sensor data is unreliable return // If the sensor data is unreliable return
if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) if (sensorEvent.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
@@ -114,7 +118,7 @@ public class CompassSensor{
if (mGravity != null && mGeomag != null) { if (mGravity != null && mGeomag != null) {
// checks that the rotation matrix is found // checks that the rotation matrix is found
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()){
@@ -153,7 +157,7 @@ public class CompassSensor{
/* /*
* compensate for device orentation * compensate for device orentation
*/ */
switch (mDisplay.getOrientation()){ switch (mDisplay.getRotation()){
case Surface.ROTATION_0: case Surface.ROTATION_0:
break; break;
case Surface.ROTATION_90: case Surface.ROTATION_90:
@@ -171,10 +175,6 @@ public class CompassSensor{
mHandler.sendMessage(mHandler.obtainMessage(BEARING, (float) mAzimuth)); mHandler.sendMessage(mHandler.obtainMessage(BEARING, (float) mAzimuth));
} }
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}; };
/** /**
@@ -201,7 +201,7 @@ public class CompassSensor{
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(CompassListener listener){ public void enable(final CompassListener listener){
if(mListener == null) { if(mListener == null) {
mListener = listener; mListener = listener;
if(mSensorManager != null) if(mSensorManager != null)
@@ -229,8 +229,7 @@ public class CompassSensor{
Double.valueOf(location.getAltitude()).floatValue(), Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis()); System.currentTimeMillis());
mDelination = geomagneticField.getDeclination(); mDelination = geomagneticField.getDeclination();
} else { } else
mDelination = 0; mDelination = 0;
} }
} }
}

View File

@@ -13,6 +13,13 @@ import com.google.android.maps.GeoPoint;
*/ */
public interface GeoPointLocationListener { public interface GeoPointLocationListener {
/**
* Called when first fix is aquired
* @param isFirstFix
* @author ricky barrette
*/
public void onFirstFix(boolean isFirstFix);
/** /**
* Called when the location has changed * Called when the location has changed
* @param point * @param point
@@ -20,11 +27,4 @@ public interface GeoPointLocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
public void onLocationChanged(GeoPoint point, int accuracy); public void onLocationChanged(GeoPoint point, int accuracy);
/**
* Called when first fix is aquired
* @param isFirstFix
* @author ricky barrette
*/
public void onFirstFix(boolean isFirstFix);
} }

View File

@@ -39,30 +39,6 @@ public class GeoUtils {
public static final int EARTH_RADIUS_KM = 6371; public static final int EARTH_RADIUS_KM = 6371;
public static final double MILLION = 1000000; public static final double MILLION = 1000000;
/**
* Calculates the bearing from the user location to the destination location, or returns the bearing for north if there is no destination.
* This method is awesome for making a compass point toward the destination rather than North.
* @param user location
* @param dest location
* @param bearing Degrees East from compass
* @return Degrees East of dest location
* @author ricky barrette
*/
public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) {
if( (user == null) || (dest == null) )
return bearing;
float heading = bearing(user, dest).floatValue();
bearing = (360 - heading) + bearing;
if (bearing > 360)
return bearing - 360;
return bearing;
}
/** /**
* 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 degrees East
* @param lat1 source lat * @param lat1 source lat
@@ -73,11 +49,11 @@ public class GeoUtils {
* @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) {
double lat1Rad = Math.toRadians(lat1); final double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2); final double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1); final double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); final double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); final double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x)); return radToBearing(Math.atan2(y, x));
} }
@@ -89,13 +65,37 @@ public class GeoUtils {
* @author Google Inc. * @author Google Inc.
*/ */
public static Double bearing(final GeoPoint p1, final GeoPoint p2) { public static Double bearing(final GeoPoint p1, final GeoPoint p2) {
double lat1 = p1.getLatitudeE6() / MILLION; final double lat1 = p1.getLatitudeE6() / MILLION;
double lon1 = p1.getLongitudeE6() / MILLION; final double lon1 = p1.getLongitudeE6() / MILLION;
double lat2 = p2.getLatitudeE6() / MILLION; final double lat2 = p2.getLatitudeE6() / MILLION;
double lon2 = p2.getLongitudeE6() / MILLION; final double lon2 = p2.getLongitudeE6() / MILLION;
return bearing(lat1, lon1, lat2, lon2); return bearing(lat1, lon1, lat2, lon2);
} }
/**
* Calculates the bearing from the user location to the destination location, or returns the bearing for north if there is no destination.
* This method is awesome for making a compass point toward the destination rather than North.
* @param user location
* @param dest location
* @param bearing Degrees East from compass
* @return Degrees East of dest location
* @author ricky barrette
*/
public static float calculateBearing(final GeoPoint user, final GeoPoint dest, float bearing) {
if( user == null || dest == null )
return bearing;
final float heading = bearing(user, dest).floatValue();
bearing = 360 - heading + bearing;
if (bearing > 360)
return bearing - 360;
return bearing;
}
/** /**
* 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 geopoint
* shares the same latitude as geopoint point, this way they are on the same latitude arc. * shares the same latitude as geopoint point, this way they are on the same latitude arc.
@@ -110,8 +110,8 @@ public class GeoUtils {
distance = distance / 1000; distance = distance / 1000;
// convert lat and lon of geopoint to radians // convert lat and lon of geopoint to radians
double lat1Rad = Math.toRadians((point.getLatitudeE6() / 1e6)); final double lat1Rad = Math.toRadians(point.getLatitudeE6() / 1e6);
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
@@ -129,7 +129,7 @@ public class GeoUtils {
* 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 device, and the distanceKm() from google
* and has been proven to be damn close * and has been proven to be damn close
*/ */
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
@@ -146,12 +146,31 @@ public class GeoUtils {
* @author Google Inc. * @author Google Inc.
*/ */
public static double distanceKm(final double lat1, final double lon1, final double lat2, final double lon2) { public static double distanceKm(final double lat1, final double lon1, final double lat2, final double lon2) {
double lat1Rad = Math.toRadians(lat1); final double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2); final double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1); final double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM;
} }
/**
* computes the distance between to p1 and p2 based on the curve of the earth
* @param p1
* @param p2
* @return the distance between to p1 and p2
* @author Google Inc.
*/
public static double distanceKm(final GeoPoint p1, final GeoPoint p2) {
//if we are handed a null, return -1 so we don't break
if(p1 == null || p2 == null)
return -1;
final double lat1 = p1.getLatitudeE6() / MILLION;
final double lon1 = p1.getLongitudeE6() / MILLION;
final double lat2 = p2.getLatitudeE6() / MILLION;
final double lon2 = p2.getLongitudeE6() / MILLION;
return distanceKm(lat1, lon1, lat2, lon2);
}
/** /**
* Converts distance into a human readbale string * Converts distance into a human readbale string
* @param distance in kilometers * @param distance in kilometers
@@ -160,8 +179,8 @@ public class GeoUtils {
* @author ricky barrette * @author ricky barrette
*/ */
public static String distanceToString(double distance, final boolean returnMetric) { public static String distanceToString(double distance, final boolean returnMetric) {
DecimalFormat threeDForm = new DecimalFormat("#.###"); final DecimalFormat threeDForm = new DecimalFormat("#.###");
DecimalFormat twoDForm = new DecimalFormat("#.##"); final DecimalFormat twoDForm = new DecimalFormat("#.##");
if (returnMetric) { if (returnMetric) {
if (distance < 1) { if (distance < 1) {
@@ -191,30 +210,11 @@ public class GeoUtils {
* @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, final float fudgeFactor){
if(((accuracyRadius + locationRadius) - fudgeFactor) > distanceKm(locationPoint, userPoint)) if(accuracyRadius + locationRadius - fudgeFactor > distanceKm(locationPoint, userPoint))
return true; return true;
return false; return false;
} }
/**
* computes the distance between to p1 and p2 based on the curve of the earth
* @param p1
* @param p2
* @return the distance between to p1 and p2
* @author Google Inc.
*/
public static double distanceKm(final GeoPoint p1, final GeoPoint p2) {
//if we are handed a null, return -1 so we don't break
if(p1 == null || p2 == null)
return -1;
double lat1 = p1.getLatitudeE6() / MILLION;
double lon1 = p1.getLongitudeE6() / MILLION;
double lat2 = p2.getLatitudeE6() / MILLION;
double lon2 = p2.getLongitudeE6() / MILLION;
return distanceKm(lat1, lon1, lat2, lon2);
}
/** /**
* determines when the specified point is off the map * determines when the specified point is off the map
* @param point * @param point
@@ -226,13 +226,12 @@ public class GeoUtils {
return false; return false;
if (point == null) if (point == null)
return false; return false;
GeoPoint center = map.getMapCenter(); final GeoPoint center = map.getMapCenter();
double distance = GeoUtils.distanceKm(center, point); final double distance = GeoUtils.distanceKm(center, point);
double distanceLat = GeoUtils.distanceKm(center, new GeoPoint((center.getLatitudeE6() + (int) (map.getLatitudeSpan() / 2)), center.getLongitudeE6())); final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + map.getLatitudeSpan() / 2, center.getLongitudeE6()));
double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), (center.getLongitudeE6() + (int) (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;
} }
@@ -248,24 +247,24 @@ public class GeoUtils {
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);
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;
maxLongitude = (maxLongitude < longitude) ? longitude : maxLongitude; maxLongitude = maxLongitude < longitude ? longitude : maxLongitude;
mPoints.add(new Point(latitude, longitude)); mPoints.add(new Point(latitude, longitude));
} }
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);

View File

@@ -40,34 +40,50 @@ 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
* @param context
* @return a intent that will start the service
* @author ricky barrette
*/
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, LocationService.class);
}
/**
* a convince method for stopping the service and removing it's alarm
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
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));
}
};
}
private WakeLock mWakeLock; private WakeLock mWakeLock;
private long mPeriod = -1; private long mPeriod = -1;
private Location mLocation; private Location mLocation;
private int mStartId; private int mStartId;
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 Runnable failSafe = new Runnable() { private final Runnable failSafe = new Runnable() {
@Override @Override
public void run(){ public void run(){
stopSelf(mStartId); stopSelf(mStartId);
} }
}; };
/**
* registers this service to be waken up by android's alarm manager
* @author ricky barrette
*/
private void registerwakeUp(){
Log.d(TAG, "registerwakeUp()");
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + this.mPeriod, PendingIntent.getService(this, REQUEST_CODE, this.mIntent, 0));
}
/** /**
* broadcasts location to anything listening for updates, * broadcasts location to anything listening for updates,
* since this is the last function of the service, we call finish()u * since this is the last function of the service, we call finish()u
@@ -76,7 +92,7 @@ public class LocationService extends Service implements LocationListener {
private void broadcastLocation() { private void broadcastLocation() {
Log.d(TAG, "broadcastLocation()"); Log.d(TAG, "broadcastLocation()");
if (mLocation != null) { if (mLocation != null) {
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
@@ -87,6 +103,19 @@ public class LocationService extends Service implements LocationListener {
} }
} }
/**
* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author ricky barrette
*/
@Override
public IBinder onBind(final Intent arg0) {
// UNUSED
return null;
}
/** /**
* 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 manager, and acquire a wakelock
* (non-Javadoc) * (non-Javadoc)
@@ -96,7 +125,7 @@ public class LocationService extends Service implements LocationListener {
@Override @Override
public void onCreate(){ public void onCreate(){
mLocationManager = new AndroidGPS(this); mLocationManager = new AndroidGPS(this);
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();
@@ -124,12 +153,33 @@ public class LocationService extends Service implements LocationListener {
registerwakeUp(); registerwakeUp();
} }
@Override
public void onLocationChanged(final Location location) {
if(Debug.DEBUG)
Log.d(TAG, "got location +- "+ location.getAccuracy() +"m");
mLocation = location;
if(location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION)
stopSelf(mStartId);
}
@Override
public void onProviderDisabled(final String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(final String provider) {
// TODO Auto-generated method stub
}
/** /**
* 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 equivalent of onStartCommand in pre android 2.x
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onStart(Intent intent, int startId) { public void onStart(final Intent intent, final int startId) {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.i(TAG, "onStart.Service started with start id of: " + startId); Log.i(TAG, "onStart.Service started with start id of: " + startId);
mStartId = startId; mStartId = startId;
@@ -144,7 +194,7 @@ public class LocationService extends Service implements LocationListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public int onStartCommand(Intent intent, int flags, 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;
@@ -155,14 +205,20 @@ public class LocationService extends Service implements LocationListener {
return START_STICKY; return START_STICKY;
} }
@Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
// TODO Auto-generated method stub
}
/** /**
* Parses the incoming intent for the service options * Parses the incoming intent for the service options
* *
* @author ricky barrette * @author ricky barrette
*/ */
private void parseIntent(Intent intent){ private void parseIntent(final Intent intent){
this.mIntent = intent; mIntent = intent;
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);
@@ -172,70 +228,13 @@ public class LocationService extends Service implements LocationListener {
} }
/** /**
* (non-Javadoc) * registers this service to be waken up by android's alarm manager
* @see android.app.Service#onBind(android.content.Intent)
* @param arg0
* @return
* @author ricky barrette * @author ricky barrette
*/ */
@Override private void registerwakeUp(){
public IBinder onBind(Intent arg0) { Log.d(TAG, "registerwakeUp()");
// UNUSED final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
return null; am.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + mPeriod, PendingIntent.getService(this, REQUEST_CODE, mIntent, 0));
}
/**
*a convince method for getting an intent to start the service
* @param context
* @return a intent that will start the service
* @author ricky barrette
*/
public static Intent getStartServiceIntent(final Context context){
return new Intent(context, LocationService.class);
}
/**
* a convince method for stopping the service and removing it's alarm
* @param context
* @return a runnable that will stop the service
* @author ricky barrette
*/
public static Runnable stopService(final Context context){
return new Runnable(){
@Override
public void run(){
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));
}
};
}
@Override
public void onLocationChanged(Location location) {
if(Debug.DEBUG)
Log.d(TAG, "got location +- "+ location.getAccuracy() +"m");
mLocation = location;
if(location.getAccuracy() <= (mRequiredAccuracy > -1 ? mRequiredAccuracy : LocationLibraryConstants.MINIMUM_REQUIRED_ACCURACY) || LocationLibraryConstants.REPORT_FIRST_LOCATION){
stopSelf(mStartId);
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
} }
} }

View File

@@ -5,14 +5,14 @@
*/ */
package com.TwentyCodes.android.location; package com.TwentyCodes.android.location;
import com.TwentyCodes.android.debug.Debug;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.MotionEvent; import android.view.MotionEvent;
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
@@ -23,21 +23,12 @@ public class MapView extends com.google.android.maps.MapView {
private long mLastTouchTime; private long mLastTouchTime;
private boolean mDoubleTapZoonEnabled = true; private boolean mDoubleTapZoonEnabled = true;
/**
* @param context
* @param apiKey
* @author ricky barrette
*/
public MapView(Context context, String apiKey) {
super(context, apiKey);
}
/** /**
* @param context * @param context
* @param attrs * @param attrs
* @author ricky barrette * @author ricky barrette
*/ */
public MapView(Context context, AttributeSet attrs) { public MapView(final Context context, final AttributeSet attrs) {
super(context, attrs); super(context, attrs);
} }
@@ -47,27 +38,17 @@ public class MapView extends com.google.android.maps.MapView {
* @param defStyle * @param defStyle
* @author ricky barrette * @author ricky barrette
*/ */
public MapView(Context context, AttributeSet attrs, int defStyle) { public MapView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
} }
@Override /**
public boolean onInterceptTouchEvent(MotionEvent ev) { * @param context
* @param apiKey
if (ev.getAction() == MotionEvent.ACTION_DOWN) { * @author ricky barrette
*/
long thisTime = System.currentTimeMillis(); public MapView(final Context context, final String apiKey) {
if (this.mDoubleTapZoonEnabled && thisTime - mLastTouchTime < 250) { super(context, apiKey);
// Double tap
this.getController().zoomInFixing((int) ev.getX(), (int) ev.getY());
mLastTouchTime = -1;
} else {
// Too slow
mLastTouchTime = thisTime;
}
}
return super.onInterceptTouchEvent(ev);
} }
/** /**
@@ -77,14 +58,13 @@ public class MapView extends com.google.android.maps.MapView {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(Canvas canvas) { public void draw(final Canvas canvas) {
try { try {
if(this.getZoomLevel() >= 21) { if(getZoomLevel() >= 21)
this.getController().setZoom(20); getController().setZoom(20);
}
super.draw(canvas); super.draw(canvas);
} }
catch(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)
@@ -92,14 +72,6 @@ public class MapView extends com.google.android.maps.MapView {
} }
} }
/**
* @param isDoubleTapZoonEnabled the isDoubleTapZoonEnabled to set
* @author ricky barrette
*/
public void setDoubleTapZoonEnabled(boolean isDoubleTapZoonEnabled) {
this.mDoubleTapZoonEnabled = isDoubleTapZoonEnabled;
}
/** /**
* @return the isDoubleTapZoonEnabled * @return the isDoubleTapZoonEnabled
* @author ricky barrette * @author ricky barrette
@@ -107,4 +79,30 @@ public class MapView extends com.google.android.maps.MapView {
public boolean getDoubleTapZoonEnabled() { public boolean getDoubleTapZoonEnabled() {
return mDoubleTapZoonEnabled; return mDoubleTapZoonEnabled;
} }
@Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
final long thisTime = System.currentTimeMillis();
if (mDoubleTapZoonEnabled && thisTime - mLastTouchTime < 250) {
// Double tap
getController().zoomInFixing((int) ev.getX(), (int) ev.getY());
mLastTouchTime = -1;
} else
// Too slow
mLastTouchTime = thisTime;
}
return super.onInterceptTouchEvent(ev);
}
/**
* @param isDoubleTapZoonEnabled the isDoubleTapZoonEnabled to set
* @author ricky barrette
*/
public void setDoubleTapZoonEnabled(final boolean isDoubleTapZoonEnabled) {
mDoubleTapZoonEnabled = isDoubleTapZoonEnabled;
}
} }

View File

@@ -23,7 +23,7 @@ public class MidPoint {
* Creates a new MidPoint * Creates a new MidPoint
* @author ricky barrette * @author ricky barrette
*/ */
public MidPoint(GeoPoint midPoint, int minLatitude, int minLongitude, int maxLatitude, int maxLongitude) { public MidPoint(final GeoPoint midPoint, final int minLatitude, final int minLongitude, final int maxLatitude, final int maxLongitude) {
mMinLatitude = minLatitude; mMinLatitude = minLatitude;
mMaxLatitude = maxLatitude; mMaxLatitude = maxLatitude;
mMinLongitude = minLongitude; mMinLongitude = minLongitude;
@@ -31,15 +31,6 @@ public class MidPoint {
mMidPoint = midPoint; mMidPoint = midPoint;
} }
/**
* zooms the provided map view to the span of this mid point
* @param mMapView
* @author ricky barrette
*/
public void zoomToSpan(com.google.android.maps.MapView mMapView){
mMapView.getController().zoomToSpan((mMaxLatitude - mMinLatitude), (mMaxLongitude - mMinLongitude));
}
/** /**
* returns the calculated midpoint * returns the calculated midpoint
* @return * @return
@@ -48,4 +39,13 @@ public class MidPoint {
public GeoPoint getMidPoint(){ public GeoPoint getMidPoint(){
return mMidPoint; return mMidPoint;
} }
/**
* zooms the provided map view to the span of this mid point
* @param mMapView
* @author ricky barrette
*/
public void zoomToSpan(final com.google.android.maps.MapView mMapView){
mMapView.getController().zoomToSpan(mMaxLatitude - mMinLatitude, mMaxLongitude - mMinLongitude);
}
} }

View File

@@ -37,23 +37,24 @@ public class ReverseGeocoder {
/** /**
* Performs a google maps search for the address * Performs a google maps search for the address
* @param location * @param address to search
* @return JSON Array on google place marks nearby * @return JSON Array of google place marks
* @author ricky barrette
* @throws IOException * @throws IOException
* @throws JSONException * @throws JSONException
* @author ricky barrette
*/ */
public static JSONArray getFromLocation(final Location location) throws IOException, JSONException { public static JSONArray addressSearch(final String address) throws IOException, JSONException {
String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false"; String urlStr = "http://maps.google.com/maps/geo?q=" + address + "&output=json&sensor=false";
StringBuffer response = new StringBuffer(); urlStr = urlStr.replace(' ', '+');
HttpClient client = new DefaultHttpClient(); final StringBuffer response = new StringBuffer();
final HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
@@ -73,22 +74,22 @@ public class ReverseGeocoder {
* @author ricky barrette * @author ricky barrette
*/ */
public static String getAddressFromLocation(final Location location) { public static String getAddressFromLocation(final Location location) {
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";
StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
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 {
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -99,43 +100,42 @@ public class ReverseGeocoder {
JSONArray responseArray = null; JSONArray responseArray = null;
try { try {
responseArray = new JSONObject(response.toString()).getJSONArray("Placemark"); responseArray = new JSONObject(response.toString()).getJSONArray("Placemark");
} catch (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 {
JSONObject jsl = responseArray.getJSONObject(0); final JSONObject jsl = responseArray.getJSONObject(0);
return jsl.getString("address"); return jsl.getString("address");
} catch (JSONException e) { } catch (final JSONException e) {
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 address to search * @param location
* @return JSON Array of google place marks * @return JSON Array on google place marks nearby
* @author ricky barrette
* @throws IOException * @throws IOException
* @throws JSONException * @throws JSONException
* @author ricky barrette
*/ */
public static JSONArray addressSearch(final String address) throws IOException, JSONException { public static JSONArray getFromLocation(final Location location) throws IOException, JSONException {
String urlStr = "http://maps.google.com/maps/geo?q=" + address + "&output=json&sensor=false"; final String urlStr = "http://maps.google.com/maps/geo?q=" + location.getLatitude() + "," + location.getLongitude() + "&output=json&sensor=false";
urlStr = urlStr.replace(' ', '+'); final StringBuffer response = new StringBuffer();
StringBuffer response = new StringBuffer(); final HttpClient client = new DefaultHttpClient();
HttpClient client = new DefaultHttpClient();
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, urlStr); Log.d(TAG, urlStr);
HttpResponse hr = client.execute(new HttpGet(urlStr)); final HttpResponse hr = client.execute(new HttpGet(urlStr));
HttpEntity entity = hr.getEntity(); final HttpEntity entity = hr.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); final BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)

View File

@@ -56,11 +56,10 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
super.run(); super.run();
int index = 0; int index = 0;
boolean isCountingDown = false; boolean isCountingDown = false;
while (true) { while (true)
synchronized (this) { synchronized (this) {
if (isAborted) { if (isAborted)
break; break;
}
switch(index){ switch(index){
case 1: case 1:
@@ -72,7 +71,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
try { try {
sleep(100l); sleep(100l);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
break; break;
@@ -82,7 +81,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
isCountingDown = true; isCountingDown = true;
try { try {
sleep(200l); sleep(200l);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
break; break;
@@ -92,14 +91,13 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
isCountingDown = false; isCountingDown = false;
try { try {
sleep(2000l); sleep(2000l);
} catch (InterruptedException e) { } catch (final InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
break; break;
} }
} }
}
} }
} }
@@ -111,12 +109,12 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
private float mBearing = 0; private float mBearing = 0;
private int mAccuracy; private int mAccuracy;
private GeoPoint mPoint; private GeoPoint mPoint;
private Context mContext; private final Context mContext;
private MapView mMapView; private final MapView mMapView;
private boolean isFistFix = true; private boolean isFistFix = true;
private GeoPointLocationListener mListener; private GeoPointLocationListener mListener;
public boolean isFollowingUser = true; public boolean isFollowingUser = true;
private CompasOverlay mCompass; private final CompasOverlay mCompass;
private boolean isCompassEnabled; private boolean isCompassEnabled;
private CompassListener mCompassListener; private CompassListener mCompassListener;
@@ -127,7 +125,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param context * @param context
* @author ricky barrette * @author ricky barrette
*/ */
public BaseUserOverlay(MapView mapView, Context context) { public BaseUserOverlay(final MapView mapView, final Context context) {
super(); super();
mContext = context; mContext = context;
mMapView = mapView; mMapView = mapView;
@@ -142,7 +140,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public BaseUserOverlay(MapView mapView, Context context, boolean followUser) { public BaseUserOverlay(final MapView mapView, final Context context, final boolean followUser) {
this(mapView, context); this(mapView, context);
isFollowingUser = followUser; isFollowingUser = followUser;
} }
@@ -180,12 +178,12 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void draw(Canvas canvas, MapView mapView, boolean shadow){ public void draw(Canvas canvas, final MapView mapView, final boolean shadow){
if (isEnabled && mPoint != null) { if (isEnabled && mPoint != null) {
Point center = new Point(); final Point center = new Point();
Point left = new Point(); final Point left = new Point();
Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
GeoPoint leftGeo = GeoUtils.distanceFrom(mPoint, mAccuracy); final GeoPoint leftGeo = GeoUtils.distanceFrom(mPoint, mAccuracy);
projection.toPixels(leftGeo, left); projection.toPixels(leftGeo, left);
projection.toPixels(mPoint, center); projection.toPixels(mPoint, center);
canvas = drawAccuracyCircle(center, left, canvas); canvas = drawAccuracyCircle(center, left, canvas);
@@ -194,7 +192,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* 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);
} }
@@ -207,16 +205,15 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
private Canvas drawAccuracyCircle(Point center, Point left, Canvas canvas) { private Canvas drawAccuracyCircle(final Point center, final Point left, final Canvas canvas) {
Paint paint = new Paint(); final Paint paint = new Paint();
/* /*
* 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
*/ */
@@ -238,7 +235,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
*/ */
if(Debug.DEBUG){ if(Debug.DEBUG){
paint.setColor(Color.RED); paint.setColor(Color.RED);
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);
} }
@@ -253,11 +250,11 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @return modified canvas * @return modified canvas
* @author ricky barrette * @author ricky barrette
*/ */
private Canvas drawUser(Point point, float bearing, Canvas canvas){ private Canvas drawUser(final Point point, final float bearing, final Canvas canvas){
Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow); final Bitmap user = BitmapFactory.decodeResource(mContext.getResources(), mUserArrow);
Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(bearing); matrix.postRotate(bearing);
Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(
user, user,
0, 0, 0, 0,
user.getWidth(), user.getWidth(),
@@ -267,8 +264,8 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
); );
canvas.drawBitmap( canvas.drawBitmap(
rotatedBmp, rotatedBmp,
point.x - (rotatedBmp.getWidth() / 2), point.x - rotatedBmp.getWidth() / 2,
point.y - (rotatedBmp.getHeight() / 2), point.y - rotatedBmp.getHeight() / 2,
null null
); );
return canvas; return canvas;
@@ -279,9 +276,9 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @author ricky barrette * @author ricky barrette
*/ */
public void enableCompass(){ public void enableCompass(){
if(! this.isCompassEnabled){ if(! isCompassEnabled){
this.mMapView.getOverlays().add(this.mCompass); mMapView.getOverlays().add(mCompass);
this.isCompassEnabled = true; isCompassEnabled = true;
} }
} }
@@ -311,7 +308,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public void followUser(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;
@@ -344,7 +341,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
} }
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
if(mCompassListener != null) if(mCompassListener != null)
mCompassListener.onCompassUpdate(bearing); mCompassListener.onCompassUpdate(bearing);
mBearing = bearing; mBearing = bearing;
@@ -360,7 +357,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onLocationChanged(GeoPoint point, int accuracy) { public void onLocationChanged(final GeoPoint point, final int accuracy) {
if(mCompass != null) if(mCompass != null)
mCompass.setLocation(point); mCompass.setLocation(point);
@@ -371,7 +368,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
*/ */
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;
@@ -381,14 +378,12 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
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)
panToUserIfOffMap(point); panToUserIfOffMap(point);
} }
}
/** /**
* 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
@@ -406,35 +401,33 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* 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(GeoPoint user) { private void panToUserIfOffMap(final GeoPoint user) {
GeoPoint center = mMapView.getMapCenter(); final GeoPoint center = mMapView.getMapCenter();
double distance = GeoUtils.distanceKm(center, user); final double distance = GeoUtils.distanceKm(center, user);
double distanceLat = GeoUtils.distanceKm(center, new GeoPoint((center.getLatitudeE6() + (int) (mMapView.getLatitudeSpan() / 2)), center.getLongitudeE6())); final double distanceLat = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6() + mMapView.getLatitudeSpan() / 2, center.getLongitudeE6()));
double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), (center.getLongitudeE6() + (int) (mMapView.getLongitudeSpan() / 2)))); final double distanceLon = GeoUtils.distanceKm(center, new GeoPoint(center.getLatitudeE6(), center.getLongitudeE6() + mMapView.getLongitudeSpan() / 2));
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 unless they pan pack to them * else don't pan to user 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(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
@@ -444,7 +437,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassDrawables(int needleResId, int backgroundResId, int x, int y) { public void setCompassDrawables(final int needleResId, final int backgroundResId, final int x, final int y) {
mCompass.setDrawables(needleResId, backgroundResId, x, y); mCompass.setDrawables(needleResId, backgroundResId, x, y);
} }
@@ -453,7 +446,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void setCompassListener(CompassListener listener){ public void setCompassListener(final CompassListener listener){
mCompassListener = listener; mCompassListener = listener;
} }
@@ -461,7 +454,7 @@ public abstract class BaseUserOverlay extends Overlay implements GeoPointLocatio
* Sets the destination for the compass * Sets the destination for the compass
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
if(mCompass != null) if(mCompass != null)
mCompass.setDestination(destination); mCompass.setDestination(destination);
} }

View File

@@ -45,7 +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(Context context) { public CompasOverlay(final Context context) {
mContext = context; mContext = context;
mCompassSensor = new CompassSensor(context); mCompassSensor = new CompassSensor(context);
mX = convertDipToPx(40); mX = convertDipToPx(40);
@@ -58,7 +58,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, GeoPoint destination){ public CompasOverlay(final Context context, final GeoPoint destination){
this(context); this(context);
mDestination = destination; mDestination = destination;
} }
@@ -73,7 +73,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y dip * @param y dip
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, GeoPoint destination, int needleResId, int backgroundResId, int x, 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);
@@ -90,7 +90,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y * @param y
* @author ricky barrette * @author ricky barrette
*/ */
public CompasOverlay(Context context, int needleResId, int backgroundResId, int x, 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);
} }
@@ -100,8 +100,8 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @return px * @return px
* @author ricky barrette * @author ricky barrette
*/ */
private int convertDipToPx(int i) { private int convertDipToPx(final int i) {
Resources r = mContext.getResources(); final Resources r = mContext.getResources();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, r.getDisplayMetrics()); return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, r.getDisplayMetrics());
} }
@@ -125,22 +125,22 @@ public class CompasOverlay extends Overlay implements CompassListener {
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
Point point = new Point(); final Point point = new Point();
point.set(mX, mY); point.set(mX, mY);
//draw compass background //draw compass background
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.x - compass.getWidth() / 2,
point.y - (compass.getHeight() / 2), point.y - compass.getHeight() / 2,
null null
); );
//draw the compass needle //draw the compass needle
Bitmap arrowBitmap = BitmapFactory.decodeResource( mContext.getResources(), mNeedleResId); final Bitmap arrowBitmap = BitmapFactory.decodeResource( mContext.getResources(), mNeedleResId);
Matrix matrix = new Matrix(); final Matrix matrix = new Matrix();
matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing)); matrix.postRotate(GeoUtils.calculateBearing(mLocation, mDestination, mBearing));
Bitmap rotatedBmp = Bitmap.createBitmap( final Bitmap rotatedBmp = Bitmap.createBitmap(
arrowBitmap, arrowBitmap,
0, 0, 0, 0,
arrowBitmap.getWidth(), arrowBitmap.getWidth(),
@@ -150,8 +150,8 @@ public class CompasOverlay extends Overlay implements CompassListener {
); );
canvas.drawBitmap( canvas.drawBitmap(
rotatedBmp, rotatedBmp,
point.x - (rotatedBmp.getWidth() / 2), point.x - rotatedBmp.getWidth() / 2,
point.y - (rotatedBmp.getHeight() / 2), point.y - rotatedBmp.getHeight() / 2,
null null
); );
mapView.invalidate(); mapView.invalidate();
@@ -175,7 +175,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param listener * @param listener
* @author ricky barrette * @author ricky barrette
*/ */
public void enable(CompassListener listener){ public void enable(final CompassListener listener){
mListener = listener; mListener = listener;
enable(); enable();
} }
@@ -203,7 +203,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @author ricky barrette * @author ricky barrette
*/ */
@Override @Override
public void onCompassUpdate(float bearing) { public void onCompassUpdate(final float bearing) {
mBearing = bearing; mBearing = bearing;
/* /*
@@ -217,7 +217,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param destination * @param destination
* @author ricky barrette * @author ricky barrette
*/ */
public void setDestination(GeoPoint destination){ public void setDestination(final GeoPoint destination){
mDestination = destination; mDestination = destination;
} }
@@ -228,7 +228,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param y dip * @param y dip
* @author ricky barrette * @author ricky barrette
*/ */
public void setDrawables(int needleResId, int backgroundResId, int x, 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 +239,7 @@ public class CompasOverlay extends Overlay implements CompassListener {
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(GeoPoint location){ public void setLocation(final GeoPoint location){
mLocation = location; mLocation = location;
} }

View File

@@ -62,7 +62,7 @@ public class DirectionsOverlay {
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;
String json = downloadJSON(generateUrl(origin, destination)); final String json = downloadJSON(generateUrl(origin, destination));
drawPath(json); drawPath(json);
} }
@@ -90,8 +90,9 @@ public class DirectionsOverlay {
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "decodePoly"); Log.d(TAG, "decodePoly");
String encoded = step.getJSONObject("polyline").getString("points"); final String encoded = step.getJSONObject("polyline").getString("points");
int index = 0, len = encoded.length(); int index = 0;
final int len = encoded.length();
int lat = 0, lng = 0; int lat = 0, lng = 0;
GeoPoint last = null; GeoPoint last = null;
@@ -102,7 +103,7 @@ public class DirectionsOverlay {
result |= (b & 0x1f) << shift; result |= (b & 0x1f) << shift;
shift += 5; shift += 5;
} while (b >= 0x20); } while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); final int dlat = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lat += dlat; lat += dlat;
shift = 0; shift = 0;
@@ -112,10 +113,10 @@ public class DirectionsOverlay {
result |= (b & 0x1f) << shift; result |= (b & 0x1f) << shift;
shift += 5; shift += 5;
} while (b >= 0x20); } while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); final int dlng = (result & 1) != 0 ? ~(result >> 1) : result >> 1;
lng += dlng; lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6), (int) (((double) 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());
@@ -148,8 +149,8 @@ public class DirectionsOverlay {
Log.d(TAG, url); Log.d(TAG, url);
if(url == null) if(url == null)
throw new NullPointerException(); throw new NullPointerException();
StringBuffer response = new StringBuffer(); final StringBuffer response = new StringBuffer();
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()));
String buff = null; String buff = null;
while ((buff = br.readLine()) != null) while ((buff = br.readLine()) != null)
response.append(buff); response.append(buff);
@@ -176,12 +177,12 @@ public class DirectionsOverlay {
mDuration = new ArrayList<String>(); mDuration = new ArrayList<String>();
//get first route //get first route
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");
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 PathOverlay(getGeoPoint(leg.getJSONObject("start_location")), 12, Color.GREEN));
@@ -200,7 +201,7 @@ public class DirectionsOverlay {
*/ */
if(Debug.DEBUG) if(Debug.DEBUG)
Log.d(TAG, "processing steps"); Log.d(TAG, "processing steps");
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)

View File

@@ -65,20 +65,20 @@ public final class PathOverlay extends Overlay {
* @param when * @param when
*/ */
@Override @Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) { public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
final Projection projection = mapView.getProjection(); final Projection projection = mapView.getProjection();
final Paint paint = new Paint(); final Paint paint = new Paint();
paint.setColor(mColor); paint.setColor(mColor);
paint.setAntiAlias(true); paint.setAntiAlias(true);
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:
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:
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);
@@ -92,7 +92,7 @@ public final class PathOverlay extends Overlay {
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getEndPoint(){ public GeoPoint getEndPoint(){
return this.mEnd; return mEnd;
} }
/** /**
@@ -100,6 +100,6 @@ public final class PathOverlay extends Overlay {
* @author ricky barrette * @author ricky barrette
*/ */
public GeoPoint getStartPoint(){ public GeoPoint getStartPoint(){
return this.mStart; return mStart;
} }
} }

View File

@@ -48,7 +48,7 @@ public class RadiusOverlay extends Overlay{
* @param color desired color of the radius from Color API * @param color desired color of the radius from Color API
* @author ricky barrette * @author ricky barrette
*/ */
public RadiusOverlay(GeoPoint point, float radius, int color) { public RadiusOverlay(final GeoPoint point, final float radius, final int color) {
mPoint = point; mPoint = point;
mRadius = radius; mRadius = radius;
mColor = color; mColor = color;
@@ -82,9 +82,8 @@ 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;
}
/* /*
* paint a circle on the map * paint a circle on the map
@@ -96,7 +95,7 @@ public class RadiusOverlay extends Overlay{
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
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
@@ -114,11 +113,16 @@ public class RadiusOverlay extends Overlay{
return mPoint; return mPoint;
} }
public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0;
}
@Override @Override
public boolean onTap(GeoPoint p, MapView mapView) { public boolean onTap(final GeoPoint p, final MapView mapView) {
mPoint = p; mPoint = p;
if(this.mListener != null) if(mListener != null)
this.mListener.onLocationSelected(p); mListener.onLocationSelected(p);
return super.onTap(p, mapView); return super.onTap(p, mapView);
} }
@@ -126,7 +130,7 @@ public class RadiusOverlay extends Overlay{
* @param color * @param color
* @author ricky barrette * @author ricky barrette
*/ */
public void setColor(int color){ public void setColor(final int color){
mColor = color; mColor = color;
} }
@@ -134,25 +138,20 @@ public class RadiusOverlay extends Overlay{
* @param location * @param location
* @author ricky barrette * @author ricky barrette
*/ */
public void setLocation(GeoPoint location){ public void setLocation(final GeoPoint location){
mPoint = location; mPoint = location;
} }
public void setLocationSelectedListener(final OnLocationSelectedListener listener) {
mListener = listener;
}
/** /**
* @param radius in meters * @param radius in meters
* @author ricky barrette * @author ricky barrette
* @param radius * @param radius
*/ */
public void setRadius(int radius){ public void setRadius(final int radius){
mRadius = radius; mRadius = radius;
} }
public int getZoomLevel() {
// GeoUtils.GeoUtils.distanceFrom(mPoint , mRadius)
return 0;
}
public void setLocationSelectedListener(OnLocationSelectedListener listener) {
this.mListener = listener;
}
} }

View File

@@ -18,7 +18,7 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
private final SkyHook mSkyHook; private final SkyHook mSkyHook;
public SkyHookUserOverlay(MapView mapView, Context context) { public SkyHookUserOverlay(final MapView mapView, final Context context) {
super(mapView, context); super(mapView, context);
mSkyHook = new SkyHook(context); mSkyHook = new SkyHook(context);
} }
@@ -30,11 +30,16 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
* @param followUser * @param followUser
* @author ricky barrette * @author ricky barrette
*/ */
public SkyHookUserOverlay(MapView mapView, Context context, boolean followUser) { public SkyHookUserOverlay(final MapView mapView, final Context context, final boolean followUser) {
super(mapView, context, followUser); super(mapView, context, followUser);
mSkyHook = new SkyHook(context); mSkyHook = new SkyHook(context);
} }
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
/** /**
* Called when the location provider needs to be disabled * Called when the location provider needs to be disabled
* (non-Javadoc) * (non-Javadoc)
@@ -56,9 +61,4 @@ public class SkyHookUserOverlay extends BaseUserOverlay{
mSkyHook.getUpdates(); mSkyHook.getUpdates();
} }
@Override
public void onFirstFix(boolean isFistFix) {
// unused
}
} }

View File

@@ -18,16 +18,21 @@ public class UserOverlay extends BaseUserOverlay{
private final AndroidGPS mAndroidGPS; private final AndroidGPS mAndroidGPS;
public UserOverlay(MapView mapView, Context context) { public UserOverlay(final MapView mapView, final Context context) {
super(mapView, context); super(mapView, context);
mAndroidGPS = new AndroidGPS(context); mAndroidGPS = new AndroidGPS(context);
} }
public UserOverlay(MapView mapView, Context context, boolean followUser) { public UserOverlay(final MapView mapView, final Context context, final boolean followUser) {
super(mapView, context, followUser); super(mapView, context, followUser);
mAndroidGPS = new AndroidGPS(context); mAndroidGPS = new AndroidGPS(context);
} }
@Override
public void onFirstFix(final boolean isFistFix) {
// unused
}
@Override @Override
public void onMyLocationDisabled() { public void onMyLocationDisabled() {
mAndroidGPS.disableLocationUpdates(); mAndroidGPS.disableLocationUpdates();
@@ -38,9 +43,4 @@ public class UserOverlay extends BaseUserOverlay{
mAndroidGPS.enableLocationUpdates(this); mAndroidGPS.enableLocationUpdates(this);
} }
@Override
public void onFirstFix(boolean isFistFix) {
// unused
}
} }