I'm making an Android Studio app to control my Arduino project via Bluetooth. I've successfully connected the HC-06 module to the app with the following class:
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. How do I send and receive data from HC-06 via Bluetooth in an Android app? 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");
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.