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

The following examples show how to use com.google.android.gms.location.LocationServices. 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: MainActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
public void addGeofencesButtonHandler(View view) {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, "Google API Client not connected!", Toast.LENGTH_SHORT).show();
        return;
    }

    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
    }
}
 
Example #2
Source File: MainActivity.java    From location-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    // Get the UI widgets.
    mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
    mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button);

    // Empty list for storing geofences.
    mGeofenceList = new ArrayList<>();

    // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null.
    mGeofencePendingIntent = null;

    setButtonsEnabledState();

    // Get the geofences used. Geofence data is hard coded in this sample.
    populateGeofenceList();

   mGeofencingClient = LocationServices.getGeofencingClient(this);
}
 
Example #3
Source File: LocationController.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public LocationController(int instance) {
    super(instance);

    locationManager = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE);
    googleApiClient = new GoogleApiClient.Builder(ApplicationLoader.applicationContext).
            addApi(LocationServices.API).
            addConnectionCallbacks(this).
            addOnConnectionFailedListener(this).build();

    locationRequest = new LocationRequest();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(UPDATE_INTERVAL);
    locationRequest.setFastestInterval(FASTEST_INTERVAL);

    AndroidUtilities.runOnUIThread(() -> {
        LocationController locationController = getAccountInstance().getLocationController();
        getNotificationCenter().addObserver(locationController, NotificationCenter.didReceiveNewMessages);
        getNotificationCenter().addObserver(locationController, NotificationCenter.messagesDeleted);
        getNotificationCenter().addObserver(locationController, NotificationCenter.replaceMessagesObjects);
    });
    loadSharingLocations();
}
 
Example #4
Source File: HomeFragment.java    From SEAL-Demo with MIT License 6 votes vote down vote up
private void startLocationClient() {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(myContext);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    mStartButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //start run activity
            Intent myIntent = new Intent(myContext, RunActivity.class);
            myContext.startActivity(myIntent);
            stopLocationUpdate();
        }
    });

}
 
Example #5
Source File: AppLocationSupportFragment.java    From GooglePlayServiceLocationSupport with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiAvailability = GoogleApiAvailability.getInstance();
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).
            addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

    mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

    mLocationRequest = LocationRequest.create();

    Bundle bundle = getArguments();
    if (bundle != null)
        enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true);
    else
        enableUpdates = true;

}
 
Example #6
Source File: NearByHospitalActivity.java    From BloodBank with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.gMap);
    if (mapFragment != null) {
        mapFragment.getMapAsync(this);
    }
    else
    {
        Toast.makeText(getActivity(), "MapFragment is null, why?", Toast.LENGTH_LONG).show();
    }

}
 
Example #7
Source File: MapsActivity.java    From android-location-example with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    setUpMapIfNeeded();

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
 
Example #8
Source File: GeofenceApiHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
private void removeGeofence(GoogleApiClient googleApiClient, final String geofenceId) {
    ArrayList<String> geofenceIds = new ArrayList<>();
    geofenceIds.add(geofenceId);

    LocationServices.GeofencingApi.removeGeofences(
            googleApiClient,
            geofenceIds
    ).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            switch (status.getStatusCode()) {
                case CommonStatusCodes.SUCCESS:
                    StatusMessageHandler.showInfoMessage(context, R.string.geofence_disabled, Snackbar.LENGTH_SHORT);
            }

            Log.d(GeofenceApiHandler.class, status.toString());
        }
    }); // Result processed in onResult().
}
 
Example #9
Source File: GeofenceApiHandler.java    From PowerSwitch_Android with GNU General Public License v3.0 6 votes vote down vote up
private void addGeofence(GeofencingRequest geofencingRequest,
                         PendingIntent geofencePendingIntent) {
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager
            .PERMISSION_GRANTED) {
        return;
    }

    LocationServices.GeofencingApi.addGeofences(
            googleApiClient,
            geofencingRequest,
            geofencePendingIntent
    ).setResultCallback(new ResultCallback<Status>() {
        @Override
        public void onResult(@NonNull Status status) {
            switch (status.getStatusCode()) {
                case CommonStatusCodes.SUCCESS:
                    StatusMessageHandler.showInfoMessage(context, R.string.geofence_enabled, Snackbar.LENGTH_SHORT);
            }

            Log.d(GeofenceApiHandler.class, status.toString());
        }
    });
}
 
Example #10
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 #11
Source File: LocationSwitch.java    From react-native-location-switch with Apache License 2.0 6 votes vote down vote up
public void displayLocationSettingsRequest(final Activity activity) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(mAccuracy);
    locationRequest.setInterval(mInterval);
    locationRequest.setFastestInterval(mInterval / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    builder.setAlwaysShow(false);

    final PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new LocationResultCallback(activity));
}
 
Example #12
Source File: SplashActivity.java    From protrip with MIT License 6 votes vote down vote up
private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (mLastLocation != null) {
            mCurrentLat = String.valueOf(mLastLocation.getLatitude());
            mCurrentLng = String.valueOf(mLastLocation.getLongitude());
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(mCurrentLat), Double.parseDouble(mCurrentLng), 1);
                //mCurrentLocName = addresses.get(0).getLocality();
                mCurrentLocName = addresses.get(0).getAddressLine(1);

            } catch (Exception e) {
                Log.d(TAG, "Exception");
            }
        }
        skip();
    }

}
 
Example #13
Source File: AppLocationActivity.java    From GooglePlayServiceLocationSupport with Apache License 2.0 6 votes vote down vote up
private void requestLocationUpdates() {
    if (enableUpdates) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
        else {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            requestForCurrentLocation();
        }
    } else {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
        else {
            requestForCurrentLocation();
        }
    }
}
 
Example #14
Source File: LocationActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing15_5() {
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);
  if (permission == PERMISSION_GRANTED) {

    // LISTING 15-5: Obtaining the last known device Location
    FusedLocationProviderClient fusedLocationClient;
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    fusedLocationClient.getLastLocation()
      .addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
          // In some rare situations this can be null.
          if (location != null) {
            // TODO Do something with the returned location.
          }
        }
      });
  }
}
 
Example #15
Source File: BaseActivity.java    From mvvm-starter with MIT License 6 votes vote down vote up
public void initLocationDetection ()
{
    if (app.mGoogleApiClient == null)
    {
        //check for location permission
        if (EasyPermissions.hasPermissions(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION))
        {
            app.mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                                                                    .addOnConnectionFailedListener(this)
                                                                    .addApi(LocationServices.API)
                                                                    .build();
        }
    }
    else
    {
        app.mGoogleApiClient.connect();
    }
}
 
Example #16
Source File: MainActivity.java    From location-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    mResultReceiver = new AddressResultReceiver(new Handler());

    mLocationAddressTextView = (TextView) findViewById(R.id.location_address_view);
    mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
    mFetchAddressButton = (Button) findViewById(R.id.fetch_address_button);

    // Set defaults, then update using values stored in the Bundle.
    mAddressRequested = false;
    mAddressOutput = "";
    updateValuesFromBundle(savedInstanceState);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    updateUIWidgets();
}
 
Example #17
Source File: LocationManagerImplementation.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * RequestOld location for user location update if googleApiClient is connected.
 */
// Suppressing missing permission warning which since it is up to client to add location
// permission to their manifest.
@SuppressWarnings("MissingPermission")
private void requestLocation() {
  try {
    if (!Leanplum.isLocationCollectionEnabled() || googleApiClient == null
        || !googleApiClient.isConnected()) {
      return;
    }
    LocationRequest request = new LocationRequest();
    // Although we set the interval as |LOCATION_REQUEST_INTERVAL|, we stop listening
    // |onLocationChanged|. So we are essentially requesting location only once.
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        .setInterval(LOCATION_REQUEST_INTERVAL)
        .setFastestInterval(LOCATION_REQUEST_INTERVAL);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, this);
  } catch (Throwable throwable) {
    Log.e("Cannot request location updates.", throwable);
  }
}
 
Example #18
Source File: LocatrFragment.java    From AndroidProgramming3e with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);

    mClient = new GoogleApiClient.Builder(getActivity()).addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                    getActivity().invalidateOptionsMenu();
                }

                @Override
                public void onConnectionSuspended(int i) {

                }
            })
            .build();
}
 
Example #19
Source File: AppLocationFragment.java    From GooglePlayServiceLocationSupport with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiAvailability = GoogleApiAvailability.getInstance();
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).
            addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

    mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);

    mLocationRequest = LocationRequest.create();

    Bundle bundle = getArguments();
    if (bundle != null)
        enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true);
    else
        enableUpdates = true;

}
 
Example #20
Source File: LocationService.java    From io.appium.settings with Apache License 2.0 5 votes vote down vote up
private FusedLocationProvider createFusedLocationProvider() {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .build();
    FusedLocationProviderClient locationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    return new FusedLocationProvider(googleApiClient, locationProviderClient, this);
}
 
Example #21
Source File: MainActivity.java    From HRCarMarkerAnimation with MIT License 5 votes vote down vote up
public void displayLocation() {
    try {

        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
            // Check Permissions Now
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_LOCATION);
        } else {


            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (mLastLocation != null && mLastLocation.getLongitude() != 0.0 && mLastLocation.getLongitude() != 0.0) {

                if (mMap != null) {
                    addMarker(mMap, mLastLocation.getLatitude(), mLastLocation.getLongitude());

                }

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: TimeAttendantFastFragment.java    From iBeacon-Android with Apache License 2.0 5 votes vote down vote up
private void settingLocationRequest() {
    googleApiClient = new GoogleApiClient.Builder(getContext())
            .addApi(LocationServices.API).build();
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);
}
 
Example #23
Source File: MapLoadFragment.java    From Stayfit with Apache License 2.0 5 votes vote down vote up
private void buildGoogleApiClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
}
 
Example #24
Source File: LocationBackgroundService.java    From rn-background-location with MIT License 5 votes vote down vote up
@SuppressLint("MissingPermission")
@Override
protected void onHandleIntent(@Nullable Intent intent) {
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
    mLocationCallback = createLocationRequestCallback();

    LocationRequest locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(0)
            .setFastestInterval(0);

    new Handler(getMainLooper()).post(() -> mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, null));
}
 
Example #25
Source File: PlacesFragment.java    From nearby-android with Apache License 2.0 5 votes vote down vote up
@Override
public final void onConnected(@Nullable final Bundle bundle) {
  if (ContextCompat.checkSelfPermission(this.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    final Task getLocationTask = LocationServices.getFusedLocationProviderClient(this.getContext()).getLastLocation();
    getLocationTask.addOnCompleteListener(this.getActivity(), new OnCompleteListener<Location>() {
      @Override
      public void onComplete(@NonNull Task<Location> task) {
        startPresenter((Location) getLocationTask.getResult());
      }
    });
  } else {
    startPresenter(null);
  }
}
 
Example #26
Source File: AppLocationCompatActivity.java    From GooglePlayServiceLocationSupport with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiAvailability = GoogleApiAvailability.getInstance();
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, this).
            addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();

    mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mLocationRequest = LocationRequest.create();

    Intent intent = getIntent();
    enableUpdates = intent.getBooleanExtra(AppLocation.REQUEST_UPDATES, true);
}
 
Example #27
Source File: MockWalker.java    From AndroidProgramming3e with Apache License 2.0 5 votes vote down vote up
private MockWalker(Context context) {
    mContext = context.getApplicationContext();
    mChanges = PublishSubject.create();
    mClient = new GoogleApiClient.Builder(mContext)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .build();
    mClient.connect();
}
 
Example #28
Source File: MapsActivity.java    From Self-Driving-Car with MIT License 5 votes vote down vote up
@Override
public void onConnected(@Nullable Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(100);
    mLocationRequest.setFastestInterval(100);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
}
 
Example #29
Source File: LocationBgService.java    From Android-EasyLocation with Apache License 2.0 5 votes vote down vote up
private void stopLocationService() {
    if(handler!=null)
        handler.removeCallbacksAndMessages(null);

    Log.d(TAG,"googleApiClient removing location updates");
    if(googleApiClient!=null && googleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
        Log.d(TAG,"googleApiClient disconnect");
        googleApiClient.disconnect();
    }
    Log.d(TAG,"googleApiClient stop service");
    stopSelf();
}
 
Example #30
Source File: LocationController.java    From DebugDrawer with Apache License 2.0 5 votes vote down vote up
void stopLocationUpdates() {
    if (connected && locationRequest != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, locationListener);
        googleApiClient.disconnect();
        connected = false;
        isStarted = false;
    }
}