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

Viewed 5462

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/

2 Answers

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;
    }
}
Related