I need to transfer some data from my Android application via Bluetooth (in Arduino). I do not read or receive anything from Arduino. For my single threaded needs, I went with IntentService. After pairing, my code works fine when I connect and send data. I will disconnect after sending the data without errors. But when I try to connect a second time, I get the following error when trying myBluetoothSocket.connect ():
Read error, socket may be closed or timeout, read ret: -1
The only solution is to disconnect the Arduino device and reconnect (this does not help if I force-stop the application and try reconnecting).
Please note that everything works fine if I create 2 threads (one for reading and writing each), no matter how many times I connect and send data (thereby proving that there is nothing wrong on the Arduino side, โholding backโ the old compound).
Here is my Android code:
import android.app.IntentService; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.Context; import android.os.Build; import android.os.ParcelUuid; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.UUID; public class DataTransmissionService extends IntentService { private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final String TAG = "DataTransmissionService"; private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; private OutputStream outStream = null; private BluetoothDevice device = null; public DataTransmissionService() { super("DataTransmissionService"); } @Override protected void onHandleIntent(Intent intent) { cleanup(); if (intent != null){ btAdapter = BluetoothAdapter.getDefaultAdapter(); pairedDeviceAddress = "already_paired_device_mac_addr"; try { log.d(TAG, pairedDeviceAddress); device = btAdapter.getRemoteDevice(pairedDeviceAddress); log.d(TAG, "Device bond state : " + device.getBondState()); } catch (Exception e) { log.e(TAG, "Invalid address: " + e.getMessage()); return; } try { btSocket = createBluetoothSocket(device); } catch (IOException e) { log.e(TAG, "Socket creation failed: " + e.getMessage()); return; } try { if (!btSocket.isConnected()) { btSocket.connect(); log.d(TAG, "Connected"); } else { log.d(TAG, "Already Connected");
I tested the Nexus 5 and Samsung S5 devices (it works 5.1 and 5.0 respectively).
android bluetooth
SlowAndSteady
source share