0

In my Android application, I have the following code:

BluetoothManager bluetoothManager = (BluetoothManager)Android.App.Application.Context.GetSystemService(Java.Lang.Class.FromType(typeof(BluetoothManager)));

_bluetoothGattServer = bluetoothManager.OpenGattServer(Android.App.Application.Context, _customBluetoothGattServerCallback);

// _bluetoothGattServer is always null now

Before it would work every time, but after a few changes in my app, OpenGattServer always returns null now. The only difference that I think could be relevant is that before I was calling this code on a button-clicked event, but now I am calling this code on a different thread, invoked from a Timer.

In case that it's because of a thread issue, is there a way to force this code to run on the UI thread? (or whatever appropriate thread)

Note: I'm writing this app in Xamarin.Android, but an answer in native Android would work for me.

Drake
  • 2,679
  • 4
  • 45
  • 88
  • 1
    From your `Activity` call `runOnUiThread()`. Else, you can use this https://stackoverflow.com/questions/39917308/how-to-post-toast-from-non-ui-widget-thread/39917437#39917437 which can be used from anywhere without needing access to an `Activity`. – Xavier Rubio Jansana Apr 29 '19 at 20:47
  • 1
    That worked. So `OpenGattServer` should not be called from a different thread. – Drake Apr 29 '19 at 21:29
  • Glad it worked! Moving it to a proper answer. Could you mark it as the solution? TIA – Xavier Rubio Jansana Apr 29 '19 at 21:47

1 Answers1

2

From your tests, it must be called from the UiThread.

So, the solutions are:

  • From your Activity call runOnUiThread().
  • Else, you can use this answer which can be used from anywhere without needing access to an Activity.
Xavier Rubio Jansana
  • 6,388
  • 1
  • 27
  • 50