如何使用HandleMessage方法读取和解析Java中的数据?
我正在构建一个android应用程序,它将能够从负载传感器读取值。负载传感器连接至LCD,以显示应用于传感器和Arduino板的重量值。我只是构建这个应用程序,从LCD/负载传感器获取重量值。我正在使用HC-06蓝牙模块,我能够成功连接/配对此设备。“MainActivity”活动有一个“get data”(获取数据)按钮,用于从负载传感器读取数据,但只要按下该按钮,应用程序就会冻结。以下教程的作者告诉我,我需要编写一些“处理程序”方法。我做了一次尝试,但没有成功 我一直在学习本教程,但我一直在阅读数据 这是我的密码:如何使用HandleMessage方法读取和解析Java中的数据?,java,android,bluetooth,arduino,android-bluetooth,Java,Android,Bluetooth,Arduino,Android Bluetooth,我正在构建一个android应用程序,它将能够从负载传感器读取值。负载传感器连接至LCD,以显示应用于传感器和Arduino板的重量值。我只是构建这个应用程序,从LCD/负载传感器获取重量值。我正在使用HC-06蓝牙模块,我能够成功连接/配对此设备。“MainActivity”活动有一个“get data”(获取数据)按钮,用于从负载传感器读取数据,但只要按下该按钮,应用程序就会冻结。以下教程的作者告诉我,我需要编写一些“处理程序”方法。我做了一次尝试,但没有成功 我一直在学习本教程,但我一直在
package com.proj.splate;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
@SuppressWarnings("unused")
public class MainActivity extends Activity {
Button btnscan;
TextView txtArduino, txtString, txtStringLength, calorie;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket; //= null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Link the buttons and textViews to respective views
btnscan = (Button) findViewById(R.id.scanBtn);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endOfLineIndex = recDataString.indexOf("~");
if (endOfLineIndex > 0) {
String dataInPrint = recDataString.substring(0, endOfLineIndex);
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length();
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#')
{
//get sensor value from string between indices 1-20
String weight = recDataString.substring(1, 20);
//update the textviews with sensor values
calorie.setText(weight + "kg");
}
recDataString.delete(0, recDataString.length());
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for button to scan for data
btnscan.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0");
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
@Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
@Override
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
btSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer);
bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes();//converts entered String into bytes
try {
mmOutStream.write(msgBuffer);//write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failed", Toast.LENGTH_LONG).show();
finish();
}
}
public class BluetoothInHandler extends Handler{
private Looper sLooper = null;
private Handler mWorkerThreadHandler;
final int handlerState = 0; //used to identify handler message
protected class WorkerArgs {
Handler handler;
String input;
String output;
}
public BluetoothInHandler() {
super();
synchronized (BluetoothInHandler.class) {
if (sLooper == null) {
HandlerThread thread = new HandlerThread("AsyncWorker");
thread.start();
sLooper = thread.getLooper();
}
}
mWorkerThreadHandler = new WorkerHandler(sLooper);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == handlerState) {
WorkerArgs args = (WorkerArgs) msg.obj;
String readMessage = args.output;
//your job;
} else {
super.handleMessage(msg);
}
}
public void write(String input) {
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.input = input;
Message message = mWorkerThreadHandler.obtainMessage(handlerState);
message.obj = args;
mWorkerThreadHandler.sendMessage(message);
}
protected class WorkerHandler extends Handler {
public WorkerHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == handlerState) {
WorkerArgs args = (WorkerArgs) msg.obj;
byte[] buffer;
//the code here run in a thread, not in the ui thread
//do your job like:
byte[] bytes = mmInStream.read(buffer);
args.output = new String(bytes);
Message message = args.handler.obtainMessage(handlerState);
message.obj = args;
message.sendToTarget();
}
}
}
}
}//ConnectedThread End
}
这是我的Arduino代码:
#include <LiquidCrystal.h>
int led = 13;
int button = 12;
LiquidCrystal lcd(9, 8, 4, 5, 6, 7);
// Pins used for inputs and outputs********************************************************
float sensorValue1;
float containerValue;
char inbyte = 0;
int flag;
const int numReadings = 50;
int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;
//*******************************************************************************************
void setup()
{
pinMode(led, OUTPUT);
digitalWrite(led, HIGH);
Serial.begin(9600);
for (int thisReading = 0; thisReading < numReadings; thisReading++)
{
readings[thisReading] = 0;
}
lcd.begin(16, 2); //change to 16, 2 for smaller 16x2 screens
lcd.clear();
lcd.print("hello, world!");
delay (1000);
lcd.clear();
delay (500);
}
void loop()
{
digitalWrite(led, HIGH);
readSensor2(); //DONE
printLCD(); //DONE
return;
sendAndroidValues();
//when serial values have been received this will be true
if (Serial.available() > 0)
{
inbyte = Serial.read();
if (inbyte == '0')
{
//LED off
digitalWrite(led, LOW);
}
if (inbyte == '1')
{
//LED on
digitalWrite(led, HIGH);
}
}
//delay by 2s. Meaning we will be sent values every 2s approx
//also means that it can take up to 2 seconds to change LED state
delay(2000);
void readSensor2()
{
total = total - readings[index];
readings[index] = analogRead(A0);
total = total + readings[index];
index = index + 1;
if (index >= numReadings)
{
index = 0;
}
average = total / numReadings;
//sensorValue1 = (analogRead(A0) - 330)* i;
//delay(200);
Serial.println(average);
delay(100);
if( digitalRead(button) == HIGH && flag == 1)
{
flag = 0;
containerValue = 0;
}
else if (digitalRead(button) == HIGH && flag != 1)
{
flag = 1; //when the button is pressed the initially sesnsor
containerValue = sensorValue1;
delay(10);
}
//Serial.println(digitalRead(button));
delay (1000);
}
//sends the values from the sensor over serial to BT module
void sendAndroidValues()
{
//puts # before the values so our app knows what to do with the data
Serial.print('#');
//for loop cycles through 4 sensors and sends values via serial
Serial.print(sensorValue1);
Serial.print('+');
//technically not needed but I prefer to break up data values
//so they are easier to see when debugging
Serial.print('~'); //used as an end of transmission character - used in app for string length
Serial.println();
delay(5000); //added a delay to eliminate missed transmissions
}
void printLCD()
{
lcd.setCursor(4, 0);
lcd.print(" GRAMS ");
lcd.setCursor(4, 1);
lcd.print(sensorValue1);
}
#包括
int led=13;
int按钮=12;
液晶显示器(9,8,4,5,6,7);
//用于输入和输出的引脚********************************************************
浮动传感器值1;
浮动容器值;
半字节=0;
int标志;
常数int numReadings=50;
整数读数[整数读数];
int指数=0;
int-total=0;
整数平均=0;
//*******************************************************************************************
无效设置()
{
引脚模式(led,输出);
数字写入(led,高电平);
Serial.begin(9600);
对于(int thisReading=0;thisReading0)
{
inbyte=Serial.read();
如果(inbyte='0')
{
//引导
数字写入(led,低电平);
}
如果(inbyte='1')
{
//引导
数字写入(led,高电平);
}
}
//延迟2秒。意味着大约每2秒发送一次值
//也就是说,改变LED状态最多需要2秒钟
延迟(2000年);
void readSensor2()
{
总计=总计-读数[索引];
读数[指数]=模拟读数(A0);
总计=总计+读数[索引];
指数=指数+1;
如果(索引>=numReadings)
{
指数=0;
}
平均值=总读数/总读数;
//传感器值1=(模拟读数(A0)-330)*i;
//延迟(200);
序列号:println(平均值);
延迟(100);
如果(数字读取(按钮)=高和标志==1)
{
flag=0;
containerValue=0;
}
else if(数字读取(按钮)=高和标志!=1)
{
flag=1;//当按下按钮时,传感器开始工作
containerValue=传感器值1;
延迟(10);
}
//Serial.println(数字读取(按钮));
延迟(1000);
}
//通过串行方式将传感器的值发送至BT模块
void sendRoidValues()
{
//将#置于值之前,以便我们的应用程序知道如何处理数据
连续打印(“#”);
//for循环通过4个传感器,并通过串行总线发送值
串行打印(传感器值1);
Serial.print(“+”);
//技术上不需要,但我更喜欢分解数据值
//因此,在调试时更容易看到它们
Serial.print(“~”);//用作传输结束字符-用于应用程序中的字符串长度
Serial.println();
延迟(5000);//添加延迟以消除错过的传输
}
void printLCD()
{
lcd.setCursor(4,0);
lcd.打印(“克”);
lcd.setCursor(4,1);
lcd.打印(传感器值1);
}
不确定这是否是一个很大的问题,因为看起来你的handleMessage(Message msg)中没有做很多工作方法,但仍在主线程上创建处理程序。若要使用处理程序处理后台消息,需要向其传递单独的循环器。一种简单的方法是使用类提供循环器
但是,一旦您这样做,您将需要从handleMessage(Message msg)
将结果发布回您的UI线程,因为您不能从主线程以外的线程修改UI元素(或使用Toasts,请参阅“写入”方法)(请参阅Activity.runUnuithRead(Runnable Runnable))
此外,通过从onClickListener中调用方法的方式,您仍然将“ConnectedThread”对象用作对象……因此,它并没有真正执行您希望它执行的操作。要验证这一点,请使用Looper.myLooper()==Looper.getMainLooper()要查看当前正在执行的线程,我建议使用上面建议的处理程序解决方案,并发布可运行程序来执行
最后,由于您是ConnectedThread,所以它在一个while(true)循环中连续运行,没有暂停,这可能也会淹没您的处理程序