Java 等待在Android中调用回调方法

Java 等待在Android中调用回调方法,java,android,multithreading,asynchronous,callback,Java,Android,Multithreading,Asynchronous,Callback,我正在编写一个android应用程序,它使用蓝牙与传感器交互并获取温度值。我是通过调用connectGatt()来实现的,它是异步的,并且在建立连接后调用回调。我面临的问题是,我的代码必须等待连接建立 这是下面代码中使用的方法的实现 public boolean connect(final String address) { Log.v(LOG_TAG,"IN CONNECT METHOD"+Thread.currentThread().getName()); if(btadap

我正在编写一个android应用程序,它使用蓝牙与传感器交互并获取温度值。我是通过调用connectGatt()来实现的,它是异步的,并且在建立连接后调用回调。我面临的问题是,我的代码必须等待连接建立

这是下面代码中使用的方法的实现

public boolean connect(final String address)
{
    Log.v(LOG_TAG,"IN CONNECT METHOD"+Thread.currentThread().getName());
    if(btadapter == null || address == null)
    {
        Log.v(LOG_TAG,"Unable to get Bluetooth Adapter or Address is not valid");
        return false;
    }
    if(address != null && address.equals(btaddress) && btgatt != null)
    {
        Log.v(LOG_TAG,"Trying to connect to a bt gatt profile directly");
        boolean result = btgatt.connect();
        if(result)
            return true;
        return false;
    }
    btdevice = btadapter.getRemoteDevice(address);
    if(btdevice == null)
    {
        Log.v(LOG_TAG,"Could not find device.");
        return false;
    }
    btgatt = btdevice.connectGatt(this,false,btgattcallback);
    Log.v(LOG_TAG,btgatt.toString());
    btaddress = address;
    Log.v(LOG_TAG,"Connecting to the device");
    btConnectionState = STATE_CONNECTING;
    return true;
}
目前,我可以通过在处理程序线程中编写以下代码来解决这个问题,因为我不想在等待回调时阻塞UI线程。但我不相信这种方法

        if(mLocation != null)
        {
            connect(btaddress);   // Method encapsulates calls to connectGatt method.
            while (btConnectionState != STATE_CONNECTED) {
                continue;
            }
            while (!services_discovered) {
                continue;
            }
            //Other Code
我觉得有更好的方法解决这个问题,但在网上找不到。我用倒计时锁和信号量看到了一些答案,但我不太清楚

有人能帮我理解如何处理这样的情况吗?
谢谢。

你不能那样做。您需要使用实际的异步代码。@SLaks对不起,我没有完全理解您的意思。你的意思是我应该从connectGatt()方法的onConnectionStateChange()回调调用在连接建立后具有要执行的逻辑的方法吗?使用android asynctask()或RXY你不能这样做。您需要使用实际的异步代码。@SLaks对不起,我没有完全理解您的意思。你的意思是我应该从connectGatt()方法的onConnectionStateChange()回调调用在连接建立后执行逻辑的方法吗?使用android asynctask()或Rx