How To Get A Device Owner’s Current User Name With Xamarin Forms

Get The Current User Name with Xamarin Forms
Get The Current User Name with Xamarin Forms

Hi everyone, what’s up ?. I’m sure if you are reading this post, you may be looking for a means to have the name of your users on your app. Without having to ask them for it. If that is the case, you are at the right place. This is something tricky to accomplish, but it is possible. And as you might have guessed, yes! it requires platform specific code.With restrictions set on user information by the device’s operating system, getting this info requires permissions from the user.

Here is the source code for this post.

Getting A Device Owner’s Current User Name with Xamarin Forms

We will dive into the topic. And this post will guide through implementing this functionality on your Xamarin.Forms app quickly. Every information here is in the form of points easy to follow. First, obviously, you should create your project.

Create the interface in shared code.

Since we are using platform specific code, an interfaced has to be created in your shared project. This interface will be implemented in each platform. Here is the interface.

public interface IUserInformation
   {
       Task<string> GetUserName();
   }
Request permissions on UWP

As I mentioned in the beginning, we can’t access user information just like that. It is obvious that we need permissions from the user. This is easily done on UWP. In your app manifest file, add the User Account Information permissions.

UWP Permissions to get Current User Name with Xamarin Forms.png
UWP Permissions to get Current User Name with Xamarin Forms.png
Implement the User Information Interface on UWP

Now we are to implement this interface on UWP. The code to get the current user name with xamarin forms on UWP written here.

public async Task<string> GetUserName()
        {
            IReadOnlyList<User> users = await User.FindAllAsync();

            var current = users.Where(p => p.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && p.Type == UserType.LocalUser).FirstOrDefault();
            
            var data = await current.GetPropertyAsync(KnownUserProperties.AccountName);
            string username = data.ToString();

            if (String.IsNullOrEmpty(username))
            {
                username = $"{(await current.GetPropertyAsync(KnownUserProperties.FirstName)).ToString()} {(await current.GetPropertyAsync(KnownUserProperties.LastName)).ToString()}";
            }

            return username;
        }

You could modify this method to get the user’s profile photo and a few more information. But I won’t cover it in this post.

Adding permissions on Android

On android too, you need permissions to get user information. Add this line of code to your manifest file.

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Add a Xamarin plugin to get the current activity

If you have developed android apps. you should be aware that most often you will need a context to perform most tasks in your app. Since we are implementing an interface, which will access native android functionalities, we will definitely need the current activity. This is easy, thanks to this plugin. Follow the installation instructions on github and when you are done, come back to this post to continue to the next step.

Implementing User Information interface on Android

Once you are done installing the above plugin and making it work, we can implement the getting the current user name with Xamarin Forms.

We will follow the instructions given in the Android documentation.  This will give us several account objects, from which we will chose the appropriate. An account object has a Name property, but this contains the email instead. what we will do is split this email to get the user name from it. Here is how we do it.

public async Task<string> GetUserName()
        {
            FormsAppCompatActivity activity = CrossCurrentActivity.Current.Activity as FormsAppCompatActivity;

            AccountManager manager = AccountManager.Get(activity);
            Account[] accounts = manager.GetAccountsByType("com.google");
            List<String> emails = new List<string>();

            foreach (Account account in accounts)
            {
                var name = account.Name;
                emails.Add(account.Name);
            }

            if (emails.Any() && emails[0] != null)
            {
                String email = emails[0];
                String[] parts = email.Split('@');

                if (parts.Length > 1)
                    return parts[0];
            }

            return "";
        }

Now that we have implemented how to get the device’s current user name on each platform. We can call the platform specific code from the shared Xamarin.Forms project. NB: I’m still to find a way to implement this on iOS. Here is how we call this code in the shared project.

await DependencyService.Get<IUserInformation>().GetUserName().ContinueWith(t =>
{
    Device.BeginInvokeOnMainThread(() => UserNameLabel.Text = t.Result);
});

Conclusion

With this, you should be able to get user names on devices where your application is installed. This can be useful on various scenarios when building your app. You may also be interested about this topic :  5 Xamarin.Forms Debugging Nightmares And Their Solutions. 

If you liked this post, or it was useful to you, please 👍 like it, share it on twitter, facebook or other social media… in case you want to get updated on any new useful post, follow me on twitter  and like my page on facebook. And every other social media by clicking on the  buttons at the end of this post.

Follow me on social media and stay updated

Follow me on social media and stay updated

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.