1313#if ANDROID
1414using Java . Util ;
1515using Shiny . BluetoothLE . Hosting . Internals ;
16- using Shiny . Reflection ;
1716#endif
1817
1918namespace Shiny . BluetoothLE . Hosting ;
@@ -40,16 +39,23 @@ IServiceProvider services
4039#if ANDROID
4140 this . context = new GattServerContext ( platform ) ;
4241#endif
43- this . keyStore = keyStore ;
4442 this . logger = logger ;
43+ this . keyStore = keyStore ;
4544 this . gattChars = services . GetLazyService < IEnumerable < BleGattCharacteristic > > ( ) ;
4645 }
4746
4847
48+ const string REG_KEY = "BleHostingManager.IsRegisteredServicesAttached" ;
4949 public bool IsRegisteredServicesAttached
5050 {
51- get => this . keyStore . DefaultStore . Get < bool > ( nameof ( this . IsRegisteredServicesAttached ) , false ) ;
52- private set => this . keyStore . DefaultStore . Set ( nameof ( this . IsRegisteredServicesAttached ) , value ) ;
51+ get => this . keyStore . DefaultStore . Get ( REG_KEY , false ) ;
52+ set
53+ {
54+ if ( value )
55+ this . keyStore . DefaultStore . Set ( REG_KEY , true ) ;
56+ else
57+ this . keyStore . DefaultStore . Remove ( REG_KEY ) ;
58+ }
5359 }
5460
5561
@@ -64,14 +70,17 @@ public async void Start()
6470 }
6571 catch ( Exception ex )
6672 {
67- this . logger . LogWarning ( "Unable to reattach BLE hosted characteristics" , ex ) ;
73+ this . logger . LogWarning ( ex , "Unable to reattach BLE hosted characteristics" ) ;
6874 }
6975 }
7076 }
7177
7278
7379 public async Task AttachRegisteredServices ( )
7480 {
81+ if ( this . IsRegisteredServicesAttached )
82+ return ;
83+
7584 ( await this . RequestAccess ( ) ) . Assert ( ) ;
7685
7786 this . gattServices ??= CollectServices ( this . gattChars . Value ) ;
@@ -90,12 +99,13 @@ public void DetachRegisteredServices()
9099 if ( ! this . IsRegisteredServicesAttached )
91100 return ;
92101
93- this . IsRegisteredServicesAttached = false ;
94102 foreach ( var serviceUuid in this . gattServices ! . Keys )
95103 this . RemoveService ( serviceUuid ) ;
96104
97105 foreach ( var ch in this . gattChars . Value )
98106 ch . OnStop ( ) ; // TODO: error trap this for user?
107+
108+ this . IsRegisteredServicesAttached = true ;
99109 }
100110
101111
@@ -194,7 +204,7 @@ await characteristic
194204 }
195205 catch ( Exception ex )
196206 {
197- this . logger . LogError ( "Error executing BleGattService notification subscription" , ex ) ;
207+ this . logger . LogError ( ex , "Error executing BleGattService notification subscription" ) ;
198208 }
199209 } , attribute . Notifications ) ;
200210 }
@@ -220,7 +230,7 @@ await characteristic
220230 }
221231 catch ( Exception ex )
222232 {
223- this . logger . LogError ( "Error executing BleGattService request" , ex ) ;
233+ this . logger . LogError ( ex , "Error executing BleGattService request" ) ;
224234 if ( ! writeSuccess )
225235 request . Respond ( GattState . Failure ) ;
226236 }
0 commit comments