1、新建的一个App1项目
2、修改MainPage.xaml,加上打电话测试控件
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:App1"
x:Class="App1.MainPage">
<StackLayout>
<Label Text="请输入电话号码:" />
<Entry x:Name="phoneNumberText" Text="13103102267" />
<Button x:Name="remove_Buton" Text="清空" Clicked="OnRemove" />
<Button x:Name="callButton" Text="拨打" Clicked="OnCall" />
</StackLayout>
</ContentPage>
3、Nuget包中引用Xamarin.Essentials
安装的时候注意版本,如果报错,请及时降低 Xamarin.Essentials版本。
4、新建打电话类MakePhone.cs
/// <summary>
/// 使用Xamarin.Essentials 打电话
/// </summary>
public static class MakePhone
{
public static void PlacePhoneCall(string number)
{
try
{
PhoneDialer.Open(number);
}
catch (ArgumentNullException anEx)
{
// Number was null or white space
}
catch (FeatureNotSupportedException ex)
{
// Phone Dialer is not supported on this device.
}
catch (Exception ex)
{
// Other error has occurred.
}
}
}
这个基本是抄官方文档的。我这里改成静态类了。Xamarin.Essentials里的一些API都是跨平台的,按照官当文档的API做就可以了。如果想了解单平台的运作源码,可以参照官方文档的github源代码。
5、实现MainPage.xaml视图按钮的方法
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
void OnRemove(object sender, EventArgs e)
{
phoneNumberText.Text = string.Empty;
}
async void OnCall(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(phoneNumberText.Text))
{
MakePhone.PlacePhoneCall(phoneNumberText.Text);
}
else
{
await DisplayAlert("提示", "请输入号码", "确定");
}
}
}
MakePhone.PlacePhoneCall(phoneNumberText.Text);调用打电话。
6、测试
顺利弹出拨号同页面,调用成功。 我尝试在我的手机中安装,没有问题!