我已经下载了蓝牙聊天应用程序的android示例,使用蓝牙在两个Android设备之间发送文本.
我在两个Android设备上安装并运行了这个应用程序.
我在那段代码中遇到了很多问题
1.清除服务发现失败异常:
对于服务发现失败的异常,在蓝牙聊天服务中,我检查了sdk版本和sdk版本大于Ginger Bread,
我已经使用Method类来调用RfCOMM套接字连接,并且我的第一个异常在这种方法中得到了解决.
例外代码
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Run Code Online (Sandbox Code Playgroud)
修复了异常代码
try {
if (Build.VERSION.SDK_INT < 9) {
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
Method m = null;
try {
m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e(TAG, "create() failed", e);
}
Run Code Online (Sandbox Code Playgroud)
2.清除java.io.IOException:软件导致连接中止
我已经检查了InputStream是否可用
例外代码
bytes = mmInStream.read(buffer);
Run Code Online (Sandbox Code Playgroud)
修复了异常代码
if (mmInStream.available() > 0) {
// Read from the InputStream
bytes = mmInStream.read(buffer);
Run Code Online (Sandbox Code Playgroud)
现在我的问题是当我尝试在连接的设备之间发送数据时,它会在写入输出流时抛出以下错误消息"Connection Reset By Peer"
例外代码:
public void write(byte[] buffer, int start, int end) {
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
if (mmOutStream !=null) {
try {
mmOutStream.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
Log.e("OutputStream Null","");
}
}
Run Code Online (Sandbox Code Playgroud)
==更新==
即使它显示两个设备都已连接,但accept方法返回失败
**06-19 10:30:23.625: D/BluetoothChatService(2630): connected
06-19 10:30:23.625: D/BluetoothChatService(2630): cancel Thread[AcceptThread,5,main]
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): abortNative
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...asocket_abort(50) complete
06-19 10:30:23.625: V/BluetoothSocket.cpp(2630): ...accept(50, RFCOMM) = -1 (errno 125)
06-19 10:30:23.632: E/BluetoothChatService(2630): accept() failed
06-19 10:30:23.632: E/BluetoothChatService(2630): java.io.IOException: Operation Canceled
06-19 10:30:23.632: E/BluetoothChatService(2630): at android.bluetooth.BluetoothSocket.acceptNative(Native Method)
Run Code Online (Sandbox Code Playgroud)
我自己的聊天示例遇到了很多问题,所以我尝试了另一种方法。
首先,您必须使一个设备成为主机,另一个成为客户端,这与该示例配合得很好。如果您没有运行此程序,我也可以为您提供该代码。
使用上面的类,您可以获得连接的套接字。使用它将它传递给此类,然后您可以使用 write 方法发送。并且传入的消息会在运行方法中自动解析(我在前面添加了消息 ID 和长度,这就是为什么那里发生了这么多事情)
private class ConnectedThread extends Thread {
/** the connection socket */
private final BluetoothSocket mmSocket;
/** input stream for incoming messages */
private final InputStream mmInStream;
/** output stream for outgoing messages */
private final OutputStream mmOutStream;
/**
* save the socket and get the streams
*
* @param socket
*/
public 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) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
/**
* reads incoming data and splits it into single messages
*/
public void run() {
/** buffer for a single byte message */
byte[] buffer = new byte[1024];
/** number of bytes returned from read() */
int bytes;
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// read overhead from the InputStream
bytes = mmInStream.read(buffer, 0, LEN_SIZE + LEN_TYPE);
// if no bytes are read, wait for a new message
if (bytes == 0)
continue;
// get the size bytes and convert them to int
byte[] size_arr = new byte[LEN_SIZE];
for (int i = 0; i < LEN_SIZE; i++)
size_arr[i] = buffer[i];
int size = convertByteArrayToInt(size_arr, LEN_SIZE);
// the type is 1 byte after the size
byte type = buffer[LEN_SIZE];
// array for the output data
byte[] output = new byte[size + LEN_TYPE];
output[0] = type;
// current position, read until cPos == size
int cPos = 0;
while (cPos < size) {
// either read the buffer lenght or the remaining bytes
int read_len = Math.min(buffer.length, size - cPos);
bytes = mmInStream.read(buffer, 0, read_len);
// write the bytes to the output
for (int i = 0; i < bytes; i++)
output[cPos + i + LEN_TYPE] = buffer[i];
// increase the current position
cPos += bytes;
}
// add the message to the queue
mMessageData.add(output);
// tell the service about the new message
mHandler.obtainMessage(BluetoothService.CONNECTION_RECV_MSG, mConnectionAddress).sendToTarget();
} catch (IOException e) {
// tell the service about the disconnect
mHandler.obtainMessage(BluetoothService.CONNECTION_LOST, mConnectionAddress).sendToTarget();
e.printStackTrace();
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* writes a byte stream to the connection
*
* @param bytes
* the byte stream
*/
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes, 0, bytes.length);
mmOutStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* close the socket
*/
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
Run Code Online (Sandbox Code Playgroud)
}
这对我有用,我希望它也对你有用。如果您有任何疑问,请随时询问:-)
| 归档时间: |
|
| 查看次数: |
2764 次 |
| 最近记录: |