通过蓝牙发送字符串,我需要一些信息
Sending String via Bluetooth , I need some information
我正在开发一个应该与 Bluehood 完全相同的应用程序,该应用程序在 google 市场上。
所以我现在正在研究蓝牙。事实上,我想在两个设备之间传输字符串 (JSON)。我看过很多关于 Whosebug 的帖子和互联网上的一些例子,但对我来说不是很清楚。
我知道我必须使用 createInsecureRfcommSocketToServiceRecord 来发送信息并使用 listenUsingInsecureRfcommWithServiceRecord 来接收它们,但我正在搜索一些简单的教程来解释它是如何工作的以及如何在两个设备之间传输数据。
提前感谢您的解释...
很难知道我是否有效地回答了这个问题,因为您说您已经搜索了网络并且我在 android com on Bluetooth 找到了最有用的教程之一。我提供了部分代码,不是完整的线程 classes,而是让您了解如何使用临时套接字,直到找到套接字并使其成为最终套接字,在连接期间,以及如何使用的骨架线程管理连接过程的每个阶段。
listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
用于创建服务器套接字。它侦听连接。它就像一个服务器。这是在充当服务器或侦听传入连接的设备上。
这是一个单独的线程完成的。
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothConnection.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
}
有一个单独的线程充当客户端,寻求连接。它去寻找一个连接。这是在寻求与服务器设备连接的设备上。 (这些可以互换)。
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
}
connectionFailed();
return;
}
然后您需要一个线程来管理实际连接。当客户端遇到服务器。也在单独的线程中。
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
BluetoothConnection.this.start();
break;
}
}
}
在此线程中,您还拥有用于管理通过此连接写入数据的代码。
通过 android.com 提供了 samples。
我还发现 this tutorial 很好,作为蓝牙发现和连接的简单背景,尽管它不能为您提供读写数据所需的一切。
就读取和写入数据而言,以下代码段是处理读取数据并将其解析为可用内容的方法的示例。从连接线程中调用处理程序。在这种情况下,我将数据附加到 textView,但你可以用它做任何你想做的事情,它展示了如何将它放入一个字符串中。 (这就是您要找的)。
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
textView1.append("\nMessage " + messageCount + ": " + readMessage);
....
同样有一些代码可以写消息 - 这是在连接的线程中 class。但是,我使用带有要发送的按钮的 OnClick 事件来获取此信息。从 EditText 中获取文本并将其发送到函数以将字符串解析为字节。
其中 message 是一个字符串,mChatService 正在从已连接线程调用 write 方法。
将字符串转换为字节数组,以便发送。
// Get the message bytes and tell the BTManager to write
byte[] send = message.getBytes();
mChatService.write(send);
从连接的线程写入方法:
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
}
}
值得注意的是,必须监控设备的状态(您可以查看相关教程)。
让后台线程远离 UI 也很重要。所以这就是技巧(和处理程序)在 UI 和套接字连接之间传输数据的地方。
我正在开发一个应该与 Bluehood 完全相同的应用程序,该应用程序在 google 市场上。
所以我现在正在研究蓝牙。事实上,我想在两个设备之间传输字符串 (JSON)。我看过很多关于 Whosebug 的帖子和互联网上的一些例子,但对我来说不是很清楚。
我知道我必须使用 createInsecureRfcommSocketToServiceRecord 来发送信息并使用 listenUsingInsecureRfcommWithServiceRecord 来接收它们,但我正在搜索一些简单的教程来解释它是如何工作的以及如何在两个设备之间传输数据。
提前感谢您的解释...
很难知道我是否有效地回答了这个问题,因为您说您已经搜索了网络并且我在 android com on Bluetooth 找到了最有用的教程之一。我提供了部分代码,不是完整的线程 classes,而是让您了解如何使用临时套接字,直到找到套接字并使其成为最终套接字,在连接期间,以及如何使用的骨架线程管理连接过程的每个阶段。
listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
用于创建服务器套接字。它侦听连接。它就像一个服务器。这是在充当服务器或侦听传入连接的设备上。
这是一个单独的线程完成的。
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
synchronized (BluetoothConnection.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
}
break;
}
}
}
}
}
有一个单独的线程充当客户端,寻求连接。它去寻找一个连接。这是在寻求与服务器设备连接的设备上。 (这些可以互换)。
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
}
mmSocket = tmp;
}
public void run() {
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
}
connectionFailed();
return;
}
然后您需要一个线程来管理实际连接。当客户端遇到服务器。也在单独的线程中。
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
BluetoothConnection.this.start();
break;
}
}
}
在此线程中,您还拥有用于管理通过此连接写入数据的代码。
通过 android.com 提供了 samples。 我还发现 this tutorial 很好,作为蓝牙发现和连接的简单背景,尽管它不能为您提供读写数据所需的一切。
就读取和写入数据而言,以下代码段是处理读取数据并将其解析为可用内容的方法的示例。从连接线程中调用处理程序。在这种情况下,我将数据附加到 textView,但你可以用它做任何你想做的事情,它展示了如何将它放入一个字符串中。 (这就是您要找的)。
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
textView1.append("\nMessage " + messageCount + ": " + readMessage);
....
同样有一些代码可以写消息 - 这是在连接的线程中 class。但是,我使用带有要发送的按钮的 OnClick 事件来获取此信息。从 EditText 中获取文本并将其发送到函数以将字符串解析为字节。
其中 message 是一个字符串,mChatService 正在从已连接线程调用 write 方法。 将字符串转换为字节数组,以便发送。
// Get the message bytes and tell the BTManager to write
byte[] send = message.getBytes();
mChatService.write(send);
从连接的线程写入方法:
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer).sendToTarget();
} catch (IOException e) {
}
}
值得注意的是,必须监控设备的状态(您可以查看相关教程)。
让后台线程远离 UI 也很重要。所以这就是技巧(和处理程序)在 UI 和套接字连接之间传输数据的地方。