Reputation: 575
I have made use of property changed event
to assign a value to a bool
value in an attempt to get the connectivity status.
However, I want to listen for this change of the variable from another class and perform some action. How can I achieve this in C#
?
private bool isDisconnected;
public bool IsDisconnected
{
get { return isDisconnected; }
set
{
isDisconnected = value;
OnPropertyChanged("IsDisconnected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public override void OnConnectionStateChange(BluetoothGatt gatt, [GeneratedEnum] GattStatus status, [GeneratedEnum] ProfileState newState)
{
base.OnConnectionStateChange(gatt, status, newState);
if(newState == ProfileState.Connected)
{
isDisconnected = true;
gatt.DiscoverServices();
}
else if(newState == ProfileState.Disconnected)
{
gatt.Close();
isDisconnected = true;
Log.Info("BLE", "Status: Disconnected");
}
}
In another class which is basically a Service
, I want to listen for the variable IsDisconnected
. Please someone help me.
My Service class:
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
try
{
Toast.MakeText(this, "Background service started", ToastLength.Long);
t = new Thread(() =>
{
Task.Run(async () =>
{
ConnectionListener gatt = new ConnectionListener ();
gatt.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(GattCallback.IsDisconnected))
{
}
};
});
});
t.Start();
}
}
Upvotes: 0
Views: 1499
Reputation: 39072
Suppose the instance of your class is called connection
. Then from another class you hook up the PropertyChanged
event:
connection.PropertyChanged += (s,e) =>
{
if (e.PropertyName == nameof(YourClass.IsDisconnected))
{
//isDisconnected changed, perform your logic
}
}
Of course this is just a sample code and it would be appropriate to move the event handling to a method if the two instances have different lifetime. By doing that you can later unsubscribe from the event so that you don't introduce memory leaks.
Also you need to update the GattCallback
class to set the IsDisconnected
property instead of the isDisconnected
field in the OnConnectionChange
method:
if(newState == ProfileState.Connected)
{
IsDisconnected = false; //notice change true -> false
gatt.DiscoverServices();
}
else if(newState == ProfileState.Disconnected)
{
gatt.Close();
IsDisconnected = true;
Log.Info("BLE", "Status: Disconnected");
}
Also it seems you had a bug there - you were setting IsDisconnected
to true
in both cases, which is probably not what you want.
Upvotes: 3