Test Script

Saturday, April 27, 2013

Fetching User's Email ID

Hi guys in this tutorial I am going to be showing you how to fetch the user's email Id which has been tied to the users device. This is a very short & simple tutorial so without wasting further time lets get to work :

================================================================
MainActivity.java
================================================================


package com.example.testemail;



import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String emailId = getEmailId();
        Toast.makeText(getApplicationContext(), emailId, 500).show();

}

   public String getEmailId(){

      Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
    
   
    for(Account account: accounts)
    {
        String emailId=account.toString();
        Log.d("List of  email id's of user", emailId);

    }

     String myEmailid=accounts[0].name;

    return myEmailid;
   }

}

================================================================

You also need a permission to access the Accounts 

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

So add the above permission to your Manifest file.

================================================================




So, let me quickly explain what i did above :
1) I created a method which fetches the User's email ID
2) Here we get a Array of Accounts using the AccountManager, notice "getAccountsByType("com.google");" 
that is used to to get all Gmail Accounts configured in the users device

3) "accounts[0].name"  gives me the Email Id of the first Account of the user, which is most likely to be the users actual Gmail Id.

4) Finally added a permission of GET_ACCOUNTS required to access the accounts.

Thats all there is, this is used to fetch user's gmail Id programmatically.


================================================================

Note : Try this on a actual device rather than a emulator because the emulator has no Email Id by default .

If this post helped you, please do drop a comment & i will be happy !

As always feel  free to comment or fire any queries to me ! 



No comments:

Post a Comment

UA-42774700-1 Twitter Bird Gadget