-1

我想要什么,从服务中,我想在 gmail 通知到达时阅读 gmail 消息正文。当 Gmail 通知到达时,会发生警报,​​我会在 alarmReceiver 中获得全文。

我在这里得到了 android 快速入门 gsuits api:https ://developers.google.com/gsuite/guides/android 。但这里只描述了 Android Sdk 和 Dependencies。我没有找到捕获 gmail 正文的整个过程。

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.google.android.gms:play-services-auth:15.0.1'
compile 'pub.devrel:easypermissions:0.3.0'
compile('com.google.api-client:google-api-client-android:1.23.0') {
    exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-<API>-<VERSION>') {
    exclude group: 'org.apache.httpcomponents'
}}

之后,我可以在我的 android 应用程序中检索/获取 gmail 正文的逐步整个过程是什么?

4

1 回答 1

1

更新:如果有人需要,扩展版本(中):https ://shorturl.at/zKQR7


首先,您需要确保您已使用 Google 进行身份验证。您可以使用 Firebase Auth 来做到这一点(在使用之前,您必须查看它的配置方式,有很好的文档可用):

            val providers = arrayListOf(
                AuthUI.IdpConfig.GoogleBuilder().build()
            )

            startActivityForResult(
                AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
                RQ_FIREBASE_AUTH
            )

验证后,您可以使用FirebaseAuth.getInstance().currentUser.

下一步是设置 Gmail 服务:

            val credential = GoogleAccountCredential.usingOAuth2(
                applicationContext, listOf(GmailScopes.GMAIL_LABELS, GmailScopes.GMAIL_READONLY)
            )
                .setBackOff(ExponentialBackOff())
                .setSelectedAccountName(FirebaseAuth.getInstance().currentUser?.email)

            val service = Gmail.Builder(
                NetHttpTransport(), AndroidJsonFactory.getDefaultInstance(), credential
            )
                .setApplicationName("YourAppName")
                .build()

请注意,上述内容当然不是生产就绪的东西。

最后,这里是阅读部分:

val messageRead = service.users().messages()?.get(FirebaseAuth.getInstance().currentUser?.email, message?.id)?.setFormat("raw")?.execute()

因此,您可以像这样大致了解您的消息正文messageRead?.snippet

不过,有两件不明显的事情需要注意:

  1. 您必须期待并处理UserRecoverableAuthIOException异常。这就是用户必须明确授予您的应用程序使用消息执行某些操作的点

  2. 所有这些execute调用都不是主线程的句柄。

希望能帮助到你!(抱歉没有时间写详细的操作方法)。

于 2020-03-07T15:06:06.523 回答