java - 在Android中通过蓝牙发送字符串
问题描述
我正在寻找如何在 Android 中通过蓝牙发送文本/字符串。我找到了结果。
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我从代码中了解到,每次通过蓝牙发送数据时,我都必须单击允许。但是,我想在我的应用程序中显示该字符串。
任务 :
然后,我将通过蓝牙从我的应用程序发送一个字符串,然后在另一部手机中获取并显示/使用该字符串。
上面的源代码是不可能的。那么,如何以编程方式通过蓝牙接收和发送字符串?
解决方案
推荐阅读
- perl - Net::SSH::Perl:收到断开连接消息:用户名身份验证失败太多
- reactjs - 在redux中API调用成功后调用另一个动作?
- networking - NS2中的Linux TCP拥塞控制算法
- r - 在R中一次替换矩阵中的多个值
- apache - 将站点移动到子域,.htaccess 重定向 Apache
- css - 单击时在两个 ngClass 类之间切换,但仅适用于单击的元素
- c - 哪个函数负责在linux“usbserial”驱动程序中接收数据?
- r - gauher(k) 中的错误:使用 difGenLord 函数找不到对象“gh”
- vba - 这个 Visual Basic 代码有什么作用?微软 word 宏
- ssas-2008 - 浏览度量时,SSAS Cube 不显示数据