我正在制作一个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();
}

}


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

最佳答案

使用以下代码段解决了该问题:

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

09-25 22:24