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

The following examples show how to use com.google.android.gms.location.LocationSettingsResponse. 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: PlaceSearchFragment.java    From Place-Search-Service with MIT License 5 votes vote down vote up
private void startLocationUpdates() {
    mRequestingLocationUpdates = true;
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions();
                        return;
                    }
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                            mLocationCallback, Looper.myLooper());
                }
            })
            .addOnFailureListener((Activity) context, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
                                    "location settings ");
                            try {
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult((Activity) context, REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sie) {
                                Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, and cannot be " +
                                    "fixed here. Fix in Settings.";
                            Log.e(TAG, errorMessage);
                            Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show();
                            mRequestingLocationUpdates = false;
                    }
                }
            });
}
 
Example #2
Source File: BasePlatformCreate.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initiate location updates.
 */
private void initiateLocationUpdates() {

    // Set wrapper and coordinates visible (if it wasn't already).
    toggleLocationVisibilities(true);

    mSettingsClient
            .checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @SuppressLint("MissingPermission")
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                    updateLocationUI();
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(BasePlatformCreate.this, REQUEST_CHECK_LOCATION_SETTINGS);
                            }
                            catch (IntentSender.SendIntentException sie) {
                                Toast.makeText(getApplicationContext(), getString(R.string.location_intent_error), Toast.LENGTH_SHORT).show();
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            Toast.makeText(getApplicationContext(), getString(R.string.location_settings_error), Toast.LENGTH_LONG).show();
                    }
                }
            });
}
 
Example #3
Source File: EasyWayLocation.java    From EasyWayLocation with Apache License 2.0 5 votes vote down vote up
private void checkLocationSetting(){
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.setAlwaysShow(true);
    builder.addLocationRequest(locationRequest);
    SettingsClient client = LocationServices.getSettingsClient(context);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(locationSettingsResponse -> {
        if (mRequireLastLocation){
            beginUpdates();
            endUpdates();
        }else {
            beginUpdates();
        }

    });

    task.addOnFailureListener(e -> {
        if (e instanceof ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult((Activity)context,
                        LOCATION_SETTING_REQUEST_CODE);
            } catch (IntentSender.SendIntentException sendEx) {
                    sendEx.printStackTrace();
            }
        }
    });
}
 
Example #4
Source File: MyLocationMapActivity.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
/**
 * This turns on Wifi/cell location tracking using Google Play services
 * It shows a dismissible dialog for users that don't have location already enabled
 */
@SuppressLint("MissingPermission")
public void turnOnLocation() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(500);
    locationRequest.setFastestInterval(250);
    locationRequest.setPriority(Utils.useGPSForLocation(this) ? LocationRequest.PRIORITY_HIGH_ACCURACY : LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

    LocationSettingsRequest settingsRequest = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)
            .setAlwaysShow(true)
            .build();

    Task<LocationSettingsResponse> task = LocationServices.getSettingsClient(this).checkLocationSettings(settingsRequest);
    task.addOnSuccessListener(this, locationSettingsResponse -> {
        goToLastLocation(false);
    });

    task.addOnFailureListener(this, e -> {
        if (e instanceof ResolvableApiException) {
            if (isLocationDialogShowing) {
                return;
            }

            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult(MyLocationMapActivity.this, REQUEST_TURN_ON_LOCATION);

                isLocationDialogShowing = true;
            } catch (IntentSender.SendIntentException sendEx) {
                // Ignore the error.
            }
        }
    });
}
 
Example #5
Source File: AndroidLocationProvider.java    From BLE-Indoor-Positioning with Apache License 2.0 5 votes vote down vote up
private void setupLocationService() {
    Log.v(TAG, "Setting up location service");
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(getLocationRequest());
    SettingsClient client = LocationServices.getSettingsClient(activity);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(activity, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            Log.v(TAG, "Location settings satisfied");
        }
    });

    task.addOnFailureListener(activity, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            int statusCode = ((ApiException) e).getStatusCode();
            switch (statusCode) {
                case CommonStatusCodes.RESOLUTION_REQUIRED:
                    Log.w(TAG, "Location settings not satisfied, attempting resolution intent");
                    try {
                        ResolvableApiException resolvable = (ResolvableApiException) e;
                        resolvable.startResolutionForResult(activity, REQUEST_CODE_LOCATION_SETTINGS);
                    } catch (IntentSender.SendIntentException sendIntentException) {
                        Log.e(TAG, "Unable to start resolution intent");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.w(TAG, "Location settings not satisfied and can't be changed");
                    break;
            }
        }
    });
}
 
Example #6
Source File: LocationProvider.java    From LocationAware with Apache License 2.0 5 votes vote down vote up
public void setUpLocationRequest(OnSuccessListener<LocationSettingsResponse> successListener,
    OnFailureListener onFailureListener) {
  LocationRequest locationRequest = getLocationRequest();
  LocationSettingsRequest.Builder builder =
      new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
  SettingsClient settingsClient = LocationServices.getSettingsClient(context);
  Task<LocationSettingsResponse> locationSettingsResponseTask =
      settingsClient.checkLocationSettings(builder.build());

  locationSettingsResponseTask.addOnSuccessListener(successListener);

  locationSettingsResponseTask.addOnFailureListener(onFailureListener);
}
 
Example #7
Source File: MainActivity.java    From location-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Requests location updates from the FusedLocationApi. Note: we don't call this unless location
 * runtime permission has been granted.
 */
private void startLocationUpdates() {
    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                            mLocationCallback, Looper.myLooper());

                    updateUI();
                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
                                    "location settings ");
                            try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sie) {
                                Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, and cannot be " +
                                    "fixed here. Fix in Settings.";
                            Log.e(TAG, errorMessage);
                            Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                            mRequestingLocationUpdates = false;
                    }

                    updateUI();
                }
            });
}
 
Example #8
Source File: LocationGetLocationActivity.java    From coursera-android with MIT License 4 votes vote down vote up
private void continueAcquiringLocations() {

        // Start location services
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(POLLING_FREQ);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        // Used if needed to turn on settings related to location services
        SettingsClient client = LocationServices.getSettingsClient(this);
        Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
        task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                // All location settings are satisfied. The client can initialize location requests here.
                if (checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLocationCallback = getLocationCallback();
                    mLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);

                    // Schedule a runnable to stop location updates after a period of time
                    Executors.newScheduledThreadPool(1).schedule(new Runnable() {
                        @Override
                        public void run() {
                            mLocationClient.removeLocationUpdates(mLocationCallback);
                        }
                    }, MEASURE_TIME, TimeUnit.MILLISECONDS);
                }
            }
        });

        task.addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                int statusCode = ((ApiException) e).getStatusCode();
                switch (statusCode) {
                    case CommonStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied, but this can be fixed
                        // by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            ResolvableApiException resolvable = (ResolvableApiException) e;
                            resolvable.startResolutionForResult(LocationGetLocationActivity.this,
                                    REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way
                        // to fix the settings so we won't show the dialog.
                        break;
                }
            }
        });
    }
 
Example #9
Source File: SamLocationRequestService.java    From SamLocationAndGeocoding with MIT License 4 votes vote down vote up
private void setGoogleClient(){

            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(30 * 1000);
            mLocationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(mLocationRequest);

            //**************************
            builder.setAlwaysShow(true); //this is the key ingredient
            //**************************

            Task<LocationSettingsResponse> result =
                    LocationServices.getSettingsClient(context).checkLocationSettings( builder.build());

            result.addOnFailureListener((Activity) context, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    if (statusCode
                            == LocationSettingsStatusCodes
                            .RESOLUTION_REQUIRED) {
                        // Location settings are not satisfied, but this can
                        // be fixed by showing the user a dialog
                        try {
                            // Show the dialog by calling
                            // startResolutionForResult(), and check the
                            // result in onActivityResult()
                            ResolvableApiException resolvable =
                                    (ResolvableApiException) e;
                            resolvable.startResolutionForResult
                                    ((Activity) context,
                                            REQUEST_CODE);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error
                        }
                    }
                }
            });

            result.addOnSuccessListener((Activity) context, new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    startLocationUpdates();
                }
            });


    }
 
Example #10
Source File: BaseNiboFragment.java    From Nibo with MIT License 4 votes vote down vote up
/**
 * Requests location updates from the FusedLocationApi. Note: we don't call this unless location
 * runtime permission has been granted.
 */
private void startLocationUpdates() {
    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(getAppCompatActivity(), new OnSuccessListener<LocationSettingsResponse>() {
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");


                    //noinspection MissingPermission
                    if (checkPermissions()) {
                        mMap.setMyLocationEnabled(true);
                        mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                                mLocationCallback, Looper.myLooper());
                    }

                }
            })
            .addOnFailureListener(getAppCompatActivity(), new OnFailureListener() {
                @Override
                public void onFailure(@android.support.annotation.NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
                                    "location settings ");
                            try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sie) {
                                Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, and cannot be " +
                                    "fixed here. Fix in Settings.";
                            Log.e(TAG, errorMessage);
                            displayError(errorMessage);
                    }
                }
            });
}
 
Example #11
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onStart() {
  super.onStart();

  // Check if we have permission to access high accuracy fine location.
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);

  // If permission is granted, fetch the last location.
  if (permission == PERMISSION_GRANTED) {
    getLastLocation();
  } else {
    // If permission has not been granted, request permission.
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }

  // Check of the location settings are compatible with our Location Request.
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder()
      .addLocationRequest(mLocationRequest);

  SettingsClient client = LocationServices.getSettingsClient(this);

  Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse
                              locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request.
        // Request location updates.
        requestLocationUpdates();
      }
    });

  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();

      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          try {
            // Display a user dialog to resolve the location settings
            // issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(WhereAmIActivity.this,
              REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings issues can't be resolved by user.
          // Request location updates anyway.
          Log.d(TAG, "Location Settings can't be resolved.");
          requestLocationUpdates();
          break;
      }
    }
  });
}
 
Example #12
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onStart() {
  super.onStart();

  // Check if we have permission to access high accuracy fine location.
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);

  // If permission is granted, fetch the last location.
  if (permission == PERMISSION_GRANTED) {
    getLastLocation();
  } else {
    // If permission has not been granted, request permission.
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }

  // Check of the location settings are compatible with our Location Request.
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder()
      .addLocationRequest(mLocationRequest);

  SettingsClient client = LocationServices.getSettingsClient(this);

  Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse
                              locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request.
        // Request location updates.
        requestLocationUpdates();
      }
    });

  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();

      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          try {
            // Display a user dialog to resolve the location settings
            // issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(WhereAmIActivity.this,
              REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings issues can't be resolved by user.
          // Request location updates anyway.
          Log.d(TAG, "Location Settings can't be resolved.");
          requestLocationUpdates();
          break;
      }
    }
  });
}
 
Example #13
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onStart() {
  super.onStart();

  // Check if we have permission to access high accuracy fine location.
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);

  // If permission is granted, fetch the last location.
  if (permission == PERMISSION_GRANTED) {
    getLastLocation();
  } else {
    // If permission has not been granted, request permission.
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }

  // Check of the location settings are compatible with our Location Request.
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder()
      .addLocationRequest(mLocationRequest);

  SettingsClient client = LocationServices.getSettingsClient(this);

  Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse
                              locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request.
        // Request location updates.
        requestLocationUpdates();
      }
    });

  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();

      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          try {
            // Display a user dialog to resolve the location settings
            // issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(WhereAmIActivity.this,
              REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings issues can't be resolved by user.
          // Request location updates anyway.
          Log.d(TAG, "Location Settings can't be resolved.");
          requestLocationUpdates();
          break;
      }
    }
  });
}
 
Example #14
Source File: LocationActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
private void listing15_10_11_12() {
  LocationRequest request =
    new LocationRequest()
      .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
      .setInterval(5000); // Update every 5 seconds.

  // Listing 15-10: Check if the current Location Settings satisfy your requirements
  // Get the settings client.
  SettingsClient client = LocationServices.getSettingsClient(this);

  // Create a new Location Settings Request, adding our Location Requests
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder().addLocationRequest(request);

  // Check if the Location Settings satisfy our requirements.
  Task<LocationSettingsResponse> task =
    client.checkLocationSettings(builder.build());

  // Listing 15-11: Create a handler for when Location Settings satisfy your requirements
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request
        startTrackingLocation();
      }
    });

  // Listing 15-12: Request user changes to location settings
  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();
      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          // Location settings don't satisfy the requirements of the
          // Location Request, but they could be resolved through user
          // selection within a Dialog.
          try {
            // Display a user dialog to resolve the location settings issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(LocationActivity.this, REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings don't satisfy the requirements of the
          // Location Request, however it can't be resolved with a user
          // dialog.
          // TODO Start monitoring location updates anyway, or abort.
          break;
        default: break;
      }
    }
  });
}
 
Example #15
Source File: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@Override
protected void onStart() {
  super.onStart();

  // Check if we have permission to access high accuracy fine location.
  int permission = ActivityCompat.checkSelfPermission(this,
    ACCESS_FINE_LOCATION);

  // If permission is granted, fetch the last location.
  if (permission == PERMISSION_GRANTED) {
    getLastLocation();
  } else {
    // If permission has not been granted, request permission.
    ActivityCompat.requestPermissions(this,
      new String[]{ACCESS_FINE_LOCATION},
      LOCATION_PERMISSION_REQUEST);
  }

  // Check of the location settings are compatible with our Location Request.
  LocationSettingsRequest.Builder builder =
    new LocationSettingsRequest.Builder()
      .addLocationRequest(mLocationRequest);

  SettingsClient client = LocationServices.getSettingsClient(this);

  Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
  task.addOnSuccessListener(this,
    new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse
                              locationSettingsResponse) {
        // Location settings satisfy the requirements of the Location Request.
        // Request location updates.
        requestLocationUpdates();
      }
    });

  task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
      // Extract the status code for the failure from within the Exception.
      int statusCode = ((ApiException) e).getStatusCode();

      switch (statusCode) {
        case CommonStatusCodes.RESOLUTION_REQUIRED:
          try {
            // Display a user dialog to resolve the location settings
            // issue.
            ResolvableApiException resolvable = (ResolvableApiException) e;
            resolvable.startResolutionForResult(WhereAmIActivity.this,
              REQUEST_CHECK_SETTINGS);
          } catch (IntentSender.SendIntentException sendEx) {
            Log.e(TAG, "Location Settings resolution failed.", sendEx);
          }
          break;
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
          // Location settings issues can't be resolved by user.
          // Request location updates anyway.
          Log.d(TAG, "Location Settings can't be resolved.");
          requestLocationUpdates();
          break;
      }
    }
  });
}
 
Example #16
Source File: RxSettingsClient.java    From ground-android with Apache License 2.0 4 votes vote down vote up
public Single<LocationSettingsResponse> checkLocationSettings(
    LocationSettingsRequest settingsRequest) {
  return RxTask.toSingle(() -> settingsClient.checkLocationSettings(settingsRequest));
}
 
Example #17
Source File: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 4 votes vote down vote up
/**
 * Start listening for location updates. These will be emitted via the
 * {@link RCTDeviceEventEmitter} as {@code geolocationDidChange} events.
 *
 * @param options map containing optional arguments: highAccuracy (boolean), distanceFilter (double),
 *                interval (millis), fastestInterval (millis)
 */
@ReactMethod
public void startObserving(ReadableMap options) {
  ReactApplicationContext context = getContext();

  if (!LocationUtils.hasLocationPermission(context)) {
    invokeError(
      LocationError.PERMISSION_DENIED.getValue(),
      "Location permission not granted.",
      false
    );
    return;
  }

  if (!LocationUtils.isGooglePlayServicesAvailable(context)) {
    invokeError(
      LocationError.PLAY_SERVICE_NOT_AVAILABLE.getValue(),
      "Google play service is not available.",
      false
    );
    return;
  }

  boolean highAccuracy = options.hasKey("enableHighAccuracy")
    && options.getBoolean("enableHighAccuracy");

  // TODO: Make other PRIORITY_* constants available to the user
  mLocationPriority = highAccuracy ? LocationRequest.PRIORITY_HIGH_ACCURACY : DEFAULT_ACCURACY;
  mDistanceFilter = options.hasKey("distanceFilter")
    ? (float) options.getDouble("distanceFilter")
    : DEFAULT_DISTANCE_FILTER;
  mUpdateInterval = options.hasKey("interval")
    ? (long) options.getDouble("interval")
    : DEFAULT_INTERVAL;
  mFastestInterval = options.hasKey("fastestInterval")
    ? (long) options.getDouble("fastestInterval")
    : DEFAULT_INTERVAL;
  mShowLocationDialog = options.hasKey("showLocationDialog")
    ? options.getBoolean("showLocationDialog")
    : true;
  mForceRequestLocation = options.hasKey("forceRequestLocation")
    ? options.getBoolean("forceRequestLocation")
    : false;

  LocationSettingsRequest locationSettingsRequest = buildLocationSettingsRequest();

  if (mSettingsClient != null) {
    mSettingsClient.checkLocationSettings(locationSettingsRequest)
      .addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
          onLocationSettingsResponse(task, false);
        }
      });
  }
}
 
Example #18
Source File: RNFusedLocationModule.java    From react-native-geolocation-service with MIT License 4 votes vote down vote up
/**
 * Get the current position. This can return almost immediately if the location is cached or
 * request an update, which might take a while.
 *
 * @param options map containing optional arguments: timeout (millis), maximumAge (millis),
 *                highAccuracy (boolean), distanceFilter (double) and showLocationDialog (boolean)
 * @param success success callback
 * @param error   error callback
 */
@ReactMethod
public void getCurrentPosition(ReadableMap options, final Callback success, final Callback error) {
  ReactApplicationContext context = getContext();

  mSuccessCallback = success;
  mErrorCallback = error;

  if (!LocationUtils.hasLocationPermission(context)) {
    invokeError(
      LocationError.PERMISSION_DENIED.getValue(),
      "Location permission not granted.",
      true
    );
    return;
  }

  if (!LocationUtils.isGooglePlayServicesAvailable(context)) {
    invokeError(
      LocationError.PLAY_SERVICE_NOT_AVAILABLE.getValue(),
      "Google play service is not available.",
      true
    );
    return;
  }

  boolean highAccuracy = options.hasKey("enableHighAccuracy") &&
    options.getBoolean("enableHighAccuracy");

  // TODO: Make other PRIORITY_* constants available to the user
  mLocationPriority = highAccuracy ? LocationRequest.PRIORITY_HIGH_ACCURACY : DEFAULT_ACCURACY;

  mTimeout = options.hasKey("timeout") ? (long) options.getDouble("timeout") : Long.MAX_VALUE;
  mMaximumAge = options.hasKey("maximumAge")
    ? options.getDouble("maximumAge")
    : Double.POSITIVE_INFINITY;
  mDistanceFilter = options.hasKey("distanceFilter")
    ? (float) options.getDouble("distanceFilter")
    : 0;
  mShowLocationDialog = options.hasKey("showLocationDialog")
    ? options.getBoolean("showLocationDialog")
    : true;
  mForceRequestLocation = options.hasKey("forceRequestLocation")
    ? options.getBoolean("forceRequestLocation")
    : false;

  LocationSettingsRequest locationSettingsRequest = buildLocationSettingsRequest();

  if (mSettingsClient != null) {
    mSettingsClient.checkLocationSettings(locationSettingsRequest)
      .addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
        @Override
        public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
          onLocationSettingsResponse(task, true);
        }
      });
  }
}