0

I found out that this code shared by some users doesn't work in my project. Has anyone a better solution ?

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

I'm getting an error on the getLine1Number() and on the mAppContext

Yksh
  • 3,899
  • 10
  • 53
  • 101
Luis Violas
  • 77
  • 2
  • 9
  • 2
    Possible duplicate of [Programmatically obtain the phone number of the Android phone](http://stackoverflow.com/questions/2480288/programmatically-obtain-the-phone-number-of-the-android-phone) – Bajirao Shinde Mar 16 '16 at 10:54
  • What error are you getting? – stefana Mar 16 '16 at 11:00
  • "mAppContext does not exist in the current context" and "TelephonyManager does not contain a defenition for GetLine1Number()" – Luis Violas Mar 16 '16 at 11:04
  • @LuisViolas : Your code is in native Android (Java). You must use Xamarin.Android (C#). Try this : http://stackoverflow.com/a/36034077/3891036 – Yksh Mar 16 '16 at 11:22

2 Answers2

2

Your code is for native Android (Java). Try the below code of Xamarin.Android (c#).

Code:

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

Required Permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

[Edited]

Sometimes Line1Number Property will return null if the number is unavailable, but it does not say when the number might be unavailable.

These are occured due to the reason that the phone number not register in your mobile, or according to some restrictions created by the device manufactures.

From Documentation :

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.

So you have done everything right, but there is no phone number stored.

If you get null, you could display something to get the user to input the phone number on his/her own.

Community
  • 1
  • 1
Yksh
  • 3,899
  • 10
  • 53
  • 101
0

Did you add <uses-permission android:name="android.permission.READ_PHONE_STATE"/> to manifest?

It's not really perfect, but the only way (at least to my knowledge). Broader discussion is here Programmatically obtain the phone number of the Android phone

Community
  • 1
  • 1
Jakoss
  • 2,877
  • 2
  • 18
  • 32