Chat bluetooth for java

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:

Читайте также:  To rate bluetooth headsets

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 .

Читайте также:  Подавитель bluetooth своими руками

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

— Создание вашего сообщества. BlueChat представляет собой программное обеспечение Bluetooth обмена сообщениями. BlueChat позволяет увидеть другие BlueChat пользователей вокруг, пинг кто-нибудь из них, а также создавать либо частные сеансы чата или комнаты публичного обмена сообщениями с помощью Bluetooth.

* Все узлы, которые хотят общаться должны иметь BlueChat ход.

* Достаточно того, что один сверстников делает начальное & Quot; Ищите друзей & Quot; операция.

* Каждый раз, когда новый посетитель сверстников делает свой первый & Quot; Ищите друзей & Quot; операция, операция будет реорганизовать все первоначальные связи и обмена информацией профиля вещи.

* Каждый узел не будет иметь обновленный список профилей вокруг автоматически и список данного профиля будет отображаться, чтобы предупредить всех о новом встречному.

* Имейте в виду, что если более чем один равный сделать & Quot; Ищите друзей & Quot; одновременно, они не могли бы быть в состоянии видеть друг друга (из-за текущих принципов Bluetooth)

* Имейте в виду, что множество из списка профилей может занять до одной минуты. Поэтому будьте терпеливы.

Активировать как многие из ваших друзей, как вы хотите, как только вы активируете себя.

* J2ME MIDP 2.0 и JSR-82 (Midlet Bluetooth Enablement)

Вопрос 1: другие люди должны иметь эту программу, чтобы иметь возможность общаться делать?

Ответ 1: Да, другие люди должны иметь BlueChat, чтобы иметь возможность общаться.

Вопрос 2: Что происходит, когда я покупаю BlueChat?

Ответ 2: Когда вы покупаете BlueChat, вам будет предоставлен код лицензии для серийного номера для активации BlueChat. Однако Хитрость здесь заключается в том, что, как только вы активируете свой BlueChat, она получает способность активировать как и многие другие BlueChat пользователей, как вы хотите бесплатно. Неактивированной BlueChat имеет полный набор функций. Это только заливает экран с сообщениями активации после отправки 50 сообщений. Для того, чтобы отправить еще 50 & Quot; чистый & Quot; сообщения, вам необходимо перезапустить BlueChat и делать больше и Quot один, искать друзей & Quot ;. That`s все.

Читайте также:  Магнитола пионер флешка блютуз

И, наконец, для того, чтобы активировать другой BlueChat бесплатно, выберите нужный профиль и нажмите & Quot; Активировать & Quot; из экранного меню.

Вопрос 3: BlueChat продолжает говорить & Quot; Вы не можете запустить BlueChat, так как ваш телефон не имеет Java Bluetooth Enablement & Quot ;. Как это исправить?

Ответ 3: BlueChat полагается на Java функциях телефона. Это сообщение говорит, что ваш телефон не поддерживает дополнительный J2ME функцию, которая JSR-82 в техническом плане, и, к сожалению, ваш телефон не может запустить BlueChat.

BlueChat является Bluetooth Messenger. BlueChat имеет блютус чатов. BlueChat представляет собой программное обеспечение Bluetooth обмена сообщениями.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Messaging over Bluetooth (Android)

License

glodanif/BluetoothChat

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

1-to-1 chatting app over Bluetooth

This project is a test area for trying and mastering fancy programming stuff: Kotlin, MVP, DI, Coroutines, testing, Architecture Components, the newest Android features.

You can help to localize Bluetooth Chat to your language using Crowdin

Copyright 2017 Vasyl Glodan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

About

Messaging over Bluetooth (Android)

Источник

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