如何在Android上通过蓝牙接收数据? [英] How to receive data via Bluetooth on Android?
问题描述
我阅读了许多主题,但是找不到很好的答案.我正在使用蓝牙从蓝牙发送和接收数据的Android应用程序上工作.我已经完成了部分发送,并且工作正常,但是在Android上接收数据时遇到了问题. 我正在使用此库: https://android-arsenal.com/details/1/690#!description 它没有正确的教程(或者至少我没有看到它),它只是说明了如何在android上接收数据:
I read many topics, but I couldn't find good answer. I'm working on Android application that uses Bluetooth to send and receive data from Microcontroller. I have already finished sending part and it works fine, but I have problem with receiving data on Android. I'm using this library: https://android-arsenal.com/details/1/690#!description It doesn't have properly tutorial (or at least I don't see it), it just says about receiving data on android this:
//Listener for data receiving
bt.setOnDataReceivedListener(new OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
// Do something when data incoming
}
});
有人知道如何使用它吗?我试图自己编写整个蓝牙部分,但是太难了,所以我决定使用此库.我需要一直在侦听传入的数据,但也不能循环执行,因为它会阻塞UI线程.
Does anybody have any idea how to use it? I have tried to write whole Bluetooth part by myself, but it was too hard, so I decided to use this library. I need to listen for incoming datas all the time, but also I can't do it in loop, because it will block the UI thread.
推荐答案
这基本上是一个回调函数,正如您在参数中所看到的那样,它为您提供了2种类型的数据,分别是byte []和String类型的消息.现在,您只需登录2并查看如下所示为您提供了什么值
This is basically an callback function and as you can see in the parameter it is giving you 2 things data of type byte[] and message of type String. Now you can just log the 2 and see what values are being given to you like below
Log.d("Data value : " + data.toString() + "Message : " + message);
然后您可以使用它来做任何想做的事情,例如更新视图等,如下所示
And then you can do whatever that you intend to do with it like update a view, etc. like below
TextView messageView = findViewById(R.id.message);
messageView.setText(message);
这篇关于如何在Android上通过蓝牙接收数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!