我对 java 和 android 都很陌生,目前正在开发一个简单的数据记录应用程序,用于通过蓝牙发送信息。我最近改用经典蓝牙的 HM-10 (CC41) BLE 模块。由于我对使用 Gatt 特性创建连接和接收数据一无所知,因此我想继续使用套接字通信。不过,我的手机 S7 Edge 无法与 BLE 设备配对,因此我无法选择在启动 RfcommSocket 之前以编程方式创建绑定(bind)。有没有办法在不配对的情况下继续使用套接字通信?最后,我已经有了 BLE 模块的 MAC 地址,所以我宁愿不扫描。这是我的相关代码:
公共(public)类 MainActivity 扩展 AppCompatActivity 实现 Runnable {
private BluetoothAdapter adapter;
private InputStream inputStream;
private OutputStream outputStream;
private Thread thread;
private TextView Status;
private TextView Connection;
private BluetoothSocket socket = null;
public boolean threadStatusInitial; //changed the status global variables to public static
public boolean threadStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threadStatusInitial=true;
threadStatus=true;
Status=(TextView) findViewById(R.id.StatusID);
Connection=(TextView) findViewById(R.id.ConnectionStatus);
adapter= BluetoothAdapter.getDefaultAdapter();
if(adapter==null){
Toast.makeText(this,"bluetooth is unavailable",Toast.LENGTH_SHORT).show();
finish();
return;
}
thread=new Thread(this);
}
public void connect(View view){
BluetoothDevice device=adapter.getRemoteDevice("3C:A3:08:94:C3:11");
try {
socket=device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
socket.connect();
Connection.setText("Connected");
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
if (threadStatusInitial){
thread.start();
threadStatusInitial=false; //this ensures that the thread.start() method will only be called during the initial connection
}
threadStatus=true;
} catch (IOException e) {
Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
与线程相关的全局变量与在断开连接和重新连接到 BLE 模块期间维护日志记录线程有关。
谢谢!
最佳答案
首先,低功耗蓝牙并不意味着使用套接字进行连接和数据传输。 BLE 的重点是保持尽可能低的功耗,这是套接字无法实现的,因为无论我们是否发送任何数据,它们都会保持连续的数据传输流。 您可以从此链接获取有关 android-HM10 通信的帮助。
http://android-er.blogspot.in/2015/12/connect-hm-10-ble-module-to-android.html
关于java - 在不配对的情况下使用带 BLE 的 Rfcomm 套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49416045/