Java Code Examples for com.google.android.gms.tasks.Task#addOnFailureListener()

The following examples show how to use com.google.android.gms.tasks.Task#addOnFailureListener() . 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: RecipeActivity.java    From app-indexing with Apache License 2.0 6 votes vote down vote up
private void indexRecipe() {
    Indexable recipeToIndex = new Indexable.Builder()
            .setName(mRecipe.getTitle())
            .setUrl(mRecipe.getRecipeUrl())
            .setImage(mRecipe.getPhoto())
            .setDescription(mRecipe.getDescription())
            .build();

    Task<Void> task = FirebaseAppIndex.getInstance().update(recipeToIndex);
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "App Indexing API: Successfully added " + mRecipe.getTitle() + " to " +
                    "index");
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "App Indexing API: Failed to add " + mRecipe.getTitle() + " to index. " +
                    "" + exception.getMessage());
        }
    });
}
 
Example 2
Source File: EnterPhoneNumberFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void handleRequestVerification(@NonNull Context context, @NonNull String e164number, boolean fcmSupported) {
  setSpinning(register);
  disableAllEntries();

  if (fcmSupported) {
    SmsRetrieverClient client = SmsRetriever.getClient(context);
    Task<Void>         task   = client.startSmsRetriever();

    task.addOnSuccessListener(none -> {
      Log.i(TAG, "Successfully registered SMS listener.");
      requestVerificationCode(e164number, RegistrationCodeRequest.Mode.SMS_WITH_LISTENER);
    });

    task.addOnFailureListener(e -> {
      Log.w(TAG, "Failed to register SMS listener.", e);
      requestVerificationCode(e164number, RegistrationCodeRequest.Mode.SMS_WITHOUT_LISTENER);
    });
  } else {
    Log.i(TAG, "FCM is not supported, using no SMS listener");
    requestVerificationCode(e164number, RegistrationCodeRequest.Mode.SMS_WITHOUT_LISTENER);
  }
}
 
Example 3
Source File: RecipeActivity.java    From app-indexing with Apache License 2.0 6 votes vote down vote up
private void indexNote() {
    Note note = mRecipe.getNote();
    Indexable noteToIndex = Indexables.noteDigitalDocumentBuilder()
            .setName(mRecipe.getTitle() + " Note")
            .setText(note.getText())
            .setUrl(mRecipe.getNoteUrl())
            .build();

    Task<Void> task = FirebaseAppIndex.getInstance().update(noteToIndex);
    // [START_EXCLUDE]
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.d(TAG, "App Indexing API: Successfully added note to index");
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.e(TAG, "App Indexing API: Failed to add note to index. " + exception
                    .getMessage());
        }
    });
    // [END_EXCLUDE]
}
 
Example 4
Source File: ConfigCacheClient.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Reimplementation of {@link Tasks#await(Task, long, TimeUnit)} because that method has a
 * precondition that fails when run on the main thread.
 *
 * <p>This blocking method is required because the current FRC API has synchronous getters that
 * read from a cache that is loaded from disk. In other words, the synchronous methods rely on an
 * async task, so the getters have to block at some point.
 *
 * <p>Until the next breaking change in the API, this use case must be implemented, even though it
 * is against Android best practices.
 */
private static <TResult> TResult await(Task<TResult> task, long timeout, TimeUnit unit)
    throws ExecutionException, InterruptedException, TimeoutException {
  AwaitListener<TResult> waiter = new AwaitListener<>();

  task.addOnSuccessListener(DIRECT_EXECUTOR, waiter);
  task.addOnFailureListener(DIRECT_EXECUTOR, waiter);
  task.addOnCanceledListener(DIRECT_EXECUTOR, waiter);

  if (!waiter.await(timeout, unit)) {
    throw new TimeoutException("Task await timed out.");
  }

  if (task.isSuccessful()) {
    return task.getResult();
  } else {
    throw new ExecutionException(task.getException());
  }
}
 
Example 5
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 6
Source File: UpdateService.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
private void removeWearableData(Uri dataItemUri) {

        Task<Integer> dataDeleteTask =
                Wearable.getDataClient(getApplicationContext()).deleteDataItems(dataItemUri);

        dataDeleteTask.addOnSuccessListener(getIntegerOnSuccessListener());
        dataDeleteTask.addOnFailureListener(getOnFailureListener(dataItemUri));
    }
 
Example 7
Source File: PlaceAndPhotoTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the {@link Place} specified via the UI and displays it. May also trigger {@link
 * #fetchPhoto(PhotoMetadata)} if set in the UI.
 */
private void fetchPlace() {
  responseView.setText(null);
  photoView.setImageBitmap(null);
  dismissKeyboard(findViewById(R.id.place_id_field));

  final boolean isFetchPhotoChecked = isFetchPhotoChecked();
  List<Field> placeFields = getPlaceFields();
  String customPhotoReference = getCustomPhotoReference();
  if (!validateInputs(isFetchPhotoChecked, placeFields, customPhotoReference)) {
    return;
  }

  setLoading(true);

  FetchPlaceRequest request = FetchPlaceRequest.newInstance(getPlaceId(), placeFields);
  Task<FetchPlaceResponse> placeTask = placesClient.fetchPlace(request);

  placeTask.addOnSuccessListener(
      (response) -> {
        responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked()));
        if (isFetchPhotoChecked) {
          attemptFetchPhoto(response.getPlace());
        }
      });

  placeTask.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  placeTask.addOnCompleteListener(response -> setLoading(false));
}
 
Example 8
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 9
Source File: AutocompleteTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
private void findAutocompletePredictions() {
  setLoading(true);

  FindAutocompletePredictionsRequest.Builder requestBuilder =
      FindAutocompletePredictionsRequest.builder()
              .setQuery(getQuery())
              .setCountries(getCountries())
              .setOrigin((getOrigin()))
              .setLocationBias(getLocationBias())
              .setLocationRestriction(getLocationRestriction())
              .setTypeFilter(getTypeFilter());

  if (isUseSessionTokenChecked()) {
    requestBuilder.setSessionToken(AutocompleteSessionToken.newInstance());
  }

  Task<FindAutocompletePredictionsResponse> task =
      placesClient.findAutocompletePredictions(requestBuilder.build());

  task.addOnSuccessListener(
      (response) ->
          responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));

  task.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  task.addOnCompleteListener(response -> setLoading(false));
}
 
Example 10
Source File: PlaceAndPhotoTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the {@link Place} specified via the UI and displays it. May also trigger {@link
 * #fetchPhoto(PhotoMetadata)} if set in the UI.
 */
private void fetchPlace() {
  responseView.setText(null);
  photoView.setImageBitmap(null);
  dismissKeyboard(findViewById(R.id.place_id_field));

  final boolean isFetchPhotoChecked = isFetchPhotoChecked();
  List<Field> placeFields = getPlaceFields();
  String customPhotoReference = getCustomPhotoReference();
  if (!validateInputs(isFetchPhotoChecked, placeFields, customPhotoReference)) {
    return;
  }

  setLoading(true);

  FetchPlaceRequest request = FetchPlaceRequest.newInstance(getPlaceId(), placeFields);
  Task<FetchPlaceResponse> placeTask = placesClient.fetchPlace(request);

  placeTask.addOnSuccessListener(
      (response) -> {
        responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked()));
        if (isFetchPhotoChecked) {
          attemptFetchPhoto(response.getPlace());
        }
      });

  placeTask.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  placeTask.addOnCompleteListener(response -> setLoading(false));
}
 
Example 11
Source File: AutocompleteTestActivity.java    From android-places-demos with Apache License 2.0 5 votes vote down vote up
private void findAutocompletePredictions() {
  setLoading(true);

  FindAutocompletePredictionsRequest.Builder requestBuilder =
      FindAutocompletePredictionsRequest.builder()
              .setQuery(getQuery())
              .setCountries(getCountries())
              .setOrigin((getOrigin()))
              .setLocationBias(getLocationBias())
              .setLocationRestriction(getLocationRestriction())
              .setTypeFilter(getTypeFilter());

  if (isUseSessionTokenChecked()) {
    requestBuilder.setSessionToken(AutocompleteSessionToken.newInstance());
  }

  Task<FindAutocompletePredictionsResponse> task =
      placesClient.findAutocompletePredictions(requestBuilder.build());

  task.addOnSuccessListener(
      (response) ->
          responseView.setText(StringUtil.stringify(response, isDisplayRawResultsChecked())));

  task.addOnFailureListener(
      (exception) -> {
        exception.printStackTrace();
        responseView.setText(exception.getMessage());
      });

  task.addOnCompleteListener(response -> setLoading(false));
}
 
Example 12
Source File: MainActivity.java    From location-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Removes activity recognition updates using
 * {@link ActivityRecognitionClient#removeActivityUpdates(PendingIntent)}. Registers success and
 * failure callbacks.
 */
public void removeActivityUpdatesButtonHandler(View view) {
    Task<Void> task = mActivityRecognitionClient.removeActivityUpdates(
            getActivityDetectionPendingIntent());
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void result) {
            Toast.makeText(mContext,
                    getString(R.string.activity_updates_removed),
                    Toast.LENGTH_SHORT)
                    .show();
            setUpdatesRequestedState(false);
            // Reset the display.
            mAdapter.updateActivities(new ArrayList<DetectedActivity>());
        }
    });

    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.w(TAG, "Failed to enable activity recognition.");
            Toast.makeText(mContext, getString(R.string.activity_updates_not_removed),
                    Toast.LENGTH_SHORT).show();
            setUpdatesRequestedState(true);
        }
    });
}
 
Example 13
Source File: PlaceAndPhotoTestActivity.java    From android-places-demos with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches a Bitmap using the Places API and displays it.
 *
 * @param photoMetadata from a {@link Place} instance.
 */
private void fetchPhoto(PhotoMetadata photoMetadata) {
  photo = photoMetadata;

  photoView.setImageBitmap(null);
  setLoading(true);

  String customPhotoReference = getCustomPhotoReference();
  if (!TextUtils.isEmpty(customPhotoReference)) {
    photoMetadata = PhotoMetadata.builder(customPhotoReference).build();
  }

  FetchPhotoRequest.Builder photoRequestBuilder = FetchPhotoRequest.builder(photoMetadata);

  Integer maxWidth = readIntFromTextView(R.id.photo_max_width);
  if (maxWidth != null) {
    photoRequestBuilder.setMaxWidth(maxWidth);
  }

  Integer maxHeight = readIntFromTextView(R.id.photo_max_height);
  if (maxHeight != null) {
    photoRequestBuilder.setMaxHeight(maxHeight);
  }

  Task<FetchPhotoResponse> photoTask = placesClient.fetchPhoto(photoRequestBuilder.build());

  photoTask.addOnSuccessListener(
      response -> {
        Bitmap bitmap = response.getBitmap();
        photoView.setImageBitmap(bitmap);
        StringUtil.prepend(responseView, StringUtil.stringify(bitmap));
      });

  photoTask.addOnFailureListener(
      exception -> {
        exception.printStackTrace();
        StringUtil.prepend(responseView, "Photo: " + exception.getMessage());
      });

  photoTask.addOnCompleteListener(response -> setLoading(false));
}
 
Example 14
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 15
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 16
Source File: PhoneNumberVerifier.java    From android-credentials with Apache License 2.0 4 votes vote down vote up
/**
 * Handle action Foo in the provided background thread with the provided
 * parameters.
 */
private void startVerify(String phoneNo) {
    // Make this a foreground service
    notifyStatus(STATUS_STARTED, phoneNo);
    setVerificationState(phoneNo, false);

    // Start SMS receiver code
    Task<Void> task = smsRetrieverClient.startSmsRetriever();
    task.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            smsReceiver.setTimeout();
            notifyStatus(STATUS_REQUEST_SENT, null);
            Log.d(TAG, "SmsRetrievalResult status: Success");
            Toast.makeText(PhoneNumberVerifier.this, getString(R.string.verifier_registered),
                    Toast.LENGTH_SHORT).show();
        }
    });
    task.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "SmsRetrievalResult start failed.", e);
            stopSelf();
        }
    });


    // Communicate to background servers to send SMS and get the expect OTP
    notifyStatus(STATUS_REQUESTING, phoneNo);
    api.request(phoneNo,
            new ApiHelper.RequestResponse() {
                @Override
                public void onResponse(boolean success) {
                    if (success) {
                        Toast.makeText(PhoneNumberVerifier.this,
                                getString(R.string.verifier_server_response),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Log.e(TAG, "Unsuccessful request call.");
                        Toast.makeText(PhoneNumberVerifier.this,
                                getString(R.string.toast_unverified), Toast.LENGTH_LONG).show();
                        stopSelf();
                    }
                }
            }, new ApiHelper.ApiError() {
                @Override
                public void onError(VolleyError error) {
                    // Do something else.
                    Log.d(TAG, "Error getting response");
                    Toast.makeText(PhoneNumberVerifier.this,
                            getString(R.string.toast_request_error), Toast.LENGTH_LONG).show();
                    stopSelf();
                }
            });
}
 
Example 17
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 18
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 19
Source File: LocationPickerActivity.java    From LocationPicker with MIT License 4 votes vote down vote up
private void showCurrentLocationOnMap(final boolean isDirectionClicked) {

        if (checkAndRequestPermissions()) {

            @SuppressLint("MissingPermission")
            Task<Location> lastLocation = fusedLocationProviderClient.getLastLocation();
            lastLocation.addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        mMap.clear();
                        if (isDirectionClicked) {
                            currentLatitude = location.getLatitude();
                            currentLongitude = location.getLongitude();
                            //Go to Map for Directions
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                    "http://maps.google.com/maps?saddr=" + currentLatitude + ", " + currentLongitude + "&daddr=" + mLatitude + ", " + mLongitude + ""));
                            LocationPickerActivity.this.startActivity(intent);
                        } else {
                            //Go to Current Location
                            mLatitude = location.getLatitude();
                            mLongitude = location.getLongitude();
                            LocationPickerActivity.this.getAddressByGeoCodingLatLng();
                        }

                    } else {
                        //Gps not enabled if loc is null
                        LocationPickerActivity.this.getSettingsLocation();
                        Toast.makeText(LocationPickerActivity.this, "Location not Available", Toast.LENGTH_SHORT).show();

                    }
                }
            });
            lastLocation.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //If perm provided then gps not enabled
//                getSettingsLocation();
                    Toast.makeText(LocationPickerActivity.this, "Location Not Availabe", Toast.LENGTH_SHORT).show();

                }
            });
        }

    }
 
Example 20
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;
      }
    }
  });
}