如何读取连续数据并显示它 [英] How to read continuous data and display it
问题描述
我要送的PIC连续数据(从模拟输入),蓝牙模块,然后我试图与Android阅读(超级终端,我得到的值从0到255)。我怎么可以改变我的code读取3个字节的字符串,并立即显示成TextView的。现在,我可以显示数据,但它的速度太慢和值更新,只有当按钮是pressed。这是我的MainActivity.java:
公共类MainActivity延伸活动{
私有静态最后字符串变量=bluetooth2;
按钮BTN1,BTN2,btn3,btn4;
TextView的txtArduino;
处理程序H;
私有静态最终诠释REQUEST_ENABLE_BT = 1;
最终诠释RECIEVE_MESSAGE = 1; //为处理程序状态
私人BluetoothAdapter btAdapter = NULL;
私有的BluetoothSocket btSocket = NULL;
私人StringBuilder的SB =新的StringBuilder();
私人ConnectedThread mConnectedThread;
// SPP UUID服务
私有静态最后UUID MY_UUID = UUID.fromString(00001101-0000-1000-8000-00805F9B34FB);
//蓝牙模块的MAC地址(你必须编辑这一行)
私有静态字符串的地址=00:12:09:25:92:57;
/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
BTN1 =(按钮)findViewById(R.id.btn1); //活性没有。 1
BTN2 =(按钮)findViewById(R.id.btn2); //活性没有。 2
btn3 =(按钮)findViewById(R.id.btn3); //活性没有。 3
btn4 =(按钮)findViewById(R.id.btn4); //活性没有。 4
txtArduino =(TextView中)findViewById(R.id.txtArduino);从Arduino的//显示接收到的数据
H =新的处理程序(){
公共无效的handleMessage(android.os.Message味精){
开关(msg.what){
案例RECIEVE_MESSAGE:
字节[]的ReadBuf =(字节[])msg.obj;
字符串strIncom =新的String(的ReadBuf,0,msg.arg1); //创建一个从字节数组字符串
//Toast.makeText(MainActivity.this,strIncom,Toast.LENGTH_SHORT).show();
sb.append(strIncom); //添加字符串
INT endOfLineIndex = sb.indexOf(\ r \ N); //确定最终的行
如果(endOfLineIndex大于0){//如果行尾的,
串sbprint = sb.substring(0,endOfLineIndex); //提取物串
sb.delete(0,sb.length()); //明了
txtArduino.setText(数据来自PIC:+ sbprint); //更新的TextView
//btn2.setEnabled(true);
//btn1.setEnabled(true);
}
//Log.d(TAG,...的字符串:+ sb.toString()+字节:+ msg.arg1 +...);
打破;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); //获取蓝牙适配器
checkBTState();
btn1.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
//btn1.setEnabled(false);
mConnectedThread.write(0); //发送0通过蓝牙
//Toast.makeText(getBaseContext(),点亮LED,Toast.LENGTH_SHORT).show();
如果(v.getId()== R.id.btn1){
//定义一个新的意向第二活动
意向意图=新的意图(MainActivity.this,NewClass1.class);
//启动的第二项活动
MainActivity.this.startActivity(意向);
}}
});
btn2.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
//btn2.setEnabled(false);
mConnectedThread.write(1); //发送1通过蓝牙
如果(v.getId()== R.id.btn2){
//定义一个新的意向第二活动
意向意图=新的意图(MainActivity.this,NewClass2.class);
//启动的第二项活动
MainActivity.this.startActivity(意向);
}}
});
btn3.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
//btn3.setEnabled(false);
mConnectedThread.write(2); //发送2通过蓝牙
如果(v.getId()== R.id.btn3){
//定义一个新的意向第二活动
意向意图=新的意图(MainActivity.this,NewClass3.class);
//启动的第二项活动
MainActivity.this.startActivity(意向);
}}
});
btn4.setOnClickListener(新OnClickListener(){
公共无效的onClick(视图v){
//btn4.setEnabled(false);
mConnectedThread.write(3); //发送3通过蓝牙
如果(v.getId()== R.id.btn4){
//定义一个新的意向第二活动
意向意图=新的意图(MainActivity.this,NewClass4.class);
//启动的第二项活动
MainActivity.this.startActivity(意向);
}}
});
}
@覆盖
公共无效onResume(){
super.onResume();
Log.d(TAG,...... onResume - 尝试连接......);
//设置一个指针到远程节点使用它的地址。
BluetoothDevice类设备= btAdapter.getRemoteDevice(地址);
需要//两件事情来建立连接:
// MAC地址,这是我们得到了上面。
//服务ID或UUID。在这种情况下,我们使用的是
// UUID为SPP。
尝试 {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
}赶上(IOException异常E){
errorExit(致命错误,在onResume()和插座创建失败:+ e.getMessage()+。);
}
//发现是资源密集型的。请确保它不会对
//当您尝试连接并传递你的信息。
btAdapter.cancelDiscovery();
//建立连接。这将阻止,直到它连接。
Log.d(TAG,...连接...);
尝试 {
btSocket.connect();
Log.d(TAG,......连接正常......);
}赶上(IOException异常E){
尝试 {
btSocket.close();
}赶上(IOException异常E2){
errorExit(致命错误,在onResume()和无法连接的故障期间关闭套接字+ e2.getMessage()+。);
}
}
//创建一个数据流,所以我们可以跟服务器。
Log.d(TAG,......创建套接字......);
mConnectedThread =新ConnectedThread(btSocket);
mConnectedThread.start();
}
@覆盖
公共无效的onPause(){
super.onPause();
Log.d(TAG,......在的onPause()...);
尝试 {
btSocket.close();
}赶上(IOException异常E2){
errorExit(致命错误,在的onPause(),并没有关闭套接字。+ e2.getMessage()+。);
}
}
私人无效checkBTState(){
//检查支持蓝牙,然后检查,以确保它已开启
//仿真器不支持蓝牙和将返回null
如果(btAdapter == NULL){
errorExit(致命错误,蓝牙不支持);
} 其他 {
如果(btAdapter.isEnabled()){
Log.d(TAG,...蓝牙开......);
} 其他 {
//提示用户打开蓝牙
意图enableBtIntent =新的意图(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
Toast.makeText(getBaseContext(),保持通话!,Toast.LENGTH_SHORT).show();
}
}
}
私人无效errorExit(标题字符串,字符串消息){
Toast.makeText(getBaseContext(),标题+ - +消息,Toast.LENGTH_LONG).show();
完();
}
私有类ConnectedThread继承Thread {
私人最终的BluetoothSocket mmSocket;
私人最终的InputStream mmInStream;
私人最终的OutputStream mmOutStream;
公共ConnectedThread(的BluetoothSocket插座){
mmSocket =插座;
InputStream的tmpIn = NULL;
OutputStream的tmpOut = NULL;
//获取输入和输出流,因为使用临时对象
//成员流是最终的
尝试 {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}赶上(IOException异常E){}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
公共无效的run(){
byte []的缓冲区=新的字节[256]; //缓冲存储器的流
诠释字节; //个字节read()返回
//继续听InputStream的,直到发生异常
而(真){
尝试 {
//读取从InputStream
字节= mmInStream.read(缓冲区); //获取字节数和消息的缓冲
h.obtainMessage(RECIEVE_MESSAGE,字节,-1,缓冲液).sendToTarget(); //发送到消息队列处理程序
}赶上(IOException异常E){
打破;
}
}
}
/ *调用此从主活动将数据发送到所述远程装置* /
公共无效写入(字符串消息){
Log.d(TAG,......要发送的数据:+信息+...);
byte []的msgBuffer = message.getBytes();
尝试 {
mmOutStream.write(msgBuffer);
}赶上(IOException异常E){
Log.d(TAG,...错误发送数据:+ e.getMessage()+...);
}
}
/ *从主要活动调用此方法以关闭连接* /
公共无效取消(){
尝试 {
mmSocket.close();
}赶上(IOException异常E){}
}
}
}
和activity_main.xml:
< RelativeLayout的的xmlns:机器人=http://schemas.android.com/apk/res/android
的xmlns:工具=http://schemas.android.com/tools
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:keepScreenOn =真正的>
<的TextView
机器人:ID =@ + ID / txtArduino
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_alignParentTop =真
机器人:文本=/>
<按钮
机器人:ID =@ + ID / BTN1
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_below =@ + ID / txtArduino
机器人:文本=@字符串/ btn_1/>
<按钮
机器人:ID =@ + ID / BTN2
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_below =@ + ID / BTN1
机器人:文本=@字符串/ btn_2/>
<按钮
机器人:ID =@ + ID / btn3
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_below =@ + ID / BTN2
机器人:文本=@字符串/ btn_3/>
<按钮
机器人:ID =@ + ID / btn4
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentLeft =真
机器人:layout_below =@ + ID / btn3
机器人:文本=@字符串/ btn_4/>
< / RelativeLayout的>
当我需要运行的东西,每隔一段时间我使用一个处理程序。
处理程序的ViewHandler =新的处理程序();
可运行的UpdateView =新的Runnable(){
@覆盖
公共无效的run(){
mEmulatorView.invalidate();
viewHandler.postDelayed(更新视图,1000);
}
};
要调用这个在我的方法:
viewHandler.post(更新视图);
在这种情况下,我被它无效更新我的屏幕每隔1000毫秒。
编辑:满code样品
处理程序的ViewHandler =新的处理程序();
可运行的UpdateView =新的Runnable(){
@覆盖
公共无效的run(){
mEmulatorView.invalidate();
如果(statusBool ==真){
的for(int i = 1; I< dataReceived.length() - 1;我++){
如果(dataReceived.charAt(ⅰ)=='>'){
Log.d(TAG,发现>);
deviceStatus = 0;
}
如果(dataReceived.charAt(ⅰ)=='#'
&功放;&安培; dataReceived.charAt(ⅰ - 1)!=')'){
Log.d(TAG,发现#);
deviceStatus = 1;
}
如果(第(i + 1) - ; =(dataReceived.length())
&功放;&安培; dataReceived.charAt(ⅰ)==')'
&功放;&安培; dataReceived.charAt第(i + 1)=='#'){
Log.d(TAG,发现配置)#);
deviceStatus = 2;
}
}
statusBool = FALSE;
viewHandler.postDelayed(更新视图,1000);
}
}
};
公共无效onDataReceived(INT ID,byte []的数据){
dataReceived =新的String(数据);
statusBool =真;
Log.d(TAG,数据接收+ dataReceived);
((MyBAIsWrapper)二).renew(数据);
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
mSession.write(dataReceived);
}});
viewHandler.post(更新视图);
}
I'm sending continuous data from PIC (from analog input) to the bluetooth module and then I'm trying to read them with android (in HyperTerminal I get values from 0 to 255). How could I change my code to read strings of 3 bytes and immediately display them into the TextView. Now I can display data but it's too slow and values update only when button is pressed. Here is my MainActivity.java:
public class MainActivity extends Activity {
private static final String TAG = "bluetooth2";
Button btn1, btn2, btn3, btn4;
TextView txtArduino;
Handler h;
private static final int REQUEST_ENABLE_BT = 1;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:12:09:25:92:57";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1); // activity no. 1
btn2 = (Button) findViewById(R.id.btn2); // activity no. 2
btn3 = (Button) findViewById(R.id.btn3); // activity no. 3
btn4 = (Button) findViewById(R.id.btn4); // activity no. 4
txtArduino = (TextView) findViewById(R.id.txtArduino); // for display the received data from the Arduino
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
//Toast.makeText(MainActivity.this, strIncom, Toast.LENGTH_SHORT).show();
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from PIC: " + sbprint); // update TextView
//btn2.setEnabled(true);
//btn1.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//btn1.setEnabled(false);
mConnectedThread.write("0"); // Send "0" via Bluetooth
//Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
if(v.getId() == R.id.btn1){
//define a new Intent for the second Activity
Intent intent = new Intent(MainActivity.this,NewClass1.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}}
});
btn2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//btn2.setEnabled(false);
mConnectedThread.write("1"); // Send "1" via Bluetooth
if(v.getId() == R.id.btn2){
//define a new Intent for the second Activity
Intent intent = new Intent(MainActivity.this,NewClass2.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}}
});
btn3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//btn3.setEnabled(false);
mConnectedThread.write("2"); // Send "2" via Bluetooth
if(v.getId() == R.id.btn3){
//define a new Intent for the second Activity
Intent intent = new Intent(MainActivity.this,NewClass3.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}}
});
btn4.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//btn4.setEnabled(false);
mConnectedThread.write("3"); // Send "3" via Bluetooth
if(v.getId() == R.id.btn4){
//define a new Intent for the second Activity
Intent intent = new Intent(MainActivity.this,NewClass4.class);
//start the second Activity
MainActivity.this.startActivity(intent);
}}
});
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not supported");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Toast.makeText(getBaseContext(), "Connected!", Toast.LENGTH_SHORT).show();
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
And activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true" >
<TextView
android:id="@+id/txtArduino"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="" />
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/txtArduino"
android:text="@string/btn_1" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn1"
android:text="@string/btn_2" />
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn2"
android:text="@string/btn_3" />
<Button
android:id="@+id/btn4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn3"
android:text="@string/btn_4" />
</RelativeLayout>
When I need to run something every so often I use a handler.
Handler viewHandler = new Handler();
Runnable updateView = new Runnable() {
@Override
public void run() {
mEmulatorView.invalidate();
viewHandler.postDelayed(updateView, 1000);
}
};
To call this in my method:
viewHandler.post(updateView);
In this case I am updating my screen every 1000ms by invalidating it.
EDIT: full code sample
Handler viewHandler = new Handler();
Runnable updateView = new Runnable() {
@Override
public void run() {
mEmulatorView.invalidate();
if (statusBool == true) {
for (int i = 1; i < dataReceived.length() - 1; i++) {
if (dataReceived.charAt(i) == '>') {
Log.d(TAG, "found >");
deviceStatus = 0;
}
if (dataReceived.charAt(i) == '#'
&& dataReceived.charAt(i - 1) != ')') {
Log.d(TAG, "found #");
deviceStatus = 1;
}
if ((i + 1) <= (dataReceived.length())
&& dataReceived.charAt(i) == ')'
&& dataReceived.charAt(i + 1) == '#') {
Log.d(TAG, "found config )#");
deviceStatus = 2;
}
}
statusBool = false;
viewHandler.postDelayed(updateView, 1000);
}
}
};
public void onDataReceived(int id, byte[] data) {
dataReceived = new String(data);
statusBool = true;
Log.d(TAG, "in data received " + dataReceived);
((MyBAIsWrapper) bis).renew(data);
runOnUiThread(new Runnable(){
@Override
public void run() {
mSession.write(dataReceived);
}});
viewHandler.post(updateView);
}
这篇关于如何读取连续数据并显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!