LocationGetLocationActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 |
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import android.app.Activity; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; public class LocationGetLocationActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener { private static final long ONE_MIN = 1000 * 60; private static final long TWO_MIN = ONE_MIN * 2; private static final long FIVE_MIN = ONE_MIN * 5; private static final long MEASURE_TIME = 1000 * 30; private static final long POLLING_FREQ = 1000 * 10; private static final long FASTES_UPDATE_FREQ = 1000 * 2; private static final float MIN_ACCURACY = 25.0f; private static final float MIN_LAST_READ_ACCURACY = 500.0f; // Define an object that holds accuracy and frequency parameters LocationRequest mLocationRequest; // Views for display location information private TextView mAccuracyView; private TextView mTimeView; private TextView mLatView; private TextView mLngView; private int mTextViewColor = Color.GRAY; // Current best location estimate private Location mBestReading; private final String TAG = "LocationGetLocationActivity"; private boolean mFirstUpdate = true; private LocationClient mLocationClient; private Location mCurrentLocation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!servicesAvailable()) finish(); setContentView(R.layout.main); mAccuracyView = (TextView) findViewById(R.id.accuracy_view); mTimeView = (TextView) findViewById(R.id.time_view); mLatView = (TextView) findViewById(R.id.lat_view); mLngView = (TextView) findViewById(R.id.lng_view); // Create new Location Client. This class will handle callbacks mLocationClient = new LocationClient(this, this, this); // Create and define the LocationRequest mLocationRequest = LocationRequest.create(); // Use high accuracy mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // Update every 10 seconds mLocationRequest.setInterval(POLLING_FREQ); // Recieve updates no more often than every 2 seconds mLocationRequest.setFastestInterval(FASTES_UPDATE_FREQ); } @Override protected void onStart() { super.onStart(); // Connect to LocationServices mLocationClient.connect(); } @Override protected void onStop() { // Stop updates mLocationClient.removeLocationUpdates(this); // Disconnect from LocationServices mLocationClient.disconnect(); super.onStop(); } // Called back when location changes @Override public void onLocationChanged(Location location) { ensureColor(); // Determine whether new location is better than current best // estimate if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) { // Update best estimate mBestReading = location; // Update display updateDisplay(location); if (mBestReading.getAccuracy() < MIN_ACCURACY) mLocationClient.removeLocationUpdates(this); } } @Override public void onConnected(Bundle dataBundle) { // Get first reading. Get additional location updates if necessary if (servicesAvailable()) { // Get best last location measurement meeting criteria mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN); // Display last reading information if (null != mBestReading) { updateDisplay(mBestReading); } else { mAccuracyView.setText("No Initial Reading Available"); } if (null == mBestReading || mBestReading.getAccuracy() > MIN_LAST_READ_ACCURACY || mBestReading.getTime() < System.currentTimeMillis() - TWO_MIN) { mLocationClient.requestLocationUpdates(mLocationRequest, this); // Schedule a runnable to unregister location listeners Executors.newScheduledThreadPool(1).schedule(new Runnable() { @Override public void run() { mLocationClient.removeLocationUpdates(LocationGetLocationActivity.this); } }, MEASURE_TIME, TimeUnit.MILLISECONDS); } } } // Get the last known location from all providers // return best reading is as accurate as minAccuracy and // was taken no longer then maxAge milliseconds ago private Location bestLastKnownLocation(float minAccuracy, long maxAge) { Location bestResult = null; float bestAccuracy = Float.MAX_VALUE; long bestTime = Long.MIN_VALUE; // Get the best most recent location currently available mCurrentLocation = mLocationClient.getLastLocation(); if (mCurrentLocation != null) { float accuracy = mCurrentLocation.getAccuracy(); long time = mCurrentLocation.getTime(); if (accuracy < bestAccuracy) { bestResult = mCurrentLocation; bestAccuracy = accuracy; bestTime = time; } } // Return best reading or null if (bestAccuracy > minAccuracy || (System.currentTimeMillis() - bestTime) > maxAge) { return null; } else { return bestResult; } } @Override public void onDisconnected() { Log.i(TAG, "Disconnected. Try again later."); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.i(TAG, "Connection Failed. Try again later."); } private boolean servicesAvailable() { // Check that Google Play Services are available int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); // If Google Play services is available return (ConnectionResult.SUCCESS == resultCode); } // Update display private void updateDisplay(Location location) { mAccuracyView.setText("Accuracy:" + location.getAccuracy()); mTimeView.setText("Time:" + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale .getDefault()).format(new Date(location.getTime()))); mLatView.setText("Longitude:" + location.getLongitude()); mLngView.setText("Latitude:" + location.getLatitude()); } private void ensureColor() { if (mFirstUpdate) { setTextViewColor(mTextViewColor); mFirstUpdate = false; } } private void setTextViewColor(int color) { mAccuracyView.setTextColor(color); mTimeView.setTextColor(color); mLatView.setTextColor(color); mLngView.setTextColor(color); } } |
main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/accuracy_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="@color/red"> </TextView> <TextView android:id="@+id/time_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="@color/red"> </TextView> <TextView android:id="@+id/lat_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="@color/red"> </TextView> <TextView android:id="@+id/lng_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textColor="@color/red"> </TextView> </LinearLayout> |