【发布时间】:2015-10-25 17:57:31
【问题描述】:
我正在开发一个应用程序,您可以在其中将带有蓝牙的对象数组列表发送到另一台设备。 由于我是新手,我已经能够配对 2 台设备,但我无法发送内容。我遵循了谷歌指南,但我很难理解它。 这是代码:
public class ServerThread implements Runnable {
private final BluetoothServerSocket serverSocket;
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private final String APPNAME = "Quick";
private final java.util.UUID UUID = java.util.UUID.fromString("aeeb5480-1c74-45e2-bfd0-f592958cba2a");
private Handler handler;
public ServerThread(Handler handler) {
this.handler = handler;
BluetoothServerSocket tmp = null;
try {
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(APPNAME, UUID);
} catch (IOException e) {
}
serverSocket = tmp;
}
@Override
public void run() {
BluetoothSocket socket;
while (true) {
try {
BluetoothSocket tmp;
tmp = serverSocket.accept();
socket = tmp;
} catch (IOException e) {
break;
}
if (socket != null) {
}
}
}
}
.
public class ClientThread implements Runnable {
private static final UUID UUID = java.util.UUID.fromString("aeeb5480-1c74-45e2-bfd0-f592958cba2a");
private static BluetoothSocket socket;
BluetoothDevice device;
private Handler handler;
public ClientThread(BluetoothDevice device, Handler handler) {
this.handler = handler;
BluetoothSocket tmp = null;
this.device = device;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID);
} catch (IOException e) {
e.printStackTrace();
}
socket = tmp;
}
@Override
public void run() {
if (BluetoothAdapter.getDefaultAdapter().isDiscovering()) {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
}
try {
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
}
return;
}
}
public static BluetoothSocket getSocket() {
return socket;
}
}
问题是我不知道如何在设备之间传输数据以及我需要在哪里调用允许我这样做的方法。如果有人可以帮助我,那就太好了。 谢谢
【问题讨论】:
-
您必须使用
BluetoothSocket对象(它的工作方式类似于Java 标准库中的Socket对象)。您必须在run函数中这样做
标签: java android arraylist android-studio bluetooth