简体   繁体   English

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

[英]Android Post/Receive data from HC-06 via Bluetooth

I'm making an Android Studio app to control my Arduino project via Bluetooth.我正在制作一个 Android Studio 应用程序来通过蓝牙控制我的 Arduino 项目。 I've successfully connected the HC-06 module to the app with the following class:我已成功将 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();
}

}

But now when I tried to send and receive data from the app things got hard, so I'm stuck.但是现在当我尝试从应用程序发送和接收数据时,事情变得很困难,所以我被卡住了。 I've googled on how to send and receive data but I mostly find tutorials on how to make a BT app from scratch.我在谷歌上搜索了如何发送和接收数据,但我主要是找到关于如何从头开始制作 BT 应用程序的教程。 How do I send and receive data from HC-06 via Bluetooth in an Android app?如何在 Android 应用程序中通过蓝牙从 HC-06 发送和接收数据? Any code snippets?任何代码片段?

Solved it with the following snippet:使用以下代码段解决了它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM