java - 在类(class)之间切换时保存蓝牙连接

标签 java android bluetooth connection mac-address

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

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

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

public BTCommunicator myBTCommunicator = null;

将 MAC 地址放入其中。

成功连接后,我会转到另一个带有一堆按钮监听器的 Activity 。

发生的情况是,当您按下按钮时,它会调用蓝牙 Activity 中的函数,该函数应该向外部设备发送信号。

公共(public)无效updateMotorControl(int左,int右){

    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 不会保存。有办法解决这个问题吗?

最佳答案

使您的连接全局静态

public BTCommunicator myBTCommunicator = null;

SomeGlobal.class
public static BTCommunicator myBTCommunicator;

关于java - 在类(class)之间切换时保存蓝牙连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20396368/

相关文章:

Python:如何连接蓝牙设备? (Linux)

c# - 使用 CSWinRT 调用 .net5 windows api

java - 从 PaintComponent 调用 repaint 是一个好习惯吗

java - Java注解顺序是否持久?

java - TestExecutionListeners 注释防止连接 spring bean

android - OrmLite 多线程

java - Mac 操作系统和 Java 蓝牙

java - 什么时候应该使用范围注释

android - 地理围栏不可用以及如何处理

android - 应用程序完成时清除通知