首页 > 解决方案 > OpenGattServer 返回 null

问题描述

在我的 Android 应用程序中,我有以下代码:

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

在它每次都可以工作之前,但是在我的应用程序中进行了一些更改之后,OpenGattServer现在总是返回 null。我认为可能相关的唯一区别是,在我在按钮单击事件上调用此代码之前,但现在我在另一个线程上调用此代码,从Timer.

如果是因为线程问题,有没有办法强制此代码在 UI 线程上运行?(或任何适当的线程)

注意:我正在 Xamarin.Android 中编写此应用程序,但本机 Android 中的答案对我有用。

标签: android

解决方案


从您的测试中,它必须从UiThread.

因此,解决方案是:

  • 从你的Activity电话runOnUiThread()
  • 否则,您可以使用这个答案,它可以在任何地方使用,而无需访问Activity.

推荐阅读