Java Code Examples for com.google.android.gms.location.LocationResult#getLastLocation()

The following examples show how to use com.google.android.gms.location.LocationResult#getLastLocation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 7 votes vote down vote up
/**
 * Get periodic location updates based on the current location request.
 */
private void getLocationUpdates() {
  if (mFusedProviderClient != null && mLocationRequest != null) {
    mLocationCallback = new LocationCallback() {
      @Override
      public void onLocationAvailability(LocationAvailability locationAvailability) {
        if (!locationAvailability.isLocationAvailable()) {
          invokeError(
            LocationError.POSITION_UNAVAILABLE.getValue(),
            "Unable to retrieve location",
            false
          );
        }
      }

      @Override
      public void onLocationResult(LocationResult locationResult) {
        Location location = locationResult.getLastLocation();
        invokeSuccess(LocationUtils.locationToMap(location), false);
      }
    };

    mFusedProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
  }
}
 
Example 2
Source File: LocationUpdateReceiver.java    From home-assistant-Android with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    prefs = Utils.getPrefs(context);
    switch (intent.getAction()) {
        case Intent.ACTION_BOOT_COMPLETED:
        case ACTION_START_LOCATION:
            apiClient = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

            apiClient.connect();
            break;
        case ACTION_LOCATION_UPDATE:
            if (prefs.getBoolean(Common.PREF_ENABLE_LOCATION_TRACKING, false) && LocationResult.hasResult(intent)) {
                LocationResult result = LocationResult.extractResult(intent);
                Location location = result.getLastLocation();
                if (location != null)
                    logLocation(location, context);
            }
            break;
    }
}
 
Example 3
Source File: GeofenceReceiver.java    From android-sdk with MIT License 6 votes vote down vote up
private void handleLocationUpdate(Context context, Intent intent) {
    LocationResult result = LocationResult.extractResult(intent);
    LocationAvailability availability = LocationAvailability.extractLocationAvailability(intent);
    Intent service = SensorbergServiceIntents.getServiceIntentWithMessage(
            context, SensorbergServiceMessage.MSG_LOCATION_UPDATED);
    if (result != null) {
        Location location = result.getLastLocation();
        if (location != null) {
            service.putExtra(SensorbergServiceMessage.EXTRA_LOCATION, location);
        }
    }
    if (availability != null) {
        service.putExtra(SensorbergServiceMessage.EXTRA_LOCATION_AVAILABILITY,
                availability.isLocationAvailable());
    }
    if (result != null || availability != null) {
        context.startService(service);
    } else {
        Logger.log.geofenceError("Received invalid location update", null);
    }
}
 
Example 4
Source File: BasePlatformCreate.java    From indigenous-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initiate the location libraries and services.
 */
private void initLocationLibraries() {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mSettingsClient = LocationServices.getSettingsClient(this);

    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            // location is received
            mCurrentLocation = locationResult.getLastLocation();
            updateLocationUI();
        }
    };

    mRequestingLocationUpdates = false;

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    mLocationSettingsRequest = builder.build();
}
 
Example 5
Source File: FusedLocationIntentService.java    From android-notification-log with MIT License 6 votes vote down vote up
@Override
protected void onHandleIntent(@Nullable Intent intent) {
	if(LocationResult.hasResult(intent)) {
		LocationResult locationResult = LocationResult.extractResult(intent);
		Location location = locationResult.getLastLocation();

		JSONObject json = new JSONObject();
		String str = null;
		try {
			long now = System.currentTimeMillis();
			json.put("time", now);
			json.put("offset", TimeZone.getDefault().getOffset(now));
			json.put("age", now - location.getTime());
			json.put("longitude", location.getLongitude() + "");
			json.put("latitude", location.getLatitude() + "");
			json.put("accuracy", location.getAccuracy());
			str = json.toString();
		} catch (JSONException e) {
			if(Const.DEBUG) e.printStackTrace();
		}

		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		sp.edit().putString(Const.PREF_LAST_LOCATION, str).apply();
	}
}
 
Example 6
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  Location location = locationResult.getLastLocation();
  if (location != null) {
    updateTextView(location);
  }
}
 
Example 7
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  Location location = locationResult.getLastLocation();
  if (location != null) {
    updateTextView(location);
  }

  if (location != null) {
    updateTextView(location);
    if (mMap != null) {
      LatLng latLng = new LatLng(location.getLatitude(),
        location.getLongitude());
      mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
  }
}
 
Example 8
Source File: GetLocation.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private static LocationCallback getLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (locationResult == null) {
                return;
            }
            final Location thisLocation = locationResult.getLastLocation();
            UserError.Log.d(TAG, "Got location update callback!! " + thisLocation);
            if ((lastLocation == null)
                    || thisLocation.getAccuracy() < lastLocation.getAccuracy()
                    || ((thisLocation.getAccuracy() < SKIP_DISTANCE) && (thisLocation.distanceTo(lastLocation) > SKIP_DISTANCE))) {

                lastLocation = thisLocation;
                UserError.Log.d(TAG, "Got location UPDATED element: " + lastLocation);
                Inevitable.task("update-street-location", 6000, () -> lastAddress = getStreetLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
            }
        }
    };
}
 
Example 9
Source File: CustomLocationTrackingActivity.java    From android-map-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
    if (map == null) {
        return;
    }
    Location lastLocation = locationResult.getLastLocation();
    LatLng coord = new LatLng(lastLocation);
    LocationOverlay locationOverlay = map.getLocationOverlay();
    locationOverlay.setPosition(coord);
    locationOverlay.setBearing(lastLocation.getBearing());
    map.moveCamera(CameraUpdate.scrollTo(coord));
    if (waiting) {
        waiting = false;
        fab.setImageResource(R.drawable.ic_location_disabled_black_24dp);
        locationOverlay.setVisible(true);
    }
}
 
Example 10
Source File: BaseNiboFragment.java    From Nibo with MIT License 6 votes vote down vote up
/**
 * Creates a callback for receiving location events.
 */
private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            Location location = locationResult.getLastLocation();
            if (location != null) {
                extractGeocode(location.getLatitude(), location.getLongitude());


                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(), location.getLongitude()))
                        .zoom(15)
                        .build();
                mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                handleLocationRetrieval(location);
                extractGeocode(location.getLatitude(), location.getLongitude());
            }
        }
    };
}
 
Example 11
Source File: GetLocation.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static LocationCallback getLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            if (locationResult == null) {
                return;
            }
            final Location thisLocation = locationResult.getLastLocation();
            UserError.Log.d(TAG, "Got location update callback!! " + thisLocation);
            if ((lastLocation == null)
                    || thisLocation.getAccuracy() < lastLocation.getAccuracy()
                    || ((thisLocation.getAccuracy() < SKIP_DISTANCE) && (thisLocation.distanceTo(lastLocation) > SKIP_DISTANCE))) {

                lastLocation = thisLocation;
                UserError.Log.d(TAG, "Got location UPDATED element: " + lastLocation);
                Inevitable.task("update-street-location", 6000, () -> lastAddress = getStreetLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
            }
        }
    };
}
 
Example 12
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  Location location = locationResult.getLastLocation();
  if (location != null) {
    updateTextView(location);
  }

  if (location != null) {
    updateTextView(location);
    if (mMap != null) {
      LatLng latLng = new LatLng(location.getLatitude(),
        location.getLongitude());
      mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

      Calendar c = Calendar.getInstance();
      String dateTime = DateFormat.format("MM/dd/yyyy HH:mm:ss",
                                          c.getTime()).toString();

      int markerNumber = mMarkers.size()+1;
      mMarkers.add(mMap.addMarker(new MarkerOptions()
                                    .position(latLng)
                                    .title(dateTime)
                                    .snippet("Marker #" + markerNumber +
                                               " @ " + dateTime)));

      List<LatLng> points = mPolyline.getPoints();
      points.add(latLng);
      mPolyline.setPoints(points);
    }
  }
}
 
Example 13
Source File: MainActivity.java    From location-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a callback for receiving location events.
 */
private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            mCurrentLocation = locationResult.getLastLocation();
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateLocationUI();
        }
    };
}
 
Example 14
Source File: LocationGetLocationActivity.java    From coursera-android with MIT License 5 votes vote down vote up
@NonNull
private LocationCallback getLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            ensureColor();

            // Get new location
            Location location = locationResult.getLastLocation();

            // Determine whether new location is better than current best estimate
            if (null == mBestReading
                    || location.getAccuracy() < mBestReading.getAccuracy()) {

                // Update best location
                mBestReading = location;

                // Update display
                updateDisplay(location);

                // Turn off location updates if location reading is sufficiently accurate
                if (mBestReading.getAccuracy() < MIN_ACCURACY) {
                    mLocationClient.removeLocationUpdates(mLocationCallback);
                }
            }
        }
    };
}
 
Example 15
Source File: AndroidLocationPlayServiceManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
static android.location.Location extractLocationFromIntent(Intent intent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        LocationResult locationResult = LocationResult.extractResult(intent);
        if (locationResult == null) {
            return null;
        }
        return locationResult.getLastLocation();
    } else {
        return intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
    }
}
 
Example 16
Source File: GglMapLocationManager.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public void onLocationResult(LocationResult result) {
    if (this.locationMarker != null) {
        onLocationChanged(result.getLastLocation());
    } else if (result.getLastLocation() != null) {
        LatLng latLng = new LatLng(result.getLastLocation().getLatitude(), result.getLastLocation().getLongitude());
        this.locationMarker = this.mGoogleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_map)).anchor(0.5f, 0.5f));
        this.mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15.555f));
    }
}
 
Example 17
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  Location location = locationResult.getLastLocation();
  if (location != null) {
    updateTextView(location);
  }
}
 
Example 18
Source File: SingleLocationUpdate.java    From react-native-geolocation-service with MIT License 5 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  synchronized (SingleLocationUpdate.this) {
    Location location = locationResult.getLastLocation();
    invokeSuccess(LocationUtils.locationToMap(location));

    mHandler.removeCallbacks(mTimeoutRunnable);

    // Remove further location update.
    if (mFusedProviderClient != null && mLocationCallback != null) {
      mFusedProviderClient.removeLocationUpdates(mLocationCallback);
    }
  }
}
 
Example 19
Source File: PlaceSearchFragment.java    From Place-Search-Service with MIT License 5 votes vote down vote up
private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            mCurrentLocation = locationResult.getLastLocation();
            Log.e("lingquan", "the current location is " + mCurrentLocation);
            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
            updateLocationUI();
        }
    };
}
 
Example 20
Source File: ControllerFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 4 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
    Location location = locationResult.getLastLocation();
    setLastLocation(location);
}