我制作的应用程序可以发送一个字符(" B")来激活微控制器然后从中接受结果数据。数据将是0-100。但是,我仍然坚持将流数据转换为字符串。
我已经在评论中尝试了这些代码,但这个过程最终会永远循环。
这是我的代码:
public Bluetooth(startover so, Handler handler, ProgressDialog pd) {
// TODO Auto-generated constructor stub
this.handler=handler;
activity=so;
this.pd=pd;
}
@Override
public void run() {
// TODO Auto-generated method stub
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
try
{
btSocket =device.createRfcommSocketToServiceRecord(MY_UUID);
//Toast.makeText(this, "Bluetooth_socket is created", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e(TAG, "ON RESUME: Socket creation failed.", e);
}
try
{
btSocket.connect();
Log.e(TAG, "ON RESUME: BT connection established, datatransfer link open.");
//Toast.makeText(this, "Bluetooth_socket is connected", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
try
{
btSocket.close();
}
catch (IOException e2)
{
Log.e(TAG, "ON RESUME: Unable to close socket during connection failure", e2);
}
}
message = "B";
sendMessage(message);
InputStream mInput=null;
try {
mInput = btSocket.getInputStream();
System.out.println("Input Open");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted() && mBluetoothAdapter.isEnabled()) {
try {
int bytesAvailable = mInput.available();
if(bytesAvailable > 0) {
System.out.println("Pesan Diterima");
BufferedReader r = new BufferedReader(new InputStreamReader(mInput));
StringBuilder total = new StringBuilder(bytesAvailable);
String line;
//BACA LEBIH DARI 1 KARAKTER
//while ((line = r.readLine()) != null) {
// total.append(line);
//}
final String message=total.toString();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
System.out.println("Turn "+message);
activity.startActivity(new Intent(activity.getApplicationContext(),result.class).putExtra("data", message));
}
});
break;
}
}
catch (IOException ex) {
}
}
super.run();
}
private void sendMessage (String message) {
byte[] send = message.getBytes();
try {
OutputStream OutStream = btSocket.getOutputStream();
OutStream.write(send);
System.out.println("Send "+message);
}
catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
}