gpt4 book ai didi

android - 如何将数据(字符串)发送到android中的配对设备?

转载 作者:行者123 更新时间:2023-11-29 01:39:40 27 4
gpt4 key购买 nike

我是第一次使用蓝牙。我得到了配对设备的列表。现在我的要求是我需要向设备发送一些数据(一个字符串)。我怎样才能做到这一点?我尝试搜索但没有找到任何有用的东西。谁能帮忙解决这个问题?

最佳答案

这样的东西可能就足够了:

DataOutputStream os;

BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

BroadcastReceiver discoveryResult = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
BluetoothDevice remoteDevice;

remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

Toast.makeText(getApplicationContext(), "Discovered: " + remoteDeviceName + " address " + remoteDevice.getAddress(), Toast.LENGTH_SHORT).show();

try{
BluetoothDevice device = bluetooth.getRemoteDevice(remoteDevice.getAddress());

Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});

BluetoothSocket clientSocket = (BluetoothSocket) m.invoke(device, 1);

clientSocket.connect();

os = new DataOutputStream(clientSocket.getOutputStream());

new clientSock().start();
} catch (Exception e) {
e.printStackTrace();
Log.e("BLUETOOTH", e.getMessage());
}
}
};

registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));

bluetooth.enable();
if (!bluetooth.isDiscovering()) {
bluetooth.startDiscovery();
}

public class clientSock extends Thread {
public void run () {
try {
os.writeBytes("anything you want"); // anything you want
os.flush();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
}
}

您还需要大量导入,例如:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;

import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

请注意,并非所有导入对于此示例代码都是必需的,您的 IDE 可能会帮助您为您整理它们。

os.writeBytes("anything you want") 上传递数据;//任何你想要的行。

您还需要 Permissions

关于android - 如何将数据(字符串)发送到android中的配对设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25577645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com