我已经创建了一个蓝牙扫描器类作为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,因为已经有一个开放的套接字..
我在做什么错误?
您是否在清单中添加了
HaroldSer
@ScottS不,我甚至不知道我必须这样做?当我的课程位于这个名字空间时,我会添加什么:'Some.Fancy.Namespace.Droid.Bluetooth.BluetoothScanner' – Baklap4
你的单例实现看起来是正确的。也许这里有一些特定的android。当您通过intent更改活动时可能会收集实例(因为它是在OS级别上处理的,并可能导致Mono Runtime关闭)。 –