2016-12-01 99 views
0

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

您是否在清單中添加了 HaroldSer

+0

@ScottS不,我甚至不知道我必須這樣做?當我的課程位於這個名字空間時,我會添加什麼:'Some.Fancy.Namespace.Droid.Bluetooth.BluetoothScanner' – Baklap4

+0

你的單例實現看起來是正確的。也許這裏有一些特定的android。當您通過intent更改活動時可能會收集實例(因爲它是在OS級別上處理的,並可能導致Mono Runtime關閉)。 –

回答

1

您的單身人士按預期工作。我唯一可以想到的是,你對connect()的調用以某種方式失敗,因此不會將IsConnected設置爲true。 測試這一行的返回值:

BluetoothScanner.Instance.Connect(); 

我懷疑這條線:

if (this.socket.ConnectAsync().IsCompleted) 

返回假因而留下IsConnected默認爲false。

+0

嗯如果它失敗會很奇怪..因爲我的藍牙設備能夠在base.oncreateview被調用後連接。雖然它是一種異步方法,並沒有等待這可能確實是它..明天測試;) – Baklap4

+0

由於它是運行異步主線程沒有跟蹤它,而它沒有等待它永遠不會完成在時間檢查因此不設置IsConnected。如何讓它等待它結束?現在我正在使用'this.socket.Connect()'方法阻止... – Baklap4