com.google.android.gms.common.api.ResolvableApiException Java Examples

The following examples show how to use com.google.android.gms.common.api.ResolvableApiException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
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();
                    }
                }
            });
}
 
Example #2
Source File: MainActivity.java    From identity-samples with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #3
Source File: MainActivity.java    From android-credentials with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example #4
Source File: SmartLockHandlerTest.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #5
Source File: MainActivity.java    From journaldev with MIT License 5 votes vote down vote up
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");
                }
            }
        });

    }
 
Example #6
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 #7
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 #8
Source File: LocationAlarmActivity.java    From LocationAware with Apache License 2.0 5 votes vote down vote up
@Override public void startResolutionForLocation(ResolvableApiException resolvable) {
  try {
    resolvable.startResolutionForResult((Activity) context, REQUEST_CHECK_SETTINGS);
  } catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
  }
}
 
Example #9
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
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);
                    }
                }
            });
}
 
Example #10
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
}
 
Example #11
Source File: MainActivity.java    From android-credentials with Apache License 2.0 5 votes vote down vote up
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();
                    }
                }
            });
}
 
Example #12
Source File: SmartLockHandler.java    From FirebaseUI-Android with Apache License 2.0 5 votes vote down vote up
/** 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())));
                    }
                }
            });
}
 
Example #13
Source File: SettingsManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
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);
              }
            });
      });
}
 
Example #14
Source File: SettingsManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
private Completable onCheckSettingsFailure(int requestCode, Throwable t) {
  if (!(t instanceof ResolvableApiException)) {
    return Completable.error(t);
  }
  return startResolution(requestCode, (ResolvableApiException) t)
      .andThen(getNextResult(requestCode));
}
 
Example #15
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 #16
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 #17
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 #18
Source File: MainActivity.java    From identity-samples with Apache License 2.0 5 votes vote down vote up
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);
                    }
                }
            });
}
 
Example #19
Source File: MainActivity.java    From identity-samples with Apache License 2.0 5 votes vote down vote up
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;
        }
    }
}
 
Example #20
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 #21
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 #22
Source File: MainActivity.java    From android-credentials with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
                        }
                    }
                }
            });
}
 
Example #23
Source File: MainActivity.java    From android-credentials with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
                    }
                }
            });
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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;
      }
    }
  });
}