Xamarin.Forms; 在设备屏幕上显示SIM卡的电话号码

3
我希望在屏幕上显示我的设备电话号码。
在Xamarin.Android中,代码可以工作。但是我想在Xamarin.Forms中使用代码。我已经搜索过了,但是没有找到任何结果。
Android.Telephony.TelephonyManager tMgr = (Android.Telephony.TelephonyManager)this.GetSystemService(Android.Content.Context.TelephonyService);
string mPhoneNumber = tMgr.Line1Number;

-我授权: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>

当我点击btnNumaraAl时,txtPhone.Text可以是我的设备电话号码。
资源: 获取电话号码Xamarin.Android? https://developer.xamarin.com/api/type/Android.Telephony.TelephonyManager/

你尝试过使用依赖服务吗? - Timothy James
2个回答

3
  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();
    
提醒一下,在iOS上由于安全限制,您无法获取所有者的电话号码。 您可以查看此问题在iOS中以编程方式获取自己的电话号码
基于这一点,您可能需要检查您的应用程序是在Android还是iOS上运行。
switch(Device.RuntimePlatform){
  case "Android":
     //you can
     break;
  case "iOS"
     //You can't
     break;
}

什么是todoapp? - Dan

0

我在权限上遇到了问题 --> Java.Lang.SecurityException: 'getLine1NumberForDisplay: 无论是用户10198还是当前进程都没有android.permission.READ_PHONE_STATE或android.permission.READ_SMS.'

这个解决方案适用于我的Android应用

1.) 共享项目

namespace YourApp
{
   public interface IDeviceInfo
   {
      class Status
      {
         public bool Granted { get; set; } = false;
         public List<string> MobileNumbers { get; set; }
      }
      Status GetPhoneNumber();
   }
}

2.) Android项目类,假设您需要获取2个SIM卡的号码

using Android.Content;
using Android.Telephony;
using System;
using System.Collections.Generic;
using Application = Android.App.Application;

[assembly: Xamarin.Forms.Dependency(typeof(YourApp.Droid.DeviceInfo))]
namespace YourApp.Droid
{
    public class DeviceInfo : IDeviceInfo
    {
        IDeviceInfo.Status IDeviceInfo.GetPhoneNumber()
        {
            var status = new IDeviceInfo.Status();
            List<string> PhoneNumbers = new List<string>();
            try
            {
                SubscriptionManager subscriptionManager = (SubscriptionManager)Application.Context.GetSystemService(Context.TelephonySubscriptionService);
                IList<SubscriptionInfo> subscriptionInfoList = subscriptionManager.ActiveSubscriptionInfoList;
                foreach (SubscriptionInfo subscriptionInfo in subscriptionInfoList)
                {
                    string numbers = subscriptionInfo.Number;
                    if (numbers.Length > 0)
                    {
                        PhoneNumbers.Add(numbers);
                    }
                }
                status.Granted = true;
                status.MobileNumbers = PhoneNumbers;
                return status;
            }
            catch (Exception)
            {
                return status;
                throw;
            }
        }
    }
}

3.) Android MainActivity.cs,添加运行时权限。

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    TryToGetPermission();
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
        switch (requestCode)
        {
            case RequestLocationId:
                {
                    if (grantResults[0] != (int)Permission.Granted)
                    {
                        Toast.MakeText(ApplicationContext, "Application cannot continue without access to the local phone device.  Exiting...", ToastLength.Long).Show();
                        Java.Lang.JavaSystem.Exit(0);
                    }
                }
                break;
        }
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#region Runtime Permission

    protected void TryToGetPermission()
    {
        if ((int)Build.VERSION.SdkInt >= 23)
        {
            GetPermissions();
            return;
        }
    }

    const int RequestLocationId = 0;
    protected void GetPermissions()
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadPhoneState) != (int)Permission.Granted)
        {
            RequestPermissions(new string[] { Manifest.Permission.ReadPhoneState }, RequestLocationId);
        }
    }

#endregion

4.) 共享项目启动页

protected override async void OnAppearing()
{
    base.OnAppearing();
    GetMobileNumber:
    switch (Device.RuntimePlatform)
    {
        case "Android":
            // App need to wait until the permission is granted
            while (DependencyService.Get<IDeviceInfo>().GetPhoneNumber().Granted == false)
            {
                await Task.Delay(1000);
                goto GetMobileNumber;
            }
            break;
        case "iOS":
            break;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接