我正在尝试创建用于控制arduino IOT项目的蓝牙应用程序。但是现在我被卡住了。当用户将输入内容填充到editText中,然后单击sendButton时,该应用程序将重置自身并打印arduino串行监视器:
11:29:52.162 -> ++DISC:SUCCESS
11:29:52.197 -> OK
与BT设备的连接是在MainActivity中完成的,当连接成功时,将调用概述活动。
Connection.java是维护BT连接的Java类。
Connection.java
package com.example.petr.smarthomeapp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class Connection extends AppCompatActivity {
// #defines for identifying shared types between calling functions
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address, name;
Context mContext;
BluetoothAdapter bluetoothAdapter;
ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
private Handler mHandler; // Our main handler that will receive callback notifications
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
public Connection(Context context) {
mContext = context;
}
public void initialize(String btAddress, String btName) {
address = btAddress;
name = btName;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == MESSAGE_READ) {
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if (msg.what == CONNECTING_STATUS) {
if (msg.arg1 == 1) {
Log.i("Stav: ", "připojeno");
Toast.makeText(mContext, "Připojeno", Toast.LENGTH_LONG).show();
} else {
Log.i("Stav: ", "připojení selhalo");
Toast.makeText(mContext, "Připojení selhalo", Toast.LENGTH_LONG).show();
}
}
}
};
connect();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connection with BT device using UUID
}
public void connect() {
Thread thread = new Thread() {
public void run() {
boolean fail = false;
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Chyba při vytváření socketu.", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Chyba při vytváření socketu", Toast.LENGTH_SHORT).show();
}
}
if (!fail) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
};
thread.start();
}
public void toast(String text) {
Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private 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[1024]; // 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.available();
if (bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmSocket.getOutputStream().write(bytes);
} catch (IOException e) {}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Overview.java
package com.example.petr.smarthomeapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Overview extends AppCompatActivity {
EditText editText;
Button sendButton;
Connection connection = new Connection(Overview.this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prehled);
editText = findViewById(R.id.editText);
sendButton = findViewById(R.id.odeslat);
}
public void odeslatClicked(View view){
connection.mConnectedThread.write(editText.getText().toString());
Log.i("Text: ", editText.getText().toString());
}
}