Java 类com.google.android.gms.common.api.ApiException 实例源码

项目:jazz-android    文件:MainActivity.java   
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

        ChatWindowConfiguration config = new ChatWindowConfiguration(
                Config.license,
                Config.group,
                account.getDisplayName(),
                account.getEmail(),
                new HashMap<String, String>()
        );

        // Signed in successfully, show authenticated UI.
        launchChat(this, config);
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w("Whoopsie", "signInResult:failed code=" + e.getStatusCode());
    }
}
项目:GodotGoogleService    文件:PlayService.java   
private void signInSilently() {
    if (isConnected()) { return; }

    GoogleSignInClient signInClient = GoogleSignIn.getClient(activity,
    GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);

    signInClient.silentSignIn().addOnCompleteListener(activity,
    new OnCompleteListener<GoogleSignInAccount>() {
        @Override
        public void onComplete(@NonNull Task<GoogleSignInAccount> task) {
            if (task.isSuccessful()) {
                // The signed in account is stored in the task's result.
                try {
                    mAccount = task.getResult(ApiException.class);
                    succeedSignIn();
                } catch (ApiException e) {
                    Log.w(TAG, "SignInResult::Failed code="
                    + e.getStatusCode() + ", Message: "
                    + e.getStatusMessage());
                }
            } else {
                // Player will need to sign-in explicitly using via UI
                Log.d(TAG, "Silent::Login::Failed");
            }
        }
    });
}
项目:paymentsapi-quickstart    文件:CheckoutActivity.java   
private void checkIsReadyToPay() {
    // The call to isReadyToPay is asynchronous and returns a Task. We need to provide an
    // OnCompleteListener to be triggered when the result of the call is known.
    PaymentsUtil.isReadyToPay(mPaymentsClient).addOnCompleteListener(
            new OnCompleteListener<Boolean>() {
                public void onComplete(Task<Boolean> task) {
                    try {
                        boolean result = task.getResult(ApiException.class);
                        setPwgAvailable(result);
                    } catch (ApiException exception) {
                        // Process error
                        Log.w("isReadyToPay failed", exception);
                    }
                }
            });
}
项目:MangoBloggerAndroidApp    文件:BaseAuthActivity.java   
@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);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // ...
        }
    }
}
项目:Blogg    文件:MainActivity.java   
private void handleSignInResult(Task<GoogleSignInAccount> completedTask){
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

        // Signed in successfully, show authenticated UI.
        updateUI(account);

        googleSignInAccount = account;
        mAuthorizedAccount = account.getAccount();

        GetListOfBlogTask task = new GetListOfBlogTask(mAuthorizedAccount);
        task.execute();
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Tools.loge("signInResult:failed code=" + e.getStatusCode());
        updateUI(null);
    }
}
项目:android-play-safetynet    文件:SafetyNetSampleFragment.java   
@Override
public void onFailure(@NonNull Exception e) {
    // An error occurred while communicating with the service.
    mResult = null;

    if (e instanceof ApiException) {
        // An error with the Google Play Services API contains some additional details.
        ApiException apiException = (ApiException) e;
        Log.d(TAG, "Error: " +
                CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " +
                apiException.getStatusMessage());
    } else {
        // A different, unknown type of error occurred.
        Log.d(TAG, "ERROR! " + e.getMessage());
    }

}
项目:quickstart-android    文件:GoogleSignInActivity.java   
@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);
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
            Log.w(TAG, "Google sign in failed", e);
            // [START_EXCLUDE]
            updateUI(null);
            // [END_EXCLUDE]
        }
    }
}
项目:google-services    文件:ServerAuthCodeActivity.java   
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_GET_AUTH_CODE) {
        // [START get_auth_code]
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            String authCode = account.getServerAuthCode();

            // Show signed-un UI
            updateUI(account);

            // TODO(developer): send code to server and exchange for access/refresh/ID tokens
        } catch (ApiException e) {
            Log.w(TAG, "Sign-in failed", e);
            updateUI(null);
        }
        // [END get_auth_code]
    }
}
项目:google-services    文件:RestApiActivity.java   
private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) {
    Log.d(TAG, "handleSignInResult:" + completedTask.isSuccessful());

    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        updateUI(account);

        // Store the account from the result
        mAccount = account.getAccount();

        // Asynchronously access the People API for the account
        getContacts();
    } catch (ApiException e) {
        Log.w(TAG, "handleSignInResult:error", e);

        // Clear the local account
        mAccount = null;

        // Signed out, show unauthenticated UI.
        updateUI(null);
    }
}
项目:android-basic-samples    文件:MainActivity.java   
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  super.onActivityResult(requestCode, resultCode, intent);
  if (requestCode == RC_SIGN_IN) {
    Task<GoogleSignInAccount> task =
        GoogleSignIn.getSignedInAccountFromIntent(intent);

    try {
      GoogleSignInAccount account = task.getResult(ApiException.class);
      onConnected(account);
    } catch (ApiException apiException) {
      String message = apiException.getMessage();
      if (message == null || message.isEmpty()) {
        message = getString(R.string.signin_other_error);
      }

      onDisconnected();

      new AlertDialog.Builder(this)
          .setMessage(message)
          .setNeutralButton(android.R.string.ok, null)
          .show();
    }
  }
}
项目:wirtualnaApteczka    文件:GoogleAuthenticationUtils.java   
public static void analyseGoogleLoginResult(Intent data, AppCompatActivity activity) {
    Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);

    try {
        GoogleSignInAccount account = task.getResult(ApiException.class);
        GoogleAuthenticationUtils.authenticateInFirebaseUsingGoogleAccount(account, activity);
    } catch (ApiException e) {
        Toast.makeText(activity, R.string.authentication_failed, Toast.LENGTH_SHORT).show();
    }
}
项目:NightSkyGuide    文件:MainActivity.java   
private void startLocationUpdates() {
    // if settings are satisfied initialize location requests
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            locUpdates = true;
            // All location settings are satisfied.
            //noinspection MissingPermission - this comment needs to stay here to stop inspection on next line
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
        }
    })
            // if settings need to be changed prompt user
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case 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(MainActivity.this, REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sendEx) {
                                // Ignore the error
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // location settings are not satisfied, however no way to fix the settings so don't show dialog.
                            Toast.makeText(MainActivity.this, "Location Services Unavailable", Toast.LENGTH_LONG).show();
                            useGPS = false;
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putBoolean("use_device_location", false);
                            edit.apply();
                            break;
                    }
                }
            });
}
项目:cat-is-a-dog    文件:GoogleAuthenticator.java   
/**
 * Authenticates the user if Google sign in is successful
 * @param completedTask completed google sign in task
 */
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        firebaseAuthWithGoogle(account);
        // Signed in successfully, show authenticated UI.
        //updateUI(account);
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
        onFailed();
    }
}
项目:BLE-Indoor-Positioning    文件:AndroidLocationProvider.java   
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;
            }
        }
    });
}
项目:HiGoogle    文件:HiGoogle.java   
public void fromActivityResult(int requestCode, Intent data){
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            onLoginListener.onSuccess(account);
        } catch (ApiException e) {
            onLoginListener.onFailed(e+"");
        }
    }
}
项目:WalkGraph    文件:MapFragmentImpl.java   
/**
 * Method to check for the location settings of the device,
 * if it doesn't fit the current requirement of the app
 * open the settings for user to change them, if the settings are OK, starts the TimeService.
 */

@Override
public void startLocationService() {
    LocationRequest request = new LocationRequest()
            .setFastestInterval(1500)
            .setInterval(3000)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder settingsRequest = new LocationSettingsRequest.Builder();
    settingsRequest.addLocationRequest(request);

    SettingsClient client = LocationServices.getSettingsClient(getActivity());
    Task<LocationSettingsResponse> responseTask = client.checkLocationSettings
            (settingsRequest.build());

    responseTask.addOnSuccessListener(getActivity(), locationSettingsResponse ->
            locationScheduler());

    responseTask.addOnFailureListener(getActivity(), e -> {
        int statusCode = ((ApiException) e).getStatusCode();

        switch (statusCode){
            case CommonStatusCodes.RESOLUTION_REQUIRED:
                try {
                    ResolvableApiException apiException = ((ResolvableApiException)e);
                    apiException.startResolutionForResult(getActivity(), permissionCode);
                    Log.d(TAG, "Dialog displayed");
                }catch (IntentSender.SendIntentException sendIntentException){
                    Log.d(TAG, "Error displaying dialogBox", sendIntentException);
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                Log.d(TAG, "Unable to turn on location service", e);

        }
    });
}
项目:flavordex    文件:PhotoSyncHelper.java   
/**
 * Set up the Drive API client.
 *
 * @param prefs The SharedPreferences
 * @return Whether the setup was successful
 */
private boolean setupClient(@NonNull SharedPreferences prefs) {
    final GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestScopes(Drive.SCOPE_APPFOLDER)
                    .build();
    final GoogleSignInClient signInClient = GoogleSignIn.getClient(mContext, signInOptions);
    try {
        final GoogleSignInAccount signInAccount = Tasks.await(signInClient.silentSignIn());

        mClient = Drive.getDriveClient(mContext, signInAccount);
        mResourceClient = Drive.getDriveResourceClient(mContext, signInAccount);

        Log.d(TAG, "Connection successful. sync: " + mShouldSync + " media: " + mMediaMounted);

        return true;
    } catch(ExecutionException e) {
        final ApiException result = (ApiException)e.getCause();
        switch(result.getStatusCode()) {
            case GoogleSignInStatusCodes.SIGN_IN_REQUIRED:
            case GoogleSignInStatusCodes.INVALID_ACCOUNT:
                Log.i(TAG, "User not signed in. Disabling photo syncing.");
                prefs.edit().putBoolean(FlavordexApp.PREF_SYNC_PHOTOS, false).apply();
                break;
            case GoogleSignInStatusCodes.API_NOT_CONNECTED:
            case GoogleSignInStatusCodes.NETWORK_ERROR:
            case GoogleSignInStatusCodes.INTERNAL_ERROR:
                Log.i(TAG, "Google Drive service unavailable. Disabling photo syncing.");
                prefs.edit().putBoolean(FlavordexApp.PREF_SYNC_PHOTOS, false).apply();
        }

        Log.w(TAG, "Connection failed! Reason: " + result.getMessage());
    } catch(InterruptedException ignored) {
    }

    return false;
}
项目:google-services    文件:IdTokenActivity.java   
private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        String idToken = account.getIdToken();

        // TODO(developer): send ID Token to server and validate

        updateUI(account);
    } catch (ApiException e) {
        Log.w(TAG, "handleSignInResult:error", e);
        updateUI(null);
    }
}
项目:google-services    文件:SignInActivity.java   
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

        // Signed in successfully, show authenticated UI.
        updateUI(account);
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
        updateUI(null);
    }
}
项目:google-services    文件:SignInActivityWithDrive.java   
private void handleSignInResult(@Nullable Task<GoogleSignInAccount> completedTask) {
    Log.d(TAG, "handleSignInResult:" + completedTask.isSuccessful());

    try {
        // Signed in successfully, show authenticated U
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        updateUI(account);
    } catch (ApiException e) {
        // Signed out, show unauthenticated UI.
        Log.w(TAG, "handleSignInResult:error", e);
        updateUI(null);
    }
}
项目:androidApp    文件:PositionProvider.java   
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());
                        }
                    }
                });
    }
}
项目:android-play-location    文件:GeofenceErrorMessages.java   
/**
 * Returns the error string for a geofencing exception.
 */
public static String getErrorString(Context context, Exception e) {
    if (e instanceof ApiException) {
        return getErrorString(context, ((ApiException) e).getStatusCode());
    } else {
        return context.getResources().getString(R.string.unknown_geofence_error);
    }
}
项目:android-basic-samples    文件:MainActivity.java   
private void handleException(Exception e, String details) {
  int status = 0;

  if (e instanceof ApiException) {
    ApiException apiException = (ApiException) e;
    status = apiException.getStatusCode();
  }

  String message = getString(R.string.status_exception_error, details, status, e);

  new AlertDialog.Builder(MainActivity.this)
      .setMessage(message)
      .setNeutralButton(android.R.string.ok, null)
      .show();
}
项目:android-basic-samples    文件:SkeletonActivity.java   
/**
 * Since a lot of the operations use tasks, we can use a common handler for whenever one fails.
 *
 * @param exception The exception to evaluate.  Will try to display a more descriptive reason for
 *                  the exception.
 * @param details   Will display alongside the exception if you wish to provide more details for
 *                  why the exception happened
 */
private void handleException(Exception exception, String details) {
  int status = 0;

  if (exception instanceof TurnBasedMultiplayerClient.MatchOutOfDateApiException) {
    TurnBasedMultiplayerClient.MatchOutOfDateApiException matchOutOfDateApiException =
        (TurnBasedMultiplayerClient.MatchOutOfDateApiException) exception;

    new AlertDialog.Builder(this)
        .setMessage("Match was out of date, updating with latest match data...")
        .setNeutralButton(android.R.string.ok, null)
        .show();

    TurnBasedMatch match = matchOutOfDateApiException.getMatch();
    updateMatch(match);

    return;
  }

  if (exception instanceof ApiException) {
    ApiException apiException = (ApiException) exception;
    status = apiException.getStatusCode();
  }

  if (!checkStatusCode(status)) {
    return;
  }

  String message = getString(R.string.status_exception_error, details, status, exception);

  new AlertDialog.Builder(this)
      .setMessage(message)
      .setNeutralButton(android.R.string.ok, null)
      .show();
}
项目:android-basic-samples    文件:MainActivity.java   
/**
 * Since a lot of the operations use tasks, we can use a common handler for whenever one fails.
 *
 * @param exception The exception to evaluate.  Will try to display a more descriptive reason for the exception.
 * @param details   Will display alongside the exception if you wish to provide more details for why the exception
 *                  happened
 */
private void handleException(Exception exception, String details) {
  int status = 0;

  if (exception instanceof ApiException) {
    ApiException apiException = (ApiException) exception;
    status = apiException.getStatusCode();
  }

  String message = getString(R.string.status_exception_error, details, status, exception);

  new AlertDialog.Builder(MainActivity.this)
      .setMessage(message)
      .setNeutralButton(android.R.string.ok, null)
      .show();

  // Note that showing a toast is done here for debugging. Your application should
  // resolve the error appropriately to your app.
  if (status == GamesClientStatusCodes.SNAPSHOT_NOT_FOUND) {
    Log.i(TAG, "Error: Snapshot not found");
    Toast.makeText(getBaseContext(), "Error: Snapshot not found",
        Toast.LENGTH_SHORT).show();
  } else if (status == GamesClientStatusCodes.SNAPSHOT_CONTENTS_UNAVAILABLE) {
    Log.i(TAG, "Error: Snapshot contents unavailable");
    Toast.makeText(getBaseContext(), "Error: Snapshot contents unavailable",
        Toast.LENGTH_SHORT).show();
  } else if (status == GamesClientStatusCodes.SNAPSHOT_FOLDER_UNAVAILABLE) {
    Log.i(TAG, "Error: Snapshot folder unavailable");
    Toast.makeText(getBaseContext(), "Error: Snapshot folder unavailable.",
        Toast.LENGTH_SHORT).show();
  }
}
项目:NightSkyGuide    文件:SettingsActivity.java   
public void startLocationUpdates() {
    // if settings are satisfied initialize location requests
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest).addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            locUpdates = true;
            // All location settings are satisfied.
            //noinspection MissingPermission - this comment needs to stay here to stop inspection on next line
            mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
        }
    })
            // if settings need to be changed prompt user
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case 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(SettingsActivity.this, REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sendEx) {
                                // Ignore the error
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // location settings are not satisfied, however no way to fix the settings so don't show dialog.
                            Toast.makeText(context, "Location Services Unavailable", Toast.LENGTH_LONG).show();
                            useGPS = false;
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putBoolean("use_device_location", false);
                            edit.apply();
                            settingsFragment.useDeviceLocation.setChecked(false);
                            settingsFragment.setLocSummary();
                            break;
                    }
                }
            });
}
项目:SpaceRace    文件:MapActivity.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(this, new OnSuccessListener<LocationSettingsResponse>() {
                @SuppressLint({"MissingPermission", "StaticFieldLeak"})
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

                    mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                            mLocationCallback, Looper.myLooper());
                    updateUI(null);
                }
            })
            .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 " + ((ApiException) e).getStatusMessage());
                            try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(MapActivity.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(MapActivity.this, errorMessage, Toast.LENGTH_LONG).show();
                            mRequestingLocationUpdates = false;
                    }

                    updateUI(null);
                }
            });
}
项目:SpaceRace    文件:AbsRoomActivity.java   
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    switch (requestCode) {
        case RC_SIGN_IN:
            Task<GoogleSignInAccount> task =
                    GoogleSignIn.getSignedInAccountFromIntent(intent);

            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                onConnected(account);
            } catch (ApiException apiException) {
                String message = apiException.getMessage();
                message = getString(R.string.signin_other_error) + " " + "(" + message + ")";

                onDisconnected();

                new AlertDialog.Builder(this)
                        .setTitle(R.string.error_during_signin)
                        .setMessage(message + apiException.toString())
                        .setNeutralButton(android.R.string.ok, null)
                        .show();
            }
            break;
        case RC_SELECT_PLAYERS:
            // we got the result from the "select players" UI -- ready to create the room
            handleSelectPlayersResult(resultCode, intent);
            break;
        case RC_INVITATION_INBOX:
            // we got the result from the "select invitation" UI (invitation inbox). We're
            // ready to accept the selected invitation:
            handleInvitationInboxResult(resultCode, intent);
            break;
        case RC_WAITING_ROOM:
            // we got the result from the "waiting room" UI.
            if (resultCode == Activity.RESULT_OK) {
                // ready to start playing
                Log.d("ROOM", "Starting game (waiting room returned OK).");
                startGame();
            } else if (resultCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
                // player indicated that they want to leave the room

            } else if (resultCode == Activity.RESULT_CANCELED) {
                // Dialog was cancelled (user pressed back key, for instance). In our game,
                // this means leaving the room too. In more elaborate games, this could mean
                // something else (like minimizing the waiting room UI).

            }
            break;
    }

    super.onActivityResult(requestCode, resultCode, intent);

}
项目:WeatherPlus    文件:MainActivity.java   
private void checkLocationSettings() {
    Log.d(TAG, "Checking device's configuration");

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

    LocationSettingsRequest mLocationSettingsRequest = builder.build();

    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)

            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {

                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.d(TAG, "All location settings are satisfied");

                    findCurrentLocation();
                }
            })

            .addOnFailureListener(this, new OnFailureListener() {

                @Override
                public void onFailure(@NonNull Exception e) {
                    int statusCode = ((ApiException) e).getStatusCode();

                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.d(TAG, "Location settings are not satisfied. Attempting to " +
                                    "upgrade location settings");

                            try {
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult(MainActivity.this,
                                        REQUEST_CHECK_SETTINGS);

                                if (mResultCallBack != null)
                                    mResultCallBack.onConfigurationNeeded();

                            } catch (IntentSender.SendIntentException sie) {
                                Log.d(TAG, "PendingIntent unable to execute request.");

                                if (mResultCallBack != null)
                                    mResultCallBack.onError(sie.getMessage());
                            }
                            break;

                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, " +
                                    "and cannot be fixed here. Fix in Settings.";
                            Log.d(TAG, errorMessage);

                            if (mResultCallBack != null)
                                mResultCallBack.onError(errorMessage);
                    }
                }
            });
}
项目:googleplayAPI    文件:MainActivity.java   
protected void startLocationUpdates() {
    //first check to see if I have permissions (marshmallow) if I don't then ask, otherwise start up the demo.
    if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) &&
            (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        //I'm on not explaining why, just asking for permission.
        Log.v(TAG, "asking for permissions");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                MainActivity.REQUEST_ACCESS_startLocationUpdates);
        return;
    }

    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @SuppressLint("MissingPermission")
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

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

                }
            })
            .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;
                    }


                }
            });


}
项目:googleplayAPI    文件:MainActivity.java   
protected void startLocationUpdates() {
    //first check to see if I have permissions (marshmallow) if I don't then ask, otherwise start up the demo.
    if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) &&
            (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        //I'm on not explaining why, just asking for permission.
        Log.v(TAG, "asking for permissions");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                MainActivity.REQUEST_ACCESS_startLocationUpdates);
        return;
    }
    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
                @SuppressLint("MissingPermission")
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                    Log.i(TAG, "All location settings are satisfied.");

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

                }
            })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    mRequestingLocationUpdates = false;
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.i(TAG, "Location settings are not satisfied. ");
                            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;
                    }


                }
            });
}
项目:android-play-location    文件:MainActivity.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(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();
                }
            });
}
项目:android-basic-samples    文件:MainActivity.java   
/**
 * Since a lot of the operations use tasks, we can use a common handler for whenever one fails.
 *
 * @param exception The exception to evaluate.  Will try to display a more descriptive reason for the exception.
 * @param details   Will display alongside the exception if you wish to provide more details for why the exception
 *                  happened
 */
private void handleException(Exception exception, String details) {
  int status = 0;

  if (exception instanceof ApiException) {
    ApiException apiException = (ApiException) exception;
    status = apiException.getStatusCode();
  }

  String errorString = null;
  switch (status) {
    case GamesCallbackStatusCodes.OK:
      break;
    case GamesClientStatusCodes.MULTIPLAYER_ERROR_NOT_TRUSTED_TESTER:
      errorString = getString(R.string.status_multiplayer_error_not_trusted_tester);
      break;
    case GamesClientStatusCodes.MATCH_ERROR_ALREADY_REMATCHED:
      errorString = getString(R.string.match_error_already_rematched);
      break;
    case GamesClientStatusCodes.NETWORK_ERROR_OPERATION_FAILED:
      errorString = getString(R.string.network_error_operation_failed);
      break;
    case GamesClientStatusCodes.INTERNAL_ERROR:
      errorString = getString(R.string.internal_error);
      break;
    case GamesClientStatusCodes.MATCH_ERROR_INACTIVE_MATCH:
      errorString = getString(R.string.match_error_inactive_match);
      break;
    case GamesClientStatusCodes.MATCH_ERROR_LOCALLY_MODIFIED:
      errorString = getString(R.string.match_error_locally_modified);
      break;
    default:
      errorString = getString(R.string.unexpected_status, GamesClientStatusCodes.getStatusCodeString(status));
      break;
  }

  if (errorString == null) {
    return;
  }

  String message = getString(R.string.status_exception_error, details, status, exception);

  new AlertDialog.Builder(MainActivity.this)
      .setTitle("Error")
      .setMessage(message + "\n" + errorString)
      .setNeutralButton(android.R.string.ok, null)
      .show();
}
项目:android-basic-samples    文件:MainActivity.java   
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

  if (requestCode == RC_SIGN_IN) {

    Task<GoogleSignInAccount> task =
        GoogleSignIn.getSignedInAccountFromIntent(intent);

    try {
      GoogleSignInAccount account = task.getResult(ApiException.class);
      onConnected(account);
    } catch (ApiException apiException) {
      String message = apiException.getMessage();
      if (message == null || message.isEmpty()) {
        message = getString(R.string.signin_other_error);
      }

      onDisconnected();

      new AlertDialog.Builder(this)
          .setMessage(message)
          .setNeutralButton(android.R.string.ok, null)
          .show();
    }
  } else if (requestCode == RC_SELECT_PLAYERS) {
    // we got the result from the "select players" UI -- ready to create the room
    handleSelectPlayersResult(resultCode, intent);

  } else if (requestCode == RC_INVITATION_INBOX) {
    // we got the result from the "select invitation" UI (invitation inbox). We're
    // ready to accept the selected invitation:
    handleInvitationInboxResult(resultCode, intent);

  } else if (requestCode == RC_WAITING_ROOM) {
    // we got the result from the "waiting room" UI.
    if (resultCode == Activity.RESULT_OK) {
      // ready to start playing
      Log.d(TAG, "Starting game (waiting room returned OK).");
      startGame(true);
    } else if (resultCode == GamesActivityResultCodes.RESULT_LEFT_ROOM) {
      // player indicated that they want to leave the room
      leaveRoom();
    } else if (resultCode == Activity.RESULT_CANCELED) {
      // Dialog was cancelled (user pressed back key, for instance). In our game,
      // this means leaving the room too. In more elaborate games, this could mean
      // something else (like minimizing the waiting room UI).
      leaveRoom();
    }
  }
  super.onActivityResult(requestCode, resultCode, intent);
}