android.content.IntentSender.SendIntentException#com.google.android.gms.common.api.ResolvableApiException源码实例Demo

下面列出了android.content.IntentSender.SendIntentException#com.google.android.gms.common.api.ResolvableApiException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: identity-samples   文件: MainActivity.java
/**
 * Attempt to resolve a non-successful result from an asynchronous request.
 * @param rae the ResolvableApiException to resolve.
 * @param requestCode the request code to use when starting an Activity for result,
 *                    this will be passed back to onActivityResult.
 */
private void resolveResult(ResolvableApiException rae, int requestCode) {
    // We don't want to fire multiple resolutions at once since that can result
    // in stacked dialogs after rotation or another similar event.
    if (mIsResolving) {
        Log.w(TAG, "resolveResult: already resolving.");
        return;
    }
    
    Log.d(TAG, "Resolving: " + rae);
    try {
        rae.startResolutionForResult(MainActivity.this, requestCode);
        mIsResolving = true;
    } catch (IntentSender.SendIntentException e) {
        Log.e(TAG, "STATUS: Failed to send resolution.", e);
        hideProgress();
    }
}
 
源代码2 项目: android-credentials   文件: MainActivity.java
/**
 * Attempt to resolve a non-successful result from an asynchronous request.
 * @param rae the ResolvableApiException to resolve.
 * @param requestCode the request code to use when starting an Activity for result,
 *                    this will be passed back to onActivityResult.
 */
private void resolveResult(ResolvableApiException rae, int requestCode) {
    // We don't want to fire multiple resolutions at once since that can result
    // in stacked dialogs after rotation or another similar event.
    if (mIsResolving) {
        Log.w(TAG, "resolveResult: already resolving.");
        return;
    }
    
    Log.d(TAG, "Resolving: " + rae);
    try {
        rae.startResolutionForResult(MainActivity.this, requestCode);
        mIsResolving = true;
    } catch (IntentSender.SendIntentException e) {
        Log.e(TAG, "STATUS: Failed to send resolution.", e);
        hideProgress();
    }
}
 
源代码3 项目: identity-samples   文件: MainActivity.java
private void requestCredentials(final boolean shouldResolve, boolean onlyPasswords) {
    CredentialRequest.Builder crBuilder = new CredentialRequest.Builder()
            .setPasswordLoginSupported(true);

    if (!onlyPasswords) {
        crBuilder.setAccountTypes(IdentityProviders.GOOGLE);
    }

    showProgress();
    mCredentialsClient.request(crBuilder.build()).addOnCompleteListener(
            new OnCompleteListener<CredentialRequestResponse>() {
                @Override
                public void onComplete(@NonNull Task<CredentialRequestResponse> task) {
                    hideProgress();

                    if (task.isSuccessful()) {
                        // Auto sign-in success
                        handleCredential(task.getResult().getCredential());
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException && shouldResolve) {
                        // Getting credential needs to show some UI, start resolution
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_READ);
                    } else {
                        Log.w(TAG, "request: not handling exception", e);
                    }
                }
            });
}
 
源代码4 项目: identity-samples   文件: MainActivity.java
private void resolveResult(ResolvableApiException rae, int requestCode) {
    if (!mIsResolving) {
        try {
            rae.startResolutionForResult(MainActivity.this, requestCode);
            mIsResolving = true;
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "Failed to send Credentials intent.", e);
            mIsResolving = false;
        }
    }
}
 
源代码5 项目: identity-samples   文件: MainActivity.java
private void saveCredential(Credential credential) {
    if (credential == null) {
        Log.w(TAG, "Ignoring null credential.");
        return;
    }

    mCredentialsClient.save(mCredential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "save:SUCCESS");
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // Saving the credential can sometimes require showing some UI
                        // to the user, which means we need to fire this resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_SAVE);
                    } else {
                        Log.w(TAG, "save:FAILURE", e);
                        Toast.makeText(MainActivity.this,
                                "Unexpected error, see logs for detals",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 
源代码6 项目: indigenous-android   文件: BasePlatformCreate.java
/**
 * 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();
                    }
                }
            });
}
 
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;
                    }
                }
            });
}
 
源代码8 项目: EasyWayLocation   文件: EasyWayLocation.java
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();
            }
        }
    });
}
 
源代码9 项目: ground-android   文件: SettingsManager.java
private Completable onCheckSettingsFailure(int requestCode, Throwable t) {
  if (!(t instanceof ResolvableApiException)) {
    return Completable.error(t);
  }
  return startResolution(requestCode, (ResolvableApiException) t)
      .andThen(getNextResult(requestCode));
}
 
源代码10 项目: ground-android   文件: SettingsManager.java
private Completable startResolution(int requestCode, ResolvableApiException resolvableException) {
  return Completable.create(
      em -> {
        Log.d(TAG, "Prompting user to enable settings");
        activityStreams.withActivity(
            act -> {
              try {
                resolvableException.startResolutionForResult(act, requestCode);
                em.onComplete();
              } catch (SendIntentException e) {
                em.onError(e);
              }
            });
      });
}
 
源代码11 项目: LocationAware   文件: LocationAlarmActivity.java
@Override public void startResolutionForLocation(ResolvableApiException resolvable) {
  try {
    resolvable.startResolutionForResult((Activity) context, REQUEST_CHECK_SETTINGS);
  } catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
  }
}
 
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;
            }
        }
    });
}
 
源代码13 项目: AirMapSDK-Android   文件: MyLocationMapActivity.java
/**
 * 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.
            }
        }
    });
}
 
源代码14 项目: journaldev   文件: MainActivity.java
public void saveCredentials(Credential credential) {


        mCredentialsApiClient.save(credential).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "SAVE: OK");
                    showToast("Credentials saved");
                    return;
                }

                Exception e = task.getException();
                if (e instanceof ResolvableApiException) {
                    // Try to resolve the save request. This will prompt the user if
                    // the credential is new.
                    ResolvableApiException rae = (ResolvableApiException) e;
                    try {
                        rae.startResolutionForResult(MainActivity.this, RC_SAVE);
                    } catch (IntentSender.SendIntentException f) {
                        // Could not resolve the request
                        Log.e(TAG, "Failed to send resolution.", f);
                        showToast("Saved failed");
                    }
                } else {
                    // Request has no resolution
                    showToast("Saved failed");
                }
            }
        });

    }
 
源代码15 项目: android-credentials   文件: MainActivity.java
private void requestCredentials(final boolean shouldResolve, boolean onlyPasswords) {
    CredentialRequest.Builder crBuilder = new CredentialRequest.Builder()
            .setPasswordLoginSupported(true);

    if (!onlyPasswords) {
        crBuilder.setAccountTypes(IdentityProviders.GOOGLE);
    }

    showProgress();
    mCredentialsClient.request(crBuilder.build()).addOnCompleteListener(
            new OnCompleteListener<CredentialRequestResponse>() {
                @Override
                public void onComplete(@NonNull Task<CredentialRequestResponse> task) {
                    hideProgress();

                    if (task.isSuccessful()) {
                        // Auto sign-in success
                        handleCredential(task.getResult().getCredential());
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException && shouldResolve) {
                        // Getting credential needs to show some UI, start resolution
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_READ);
                    } else {
                        Log.w(TAG, "request: not handling exception", e);
                    }
                }
            });
}
 
源代码16 项目: android-credentials   文件: MainActivity.java
private void resolveResult(ResolvableApiException rae, int requestCode) {
    if (!mIsResolving) {
        try {
            rae.startResolutionForResult(MainActivity.this, requestCode);
            mIsResolving = true;
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "Failed to send Credentials intent.", e);
            mIsResolving = false;
        }
    }
}
 
源代码17 项目: android-credentials   文件: MainActivity.java
private void saveCredential(Credential credential) {
    if (credential == null) {
        Log.w(TAG, "Ignoring null credential.");
        return;
    }

    mCredentialsClient.save(mCredential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "save:SUCCESS");
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // Saving the credential can sometimes require showing some UI
                        // to the user, which means we need to fire this resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_CREDENTIALS_SAVE);
                    } else {
                        Log.w(TAG, "save:FAILURE", e);
                        Toast.makeText(MainActivity.this,
                                "Unexpected error, see logs for detals",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
 
源代码18 项目: FirebaseUI-Android   文件: SmartLockHandler.java
/** Initialize saving a credential. */
public void saveCredentials(@Nullable Credential credential) {
    if (!getArguments().enableCredentials) {
        setResult(Resource.forSuccess(mResponse));
        return;
    }
    setResult(Resource.<IdpResponse>forLoading());

    if (credential == null) {
        setResult(Resource.<IdpResponse>forFailure(new FirebaseUiException(
                ErrorCodes.UNKNOWN_ERROR, "Failed to build credential.")));
        return;
    }

    deleteUnusedCredentials();
    getCredentialsClient().save(credential)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        setResult(Resource.forSuccess(mResponse));
                    } else if (task.getException() instanceof ResolvableApiException) {
                        ResolvableApiException rae = (ResolvableApiException) task.getException();
                        setResult(Resource.<IdpResponse>forFailure(
                                new PendingIntentRequiredException(
                                        rae.getResolution(), RequestCodes.CRED_SAVE)));
                    } else {
                        Log.w(TAG, "Non-resolvable exception: " + task.getException());
                        setResult(Resource.<IdpResponse>forFailure(new FirebaseUiException(
                                ErrorCodes.UNKNOWN_ERROR,
                                "Error when saving credential.",
                                task.getException())));
                    }
                }
            });
}
 
源代码19 项目: FirebaseUI-Android   文件: SmartLockHandlerTest.java
@Test
public void testSaveCredentials_resolution() {
    mHandler.getOperation().observeForever(mResultObserver);

    // Mock credentials to throw an RAE
    ResolvableApiException mockRae = mock(ResolvableApiException.class);
    when(mMockCredentials.save(any(Credential.class)))
            .thenReturn(AutoCompleteTask.<Void>forFailure(mockRae));

    // Kick off save
    mHandler.saveCredentials(TestHelper.getMockFirebaseUser(), TestConstants.PASSWORD, null);

    InOrder inOrder = inOrder(mResultObserver);

    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isLoading()));

    // Make sure we get a resolution
    ArgumentCaptor<Resource<IdpResponse>> resolveCaptor =
            ArgumentCaptor.forClass(Resource.class);
    inOrder.verify(mResultObserver).onChanged(resolveCaptor.capture());

    // Call activity result
    PendingIntentRequiredException e =
            ((PendingIntentRequiredException) resolveCaptor.getValue().getException());
    mHandler.onActivityResult(e.getRequestCode(), Activity.RESULT_OK);

    // Make sure we get success
    inOrder.verify(mResultObserver)
            .onChanged(argThat(ResourceMatchers.<IdpResponse>isSuccess()));
}
 
源代码20 项目: identity-samples   文件: MainActivity.java
/**
 * Called when the save button is clicked.  Reads the entries in the email and password
 * fields and attempts to save a new Credential to the Credentials API.
 */
private void saveCredentialClicked() {
    String email = mEmailField.getText().toString();
    String password = mPasswordField.getText().toString();

    // Create a Credential with the user's email as the ID and storing the password.  We
    // could also add 'Name' and 'ProfilePictureURL' but that is outside the scope of this
    // minimal sample.
    Log.d(TAG, "Saving Credential:" + email + ":" + anonymizePassword(password));
    final Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();

    showProgress();

    // NOTE: this method unconditionally saves the Credential built, even if all the fields
    // are blank or it is invalid in some other way.  In a real application you should contact
    // your app's back end and determine that the credential is valid before saving it to the
    // Credentials backend.
    showProgress();

    mCredentialsClient.save(credential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        showToast("Credential saved.");
                        hideProgress();
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // The first time a credential is saved, the user is shown UI
                        // to confirm the action. This requires resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_SAVE);
                    } else {
                        // Save failure cannot be resolved.
                        Log.w(TAG, "Save failed.", e);
                        showToast("Credential Save Failed");
                        hideProgress();
                    }
                }
            });
}
 
源代码21 项目: identity-samples   文件: MainActivity.java
/**
 * Request Credentials from the Credentials API.
 */
private void requestCredentials() {
    // Request all of the user's saved username/password credentials.  We are not using
    // setAccountTypes so we will not load any credentials from other Identity Providers.
    CredentialRequest request = new CredentialRequest.Builder()
            .setPasswordLoginSupported(true)
            .setIdTokenRequested(shouldRequestIdToken())
            .build();

    showProgress();

    mCredentialsClient.request(request).addOnCompleteListener(
            new OnCompleteListener<CredentialRequestResponse>() {
                @Override
                public void onComplete(@NonNull Task<CredentialRequestResponse> task) {
                    hideProgress();

                    if (task.isSuccessful()) {
                        // Successfully read the credential without any user interaction, this
                        // means there was only a single credential and the user has auto
                        // sign-in enabled.
                        processRetrievedCredential(task.getResult().getCredential(), false);
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // This is most likely the case where the user has multiple saved
                        // credentials and needs to pick one. This requires showing UI to
                        // resolve the read request.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_READ);
                        return;
                    }

                    if (e instanceof ApiException) {
                        ApiException ae = (ApiException) e;
                        if (ae.getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED) {
                            // This means only a hint is available, but we are handling that
                            // elsewhere so no need to act here.
                        } else {
                            Log.w(TAG, "Unexpected status code: " + ae.getStatusCode());
                        }
                    }
                }
            });
}
 
@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;
      }
    }
  });
}
 
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;
      }
    }
  });
}
 
@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;
      }
    }
  });
}
 
@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;
      }
    }
  });
}
 
@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;
      }
    }
  });
}
 
源代码27 项目: Nibo   文件: BaseNiboFragment.java
/**
 * 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);
                    }
                }
            });
}
 
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();
                }
            });


    }
 
源代码29 项目: android-credentials   文件: MainActivity.java
/**
 * Called when the save button is clicked.  Reads the entries in the email and password
 * fields and attempts to save a new Credential to the Credentials API.
 */
private void saveCredentialClicked() {
    String email = mEmailField.getText().toString();
    String password = mPasswordField.getText().toString();

    // Create a Credential with the user's email as the ID and storing the password.  We
    // could also add 'Name' and 'ProfilePictureURL' but that is outside the scope of this
    // minimal sample.
    Log.d(TAG, "Saving Credential:" + email + ":" + anonymizePassword(password));
    final Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();

    showProgress();

    // NOTE: this method unconditionally saves the Credential built, even if all the fields
    // are blank or it is invalid in some other way.  In a real application you should contact
    // your app's back end and determine that the credential is valid before saving it to the
    // Credentials backend.
    showProgress();

    mCredentialsClient.save(credential).addOnCompleteListener(
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        showToast("Credential saved.");
                        hideProgress();
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // The first time a credential is saved, the user is shown UI
                        // to confirm the action. This requires resolution.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_SAVE);
                    } else {
                        // Save failure cannot be resolved.
                        Log.w(TAG, "Save failed.", e);
                        showToast("Credential Save Failed");
                        hideProgress();
                    }
                }
            });
}
 
源代码30 项目: android-credentials   文件: MainActivity.java
/**
 * Request Credentials from the Credentials API.
 */
private void requestCredentials() {
    // Request all of the user's saved username/password credentials.  We are not using
    // setAccountTypes so we will not load any credentials from other Identity Providers.
    CredentialRequest request = new CredentialRequest.Builder()
            .setPasswordLoginSupported(true)
            .setIdTokenRequested(shouldRequestIdToken())
            .build();

    showProgress();

    mCredentialsClient.request(request).addOnCompleteListener(
            new OnCompleteListener<CredentialRequestResponse>() {
                @Override
                public void onComplete(@NonNull Task<CredentialRequestResponse> task) {
                    hideProgress();

                    if (task.isSuccessful()) {
                        // Successfully read the credential without any user interaction, this
                        // means there was only a single credential and the user has auto
                        // sign-in enabled.
                        processRetrievedCredential(task.getResult().getCredential(), false);
                        return;
                    }

                    Exception e = task.getException();
                    if (e instanceof ResolvableApiException) {
                        // This is most likely the case where the user has multiple saved
                        // credentials and needs to pick one. This requires showing UI to
                        // resolve the read request.
                        ResolvableApiException rae = (ResolvableApiException) e;
                        resolveResult(rae, RC_READ);
                        return;
                    }

                    if (e instanceof ApiException) {
                        ApiException ae = (ApiException) e;
                        if (ae.getStatusCode() == CommonStatusCodes.SIGN_IN_REQUIRED) {
                            // This means only a hint is available, but we are handling that
                            // elsewhere so no need to act here.
                        } else {
                            Log.w(TAG, "Unexpected status code: " + ae.getStatusCode());
                        }
                    }
                }
            });
}