如何解决蓝牙绑定设备无法以xamarin形式工作
我正在将列表与Bluetooth绑定设备绑定,然后在我的代码中启用Bluetooth。但是问题是它第一次不起作用,它在我第二次点击搜索按钮时起作用。另外,当我第一次从设置中手动启用蓝牙,然后单击搜索按钮时,它也起作用。主要的奇迹是,当我在方法上使用断点并逐步进行操作时,效果却不尽人意。直到最后一天,Woking都很好,但是现在发生了什么却没有用。我正在分享我的代码。感谢您的帮助...
///接口类
public interface IBlueToothService
{
public ObservableCollection<string> GetDeviceList();
public Task Print(string deviceName,string text);
}
//本地android依赖类
[assembly: Xamarin.Forms.Dependency(typeof(AndroidBlueToothService))]
namespace R1Soft_App.Droid.DependencyServices
{
class AndroidBlueToothService : IBlueToothService
{
public ObservableCollection<string> GetDeviceList()
{
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
if (bluetoothAdapter.IsEnabled == false)
{
bluetoothAdapter.Enable();
}
var btdevice = bluetoothAdapter?.BondedDevices.Select(i => i.Name).OrderBy(x =>
x).ToList();
return new ObservableCollection <string>(btdevice);
}
}
public async Task Print(string deviceName,string text)
{
UserDialogs.Instance.ShowLoading();
using (BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter)
{
if (bluetoothAdapter.IsEnabled == false)
{
bluetoothAdapter.Enable();
}
BluetoothDevice device = (from bd in bluetoothAdapter?.BondedDevices
where bd?.Name == deviceName
select bd).FirstOrDefault();
try
{
using (BluetoothSocket bluetoothSocket = device?.
CreateRfcommSocketToServiceRecord(
UUID.FromString("00001101-0000-1000-8000-00805f9b34fb")))
{
bluetoothSocket?.Connect();
byte[] buffer = Encoding.UTF8.GetBytes(text);
bluetoothSocket?.OutputStream.Write(buffer,buffer.Length);
bluetoothSocket.Close();
}
}
catch (Exception ex)
{
throw ex;
}
UserDialogs.Instance.HideLoading();
}
}
}
}
//查看模型代码
private readonly IBlueToothService blueToothService;
public AddPrinterViewModel()
{
try
{
blueToothService = DependencyService.Get<IBlueToothService>();
}
catch(Exception ex)
{
App.Current.MainPage.DisplayAlert("Alert",ex.Message.ToString(),"Ok");
}
}
public ObservableCollection<string> deviceList = new ObservableCollection<string>();
public ObservableCollection<string> DeviceList
{
get
{
return deviceList;
}
set
{
deviceList = value;
OnPropertyChanged(nameof(DeviceList));
}
}
private Command searchCommand;
public Command SearchCommand
{
get { return searchCommand ?? (searchCommand = new Command(() => ExecuteSearchCommand())); }
}
public async void ExecuteSearchCommand()
{
try
{
var list = blueToothService.GetDeviceList();
DeviceList = list;
}
catch (Exception ex)
{
await App.Current.MainPage.DisplayAlert("Alert","Ok");
}
UserDialogs.Instance.HideLoading();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。