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

The following examples show how to use com.google.android.gms.location.LocationListener. 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: LeanplumLocationManagerTest.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * Tests for requestLocation.
 *
 * @throws Exception
 */
@Test
public void requestLocation() throws Exception {
  GoogleApiClient mockGoogleApiClient = mock(GoogleApiClient.class);
  doReturn(true).when(mockGoogleApiClient).isConnected();

  LocationManager mockLocationManager = spy(mLocationManager);
  Whitebox.setInternalState(mockLocationManager, "googleApiClient", mockGoogleApiClient);

  FusedLocationProviderApi mockLocationProviderApi = mock(FusedLocationProviderApi.class);
  Whitebox.setInternalState(LocationServices.class, "FusedLocationApi", mockLocationProviderApi);

  // Testing when a customer did not disableLocationCollection.
  Whitebox.invokeMethod(mockLocationManager, "requestLocation");
  verify(mockLocationProviderApi).requestLocationUpdates(any(GoogleApiClient.class),
      any(LocationRequest.class), any(LocationListener.class));

  // Testing when a customer disableLocationCollection.
  Leanplum.disableLocationCollection();
  Whitebox.invokeMethod(mockLocationManager, "requestLocation");
  verifyNoMoreInteractions(mockLocationProviderApi);
}
 
Example #2
Source File: LocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 6 votes vote down vote up
public void requestLocationUpdates(LocationRequest request, final LocationListener listener)
        throws RemoteException {
    if (nativeLocation != null) {
        nativeLocation.requestLocationUpdates(request, listener);
    } else {
        if (!listenerMap.containsKey(listener)) {
            listenerMap.put(listener, new ILocationListener.Stub() {
                @Override
                public void onLocationChanged(Location location) throws RemoteException {
                    listener.onLocationChanged(location);
                }
            });
        }
        getServiceInterface().requestLocationUpdatesWithPackage(request,
                listenerMap.get(listener), getContext().getPackageName());
    }
}
 
Example #3
Source File: LocationHelper.java    From PrayTime-Android with Apache License 2.0 6 votes vote down vote up
private void checkLocationAndInit() {
  if (sLastLocation == null) {
    sLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
  }

  if (sLastLocation == null) {
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, createLocationRequest(), new LocationListener() {
      @Override
      public void onLocationChanged(Location location) {
        sLastLocation = location;
        if (mCallback != null) {
          mCallback.onLocationChanged(sLastLocation);
        }
        initAppAfterCheckingLocation();
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
      }
    });

  } else {
    initAppAfterCheckingLocation();
  }
}
 
Example #4
Source File: GooglePlayClientWrapper.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
public GooglePlayClientWrapper(final AbstractBarterLiActivity activity, final LocationListener locationListener) {
    mActivity = activity;
    mLocationClient = new LocationClient(mActivity, this, this);
    mLocationListener = locationListener;
    mLocationRequest = LocationRequest
                    .create()
                    .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                    .setInterval(UPDATE_INTERVAL)
                    .setFastestInterval(FASTEST_INTERVAL);
}
 
Example #5
Source File: LocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 5 votes vote down vote up
public void removeLocationUpdates(LocationListener listener) throws RemoteException {
    if (nativeLocation != null) {
        nativeLocation.removeLocationUpdates(listener);
    } else {
        getServiceInterface().removeLocationUpdatesWithListener(listenerMap.get(listener));
    }
}
 
Example #6
Source File: LocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 5 votes vote down vote up
public void requestLocationUpdates(LocationRequest request, LocationListener listener,
                                   Looper looper) throws RemoteException {
    if (nativeLocation != null) {
        nativeLocation.requestLocationUpdates(request, listener, looper);
    }
    requestLocationUpdates(request, listener); // TODO
}
 
Example #7
Source File: NativeLocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 5 votes vote down vote up
public void requestLocationUpdates(LocationRequest request, LocationListener listener, Looper
        looper) {
    Log.d(TAG, "requestLocationUpdates()");
    if (nativeListenerMap.containsKey(listener)) {
        removeLocationUpdates(listener);
    }
    nativeListenerMap.put(listener, new NativeListener(listener, request.getNumUpdates()));
    locationManager.requestLocationUpdates(request.getInterval(),
            request.getSmallestDesplacement(), makeNativeCriteria(request),
            nativeListenerMap.get(listener), looper);
}
 
Example #8
Source File: LocationService.java    From go-bees with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stop requesting location updates.
 *
 * @param listener LocationListener.
 */
void stopLocationUpdates(LocationListener listener) {
    if (locationRequest != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                googleApiClient, listener);
    }
}
 
Example #9
Source File: LocationService.java    From go-bees with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Start requesting location updates.
 *
 * @param listener LocationListener.
 */
void startLocationUpdates(LocationListener listener) {
    if (locationRequest != null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                googleApiClient, locationRequest, listener);
    }
}
 
Example #10
Source File: LocationService.java    From go-bees with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Configure parameters for requests to the fused location provider.
 *
 * @param callback LocationListener.
 */
void createLocationRequest(LocationListener callback) {
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
            locationRequest, callback);
}
 
Example #11
Source File: MyTracksLocationManager.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Removes location updates.
 * 
 * @param locationListener the location listener
 */
public void removeLocationUpdates(final LocationListener locationListener) {
  handler.post(new Runnable() {
      @Override
    public void run() {
      requestLocationUpdates = null;
      if (locationClient != null && locationClient.isConnected()) {
        locationClient.removeLocationUpdates(locationListener);
      }
    }
  });
}
 
Example #12
Source File: MyTracksLocationManager.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Requests location updates. This is an ongoing request, thus the caller
 * needs to check the status of {@link #isAllowed}.
 * 
 * @param minTime the minimal time
 * @param minDistance the minimal distance
 * @param locationListener the location listener
 */
public void requestLocationUpdates(
    final long minTime, final float minDistance, final LocationListener locationListener) {
  handler.post(new Runnable() {
      @Override
    public void run() {
      requestLocationUpdatesTime = minTime;
      requestLocationUpdatesDistance = minDistance;
      requestLocationUpdates = locationListener;
      connectionCallbacks.onConnected(null);
    }
  });
}
 
Example #13
Source File: MyTracksLocationManager.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Request last location.
 * 
 * @param locationListener location listener
 */
public void requestLastLocation(final LocationListener locationListener) {
  handler.post(new Runnable() {
      @Override
    public void run() {
      if (!isAllowed()) {
        requestLastLocation = null;
        locationListener.onLocationChanged(null);
      } else {
        requestLastLocation = locationListener;
        connectionCallbacks.onConnected(null);
      }
    }
  });
}
 
Example #14
Source File: SearchListActivity.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the intent.
 * 
 * @param intent the intent
 */
private void handleIntent(Intent intent) {
  if (!Intent.ACTION_SEARCH.equals(intent.getAction())) {
    Log.e(TAG, "Invalid intent action: " + intent);
    finish();
    return;
  }

  final String textQuery = intent.getStringExtra(SearchManager.QUERY);
  setTitle(textQuery);

  final MyTracksLocationManager myTracksLocationManager = new MyTracksLocationManager(
      this, Looper.myLooper(), true);
  LocationListener locationListener = new LocationListener() {
      @Override
    public void onLocationChanged(final Location location) {
      myTracksLocationManager.close();
      new Thread() {
          @Override
        public void run() {
          SearchQuery query = new SearchQuery(
              textQuery, location, -1L, System.currentTimeMillis());
          doSearch(query);
        }
      }.start();
    }
  };
  myTracksLocationManager.requestLastLocation(locationListener);
}
 
Example #15
Source File: LocationAsyncEmitter.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void call(AsyncEmitter<Location> locationAsyncEmitter) {

    LocationListener locationListener = locationAsyncEmitter::onNext;

    GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener = connectionResult ->
            locationAsyncEmitter.onError(new LocationUnavailableException("Failed to connect to Google Play Services!"));

    GoogleApiClient.ConnectionCallbacks connectionCallbacks = new GoogleApiClient.ConnectionCallbacks() {
        @Override
        public void onConnected(@Nullable Bundle bundle) {
            try {
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, locationListener);
            } catch (SecurityException e) {
                locationAsyncEmitter.onError(new LocationUnavailableException("Location permission not available!"));
            }
        }

        @Override
        public void onConnectionSuspended(int i) {
            locationAsyncEmitter.onError(new LocationUnavailableException("Connection lost to Google Play Services"));

        }
    };

    googleApiClient.registerConnectionCallbacks(connectionCallbacks);
    googleApiClient.registerConnectionFailedListener(onConnectionFailedListener);
    googleApiClient.connect();

    locationAsyncEmitter.setCancellation(() -> {
        LocationAsyncEmitter.this.locationRequest = null;
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener);
        googleApiClient.unregisterConnectionCallbacks(connectionCallbacks);
        googleApiClient.unregisterConnectionFailedListener(onConnectionFailedListener);
    });
}
 
Example #16
Source File: LocatrFragment.java    From AndroidProgramming3e with Apache License 2.0 5 votes vote down vote up
private void findImage() {
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setNumUpdates(1);
    request.setInterval(0);
    LocationServices.FusedLocationApi
            .requestLocationUpdates(mClient, request, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.i(TAG, "Got a fix: " + location);
                    new SearchTask().execute(location);
                }
            });
}
 
Example #17
Source File: LocatrFragment.java    From AndroidProgramming3e with Apache License 2.0 5 votes vote down vote up
private void findImage() {
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setNumUpdates(1);
    request.setInterval(0);
    LocationServices.FusedLocationApi
            .requestLocationUpdates(mClient, request, new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Log.i(TAG, "Got a fix: " + location);
                    new SearchTask().execute(location);
                }
            });
}
 
Example #18
Source File: LocationController.java    From DebugDrawer with Apache License 2.0 4 votes vote down vote up
void setLocationListener(LocationListener listener) {
    locationListener = listener;
}
 
Example #19
Source File: NativeLocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 4 votes vote down vote up
public void requestLocationUpdates(LocationRequest request, LocationListener listener) {
    requestLocationUpdates(request, listener, Looper.getMainLooper());
}
 
Example #20
Source File: NativeLocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 4 votes vote down vote up
public void removeLocationUpdates(LocationListener listener) {
    Log.d(TAG, "removeLocationUpdates()");
    locationManager.removeUpdates(nativeListenerMap.get(listener));
    nativeListenerMap.remove(listener);
}
 
Example #21
Source File: NativeLocationClientImpl.java    From android_external_GmsLib with Apache License 2.0 4 votes vote down vote up
private NativeListener(LocationListener listener, int count) {
    this.listener = listener;
    this.count = count;
}
 
Example #22
Source File: RequestListenerService.java    From arcgis-runtime-demos-android with Apache License 2.0 4 votes vote down vote up
/**
 * Handles issuing a response to a FeatureType response. A FeatureType response
 * indicates that the Wear devices wants a feature of the specified FeatureType
 * to be collected at the current device location.
 *
 * @param event the MessageEvent from the Wear device
 * @param client the Google API client used to communicate
 */
private void handleFeatureTypeResponse(final MessageEvent event, final GoogleApiClient client) {
  // Create a PutDataMapRequest with the status response path
  final PutDataMapRequest req = PutDataMapRequest.create(STATUS_RESPONSE);
  final DataMap dm = req.getDataMap();
  // Put the current time into the data map, which forces an onDataChanged event (this event
  // only occurs when data actually changes, so putting the time ensures something always changes)
  dm.putLong("Time", System.currentTimeMillis());
  try {
    // Request a single high precision location update
    LocationRequest request = LocationRequest.create()
            .setNumUpdates(1)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(client, request, new LocationListener() {
      @Override
      public void onLocationChanged(Location location) {
        // When we've got a location, get the FeatureType that matches the specified name
        Log.i("Test", "Received location");
        String featureTypeName = new String(event.getData());
        FeatureType type = null;
        for (FeatureType ft : sArcGISFeatureLayer.getTypes()) {
          if (ft.getName().equals(featureTypeName)) {
            type = ft;
            break;
          }
        }
        // Only proceed if we found a matching type (which we always should)
        if (type != null) {
          // Create a new feature of the specified type at the current location
          Graphic g = sArcGISFeatureLayer.createFeatureWithType(type, new Point(location.getLongitude(), location.getLatitude()));
          // Apply the edit to the service
          sArcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
            @Override
            public void onCallback(FeatureEditResult[][] featureEditResults) {
              // Check that we have a success and report success
              if (featureEditResults[0].length > 0) {
                FeatureEditResult fer = featureEditResults[0][0];
                if (fer.isSuccess()) {
                  Log.i("Test", "Successfully added feature");
                  // Put a boolean indicating success into the data map
                  dm.putBoolean("success", true);
                } else {
                  Log.e("Test", "Failed to add feature: " + fer.getError().getDescription());
                  // Put a boolean indicating failure into the data map
                  dm.putBoolean("success", false);
                  // Put a string with the reason for failure into the data map
                  dm.putString("reason", "Error code: " + fer.getError().getCode());
                }
              }
              // Put the DataItem into the Data API stream
              Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
            }

            @Override
            public void onError(Throwable throwable) {
              Log.d("Test", "Failed to add new graphic");
              // Put a boolean indicating failure into the data map
              dm.putBoolean("success", false);
              // Put a string with the reason for failure into the data map
              dm.putString("reason", throwable.getLocalizedMessage());
              // Put the DataItem into the Data API stream
              Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
            }
          });
        } else {
          // If we don't have a matching feature type (which should never happen), log an error
          Log.e("Test", "Could not determine type");
          // Put a boolean indicating failure into the data map
          dm.putBoolean("success", false);
          // Put a string with the reason for failure into the data map
          dm.putString("reason", "Specified type not found");
          // Put the DataItem into the Data API stream
          Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
        }
      }
    });
  } catch (SecurityException se) {
    // If we caught an exception trying to get the location, likelihood is that the location
    // permission has not been granted by the user
    Log.e("Test", "Could not access location");
    // Put a boolean indicating failure into the data map
    dm.putBoolean("success", false);
    // Put a string with the reason for failure into the data map
    dm.putString("reason", "Could not access location. Check permissions.");
    // Put the DataItem into the Data API stream
    Wearable.DataApi.putDataItem(client, req.asPutDataRequest());
  }
}
 
Example #23
Source File: CollectionActivity.java    From arcgis-runtime-demos-android with Apache License 2.0 4 votes vote down vote up
/**
 * Collects a feature of the specified type at the current device location.
 *
 * @param featureTypeName the type of feature to collect
 */
private void collectFeature(final String featureTypeName) {
  try {
    // Request a single high precision location update
    LocationRequest request = LocationRequest.create()
            .setNumUpdates(1)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, new LocationListener() {
      @Override
      public void onLocationChanged(Location location) {
        // When we've got a location, get the FeatureType that matches the specified name
        FeatureType type = null;
        for (FeatureType ft : mArcGISFeatureLayer.getTypes()) {
          if (ft.getName().equals(featureTypeName)) {
            type = ft;
            break;
          }
        }
        // Only proceed if we found a matching type (which we always should)
        if (type != null) {
          // Create a new feature of the specified type at the current location
          Graphic g = mArcGISFeatureLayer.createFeatureWithType(type, new Point(location.getLongitude(), location.getLatitude()));
          // Apply the edit to the service
          mArcGISFeatureLayer.applyEdits(new Graphic[]{g}, null, null, new CallbackListener<FeatureEditResult[][]>() {
            @Override
            public void onCallback(FeatureEditResult[][] featureEditResults) {
              // Check that we have a success and report success
              if (featureEditResults[0].length > 0) {
                FeatureEditResult fer = featureEditResults[0][0];
                if (fer.isSuccess()) {
                  Log.i("Test", "Successfully added feature: " + fer.getObjectId());
                  Toast.makeText(CollectionActivity.this, "Successful collection!", Toast.LENGTH_SHORT).show();
                } else {
                  Log.e("Test", "Failed to add feature: " + fer.getError().getDescription());
                }
              }
            }

            @Override
            public void onError(Throwable throwable) {
              Log.e("Test", "Failed to add new graphic");
            }
          });
        } else {
          // If we don't have a matching feature type (which should never happen), log an error
          Log.e("Test", "Could not determine type");
        }
      }
    });
  } catch (SecurityException se) {
    // If we caught an exception trying to get the location, likelihood is that the location
    // permission has not been granted by the user
    Log.e("Test", "Could not access location. Check permissions.");
  }
}