Search code examples
androidxamarinxamarin.androidxamarin.forms

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