我已經創建了一個藍牙掃描器類作爲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關閉)。 –