Search code examples
javaandroidgoogle-apigoogle-drive-api

onActivityResult always returning not authorized


I'm trying to just sign a user to the app to be able to use Google Drive API, but in my activityResults I always get the else statement and that means the user is not authorized or the sign in have failed. Why might this be? I have followed the official docs.

Here is my code:

private static final int REQUEST_CODE_SIGN_IN = 0;
    private DriveClient mDriveClient;
    private DriveResourceClient mDriveResourceClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        signIn();
    }



    private void initializeDriveClient(GoogleSignInAccount signInAccount) {
        mDriveClient = Drive.getDriveClient(getApplicationContext(), signInAccount);
        mDriveResourceClient = Drive.getDriveResourceClient(getApplicationContext(), signInAccount);
    }

    /**
     * Starts the sign-in process and initializes the Drive client.
     */
    private void signIn() {
        Set<Scope> requiredScopes = new HashSet<>(2);
        requiredScopes.add(Drive.SCOPE_FILE);
        requiredScopes.add(Drive.SCOPE_APPFOLDER);
        GoogleSignInAccount signInAccount = GoogleSignIn.getLastSignedInAccount(this);
        if (signInAccount != null && signInAccount.getGrantedScopes().containsAll(requiredScopes)) {
            initializeDriveClient(signInAccount);
        } else {
            GoogleSignInOptions signInOptions =
                    new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .requestScopes(Drive.SCOPE_FILE)
                            .requestScopes(Drive.SCOPE_APPFOLDER)
                            .build();
            GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(this, signInOptions);
            startActivityForResult(googleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case REQUEST_CODE_SIGN_IN:
                if (resultCode == Activity.RESULT_OK) {
                    // App is authorized, you can go back to sending the API request

                    Log.e("SignIn", "App autorizada");
                } else {
                    // User denied access, show him the account chooser again
                    Log.e("SignIn", "App No Autorizada");
                    finish();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Solution

  • Solved my own problem pasting the SHA1 and package name into credentials in my google console, it seemed i was doing something wrong with the credentials.