Bluetooth chat in android

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:

Читайте также:  Obd2 ii bluetooth diagnostic car auto interface scanner

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 1.3.2. Скриншот 1 Bluetooth Chat 1.3.2. Скриншот 2 Bluetooth Chat 1.3.2. Скриншот 3 Bluetooth Chat 1.3.2. Скриншот 4

Bluetooth Chat – это необычное и простое приложение, которое даст вам возможность отправлять сообщение с помощью технологии Bluetooth.

Несмотря на то, что на дворе 21 век, качественное покрытие 3G/4G интернета есть далеко не во всех регионах. Но, поскольку без интернета в наше время никуда, проблемы с сетью приносят значительный дискомфорт. С помощью Bluetooth Chat вы сможете обмениваться короткими сообщениями, не подключаясь к сети Интернет. Bluetooth Chat может стать незаменимым помощником для школьников, студентов или путешественников, у которых доступ к Wi-Fi или 3G/4G сети есть не всегда.

Читайте также:  Bluetooth sap driver initialization failed

Если у ваших собеседников нет еще приложения 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);

an-app-wants-to-turn-on-bluetooth

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.

an-app-wants-to-make-your-phone-visible-to-other-bluetooth-devices-for-300-seconds

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:

Читайте также:  Asus f552c bluetooth driver

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.

bluetooth-pairing-request

Connection as Server:

  1. Make object of BluetoothServerSocket by calling the listenUsingRfcommWithServiceRecord().
  2. Listening for connection requests by calling accept().
  3. 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:

  1. Create object of BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID) on BluetoothDevice object.
  2. 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

  1. After establishing connection successfully, each device has connected BluetoothSocket.
  2. 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.

Источник

Оцените статью
Adblock
detector