从 UI 线程调用 GattCallback 中的函数

Call Function in GattCallback from UI thread

  1. 我的情况: 我正在使用 BLE 与传感器通信,将 'Session' 对象作为字符串从传感器发送到 android 设备。

当所有会话都在 android 设备上时,我在 UI 线程上调用一个会话,使用 Volley 将它们上传到服务器。 (来电'uploadSessions()')

当所有会话都在服务器上时(在我收到服务器确认已收到的响应后),我需要擦除传感器的内存。 (onResponse 调用 'sessionsSuccessfullyUploaded()')

问题:我无法从 UI 线程访问 GattCallback 中的函数(无法从 'sessionsSuccessfullyUploaded()' 调用 'eraseDevice()')

  1. 我试过的:我试过循环, 我在回调中这样做:

    public void waitForServerResponse() {

            int WAIT_INTERVAL = 500;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run () {
    
                    if(sessionCountUploadedToServer == IBSessionCount) {
                        eraseDevice();
                    } else waitForServerResponse();
    
                }
            },WAIT_INTERVAL);
        }`
    

我收到此错误:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

mHandler 是从非UI 线程创建的。如果您想执行任何 UI 操作,请确保在主线程上创建它。

如果您不打算执行 UI 操作,则按照错误提示调用 Looper.Prepare() - 在构造处理程序的线程中。

创建 mHandler 如下:

HandlerThread mHandlerThread = new HandlerThread("tHandlerThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());

或者,您也可以考虑使用 AsyncTask 或 IntentService - 这些可能更适合您正在尝试执行的操作 - 后台操作。

查看广播意图和接收器。本文档可以帮助:

http://www.techotopia.com/index.php/Android_Broadcast_Intents_and_Broadcast_Receivers

将回调放在扩展 Service

的特殊蓝牙服务 Class 中也有帮助