Search in sources :

Example 21 with ApiException

use of com.google.android.gms.common.api.ApiException in project android-play-location by googlesamples.

the class MainActivity method startLocationUpdates.

/**
 * 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();
        }
    });
}
Also used : ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) LocationSettingsResponse(com.google.android.gms.location.LocationSettingsResponse) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) ApiException(com.google.android.gms.common.api.ApiException)

Example 22 with ApiException

use of com.google.android.gms.common.api.ApiException in project coursera-android by aporter.

the class LocationGetLocationActivity method continueAcquiringLocations.

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:
                    // 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:
                    // to fix the settings so we won't show the dialog.
                    break;
            }
        }
    });
}
Also used : ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) LocationRequest(com.google.android.gms.location.LocationRequest) LocationSettingsResponse(com.google.android.gms.location.LocationSettingsResponse) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) ApiException(com.google.android.gms.common.api.ApiException) SettingsClient(com.google.android.gms.location.SettingsClient) LocationSettingsRequest(com.google.android.gms.location.LocationSettingsRequest) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 23 with ApiException

use of com.google.android.gms.common.api.ApiException in project quickstart-android by firebase.

the class GoogleSignInFragment method onActivityResult.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
            firebaseAuthWithGoogle(account.getIdToken());
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            updateUI(null);
        }
    }
}
Also used : GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) ApiException(com.google.android.gms.common.api.ApiException)

Example 24 with ApiException

use of com.google.android.gms.common.api.ApiException in project androidApp by InspectorIncognito.

the class PositionProvider method startLocationUpdates.

private void startLocationUpdates(LocationRequest request) {
    Log.d(TAG, "startLocationUpdates");
    if (ActivityCompat.checkSelfPermission(googleApiClient.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(googleApiClient.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Asked to update positions without permissions");
        throw new IllegalStateException("Asked to update positions without permissions");
    }
    if (googleApiClient.isConnected()) {
        requesting = true;
        if (Looper.myLooper() == null) {
            Looper.prepare();
        }
        Log.d(TAG, "Connected to API, requesting updates");
        fusedLocationProviderClient.requestLocationUpdates(request, locationCallback, null).addOnSuccessListener(new OnSuccessListener<Void>() {

            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "Task success");
            }
        }).addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ApiException) {
                    Log.d(TAG, "onFailure: " + ((ApiException) e).getStatusMessage());
                } else {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }
            }
        });
    }
}
Also used : OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ApiException(com.google.android.gms.common.api.ApiException) ApiException(com.google.android.gms.common.api.ApiException)

Example 25 with ApiException

use of com.google.android.gms.common.api.ApiException in project FirebaseUI-Android by firebase.

the class SignInKickstarter method start.

public void start() {
    if (!TextUtils.isEmpty(getArguments().emailLink)) {
        setResult(Resource.forFailure(new IntentRequiredException(EmailLinkCatcherActivity.createIntent(getApplication(), getArguments()), RequestCodes.EMAIL_FLOW)));
        return;
    }
    // Signing in with Generic IDP puts the app in the background - it can be reclaimed by the
    // OS during the sign in flow.
    Task<AuthResult> pendingResultTask = getAuth().getPendingAuthResult();
    if (pendingResultTask != null) {
        pendingResultTask.addOnSuccessListener(authResult -> {
            final IdpResponse response = new IdpResponse.Builder(new User.Builder(authResult.getCredential().getProvider(), authResult.getUser().getEmail()).build()).build();
            handleSuccess(response, authResult);
        }).addOnFailureListener(e -> setResult(Resource.forFailure(e)));
        return;
    }
    // Only support password credentials if email auth is enabled
    boolean supportPasswords = ProviderUtils.getConfigFromIdps(getArguments().providers, EmailAuthProvider.PROVIDER_ID) != null;
    List<String> accountTypes = getCredentialAccountTypes();
    // If the request will be empty, avoid the step entirely
    boolean willRequestCredentials = supportPasswords || accountTypes.size() > 0;
    if (getArguments().enableCredentials && willRequestCredentials) {
        setResult(Resource.forLoading());
        GoogleApiUtils.getCredentialsClient(getApplication()).request(new CredentialRequest.Builder().setPasswordLoginSupported(supportPasswords).setAccountTypes(accountTypes.toArray(new String[accountTypes.size()])).build()).addOnCompleteListener(task -> {
            try {
                handleCredential(task.getResult(ApiException.class).getCredential());
            } catch (ResolvableApiException e) {
                if (e.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) {
                    setResult(Resource.forFailure(new PendingIntentRequiredException(e.getResolution(), RequestCodes.CRED_HINT)));
                } else {
                    startAuthMethodChoice();
                }
            } catch (ApiException e) {
                startAuthMethodChoice();
            }
        });
    } else {
        startAuthMethodChoice();
    }
}
Also used : ProviderUtils(com.firebase.ui.auth.util.data.ProviderUtils) Bundle(android.os.Bundle) EmailLinkCatcherActivity(com.firebase.ui.auth.ui.email.EmailLinkCatcherActivity) EMAIL_LINK_PROVIDER(com.firebase.ui.auth.AuthUI.EMAIL_LINK_PROVIDER) PhoneActivity(com.firebase.ui.auth.ui.phone.PhoneActivity) NonNull(androidx.annotation.NonNull) User(com.firebase.ui.auth.data.model.User) IntentRequiredException(com.firebase.ui.auth.data.model.IntentRequiredException) Intent(android.content.Intent) Resource(com.firebase.ui.auth.data.model.Resource) ExtraConstants(com.firebase.ui.auth.util.ExtraConstants) GoogleApiUtils(com.firebase.ui.auth.util.GoogleApiUtils) PhoneAuthProvider(com.google.firebase.auth.PhoneAuthProvider) Task(com.google.android.gms.tasks.Task) ArrayList(java.util.ArrayList) GoogleAuthProvider(com.google.firebase.auth.GoogleAuthProvider) AuthMethodPickerActivity(com.firebase.ui.auth.ui.idp.AuthMethodPickerActivity) SingleSignInActivity(com.firebase.ui.auth.ui.idp.SingleSignInActivity) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) AuthUI(com.firebase.ui.auth.AuthUI) FirebaseAuthInvalidCredentialsException(com.google.firebase.auth.FirebaseAuthInvalidCredentialsException) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) EmailActivity(com.firebase.ui.auth.ui.email.EmailActivity) UserCancellationException(com.firebase.ui.auth.data.model.UserCancellationException) FirebaseAuthInvalidUserException(com.google.firebase.auth.FirebaseAuthInvalidUserException) SignInViewModelBase(com.firebase.ui.auth.viewmodel.SignInViewModelBase) TextUtils(android.text.TextUtils) PendingIntentRequiredException(com.firebase.ui.auth.data.model.PendingIntentRequiredException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) CredentialRequestResponse(com.google.android.gms.auth.api.credentials.CredentialRequestResponse) CredentialRequest(com.google.android.gms.auth.api.credentials.CredentialRequest) CommonStatusCodes(com.google.android.gms.common.api.CommonStatusCodes) List(java.util.List) Credential(com.google.android.gms.auth.api.credentials.Credential) Nullable(androidx.annotation.Nullable) EmailAuthProvider(com.google.firebase.auth.EmailAuthProvider) Application(android.app.Application) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) RequestCodes(com.firebase.ui.auth.viewmodel.RequestCodes) AuthResult(com.google.firebase.auth.AuthResult) ErrorCodes(com.firebase.ui.auth.ErrorCodes) Activity(android.app.Activity) ApiException(com.google.android.gms.common.api.ApiException) IdpResponse(com.firebase.ui.auth.IdpResponse) CredentialRequest(com.google.android.gms.auth.api.credentials.CredentialRequest) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) AuthResult(com.google.firebase.auth.AuthResult) IntentRequiredException(com.firebase.ui.auth.data.model.IntentRequiredException) PendingIntentRequiredException(com.firebase.ui.auth.data.model.PendingIntentRequiredException) PendingIntentRequiredException(com.firebase.ui.auth.data.model.PendingIntentRequiredException) IdpResponse(com.firebase.ui.auth.IdpResponse) ResolvableApiException(com.google.android.gms.common.api.ResolvableApiException) ApiException(com.google.android.gms.common.api.ApiException)

Aggregations

ApiException (com.google.android.gms.common.api.ApiException)28 GoogleSignInAccount (com.google.android.gms.auth.api.signin.GoogleSignInAccount)15 ResolvableApiException (com.google.android.gms.common.api.ResolvableApiException)10 LocationSettingsResponse (com.google.android.gms.location.LocationSettingsResponse)9 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)7 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)6 LocationRequest (com.google.android.gms.location.LocationRequest)5 LocationSettingsRequest (com.google.android.gms.location.LocationSettingsRequest)5 IntentSender (android.content.IntentSender)4 Intent (android.content.Intent)3 NonNull (androidx.annotation.NonNull)3 FirebaseAuthInvalidUserException (com.google.firebase.auth.FirebaseAuthInvalidUserException)3 Bundle (android.os.Bundle)2 TextUtils (android.text.TextUtils)2 Nullable (androidx.annotation.Nullable)2 UserCancellationException (com.firebase.ui.auth.data.model.UserCancellationException)2 AuthMethodPickerActivity (com.firebase.ui.auth.ui.idp.AuthMethodPickerActivity)2 ExtraConstants (com.firebase.ui.auth.util.ExtraConstants)2 GoogleApiUtils (com.firebase.ui.auth.util.GoogleApiUtils)2 ProviderUtils (com.firebase.ui.auth.util.data.ProviderUtils)2