Search code examples
androiduseridgoogle-account

Android: user ID account (not ID phone)


I have an app that save the user image but i would save with each image also user id.

The user can change telephone device but the google account is always the same.

I need a code string that identify the user and not the phone.

Maybe a numeric id, not necessarily google account email.

I have this code but is wrong (return device id and not user id)

TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephoneCode = tm.getDeviceId();

or

String code=Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

# # # # # # # # #

I have test with

AccountManager mgr = AccountManager.get(getApplicationContext());
Account[] accounts = mgr.getAccountsByType("com.google");
String userCode=accounts.toString();

In this code return a string:

[Landroid.accounts.Account;@318ca48b

This alphanumeric code always change!

Thank's Daniele.


Solution

  • Here is how I do it:

    AccountManager accountManager = AccountManager.get(getApplicationContext());
    
    Account[] accounts = accountManager.getAccountsByType("com.google");
    
    for (Account a: accounts) {
        if (a.name.contains("@gmail.com")) {
            return a.name;
        }
    }
    

    This will return the first account that ends in @gmail.com; there can be more than one.