com.google.android.gms.location.LocationCallback Java Examples

The following examples show how to use com.google.android.gms.location.LocationCallback. 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: LocationBackgroundService.java    From rn-background-location with MIT License 6 votes vote down vote up
private LocationCallback createLocationRequestCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                LocationCoordinates locationCoordinates = createCoordinates(location.getLatitude(), location.getLongitude());
                broadcastLocationReceived(locationCoordinates);
                mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            }
        }
    };
}
 
Example #3
Source File: GoogleLocationEngineImplAdditionalTest.java    From mapbox-events-android with MIT License 6 votes vote down vote up
@Before
public void setUp() {
  location = mock(Location.class);
  when(location.getLatitude()).thenReturn(1.0);
  when(location.getLongitude()).thenReturn(2.0);
  locationList.clear();
  locationList.add(location);
  fusedLocationProviderClient = mock(FusedLocationProviderClient.class);
  mockTask = mock(Task.class);
  mockLocationTask = mock(Task.class);
  when(fusedLocationProviderClient.getLastLocation()).thenReturn(mockLocationTask);
  when(fusedLocationProviderClient
    .requestLocationUpdates(any(LocationRequest.class), any(LocationCallback.class), any(Looper.class)))
    .thenAnswer(new Answer<Task<Void>>() {
      @Override
      public Task<Void> answer(InvocationOnMock invocation) {
        LocationCallback listener = (LocationCallback) invocation.getArguments()[1];
        listener.onLocationResult(LocationResult.create(locationList));
        return mockTask;
      }
    });

  engine = new LocationEngineProxy<>(new GoogleLocationEngineImpl(fusedLocationProviderClient));
}
 
Example #4
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 #5
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 #6
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 #7
Source File: CoordinatesView.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void startRequestingLocation() {
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(5000);
    locationRequest.setFastestInterval(1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult != null) {
                Double latitude = locationResult.getLocations().get(0).getLatitude();
                Double longitude = locationResult.getLocations().get(0).getLongitude();
                updateLocation(GeometryHelper.createPointGeometry(longitude, latitude));
                mFusedLocationClient.removeLocationUpdates(locationCallback);
            }
        }
    };

    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions((ActivityGlobalAbstract) getContext(),
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                ACCESS_LOCATION_PERMISSION_REQUEST);
    } else
        mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);

}
 
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: EasyWayLocation.java    From EasyWayLocation with Apache License 2.0 6 votes vote down vote up
/**
 * Starts updating the location and requesting new updates after the defined interval
 */
@SuppressLint("MissingPermission")
private void beginUpdates() {
    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                mListener.locationCancelled();
            }else {
                for (Location location : locationResult.getLocations()) {
                    mListener.currentLocation(location);
                }
            }

        }
    };

    fusedLocationClient.requestLocationUpdates(locationRequest,
            locationCallback,
            Looper.getMainLooper());
}
 
Example #10
Source File: Location.java    From UberClone with MIT License 5 votes vote down vote up
public Location(AppCompatActivity activity, final locationListener locationListener) {
    this.activity=activity;
    fusedLocationClient=new FusedLocationProviderClient(activity.getApplicationContext());

    inicializeLocationRequest();
    locationCallback=new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            locationListener.locationResponse(locationResult);
        }
    };
}
 
Example #11
Source File: AndroidLocationProvider.java    From BLE-Indoor-Positioning with Apache License 2.0 5 votes vote down vote up
private LocationCallback createLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            Log.v(TAG, "Received location result with " + locationResult.getLocations().size() + " locations");
            onLocationUpdateReceived(locationResult.getLastLocation());
        }
    };
}
 
Example #12
Source File: GoogleLocationEngineImpl.java    From mapbox-events-android with MIT License 5 votes vote down vote up
@SuppressLint("MissingPermission")
@Override
public void requestLocationUpdates(@NonNull LocationEngineRequest request,
                                   @NonNull LocationCallback listener,
                                   @Nullable Looper looper) throws SecurityException {
  fusedLocationProviderClient.requestLocationUpdates(toGMSLocationRequest(request), listener, looper);
}
 
Example #13
Source File: Location.java    From UberClone with MIT License 5 votes vote down vote up
public Location(AppCompatActivity activity, final locationListener locationListener) {
    this.activity=activity;
    fusedLocationClient=new FusedLocationProviderClient(activity.getApplicationContext());

    inicializeLocationRequest();
    locationCallback=new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            locationListener.locationResponse(locationResult);
        }
    };
}
 
Example #14
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 #15
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 #16
Source File: CalculationModulesArrayList.java    From GNSS_Compare with Apache License 2.0 5 votes vote down vote up
public CalculationModulesArrayList(){
    gnssCallback = new GnssMeasurementsEvent.Callback() {
        @Override
        public void onGnssMeasurementsReceived(GnssMeasurementsEvent eventArgs) {
        super.onGnssMeasurementsReceived(eventArgs);

        Log.d(TAG, "onGnssMeasurementsReceived: invoked!");

        for (CalculationModule calculationModule : CalculationModulesArrayList.this)
            calculationModule.updateMeasurements(eventArgs);

        if(mPoseUpdatedListener !=null)
            mPoseUpdatedListener.onPoseUpdated();
        }
    };

    locationRequest = new LocationRequest();

    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setMaxWaitTime(500);
    locationRequest.setInterval(1000);
    locationRequest.setFastestInterval(100);

    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {

        final Location lastLocation = locationResult.getLocations().get(locationResult.getLocations().size()-1);

        if(lastLocation != null) {
            synchronized (this) {
                for (CalculationModule calculationModule : CalculationModulesArrayList.this)
                    calculationModule.updateLocationFromGoogleServices(lastLocation);

            }
        }
        }
    };
}
 
Example #17
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 #18
Source File: LocationUpdatesService.java    From location-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            onNewLocation(locationResult.getLastLocation());
        }
    };

    createLocationRequest();
    getLastLocation();

    HandlerThread handlerThread = new HandlerThread(TAG);
    handlerThread.start();
    mServiceHandler = new Handler(handlerThread.getLooper());
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Android O requires a Notification Channel.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        // Create the channel for the notification
        NotificationChannel mChannel =
                new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);

        // Set the Notification Channel for the Notification Manager.
        mNotificationManager.createNotificationChannel(mChannel);
    }
}
 
Example #19
Source File: GoogleLocationEngineImpl.java    From mapbox-events-android with MIT License 4 votes vote down vote up
@NonNull
@Override
public LocationCallback createListener(LocationEngineCallback<LocationEngineResult> callback) {
  return new GoogleLocationEngineCallbackTransport(callback);
}
 
Example #20
Source File: GetLocation.java    From xDrip-plus with GNU General Public License v3.0 4 votes vote down vote up
public synchronized static void getLocation() {

        final Context context = xdrip.getAppContext();


        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            UserError.Log.wtf(TAG, "No permission to obtain location");
            return;
        }


        mApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API)

                //.addConnectionCallbacks(context)
                //.addOnConnectionFailedListener(context)
                .build();

        mApiClient.blockingConnect(60, TimeUnit.SECONDS);


        final Runnable runnable = () -> {
            if (mApiClient.isConnected()) {
                @SuppressLint("MissingPermission") final Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
                if (location != null) {
                    lastLocation = location;
                    UserError.Log.d(TAG, location.toString());
                    lastAddress = getStreetLocation(location.getLatitude(), location.getLongitude());
                    UserError.Log.d(TAG, "Address: " + lastAddress);
                    addressUpdated = JoH.tsl();

                    if (ActivityCompat.checkSelfPermission(xdrip.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(xdrip.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        UserError.Log.wtf(TAG, "Could not determine location as permission has been removed!");
                        return;
                    }

                    final LocationCallback callback = getLocationCallback();

                    Inevitable.task("update gps location", 200, () -> {
                        UserError.Log.d(TAG, "Requesting live GPS updates");
                        LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient,
                                getLocationRequest(), callback, Looper.getMainLooper());
                    });
                    Inevitable.task("remove gps updates " + JoH.tsl(), GPS_ACTIVE_TIME,
                            () -> LocationServices.FusedLocationApi.removeLocationUpdates(mApiClient, callback));

                } else {
                    UserError.Log.e(TAG, "Location result was null");
                    // TODO retry ?
                }
            } else {
                UserError.Log.e(TAG, "Could not connect google api");
            }
        };


        if (!mApiClient.isConnected()) {
            mApiClient.connect();
            UserError.Log.d(TAG, "Delaying location request as api not connected");
            Inevitable.task("get location", 5000, runnable);
        } else {
            runnable.run();
        }

    }
 
Example #21
Source File: GetLocation.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
public synchronized static void getLocation() {

        final Context context = xdrip.getAppContext();


        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            UserError.Log.wtf(TAG, "No permission to obtain location");
            return;
        }


        mApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API)

                //.addConnectionCallbacks(context)
                //.addOnConnectionFailedListener(context)
                .build();

        mApiClient.blockingConnect(60, TimeUnit.SECONDS);


        final Runnable runnable = () -> {
            if (mApiClient.isConnected()) {
                @SuppressLint("MissingPermission") final Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
                if (location != null) {
                    lastLocation = location;
                    UserError.Log.d(TAG, location.toString());
                    lastAddress = getStreetLocation(location.getLatitude(), location.getLongitude());
                    UserError.Log.d(TAG, "Address: " + lastAddress);
                    addressUpdated = JoH.tsl();

                    if (ActivityCompat.checkSelfPermission(xdrip.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                            && ActivityCompat.checkSelfPermission(xdrip.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        UserError.Log.wtf(TAG, "Could not determine location as permission has been removed!");
                        return;
                    }

                    final LocationCallback callback = getLocationCallback();

                    Inevitable.task("update gps location", 200, () -> {
                        UserError.Log.d(TAG, "Requesting live GPS updates");
                        LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient,
                                getLocationRequest(), callback, Looper.getMainLooper());
                    });
                    Inevitable.task("remove gps updates " + JoH.tsl(), GPS_ACTIVE_TIME,
                            () -> LocationServices.FusedLocationApi.removeLocationUpdates(mApiClient, callback));

                } else {
                    UserError.Log.e(TAG, "Location result was null");
                    // TODO retry ?
                }
            } else {
                UserError.Log.e(TAG, "Could not connect google api");
            }
        };


        if (!mApiClient.isConnected()) {
            mApiClient.connect();
            UserError.Log.d(TAG, "Delaying location request as api not connected");
            Inevitable.task("get location", 5000, runnable);
        } else {
            runnable.run();
        }

    }
 
Example #22
Source File: AndroidLocationProvider.java    From BLE-Indoor-Positioning with Apache License 2.0 4 votes vote down vote up
private LocationCallback getLocationCallback() {
    if (locationCallback == null) {
        locationCallback = createLocationCallback();
    }
    return locationCallback;
}
 
Example #23
Source File: FusedLocationModule.java    From react-native-fused-location with MIT License 4 votes vote down vote up
@SuppressWarnings("All")
@ReactMethod
public void getFusedLocation(boolean forceNewLocation, final Promise promise) {
    try {
        if (!areProvidersAvailable()) {
            promise.reject(TAG, ERROR_NO_LOCATION_PROVIDER);
            return;
        }
        if (!checkForPlayServices()) {
            promise.reject(TAG, ERROR_PLAY_SERVICES_NOT_FOUND);
            return;
        }
        if (ActivityCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getReactApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            promise.reject(TAG, ERROR_UNAUTHORIZED);
            return;
        }
        final GoogleApiClient googleApiClient;
        LocationRequest request = buildLR();
        googleApiClient = new GoogleApiClient.Builder(getReactApplicationContext())
                .addApi(LocationServices.API)
                .build();
        googleApiClient.blockingConnect();
        final Location location;
        if (!forceNewLocation) {
            location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        } else {
            location = null;
        }
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    super.onLocationResult(locationResult);
                    promise.resolve(convertLocationToJSON(locationResult.getLastLocation()));
                }

                @Override
                public void onLocationAvailability(LocationAvailability locationAvailability) {
                    super.onLocationAvailability(locationAvailability);
                    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
                    googleApiClient.disconnect();
                    if (!locationAvailability.isLocationAvailable()) {
                        promise.reject(TAG, "Location not available. Does your phone have GPS turned on and internet connectivity?");
                    }
                }
            }, null);
            return;
        }
        promise.resolve(convertLocationToJSON(location));
        googleApiClient.disconnect();
    } catch (Exception ex) {
        Log.e(TAG, "Native Location Module ERR - " + ex.toString());
        promise.reject(TAG, ex.toString());
    }
}
 
Example #24
Source File: GoogleLocationEngineImplTest.java    From mapbox-events-android with MIT License 4 votes vote down vote up
@Test
public void removeLocationUpdatesForInvalidListener() {
  LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.class);
  engine.removeLocationUpdates(callback);
  verify(fusedLocationProviderClientMock, never()).removeLocationUpdates(any(LocationCallback.class));
}
 
Example #25
Source File: GoogleLocationEngineImpl.java    From mapbox-events-android with MIT License 4 votes vote down vote up
@Override
public void removeLocationUpdates(@NonNull LocationCallback listener) {
  if (listener != null) {
    fusedLocationProviderClient.removeLocationUpdates(listener);
  }
}
 
Example #26
Source File: GglMapLocationManager.java    From FimiX8-RE with MIT License 4 votes vote down vote up
public void onStop() {
    if (this.mGoogleApiClient != null && this.mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(this.mGoogleApiClient, (LocationCallback) this);
        this.mGoogleApiClient.disconnect();
    }
}
 
Example #27
Source File: LocationProvider.java    From LocationAware with Apache License 2.0 4 votes vote down vote up
public void stopLocationUpdates(LocationCallback locationCallback) {
  locationProviderClient.removeLocationUpdates(locationCallback);
}
 
Example #28
Source File: LocationProvider.java    From LocationAware with Apache License 2.0 4 votes vote down vote up
@SuppressLint("MissingPermission")
public void startLocationUpdates(LocationCallback locationCallback) {
  locationProviderClient.requestLocationUpdates(getLocationRequest(), locationCallback, null);
}
 
Example #29
Source File: MainActivity.java    From GNSS_Compare with Apache License 2.0 4 votes vote down vote up
/**
 * Registers GNSS measurement event manager callback.
 */
private void registerLocationManager() {

    mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    gnssCallback = new GnssMeasurementsEvent.Callback() {
        @Override
        public void onGnssMeasurementsReceived(GnssMeasurementsEvent eventArgs) {
            super.onGnssMeasurementsReceived(eventArgs);

            Log.d(TAG, "onGnssMeasurementsReceived (MainActivity): invoked!");

            if (rawMeasurementsLogger.isStarted())
                rawMeasurementsLogger.onGnssMeasurementsReceived(eventArgs);
        }
    };

    final LocationRequest locationRequest = new LocationRequest();

    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setMaxWaitTime(500);
    locationRequest.setInterval(1000);
    locationRequest.setFastestInterval(100);

    locationCallback = new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {

            final Location lastLocation = locationResult.getLocations().get(locationResult.getLocations().size()-1);

            if(lastLocation != null) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for(DataViewer dataViewer : mPagerAdapter.getViewers()) {
                            dataViewer.onLocationFromGoogleServicesResult(lastLocation);
                        }
                    }
                });

                Log.i(TAG, "locationFromGoogleServices: New location (phone): "
                        + lastLocation.getLatitude() + ", "
                        + lastLocation.getLongitude() + ", "
                        + lastLocation.getAltitude());

            }
        }
    };

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        mFusedLocationClient.requestLocationUpdates(
                locationRequest,
                locationCallback,
                null);

        mLocationManager.registerGnssMeasurementsCallback(
                gnssCallback);


    }
}
 
Example #30
Source File: ControllerFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 4 votes vote down vote up
LocationCallbackReference(LocationCallback locationCallback) {
    weakLocationCallback = new WeakReference<>(locationCallback);
}