【问题标题】:Saving a Bluetooth connection while switching between classes在课程之间切换时保存蓝牙连接
【发布时间】:2025-12-02 10:55:01
【问题描述】:

我正在通过蓝牙从应用程序发送一些信号。

我的应用程序的工作方式是,它首先输入一个处理所有蓝牙相关事物的活动。这里显示了所有找到的设备的布局。

当一个设备被按下时,它会连接到它,如下所示:

public BTCommunicator myBTCommunicator = null;

获取 MAC 地址。

连接成功后,我带着一堆按钮监听器去另一个activity。

当你按下一个按钮时,它会从蓝牙活动中调用一个函数,该函数应该向外部设备发送一个信号。

public void updateMotorControl(int left, int right) {

    if (myBTCommunicator != null) {                                           
        // send messages via the handler
        sendBTCmessage(BTCommunicator.NO_DELAY, motorLeft, left * directionLeft, 0);
        sendBTCmessage(BTCommunicator.NO_DELAY, motorRight, right * directionRight, 0);
    }

问题是当我们返回时,myBTCommunicator == null 又一次。当我检查我的外部设备时,它仍然处于连接状态,但显然当您离开和返回时 myBTCommunicator 没有保存。有没有办法解决这个问题?

【问题讨论】:

    标签: java android bluetooth connection mac-address


    【解决方案1】:

    使您的连接全局静态

    public BTCommunicator myBTCommunicator = null;
    

    SomeGlobal.class
    public static BTCommunicator myBTCommunicator;
    

    【讨论】: