首页 > 解决方案 > 安卓后台线程控制涂鸦蓝牙设备

问题描述

我想通过安卓后台线程控制涂鸦蓝牙设备。但是我遇到了问题:当我尝试这样做时,我收到了 IllegalStateException。

我发现涂鸦库包含单例

public class OoooO00 {
 public BluetoothStateListener OooO0oo = new BluetoothStateListener() {
     ...
};

它已经实现了从 AbsBluetoothListener 继承的 BluetoothStateListener

public abstract class AbsBluetoothListener implements Callback {
 public static final int MSG_INVOKE = 1;
 public static final int MSG_SYNC_INVOKE = 2;
 public Handler mHandler;
 public Handler mSyncHandler;

 public AbsBluetoothListener() {
     if (Looper.myLooper() != null) {
         this.mHandler = new Handler(Looper.myLooper(), this);
         this.mSyncHandler = new Handler(Looper.getMainLooper(), this);
     } else {
         throw new IllegalStateException();
     }
 }

AbsBluetoothListener 控制它在带有 looper 的线程上创建。如果从没有活套的线程创建,则抛出 IllegalStateException。但是从源代码怎么看涂鸦开发者假设这个线程不是MainThred。

这个单例是在调用一些蓝牙管理器函数时创建的。这意味着这个函数必须从主线程或带looper的线程调用。

但我需要在 RX 链或协程的后台线程上调用它。

初始化tuya库以从后台线程调用蓝牙tuya api的正确方法是什么?

这时候我只找到了一种解决方法——在tuya sdk初始化后从主线程调用一些蓝牙功能。像这样:

val bleMngr = TuyaHomeSdk.getBleManager()
bleMngr.isBleLocalOnline("fakeDeviceId")

在此单例从 MainThread 调用处理程序上的所有其他蓝牙管理器函数之后。但它看起来不是有效的方式。

标签: androidbluetoothtuya

解决方案


推荐阅读