2016-12-01 68 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