Monday 21 December 2015

Android Bluetooth Terminal

Developing an android Bluetooth terminal.

Hi All,

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


Let us start

1. Firstly check whether Bluetooth is enabled or not using following code


private boolean isBluetoothEnabled(){
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    return btAdapter.isEnabled();
}


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

public void selectDevice(){
    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());
        }
    }

    // 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();
            Toast.makeText(MainActivity.this, "Device selected", Toast.LENGTH_SHORT).show();
        }
    });

    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)) {
        Toast.makeText(MainActivity.this,"no bluetooth no device select", Toast.LENGTH_LONG).show();
        // 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 while establishing Bluetooth connection. 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", "Couldn't fallback while establishing Bluetooth connection. 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(Recieving) 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();

}



Thank you

Happy coding :)

My Apps MobileUtility