Here are the examples of the java api class android.location.LocationListener taken from open source projects.
1. CustomShadowLocationManager#setTestProviderLocation()
Project: MozStumbler
File: CustomShadowLocationManager.java
File: CustomShadowLocationManager.java
@Implementation public void setTestProviderLocation(java.lang.String provider, android.location.Location loc) { // robolectric branch if (registeredListeners.get(provider) == null) { registeredListeners.put(provider, new LinkedList<LocationListener>()); } for (LocationListener listener : registeredListeners.get(provider)) { listener.onLocationChanged(loc); } }
2. OdometerService#onCreate()
Project: HeadFirstAndroid
File: OdometerService.java
File: OdometerService.java
@Override public void onCreate() { listener = new LocationListener() { @Override public void onLocationChanged(Location location) { if (lastLocation == null) { lastLocation = location; } distanceInMeters += location.distanceTo(lastLocation); lastLocation = location; } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle bundle) { } }; locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, listener); }
3. SocializeLocationManagerTest#testSocializeLocationManager()
Project: socialize-sdk-android
File: SocializeLocationManagerTest.java
File: SocializeLocationManagerTest.java
// Can't mock location manager, so just do a full integration test public void testSocializeLocationManager() { AppUtils appUtils = Mockito.mock(AppUtils.class); Mockito.when(appUtils.hasPermission((Context) Mockito.anyObject(), Mockito.eq("android.permission.ACCESS_FINE_LOCATION"))).thenReturn(false); Mockito.when(appUtils.hasPermission((Context) Mockito.anyObject(), Mockito.eq("android.permission.ACCESS_COARSE_LOCATION"))).thenReturn(true); SocializeLocationManager manager = new SocializeLocationManager(appUtils); manager.init(TestUtils.getActivity(this)); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); String bestProvider = manager.getBestProvider(criteria, true); assertNotNull(bestProvider); // May be null, so don't assert result manager.getLastKnownLocation(bestProvider); manager.isProviderEnabled(bestProvider); LocationListener listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { } }; manager.requestLocationUpdates(TestUtils.getActivity(this), bestProvider, 0, 0, listener); manager.removeUpdates(listener); }
4. PGPS#start()
Project: Protocoder
File: PGPS.java
File: PGPS.java
@ProtoMethod(description = "Start the gps. Returns lat, lon, alt, speed, bearing", example = "") @ProtoMethodParam(params = { "function(lat, lon, alt, speed, bearing)" }) public void start() { if (running) { return; } WhatIsRunning.getInstance().add(this); MLog.d(TAG, "starting GPS"); // criteria.setSpeedRequired(true); locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) { MLog.d(TAG, "GPS not enabled"); showSettingsAlert(); } else { MLog.d(TAG, "GPS enabled"); } running = true; Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // criteria.setBearingAccuracy(Criteria.ACCURACY_FINE); criteria.setCostAllowed(true); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setPowerRequirement(Criteria.POWER_HIGH); criteria.setSpeedRequired(false); provider = locationManager.getBestProvider(criteria, false); listener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { L.d(TAG, "the gps status is: " + status); // TODO add listener to see when the GPS is on or not switch(status) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: if (mLastLocation != null) { isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000; } if (isGPSFix) { // A fix has been acquired. // Do something. } else { // The fix has been lost. // Do something. } break; case GpsStatus.GPS_EVENT_FIRST_FIX: // Do something. isGPSFix = true; break; } } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); c.startActivity(intent); } @Override public void onLocationChanged(Location location) { MLog.d(TAG, "updated "); mGPSListener.event(location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getSpeed(), location.getAccuracy()); if (location == null) { return; } mLastLocationMillis = SystemClock.elapsedRealtime(); mLastLocation = location; } }; locationManager.requestLocationUpdates(provider, 100, 0.1f, listener); }
5. LocationNotifier#getCurrentLocationAsync()
Project: Parse-SDK-Android
File: LocationNotifier.java
File: LocationNotifier.java
/** * Asynchronously gets the current location of the device. * * This will request location updates from the best provider that match the given criteria * and return the first location received. * * You can customize the criteria to meet your specific needs. * * For higher accuracy, you can set {@link Criteria#setAccuracy(int)}, however result in longer * times for a fix. * * For better battery efficiency and faster location fixes, you can set * {@link Criteria#setPowerRequirement(int)}, however, this will result in lower accuracy. * * @param context * The context used to request location updates. * @param timeout * The number of milliseconds to allow before timing out. * @param criteria * The application criteria for selecting a location provider. * * @see android.location.LocationManager#getBestProvider(android.location.Criteria, boolean) * @see android.location.LocationManager#requestLocationUpdates(String, long, float, android.location.LocationListener) */ /* package */ static Task<Location> getCurrentLocationAsync(Context context, long timeout, Criteria criteria) { final TaskCompletionSource<Location> tcs = new TaskCompletionSource<>(); final Capture<ScheduledFuture<?>> timeoutFuture = new Capture<ScheduledFuture<?>>(); final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); final LocationListener listener = new LocationListener() { @Override public void onLocationChanged(Location location) { if (location == null) { return; } timeoutFuture.get().cancel(true); tcs.trySetResult(location); manager.removeUpdates(this); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }; timeoutFuture.set(ParseExecutors.scheduled().schedule(new Runnable() { @Override public void run() { tcs.trySetError(new ParseException(ParseException.TIMEOUT, "Location fetch timed out.")); manager.removeUpdates(listener); } }, timeout, TimeUnit.MILLISECONDS)); String provider = manager.getBestProvider(criteria, true); if (provider != null) { manager.requestLocationUpdates(provider, /* minTime */ 0, /* minDistance */ 0.0f, listener); } if (fakeLocation != null) { listener.onLocationChanged(fakeLocation); } return tcs.getTask(); }
6. LocationGetLocationActivity#onCreate()
Project: coursera-android
File: LocationGetLocationActivity.java
File: LocationGetLocationActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); 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); // Acquire reference to the LocationManager if (null == (mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE))) finish(); // Get best last location measurement mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN); // Display last reading information if (null != mBestReading) { updateDisplay(mBestReading); } else { mAccuracyView.setText("No Initial Reading Available"); } mLocationListener = new LocationListener() { // Called back when location changes public void onLocationChanged(Location location) { ensureColor(); if (null == mBestReading || location.getAccuracy() < mBestReading.getAccuracy()) { // Update best estimate mBestReading = location; // Update display updateDisplay(location); if (mBestReading.getAccuracy() < MIN_ACCURACY) mLocationManager.removeUpdates(mLocationListener); } } public void onStatusChanged(String provider, int status, Bundle extras) { // NA } public void onProviderEnabled(String provider) { // NA } public void onProviderDisabled(String provider) { // NA } }; }
7. LocationManagerActivity#setData()
Project: AndroidLife
File: LocationManagerActivity.java
File: LocationManagerActivity.java
@SuppressLint("SetTextI18n") private void setData() { this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { /** * ?? * ?? * ?? */ Log.i(TAG, "Longitude:" + Double.toString(location.getLongitude())); Log.i(TAG, "Latitude:" + Double.toString(location.getLatitude())); Log.i(TAG, "getAltitude:" + Double.toString(location.getAltitude())); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // for ActivityCompat#requestPermissions for more details. return; } this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { this.longitudeTV.setText(location.getLongitude() + ""); this.latitudeTV.setText(location.getLatitude() + ""); this.altitudeTV.setText(location.getAltitude() + ""); } this.getProviders(); this.getBestProvider(); }