我正在一个项目中,我必须创建一个移动应用程序,通过蓝牙读出传感器。我已经编码了蓝牙连接,我可以成功连接到我的传感器并打印出接收到的数据。只要我连接,它就会一直监听输入流,如下面的代码所示。Android编程发送连续的数据从类到片段
我的问题是,我不知道如何正确地将这些数据发送到我的片段。通常我会使用intent来发送数据,但是由于我连续收到数据,所以我不能使用这种方法。我一直在努力寻找这个解决方案几天,所以任何解决方案或建议非常赞赏。
目前的项目结构:
MainActivity.class,创建SensorConnector.class的实例。
SensorConnector.class,创建一个读出传感器的线程。像这样:
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
// Code to send incomingMessage to Dataview
} catch (IOException e) {
Log.d(TAG, "disconnected " + e);
break;
}
}
}
DataviewFragment.class,该片段在这里我想送我sensordata。包含一个文本框,我想持续更新读取传感器数据。
DataviewActivity.class,实现Dataview片段。