What I want that, from a service, I want to read the gmail message body when a gmail notification has arrived. When The Gmail Notification has arrived an alarm will occure and
Update: Extended version if anyone needs (Medium): https://shorturl.at/zKQR7
First you need to make sure you are authenticated using Google. You can do that with Firebase Auth (before use, you will have to look how it's configured, there is good documentation available) :
val providers = arrayListOf(
AuthUI.IdpConfig.GoogleBuilder().build()
)
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RQ_FIREBASE_AUTH
)
Once authenticated, you can use FirebaseAuth.getInstance().currentUser
.
Next step would be to setup Gmail service:
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()
Please note the above is not production ready stuff of course.
Finally, here is reading part:
val messageRead = service.users().messages()?.get(FirebaseAuth.getInstance().currentUser?.email, message?.id)?.setFormat("raw")?.execute()
So you can get a glimps into body of your message like this messageRead?.snippet
There are two not obvious things to note though:
You must expect and handle UserRecoverableAuthIOException
exception. This is the point when user has to explicitly grant your app to do certain stuff with messages
All these execute
calls not be handle don main thread.
Hope it helps! (sorry don't have time to write detailed how-to).