GMail API 在 UserRecoverableAuthUIException 之前授予权限

GMail API Grant Permissions Before UserRecoverableAuthUIException

我已经按照 Google 中的快速入门示例设置 GMail API:https://developers.google.com/gmail/api/quickstart/android

我的应用程序成功请求 GET_ACCOUNTS 权限并允许用户使用 select his/her gmail 帐户。 selected 帐户保存在 SharedPreferences 中供以后访问。

通过 IntentService,我的应用程序发送电子邮件。我已按照位于此处的说明进行操作:https://developers.google.com/gmail/api/guides/sending 并根据需要包含了 activation.jar、additional.jar 和 mail.jar 库。当我发送包含以下代码的电子邮件时,我收到 UserRecoverableAuthUIException:

message = service.users().messages().send(userId, message).execute();

当我捕捉到异常时,获取与异常一起存储的意图,并将意图作为一个新的 activity 启动,我会看到一个对话框,让我有机会允许我的应用程序发送电子邮件GMail 帐户:

在此对话框中按 'Allow' 后,我的应用程序发送电子邮件时没有任何其他问题。我的应用程序也出现在我的 Google 帐户在线权限页面上,表明它有权发送电子邮件。

有没有办法在我第一次获取用户帐户名时手动触发此对话框,而不是等待异常发生?

更新

如果有帮助的话,我已经能够提取意图中存储的操作和数据:

其中 KEY 是一系列字符,可能链接到我的帐户或者是一个令牌。

编辑:

以下是创建 Credentials 对象并启动我正在使用的帐户选择器 activity 的代码:

private GoogleAccountCredential mCredential;
private static final String[] SCOPES = { GmailScopes.GMAIL_COMPOSE };

内部构造函数:

mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff());

我在哪里获得帐户:

private void chooseGMailAccount() {
        String accountName = this.getSharedPreferences(getString(R.string.shared_pref_main),
                Context.MODE_PRIVATE)
                .getString(getString(R.string.srd_pref_gmail_account), null);
        if (accountName != null) {
            mCredential.setSelectedAccountName(accountName);
            configureGMailAPI();
        } else {
            startActivityForResult(
                    mCredential.newChooseAccountIntent(),
                    REQUEST_ACCOUNT_PICKER);
        }
    }

要在用户选择帐户时请求 "managing drafts and sending emails" 权限,请在构建 GoogleAccountCredential 时将 GmailScopes.GMAIL_COMPOSE 包含在范围中。

   import com.google.api.services.gmail.GmailScopes;

   String[] SCOPES = { GmailScopes.GMAIL_COMPOSE, GmailScopes.GMAIL_LABELS };
   int REQUEST_ACCOUNT_PICKER = 1001;

   GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
            getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());

   startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);

有关范围列表,请参阅 the Gmail API Javadoc

您可以尝试向您的清单添加一些权限

<uses-permission android:name="com.google.android.gm.permission.WRITE_GMAIL" />
<uses-permission android:name="com.google.android.gm.permission.AUTO_SEND" />

它仍然需要 oAuth 来进行用户身份验证,但会自动允许意图这些权限...

尚未测试,但可能有效

尝试在注册时发送邮件,即在用户选择帐户后。此时它会捕获异常,一旦你得到这个异常就会显示这个弹出窗口。在这个用户之后就可以了。我想没有直接的方法来触发这个弹出窗口。根据 developers.google.com/drive/android/auth。授权发生在发送请求时收到错误的响应。您的应用程序必须准备好捕获 UserRecoverableAuthIOException。这意味着用户需要授权该应用程序。在您的应用获得用户授权之前,您的应用无法执行任何操作。