I have created a bluetoothscanner class as a Singleton, this way throughout my whole application i'm able to communicate with the bluetoothscanner.
I thought when setting a property of a Singleton it would remain his value, apparently it does not? or am i doing something wrong?
This is my 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;
}
}
The Connect
method is called like this in my fragment:
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);
}
}
I thought on the first time it'll initialize the singleton and then reuse it over and over again. Aparently when returning back to this class and OnCreateView()
is called again it says it's not connected thus trying to connect using the connect method, thus getting an Java.IO.Exception as there's already an open socket..
What am i doing wrong?
Aucun commentaire:
Enregistrer un commentaire