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.
1 2 3 4 | 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
1 | <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.
This Xamarin Forms application to help you manage your expenses and income was built entirely with Xamarin Forms and ReactiveUI. You can download and use it or play with it for free on Android and Windows 10 (Universal Windows Platform). You can get it on Playstore, or on the Microsoft Store.
Follow me on social media and stay updatedImplementing 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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.
1 2 3 4 | 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.
Follow me on social media and stay updated Follow me on social media and stay updatedIf you find this article useful, please follow me on Twitter, Github, Linkedin, or like my Facebook page to stay updated.
Thomas Müller
Ognian Chernokozhev
aayush sapkota
Damien Doumer