Developing an Android Bluetooth terminal

Chetan Gaikwad
3 min readFeb 8, 2018

Today I will show you how to develop an android Bluetooth terminal which will send a command to other Bluetooth device and get a response from the device(SERIAL COMMUNICATION).

Let us start

  1. Firstly check whether Bluetooth is enabled or not using the following code
private boolean isBluetoothEnabled(){BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();return btAdapter.isEnabled();}

2. Get all the paired device from the phone and select the device to communicate and store the device hex key for making the connection(I have stored the key in shared preference)

public void getAllDeviceAddress(){
ArrayList deviceStrs = new ArrayList();
final ArrayList devices = new ArrayList();

BluetoothAdapter btAdapter=BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices=btAdapter.getBondedDevices();
if (pairedDevices.size() > 0)
{
for (BluetoothDevice device : pairedDevices)
{
deviceStrs.add(device.getName() + "\n"+device.getAddress());
devices.add(device.getAddress());
}
}

showDeviceSelecterDialog(deviceStrs, devices);
}

Show device selecter dialog

private void showDeviceSelecterDialog(ArrayList deviceStrs
, ArrayList devices) {
// show list
final AlertDialog.Builder alertDialog =
new AlertDialog.Builder(this);

ArrayAdapter adapter =
new ArrayAdapter(this,
android.R.layout.select_dialog_singlechoice,
deviceStrs.toArray(new String[deviceStrs.size()]));

alertDialog.setSingleChoiceItems(adapter, -1,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
int position = ((AlertDialog) dialog)
.getListView()
.getCheckedItemPosition();
String deviceAddress = (String) devices.get(position);
editor.putString(bluetoothKey, deviceAddress).commit();
}
});

alertDialog.setTitle("Choose Bluetooth device");
alertDialog.show();
}

3. Make connection with the device, Check out the fall back mechanism used

private void startConnection() throws IOException {

// get the remote Bluetooth device
final String remoteDevice = preferences.getString(
bluetoothKey
, null
);

if (remoteDevice == null || "".equals(remoteDevice)) {

// log error
Log.e(LOG, "No Bluetooth device has been selected.");
return "No Bluetooth device has been selected.";

} else {

final BluetoothAdapter btAdapter =
BluetoothAdapter.getDefaultAdapter();
dev = btAdapter.getRemoteDevice(remoteDevice);

/* * Establish Bluetooth connection * */
Log.d(LOG, "Stopping Bluetooth discovery.");
btAdapter.cancelDiscovery();

try {
// Instantiate a BluetoothSocket for the remote
// device and connect it.
sock = dev.createRfcommSocketToServiceRecord(MY_UUID);
sock.connect();

} catch (Exception e1) {
Log.e("startConnection", "There was an error" +
",Falling back..", e1);
Class<?> clazz = sock.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
try {

/************Fallback method 1*********************/
Method m = clazz.getMethod(
"createRfcommSocket"
, paramTypes
);
Object[] params = new Object[]{Integer.valueOf(1)};
sockFallback = (BluetoothSocket) m.invoke(
sock.getRemoteDevice()
, params
);
sockFallback.connect();
sock = sockFallback;

Log.e("", "Connected");

} catch (Exception e2) {
Log.e("startConnection", "Stopping app..", e2);
throw new IOException();
}
}
Log.i("BT Terminal", "connected");
}
}

Note : After successful connection use the sock(Socket object) to write and read data.

4. Writing(Sending) data to Bluetooth device

private void write(Strind data){sock.getOutputStream().write(data.getBytes());}

5. Reading(Receiving) data to Bluetooth device, Pass Input Stream to the read function

String result = readRawData(sock.getInputStream());public String readRawData(InputStream in) throws IOException {byte b = 0;StringBuilder res = new StringBuilder();// read until ‘>’ arrives OR end of stream reached char c;while(true){b = (byte) in.read();if(b == -1) // -1 if the end of the stream is reached {break;}c = (char)b;if(c == ‘>’) // read until ‘>’ arrives {break;}res.append(c);}return res.toString();}

If you want to share data fetched from Bluetooth in Realtime, you can have a look at this article

“Android Real-Time communication using MQTT” by Chetan Gaikwad https://link.medium.com/CZBPubl97U

Thank you

Happy coding :)

Let’s get connected

For any query, suggestion or improvement on my blog ping me

--

--