为什么 Android BluetoothDevice.conenctGatt 如果不使用它需要上下文

Mak*_*kov 3 android bluetooth-lowenergy

我正在开发用于 ble 通信的 android 应用程序。

我的问题是为什么这个函数

public BluetoothGatt connectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback, int transport)
Run Code Online (Sandbox Code Playgroud)

需要Context作为参数,我挖掘了函数,发现它没有在任何地方使用它,正如你在这里看到的:

public BluetoothGatt connectGatt(Context context, boolean autoConnect,
                                     BluetoothGattCallback callback, int transport,
                                     boolean opportunistic, int phy, Handler handler) {
        if (callback == null)
            throw new NullPointerException("callback is null");

        // TODO(Bluetooth) check whether platform support BLE
        //     Do the check here or in GattServer?
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        IBluetoothManager managerService = adapter.getBluetoothManager();
        try {
            IBluetoothGatt iGatt = managerService.getBluetoothGatt();
            if (iGatt == null) {
                // BLE is not supported
                return null;
            }
            BluetoothGatt gatt = new BluetoothGatt(iGatt, this, transport, opportunistic, phy);
            gatt.connect(autoConnect, callback, handler);
            return gatt;
        } catch (RemoteException e) {Log.e(TAG, "", e);}
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这个属性也没有被标记为已弃用。我试图传递 null 而不是上下文,似乎无论是否有上下文都可以正常工作 ()。

有谁知道它为什么在那里?

小智 6

好的,基于对 Android 源代码库的简短浏览,这似乎是旧设计的残余。该connectGatt函数创建一个BluetoothGatt对象,其构造函数以前需要一个Context参数。(这是在 API 18 中的方式。)BluetoothGatt最初需要该Context对象来做某事,但在六年前该类甚至公开之前,该代码已被删除。该Context构造函数的参数,但是,仍然存在。大约三年前,它终于被删除了,但那时connectGattAPI 已经公开多年,他们无法在不破坏大量现有代码的情况下删除现在无用的参数。所以他们没有。

把它想象成人类的阑尾或尾骨——进化留下的残余物:-)