我已经使用下面的代码来检测活动的蓝牙设备并创建它们的列表。准备好活动蓝牙设备列表后,我们可以从列表中选择一个设备并向该设备发送连接请求。一旦请求的设备接受连接请求,我需要从配对设备获取连续的传入数据信号。
protected void connect(BluetoothDevice device) {
try {
Log.d(TAG,"connect bluetooth");
// Create a Socket connection: need the server's UUID number of
// registered
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(device, 1);
socket.connect();
Log.d(TAG, ">>Client connectted");
inputStream = socket.getInputStream();
socket.getOutputStream();
int read = -1;
final byte[] bytes = new byte[2048];
while (true) {
synchronized (obj1) {
read = inputStream.read(bytes);
Log.d(TAG, "read:" + read);
if (read > 0) {
final int count = read;
String str = SamplesUtils.byteToHex(bytes, count);
// Log.d(TAG, "test1:" + str);
String hex = hexString.toString();
if (hex == "") {
hexString.append("<--");
} else {
if (hex.lastIndexOf("<--") < hex.lastIndexOf("-->")) {
hexString.append("\n<--");
}
}
hexString.append(str);
hex = hexString.toString();
// Log.d(TAG, "test2:" + hex);
if (hex.length() > maxlength) {
try {
hex = hex.substring(hex.length() - maxlength,
hex.length());
hex = hex.substring(hex.indexOf(" "));
hex = "<--" + hex;
hexString = new StringBuffer();
hexString.append(hex);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "e", e);
}
}
_handler.post(new Runnable() {
public void run() {
}
});
}
}
}
} catch (Exception e) {
Log.e(TAG, ">>", e);
Toast.makeText(getBaseContext(),
getResources().getString(R.string.ioexception),
Toast.LENGTH_SHORT).show();
return;
} finally {
if (socket != null) {
try {
Log.d(TAG, ">>Client Socket Close");
socket.close();
socket = null;
// this.finish();
return;
} catch (IOException e) {
Log.e(TAG, ">>", e);
}
}
}
}
我需要检测连续传入的数据信号。是否可以做到。