等待在Android中调用回调方法

时间:2017-08-22 21:07:27

标签: java android multithreading asynchronous callback

我正在编写一个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

我觉得可以有更好的方法解决这个问题,但无法在网上找到任何内容。我使用CountDownLatch和Semaphores看到了几个答案,但我并没有清楚地理解它们。

任何人都可以帮助我理解如何处理这些情况吗? 谢谢。

0 个答案:

没有答案
相关问题