连接到GATT服务器时从未调用过onServicesDiscovered [英] onServicesDiscovered never called while connecting to GATT Server

查看:255
本文介绍了连接到GATT服务器时从未调用过onServicesDiscovered的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与我的Nexus 5X(运行Android 7.1)配对的蓝牙耳机,我想连接到该耳机的GATT服务器.我用以下代码尝试过:

I have a bluetooth headset which is paired with my Nexus 5X (running Android 7.1) and I would like to connect to a GATT Server of the headset. I tried it with the following code:

private BluetoothGattCallback btleGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        Log.d(TAG, "onConnectionStateChange: " + status + ", " + newState);

        if(newState == STATE_CONNECTED) {
            Log.d(TAG, "Device connected");
            boolean ans = gatt.discoverServices();
            Log.d(TAG, "Discover Services started: " + ans);
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.d(TAG, "Number of Services: " + gatt.getServices().size());
    }
};

public void onDeviceClicked(BluetoothDevice device) {
    BluetoothGatt gatt = device.connectGatt(this, false, btleGattCallback);
    Log.d(TAG, "Connected to GATT: " + gatt.connect());
}

如果我在用户界面中单击耳机,则会调用onDeviceClicked,它会显示以下日志输出:

If I click on the headset in my UI onDeviceClicked is called and it comes to this Log output:

<!-- language: lang-none -->
Connected to GATT: true
onConnectionStateChange: 0, 2    // GATT_SUCCESS, STATE_CONNECTED
Device connected
Discover Services started: true

如您所见,onServicesDiscovered从未触发.我尝试用TRANSPORT_LE( ref )调用connectGatt,但随后却得到了onConnectionStateChange: 133, 0.我还发现了这个问题,这就是为什么我添加gatt.connect()答案二中提到的方法.

As you can see onServicesDiscovered is never fired. I tried to call connectGatt with TRANSPORT_LE (ref) but then I get a onConnectionStateChange: 133, 0. I also found this question which is why I added the gatt.connect() method as mentioned in answer two.

您有什么想法为什么我没有得到onServicesDiscovered回调?

Do you have any ideas why I don't get the onServicesDiscovered callback?

推荐答案

对我来说真正有用的是在建立连接后等待大约600毫秒,然后开始服务发现.

Something that has been really useful for me is to wait for about 600ms after the connection has been established and then start the service discovery.

这篇关于连接到GATT服务器时从未调用过onServicesDiscovered的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆