Добавление объема диска в приложение Android приводит к ошибке NeedPermission - PullRequest
0 голосов
/ 02 мая 2019

Мое приложение уже будет делать:

  1. Вход в Google с авторизацией Firebase.
  2. Загрузка аудиофайла через Firebase в облако Google.
  3. Запуск Google Speech to Text API для аудиофайла.
  4. Загрузка полученного текста в приложение.

Теперь я хочу скопировать аудиофайл и переведенный текст с моего устройства на Google Drive, но не могу получить правильные разрешения и логику.Я получаю сообщение об ошибке UserRecoverableAuthException: NeedPermission при добавлении области действия накопителя.

Что необходимо сделать, чтобы добавить разрешения на экране учетных данных Google и / или в коде приложения?

Текущий код приложенияниже.

 private void setupGoogleAndFirebase() {
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    // Scope is to allow speech to text api to read uploaded gcs audio file
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            // Strings from src/debug/res/values/strings.xml
            .requestIdToken(getString(R.string.web_client_id))
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    mAuth = FirebaseAuth.getInstance();
}

 @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);
            updateUI(null);
            displaySignOnErrorDialog(getString(R.string.google_signin_unsuccessful));
        }
    }
}

private void firebaseAuthWithGoogle(final GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
    showProgressDialog();

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithCredential:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                    // get token for passing to jobscheduler for xlat of audio
                    new Oauth2TokenTask().execute(acct.getAccount());
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithCredential:failure", task.getException());
                    displaySignOnErrorDialog(getString(R.string.firebase_signin_unsuccessful));
                    updateUI(null);
                }
                hideProgressDialog();
            });
}

 /**
 * AsyncTask that uses the credentials from Google Sign In to access the cloud api.
 */
private class Oauth2TokenTask extends AsyncTask<Account, Void, String> {

    @Override
    protected void onPreExecute() {
        showProgressDialog();
    }

    @Override
    protected String doInBackground(Account... params) {
        try {
            ArrayList<String> scopes = new ArrayList<>();
            scopes.add("https://www.googleapis.com/auth/cloud-platform");
           // Adding Drive scope below causes error.
            scopes.add("https://www.googleapis.com/auth/drive.file"); 
            GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
                    SignInActivity.this, scopes);
            credential.setSelectedAccount(params[0]);
            return credential.getToken();
        } catch (UserRecoverableAuthIOException userRecoverableException) {
            Log.w(TAG, "UserRecoverableAuthIOException", userRecoverableException);
            startActivityForResult(userRecoverableException.getIntent(), RC_RECOVERABLE);
        } catch (GoogleAuthException e) {
            Log.w(TAG, "GoogleAuthException:" + e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            Log.w(TAG, "IOException:" + e.toString());
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String oauth2Token) {
        hideProgressDialog();
        if (oauth2Token == null) {
            displaySignOnErrorDialog(getString(R.string.error_on_getting_oauth2_token));
        } else {
            TokenStorage.storeToken(SignInActivity.this, oauth2Token);
            createJobSchedulerJob(speechToTextConversionData, oauth2Token);
            finish();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...