- Simple Bluetooth chat application in Android
- Requesting Bluetooth permissions
- Checking if device supports Bluetooth
- Check if Bluetooth is Enabled
- Discovering Bluetooth devices
- Listing paired devices
- Connecting to a device
- Read and write data (text messages)
- Application output
- Conclusions
- Bluetooth Chat 1.3.2
- To Allow Two Way Text Chat Over Bluetooth in Android
- Step 1 Get Bluetooth Service
- Step 2 BluetoothAdapter class
- Step 3 isEnable() Method
- Step 4 Discover Bluetooth
- Step 5 Bluetooth Connection
- Step 6 Pairing devices
- Step 7 Read and Write Data
- Tejal Poriya
Simple Bluetooth chat application in Android
Bluetooth is a wireless technology standard for exchanging data over short distances (using short-wavelength UHF radio waves in the ISM band from 2.4 to 2.485 GHz[4]) from fixed and mobile devices, and building personal area networks (PANs). Invented by telecom vendor Ericsson in 1994,[5] it was originally conceived as a wireless alternative to RS-232 data cables. It can connect several devices, overcoming problems of synchronization.
According to this, we can «build» a local are network (LAN) by connecting devices over Bluetooth. The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth APIs. These APIs let applications wirelessly connect to other Bluetooth devices, enabling point-to-point and multipoint wireless features so we absolutely able to transferring data to other devices in the network circle.
Now, in this tutorial, I will note some important works to make a simple chat application which allows two Android devices to carry out two-way text chat over Bluetooth. If you only need full application code, please go to end of this post!
Requesting Bluetooth permissions
In order to use Bluetooth service, please add BLUETOOTH permission to your AndroidManifest.xml. Moreover, because we need to discover available devices nearby later, BLUETOOTH_ADMIN permission should be required, too:
Checking if device supports Bluetooth
Now to check whether Bluetooth is supported on device or not, we use object of BluetoothAdapter class. If getDefaultAdapter() return null, your device not supports Bluetooth. This is the «check code»:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) < Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show(); finish(); //automatic close app if Bluetooth service is not available! >
Check if Bluetooth is Enabled
if (!bluetoothAdapter.isEnabled())
You should put this code in onStart() to ensure that your app always check the connection when it launched! The «enabling request» dialog may be like this:
Discovering Bluetooth devices
In android, available devices is not discoverable by default. To scanning them, use startDiscovery() method of BluetoothAdapter class. The activity which starts scanning must register a BroadCastReceiver with BluetoothDevice.ACTION_FOUND action. After completing discovery, system will broadcast BluetoothDevice.ACTION_FOUND Intent . This Intent contains extra fields EXTRA_DEVICE and EXTRA_CLASS , representing a BluetoothDevice and a BluetoothClass, respectively. In this application, I will add detected devices to an ArrayAdapter and show by ListView :
if (bluetoothAdapter.isDiscovering()) < bluetoothAdapter.cancelDiscovery(); >bluetoothAdapter.startDiscovery(); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(discoveryFinishReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(discoveryFinishReceiver, filter);
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) < discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress()); >> else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < if (discoveredDevicesAdapter.getCount() == 0) < discoveredDevicesAdapter.add(getString(R.string.none_found)); >> > >;
Listing paired devices
Moreover, your devices can be connected to some other devices before, so you can listing them by call getBondedDevices() :
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < for (BluetoothDevice device : pairedDevices) < pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress()); >> else
In this sample application, I show a Dialog which contains 2 ListViews of paired devices and discovered devices and this result look like this:
Connecting to a device
- Initializing an instance of BluetoothServerSocket by calling the listenUsingRfcommWithServiceRecord() method.
- Listening for connection requests by calling accept()
- Release server socket by calling close()
private class AcceptThread extends Thread < private final BluetoothServerSocket serverSocket; public AcceptThread() < BluetoothServerSocket tmp = null; try < tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(APP_NAME, MY_UUID); >catch (IOException ex) < ex.printStackTrace(); >serverSocket = tmp; > public void run() < setName("AcceptThread"); BluetoothSocket socket; while (state != STATE_CONNECTED) < try < socket = serverSocket.accept(); >catch (IOException e) < break; >// If a connection was accepted if (socket != null) < synchronized (ChatController.this) < switch (state) < case STATE_LISTEN: case STATE_CONNECTING: // start the connected thread. connected(socket, socket.getRemoteDevice()); break; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already connected. Terminate // new socket. try < socket.close(); >catch (IOException e) < >break; > > > > >
- Create an instance of BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID) on BluetoothDevice object.
- Initializing the connection by calling connect() .
private class ConnectThread extends Thread < private final BluetoothSocket socket; private final BluetoothDevice device; public ConnectThread(BluetoothDevice device) < this.device = device; BluetoothSocket tmp = null; try < tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); >catch (IOException e) < e.printStackTrace(); >socket = tmp; > public void run() < setName("ConnectThread"); // Always cancel discovery because it will slow down a connection bluetoothAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try < socket.connect(); >catch (IOException e) < try < socket.close(); >catch (IOException e2) < >connectionFailed(); return; > // Reset the ConnectThread because we're done synchronized (ChatController.this) < connectThread = null; >// Start the connected thread connected(socket, device); > public void cancel() < try < socket.close(); >catch (IOException e) < >> >
private static final UUID MY_UUID = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
Read and write data (text messages)
Of course, after establishing connection successfully, we’ll do the most important work of a chat application: send/receive text messages. Now, each device has a connected BluetoothSocket , both of them can read and write data to the streams using read(byte[]) and write(byte[]) :
private class ReadWriteThread extends Thread < private final BluetoothSocket bluetoothSocket; private final InputStream inputStream; private final OutputStream outputStream; public ReadWriteThread(BluetoothSocket socket) < this.bluetoothSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try < tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); >catch (IOException e) < >inputStream = tmpIn; outputStream = tmpOut; > public void run() < byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while (true) < try < // Read from the InputStream bytes = inputStream.read(buffer); // Send the obtained bytes to the UI Activity handler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); >catch (IOException e) < connectionLost(); // Start the service over to restart listening mode ChatController.this.start(); break; >> > // write to OutputStream public void write(byte[] buffer) < try < outputStream.write(buffer); handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); >catch (IOException e) < >> public void cancel() < try < bluetoothSocket.close(); >catch (IOException e) < e.printStackTrace(); >> >
NOTE : In my sample project, I put AcceptThread , ConnectThread and ReadWriteThread classes into a class named ChatController .
Application output
Some screenshots of this simple chat app:
When you have connected to a dive |
Sending/receiving messages with connected device |
When user close app on other device, the connection was lost |
Conclusions
Bluetooth Chat 1.3.2
Bluetooth Chat – это необычное и простое приложение, которое даст вам возможность отправлять сообщение с помощью технологии Bluetooth.
Несмотря на то, что на дворе 21 век, качественное покрытие 3G/4G интернета есть далеко не во всех регионах. Но, поскольку без интернета в наше время никуда, проблемы с сетью приносят значительный дискомфорт. С помощью Bluetooth Chat вы сможете обмениваться короткими сообщениями, не подключаясь к сети Интернет. Bluetooth Chat может стать незаменимым помощником для школьников, студентов или путешественников, у которых доступ к Wi-Fi или 3G/4G сети есть не всегда.
Если у ваших собеседников нет еще приложения Bluetooth Chat, вы всегда можете поделиться .apk файлом по Bluetooth. Чтобы начать пользоваться приложением достаточно ввести имя и выбрать цвет аватара. Далее у вас отобразятся устройства, с которыми вы можете установить контакт. Все чаты сохраняются, и вы всегда можете продолжить беседу.
Особенности приложения Bluetooth Chat:
- Минималистичный дизайн;
- Не требует подключения к интернету;
- Простая регистрация;
- Возможность отправлять смс и изображения.
To Allow Two Way Text Chat Over Bluetooth in Android
Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android.
Step 1 Get Bluetooth Service
We need the Android Bluetooth service for this tutorial to work. In order to use Bluetooth service, declare BLUETOOTH permission in manifest file.
Now to initiate device discovery and to access Bluetooth setting declare BLUETOOTH_ADMIN permission.
(Note: If we require BLUETOOTH_ADMIN permission, then we have to declare BLUETOOTH permission also.)
Step 2 BluetoothAdapter class
Now to check whether Bluetooth is supported on device or not, we use object of BluetoothAdapter class.
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
If this method returns null, then it means that Bluetooth is not supported on the device and so we will close the application.
To know more about BluetoothAdapter class please refer following link:
Step 3 isEnable() Method
To check Bluetooth is enabled or not, we will use isEnabled() method on object of BluetoothAdapter class.
If Bluetooth is disabled then we request the user to enable it. And we perform this action by calling startActivityForResult() with REQUEST_ENABLE_BT action. This will open dialog to enable Bluetooth on the device.
Intent enableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
If the user clicks Allow then the onActivityResult() method receives RESULT_OK and if the user clicks Deny (or due to internal problem in device), RESULT_CANCELED is received. If returned value RESULT_OK is received then we will initiate the chat service.
Step 4 Discover Bluetooth
Now in android, device is not discoverable by default. To make device discoverable, call startActivityForResult() with BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE action. By default device is discoverable for 120 seconds. To set discoverable duration, add EXTRA_DISCOVERABLE_DURATION in intent extra. The maximum value for duration is 360 seconds.
Intent discoverableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent);
This will open dialog to enable discoverable mode.
Step 5 Bluetooth Connection
To start the chat, we first need to establish connection with the desired device. And before starting scanning for available devices, we usually get paired devices first in the list.
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = bluetoothAdapter.getBondedDevices();
Above code will return a set of BluetoothDevice objects. The object of BluetoothDevice class gives required information about remote device which is used to establish connection (Explained later).
To start scanning, call the startDiscovery() method of BluetoothAdapter class. The activity which starts scanning must register receiver with BluetoothDevice.ACTION_FOUND action. After completing discovery, system will broadcast BluetoothDevice.ACTION_FOUND intent. This Intent contains extra fields EXTRA_DEVICE and EXTRA_CLASS, representing a BluetoothDevice and a BluetoothClass, respectively.
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) < newDevicesArrayAdapter.add(device.getName() + "\n"+ device.getAddress()); >> else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED .equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (newDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText( R.string.none_found).toString(); newDevicesArrayAdapter.add(noDevices); >> > >;
To know more about BroadcastReceiver please refer following link:
To register receiver:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(discoveryFinishReceiver, filter);
Step 6 Pairing devices
To connect two devices, we must implement server side and client side mechanism. One device shall open the server socket and another should initiate the connection. Both are connected when BluetoothSocket is connected on the same RFCOMM channel. During connection procedure android framework automatically shows pairing dialog.
Connection as Server:
- Make object of BluetoothServerSocket by calling the listenUsingRfcommWithServiceRecord().
- Listening for connection requests by calling accept().
- Release server socket by calling close().
private class AcceptThread extends Thread < private final BluetoothServerSocket serverSocket; private String socketType; public AcceptThread(boolean secure) < BluetoothServerSocket tmp = null; socketType = secure ? "Secure" : "Insecure"; try < if (secure) < tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord( NAME_SECURE, MY_UUID_SECURE); >else < tmp = bluetoothAdapter .listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); >> catch (IOException e) < >serverSocket = tmp; > public void run() < setName("AcceptThread" + socketType); BluetoothSocket socket = null; while (state != STATE_CONNECTED) < try < socket = serverSocket.accept(); >catch (IOException e) < break; >if (socket != null) < synchronized (ChatService.this) < switch (state) < case STATE_LISTEN: case STATE_CONNECTING: connected(socket, socket.getRemoteDevice(), socketType); break; case STATE_NONE: case STATE_CONNECTED: try < socket.close(); >catch (IOException e) < >break; > > > > > public void cancel() < try < serverSocket.close(); >catch (IOException e) < >> >
To know more about BluetoothSocket please refer following link:
Connection as Client:
- Create object of BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID) on BluetoothDevice object.
- Initiate connection by calling connect().
private class ConnectThread extends Thread < private final BluetoothSocket socket; private final BluetoothDevice device; private String socketType; public ConnectThread(BluetoothDevice device, boolean secure) < this.device = device; BluetoothSocket tmp = null; socketType = secure ? "Secure" : "Insecure"; try < if (secure) < tmp = device .createRfcommSocketToServiceRecord(MY_UUID_SECURE); >else < tmp = device .createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); >> catch (IOException e) < >socket = tmp; > public void run() < setName("ConnectThread" + socketType); bluetoothAdapter.cancelDiscovery(); try < socket.connect(); >catch (IOException e) < try < socket.close(); >catch (IOException e2) < >connectionFailed(); return; > synchronized (ChatService.this) < connectThread = null; >connected(socket, device, socketType); > public void cancel() < try < socket.close(); >catch (IOException e) < >> >
Step 7 Read and Write Data
- After establishing connection successfully, each device has connected BluetoothSocket.
- Now one can Read and write data to the streams using read(byte[]) and write(byte[]).
private class ConnectedThread extends Thread < private final BluetoothSocket bluetoothSocket; private final InputStream inputStream; private final OutputStream outputStream; public ConnectedThread(BluetoothSocket socket, String socketType) < this.bluetoothSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try < tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); >catch (IOException e) < >inputStream = tmpIn; outputStream = tmpOut; > public void run() < byte[] buffer = new byte[1024]; int bytes; while (true) < try < bytes = inputStream.read(buffer); handler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); >catch (IOException e) < connectionLost(); ChatService.this.start(); break; >> > public void write(byte[] buffer) < try < outputStream.write(buffer); handler.obtainMessage(MainActivity.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); >catch (IOException e) < >> public void cancel() < try < bluetoothSocket.close(); >catch (IOException e) < >> >
(Note: use android-support-v7-appcompat from your SDK)
I hope you find this blog post is very helpful while working with Two Way Text Chat Over Bluetooth in Android. Let me know in comment if you have any questions regarding Android. I will reply you ASAP.
Got an Idea of Android App Development? What are you still waiting for? Contact us now and see the Idea live soon. Our company has been named as one of the best Android App Development Company in India.
Tejal Poriya
I am Android Developer, as a developer my basic goal is continue to learn and improve my development skills , to make application more user friendly.