Fawwaz Ali
Fawwaz Ali

Reputation: 57

How to get email which was first given to a android phone?

I am making a android app where I need primary email which was given at time when phone was booted first time. After digging up people said that is not possible instead go for first email that will be oldest I have a Kotlin code which I am using to retrieve the email Code is as follows:

fun getEmail(context: Context?): String? {
    val accountManager = AccountManager.get(context)
    val account = getAccount(accountManager)
    return account?.name
}
private fun getAccount(accountManager: AccountManager): Account? {
    val accounts = accountManager.getAccountsByType("com.google")
    val account: Account?
    account = if (accounts.isNotEmpty()) {
        accounts[0]
    } else {
        null
    }
    return account
}

When I call getEmail() function it returns me null instead of email

I have also added the following permissions in Manifest :

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

How do I retrieve the emails?

Upvotes: 1

Views: 641

Answers (1)

Aymen Ben Salah
Aymen Ben Salah

Reputation: 509

This worked for me Manifest.xml

    <uses-permission
        android:name="android.permission.GET_ACCOUNTS"
        android:maxSdkVersion="22" />

Kotlin

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState
    Log.d(TAG,"${getAccount(AccountManager.get(this))}")

}
    private fun getAccount(accountManager: AccountManager): Account? {
        val accounts = accountManager.getAccountsByType("com.google")
        val account: Account? = if (accounts.isNotEmpty()) {
            accounts[0]
        } else {
            null
        }
        return account
    }

console result :

Account {[email protected], type=com.google}

Upvotes: 1

Related Questions