我正在尝试连接Bluetooth
服务器和客户端。虽然这样做,有时它会连接并正常工作,有时它会显示错误,因为没有连接到Socket
。
我无法找到问题所在。代码如下所示: -
private Runnable reader = new Runnable()
{
@Override
public void run()
{
try
{
android.util.Log.e("TrackingFlow Client", " Found: " + remoteDevice.getName());
UUID uuid = UUID.fromString("4e5d48e0-75df-11e3-981f-0800200c9a66");
socket = remoteDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
android.util.Log.e("TrackingFlow Client", "Connected...");
os = new OutputStreamWriter(socket.getOutputStream());
is = socket.getInputStream();
//new Thread(writter).start();
android.util.Log.e("TrackingFlow Client", "CONTINUE_READ_WRITE" + CONTINUE_READ_WRITE);
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
//Keep reading the messages while connection is open...
while(CONTINUE_READ_WRITE)
{
android.util.Log.e("TrackingFlow Client", "Reading Started");
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1)
{
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow Client", "Read: " + sb.toString());
//Show message on UIThread
runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(MainActivity.this, sb.toString(), Toast.LENGTH_LONG).show();
}
});
}
} catch (IOException e) {e.printStackTrace();}
}
};