我设计了一个Android应用程序,通过蓝牙从Arduino Due接收串行数据。我想将这些实时数据保存到文件中,并在我停止连接后读取该文件。我的程序没有任何错误,但是当我运行它时,我得到了“不幸的是,BT已停止”消息。我找不到错误。我很感激你的意见。
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
TextView myLable;
BluetoothDevice mmDevice;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
int readBufferPosition;
volatile boolean stopWorker;
byte[] readBuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openButton = findViewById(R.id.open);
openButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
findBT();
openBT();
// readBT();
} catch (IOException ex) {
}
}
});
Button closeButton = findViewById(R.id.close);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try{
closeBT();
}catch (IOException ex){
}
}
});
Button readButton = findViewById(R.id.read);
readButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
readFile();
}
});
TextView myLable = findViewById(R.id.lable);
}
void findBT(){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null){
myLable.setText("No bluetooth adapter available!!!");
}
if(!mBluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size()> 0){
for(BluetoothDevice device : pairedDevices){
if(device.getName().equals("RNBT-744E")){
mmDevice = device;
break;
}
}
}
myLable.setText("Bluetooth Device Found :)");
}
void openBT() throws IOException{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream =mmSocket.getInputStream();
myLable.setText("Bluetooth Opened");
readBT();
}
void readBT(){
final Handler handler = new Handler();
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()&& !stopWorker){
try{
int bytesavailable = mmInputStream.available();
if(bytesavailable > 0){
byte[] packetBytes = new byte[bytesavailable];
mmInputStream.read(packetBytes);
for(int i = 0;i < bytesavailable; i++){
byte b = packetBytes[i];
if(b == delimiter){
byte[] encodeBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodeBytes, 0, encodeBytes.length);
final String data = new String (encodeBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
@Override
public void run() {
myLable.setText(data);
saveToFile();
}
});
}
}
}
}catch (IOException ex){
stopWorker = true;
}
}
}
});
workerThread.start();
}
public void saveToFile(){
String msg = myLable.getText().toString();
try {
File testFile = new File(this.getExternalFilesDir(null), "Elmira.txt");
if(!testFile.exists()){
testFile.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
writer.write(msg);
writer.close();
MediaScannerConnection.scanFile(this, new String[]{testFile.toString()}, null, null);
}
}catch (IOException e){
Log.e("ReadWriteFile", "Unable to write to the testFile.txt file.");
}
}
void closeBT() throws IOException {
stopWorker = true;
mmInputStream.close();
mmSocket.close();
myLable.setText("Bluetooth closed");
}
void readFile(){
String textFromFile = "";
File testFile = new File(this.getExternalFilesDir(null), "Elmira.txt");
if(testFile != null){
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(testFile));
String line;
while((line = reader.readLine()) != null){
textFromFile += line.toString();
textFromFile += "\n";
myLable.setText(textFromFile);
}reader.close();
} catch(Exception e){
Log.e("ReadWriteFile", "Unable to read the TestFile.txt file");
}
}
}
}