Getting the number of the phone Xamarin.Android?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 03:33:12

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/36033428/getting-the-number-of-the-phone-xamarin-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!