我在android studio中有以下代码,我们有一个带有蓝牙模块HC-05的arduino,我们正试图通过蓝牙将数据从传感器发送到Android应用程序:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temperature);
btnOn = (Button) findViewById(R.id.measure);
sensorView0 = (TextView) findViewById(R.id.temp);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
CheckBlueToothState();
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
Toast.makeText(getBaseContext(), "Start Measuring", Toast.LENGTH_SHORT).show();
}
});
}
void openBT() throws IOException {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("%"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
int dataLength = dataInPrint.length(); //get length of data received
if (recDataString.charAt(0) == '*') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, endOfLineIndex); //get sensor value from string between indices 1-5
sensorView0.setText( sensor0 ); //update the textviews with sensor values
}
recDataString.delete(0, recDataString.length()); //clear all string data
dataInPrint = " ";
}
}
}
};
beginListenForData1();
Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 1000);//Message will be delivered in 1 second.
// myLabel.setText("Bluetooth Opened");
}
void beginListenForData1() {
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInputStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
});
workerThread.start();
}
private Runnable mMyRunnable = new Runnable()
{
@Override
public void run()
{
//Change state here
}
};
private void CheckBlueToothState() {
if (mBluetoothAdapter == null) {
} else {
if (mBluetoothAdapter.isEnabled()) {
if (mBluetoothAdapter.isDiscovering()) {
} else {
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-05")) {
mmDevice = device;
break;
}
}
try {
openBT();
}
catch (IOException ex) {
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();};
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == REQUEST_ENABLE_BT) {
{CheckBlueToothState();
}
}
}
void sendData() throws IOException
{
String msg = "1";
msg += "\n";
mmOutputStream.write(msg.getBytes());
//myLabel.setText("Data Sent");
}
void sendData0() throws IOException
{
String msg = "0";
msg += "\n";
mmOutputStream.write(msg.getBytes());
//myLabel.setText("Data Sent");
}
@Override
public void onBackPressed() {
super.onBackPressed();
try {
sendData0();
} catch (IOException e) {
e.printStackTrace();
}
try {
closeBT();
} catch (IOException e) {
e.printStackTrace();
}
//System.exit(0);
this.finish();
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
}
}
该代码仅适用于第二次,因此当我第一次按下应用程序中的按钮时,它不会显示数据,但是当我第二次按下它时会显示数据,为什么会发生这种情况?