gpt4 book ai didi

java - Android 通过蓝牙从 HC-06 发送/接收数据

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:38 25 4
gpt4 key购买 nike

我正在制作一个 Android Studio 应用程序来通过蓝牙控制我的 Arduino 项目。我已成功将 HC-06 模块连接到具有以下类的应用程序:

class ConnectBT extends AsyncTask<Void, Void, Void>{
private boolean ConnectSuccess = true;

@Override
protected void onPreExecute() {

}

@Override
protected Void doInBackground(Void... devices)
{
try
{
if (Drive.btSocket == null || !Drive.isBtConnected)
{
Drive.myBluetooth = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice dispositivo = Drive.myBluetooth.getRemoteDevice(Drive.BTaddress);
Drive.btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(Drive.myUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
Drive.btSocket.connect();
}
}
catch (IOException e)
{
ConnectSuccess = false;exception here
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);

if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
}
else
{
msg("Connected.");
Drive.loadingScreen.setVisibility(View.GONE);
System.out.println("Connected");
Drive.isBtConnected = true;
}
//Drive.progress.dismiss();
}
private void msg(String s)
{
//Toast.makeText(Drive.class.,s,Toast.LENGTH_LONG).show();
}

}

但是现在,当我尝试从应用程序发送和接收数据时,事情变得很困难,所以我陷入了困境。我在谷歌上搜索了如何发送和接收数据,但我主要找到了有关如何从头开始制作 BT 应用程序的教程。如何在 Android 应用程序中通过蓝牙从 HC-06 发送和接收数据?有代码 fragment 吗?

最佳答案

用以下代码 fragment 解决了这个问题:

void sendData(String data){
if (isBtConnected){
try {
Drive.btSocket.getOutputStream().write((data).getBytes());
} catch (IOException e) {
e.printStackTrace();
msg("Failed to send Bluetooth data");
}
}
}

关于java - Android 通过蓝牙从 HC-06 发送/接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57039243/

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