为什么Android的BluetoothDevice.connectGatt方法需要传入Context参数,即使它并没有使用它?

3

我正在开发用于蓝牙通信的Android应用程序。

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

public BluetoothGatt connectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback, int transport)

此函数需要 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;
    }

奇怪的是,这个属性没有被标记为废弃。

我尝试传递 null 而不是上下文,似乎在有上下文或无上下文的情况下都可以正常工作。

有人知道为什么吗?


你有检查文件历史记录吗? - Emil
谢谢您的提问。我正在回顾和重构一些旧代码,发现了同样的问题。主活动被传递到这个方法中,这对我来说非常奇怪。我想不出为什么它需要获取活动的句柄。我将其更改为 null。 - Lehrian
1个回答

6

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

把它看作人类的阑尾或尾骨 - 进化留下的退化遗迹 :-)

我不确定这是100%安全的。他们可能会在未来的Android版本中再次使用上下文。我的意思是,他们可能不会这样做,但你永远不知道。无论如何,现在肯定不需要。 - Michal Dvorak
是的,我理解风险,无论如何,我构建系统的方式是在调用connectGatt()函数的地方远离上下文。 - Maksim Novikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接