'Xamarin.Forms; display the phone number of my SIM Card at device on the screen

I want to display the phone number of my device on the screen.

In Xamarin.Android the code is work. But I want to use a code in Xamarin.Forms. I've searched but I did not find any results.

Android.Telephony.TelephonyManager tMgr = (Android.Telephony.TelephonyManager)this.GetSystemService(Android.Content.Context.TelephonyService);
string mPhoneNumber = tMgr.Line1Number;

-I gave permission : READ_PHONE_STATE

   <StackLayout>
        <Button FontSize="Large" Text="Telefon Numarasını Al" BackgroundColor="Blue" x:Name="btnNumaraAl" Clicked="btnNumaraAl_Clicked"></Button>
        <Label FontSize="Large" BackgroundColor="Red" x:Name="txtPhone" VerticalOptions="Center" HorizontalOptions="Center"></Label>
    </StackLayout>

When I click btnNumaraAl, txtPhone.Text can be my device phone number.

Resources : Getting the number of the phone Xamarin.Android? https://developer.xamarin.com/api/type/Android.Telephony.TelephonyManager/



Solution 1:[1]

  1. Define your abstraction, an interface in your Xamarin.Forms project.

    namespace YourApp
    {
      public interface IDeviceInfo
      {
        string GetPhoneNumber();
      }
    }
    
  2. Then, you need to implement in each platform. Android implementation should look like this.

    using Android.Telephony;
    using TodoApp;
    using Xamarin.Forms;
    [assembly:Xamarin.Forms.Dependency(typeof(YourApp.Droid.DeviceInfo))]
    namespace YourApp.Droid
    {
        public class DeviceInfo: IDeviceInfo
        {
            public string GetPhoneNumber()
            {
                var tMgr = (TelephonyManager)Forms.Context.ApplicationContext.GetSystemService(Android.Content.Context.TelephonyService);
                return tMgr.Line1Number;
            }
        }
    }
    
  3. And finally, you can use in your Xamarin.Forms project using the DependencyService.

     var deviceInfo = Xamarin.Forms.DependencyService.Get<TodoApp.IDeviceInfo>();
     var number = deviceInfo.GetPhoneNumber();
    

Just to mention that on iOS you cannot get the owner phone number due to security restrictions. You can review this question Programmatically get own phone number in iOS

Based on that you may need to check if your app is on Android or iOS.

switch(Device.RuntimePlatform){
  case "Android":
     //you can
     break;
  case "iOS"
     //You can't
     break;
}

Solution 2:[2]

Im having issue with permission --> Java.Lang.SecurityException: 'getLine1NumberForDisplay: Neither user 10198 nor current process has android.permission.READ_PHONE_STATE or android.permission.READ_SMS.'

and this solution works for me in Android

1.) Shared Project

namespace YourApp
{
   public interface IDeviceInfo
   {
      class Status
      {
         public bool Granted { get; set; } = false;
         public List<string> MobileNumbers { get; set; }
      }
      Status GetPhoneNumber();
   }
}

2.) Android project class, assuming you need to get the 2 simcards numbers

using Android.Content;
using Android.Telephony;
using System;
using System.Collections.Generic;
using Application = Android.App.Application;

[assembly: Xamarin.Forms.Dependency(typeof(YourApp.Droid.DeviceInfo))]
namespace YourApp.Droid
{
    public class DeviceInfo : IDeviceInfo
    {
        IDeviceInfo.Status IDeviceInfo.GetPhoneNumber()
        {
            var status = new IDeviceInfo.Status();
            List<string> PhoneNumbers = new List<string>();
            try
            {
                SubscriptionManager subscriptionManager = (SubscriptionManager)Application.Context.GetSystemService(Context.TelephonySubscriptionService);
                IList<SubscriptionInfo> subscriptionInfoList = subscriptionManager.ActiveSubscriptionInfoList;
                foreach (SubscriptionInfo subscriptionInfo in subscriptionInfoList)
                {
                    string numbers = subscriptionInfo.Number;
                    if (numbers.Length > 0)
                    {
                        PhoneNumbers.Add(numbers);
                    }
                }
                status.Granted = true;
                status.MobileNumbers = PhoneNumbers;
                return status;
            }
            catch (Exception)
            {
                return status;
                throw;
            }
        }
    }
}

3.) Android MainActivity.cs, Add runtime permission.

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    TryToGetPermission();
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
        switch (requestCode)
        {
            case RequestLocationId:
                {
                    if (grantResults[0] != (int)Permission.Granted)
                    {
                        Toast.MakeText(ApplicationContext, "Application cannot continue without access to the local phone device.  Exiting...", ToastLength.Long).Show();
                        Java.Lang.JavaSystem.Exit(0);
                    }
                }
                break;
        }
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#region Runtime Permission

    protected void TryToGetPermission()
    {
        if ((int)Build.VERSION.SdkInt >= 23)
        {
            GetPermissions();
            return;
        }
    }

    const int RequestLocationId = 0;
    protected void GetPermissions()
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadPhoneState) != (int)Permission.Granted)
        {
            RequestPermissions(new string[] { Manifest.Permission.ReadPhoneState }, RequestLocationId);
        }
    }

#endregion

4.) Shared Project Startup Page

protected override async void OnAppearing()
{
    base.OnAppearing();
    GetMobileNumber:
    switch (Device.RuntimePlatform)
    {
        case "Android":
            // App need to wait until the permission is granted
            while (DependencyService.Get<IDeviceInfo>().GetPhoneNumber().Granted == false)
            {
                await Task.Delay(1000);
                goto GetMobileNumber;
            }
            break;
        case "iOS":
            break;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2