简体   繁体   English

Xamarin.Droid - 获取设备电话号码

[英]Xamarin.Droid - Get device phone number

I'm currently working on a Xamarin forms project in which I need to be able to get the user's phone number from device. 我目前正在开发一个Xamarin表单项目,我需要能够从设备中获取用户的电话号码。 It figured out that it was not possible to do that on iOS and Windows Phone, but I still want to do that for Android, that's why I've found on the Internet a piece of code that should be working on Android. 它发现在iOS和Windows Phone上无法做到这一点,但我仍然希望为Android做到这一点,这就是为什么我在互联网上发现了一段应该在Android上工作的代码。 I'm using MVVM pattern. 我正在使用MVVM模式。

In my ViewModel, I try to get the phone number this way : 在我的ViewModel中,我尝试以这种方式获取电话号码:

   string phoneNumber = DependencyService.Get<IPhoneNumber>().GetPhoneNumber();

Which calls this method from this class : 从这个类中调用此方法:

 public class PhoneNumber : IPhoneNumber
    {
        public string GetPhoneNumber()
        {
            TelephonyManager mTelephonyMgr;    
            mTelephonyMgr = (TelephonyManager)Application.Context.GetSystemService(Context.TelephonyService);    
            return mTelephonyMgr.Line1Number;
        }
    }

When I run my app on Android Emulator for visual studio, it works, I get a phone number made up of 11 digits. 当我在Android Emulator上为visual studio运行我的应用程序时,它可以工作,我得到一个由11位数字组成的电话号码。 But when I'm on a real device, the method returns an empty string (""). 但是当我在真实设备上时,该方法返回一个空字符串(“”)。 I've put the READ_PHONE_STATE permission in my AndroidManifest.xml file. 我在我的AndroidManifest.xml文件中放了READ_PHONE_STATE权限。 Oh also, of course, my real device has a SIM card plugged in, and it has only one SIM slot. 哦,当然,我的真实设备插有一个SIM卡,它只有一个SIM插槽。

Did I miss something ? 我错过了什么 ? I'll try to test it on another device as soon as I can, but it is currently not possible. 我会尽快在另一台设备上测试它,但目前还不可能。

Thanks for your help ! 谢谢你的帮助 !

So, as Emad said in a comment of my question : 所以,正如Emad在我的问题评论中所说:

I tried this long ago using native android programs and it was shown that many operators don't give this information. 我很久以前尝试过使用原生的android程序,但是很多运营商都没有提供这些信息。 Especially in Iran non of the active operators do that. 特别是在伊朗,没有活跃的运营商这样做。 I've heard it's even illegal! 我听说它甚至是非法的! That's why apps like Telegram and Viber ask your number. 这就是Telegram和Viber等应用程序询问您号码的原因。

So, after a few more research, it is indeed not possible to get the phone number for sure without asking the user. 因此,经过一些研究,确实无法在不询问用户的情况下获得电话号码。

Hope it helped ! 希望它有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM