androidmauiaccount

MAUI read accounts ANDROID


Is there any way to read what accounts are on Android using MAUI (e.g. Google)? I need only email whith is logged on phone.


Solution

  • First of all, please add the following permission in the AndroidManifest.xml:

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

    And then please add the following code in the MainActivity to request the permission at runtime:

    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        string[] accountPermission =
        {
            Manifest.Permission.GetAccounts,
            Manifest.Permission.ReadContacts
        };
    
        if (this.CheckSelfPermission(Manifest.Permission.GetAccounts) != Permission.Granted|| this.CheckSelfPermission(Manifest.Permission.ReadContacts) != Permission.Granted)
         {
             this.RequestPermissions(accountPermission,0);
         }
    }
    

    And then you can get accounts by the following code:

    #if ANDROID
          var accountManager = (Android.Accounts.AccountManager)Platform.CurrentActivity.GetSystemService(Android.Content.Context.AccountService);
          Android.Accounts.Account[] accounts = accountManager.GetAccounts();
    #endif