我已经创建了一个bluetoothscanner类作为Singleton,这样在我的整个应用程序中我能够与蓝牙扫描器进行通信。
我认为在设置Singleton的属性时它仍然是他的价值,显然它不是?或者我做错了什么?
这是我的单身人士:
public sealed class BluetoothScanner
{
private static readonly BluetoothScanner instance = new BluetoothScanner();
public static BluetoothScanner Instance => BluetoothScanner.instance;
public bool IsConnected { get; set; }
private BluetoothScanner()
{
this.Adapter = BluetoothAdapter.DefaultAdapter;
}
public bool Connect()
{
var bondedDevices = this.Adapter.BondedDevices;
if (!bondedDevices.Any())
{
this.SendToastMessage("No paired devices found");
this.IsConnected = false;
}
if (this.socket.ConnectAsync().IsCompleted)
{
this.SendToastMessage($"Connected to Device {this.device.Name}");
this.IsConnected = true;
}
return this.IsConnected;
}
}
在我的片段中调用Connect
方法如下:
public class ConditionSearchFragment : BaseTitledFragment<ConditionSearchViewModel>
{
protected override int FragmentId => Resource.Layout.fragment_condition_search;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if (!BluetoothScanner.Instance.IsConnected)
{
BluetoothScanner.Instance.Connect();
}
BluetoothScanner.Instance.SendKey += this.OnSendKey;
BluetoothScanner.Instance.SendToast += this.OnSendToast;
return base.OnCreateView(inflater, container, savedInstanceState);
}
}
我第一次想到它会初始化单例,然后一遍又一遍地重复使用它。很明显当返回到这个类并再次调用OnCreateView()
时,它表示它没有连接,因此尝试使用connect方法进行连接,从而得到一个Java.IO.Exception,因为那里已经是打开插座..
我做错了什么?
答案 0 :(得分:1)
你的单身人士按预期工作。我唯一能想到的是你对connect()的调用以某种方式失败,因此没有将IsConnected设置为true。 测试此行的返回值:
BluetoothScanner.Instance.Connect();
我怀疑这一行:
if (this.socket.ConnectAsync().IsCompleted)
返回false,因此将IsConnected默认为false。