私はbluetoothscannerクラスをシングルトンとして作成しました。これは私のアプリケーション全体を通してこの方法でbluetoothscannerと通信することができます。シングルトンは変更されたプロパティを保持しません
私は、シングルトンのプロパティを設定すると、それが彼の価値のままになると思った、明らかにそうではない?または私は何か間違っているのですか?
これは私のシングルトンです:
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が発生します。
違う?
@ScottSいいえ私はそうしなければならないということさえ知りませんでしたか?私のクラスがこの名前空間に住んでいる時、私はそれに何を追加しますか?Some.Fancy.Namespace.Droid.Bluetooth.BluetoothScanner' – Baklap4
あなたのシングルトンの実装が正しいように見えます。たぶんそこにはいくつかのアンドロイドがあります。インテントでアクティビティを変更するとインスタンスが収集されることがあります(OSレベルで処理され、Monoランタイムが終了する可能性があるため)。 –