获取 phone Xamarin.Android 的号码?

Getting the number of the phone Xamarin.Android?

我发现某些用户共享的这段代码在我的项目中不起作用。有没有人有更好的解决方案?

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

我在 getLine1Number()mAppContext

上遇到错误

您是否将 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 添加到清单中?

这不是很完美,但却是唯一的方法(至少据我所知)。更广泛的讨论在这里 Programmatically obtain the phone number of the Android phone

您的代码适用于本机 Android (Java)。试试下面的 Xamarin.Android (c#).

代码

代码:

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

所需权限:

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

[已编辑]

如果号码不可用,有时Line1Number属性会returnnull,但没有说明什么时候号码可能不可用。

这些是由于 phone 号码未在您的手机中注册的原因,或者根据设备制造商设置的某些限制。

From Documentation :

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

所以您做对了所有事情,但是没有存储 phone 个号码。

如果你得到 null,你可以显示一些东西让用户输入 his/her 自己的 phone 号码。