Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Bluetooth chat in Android

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to realize Bluetooth chat in Android". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to implement Bluetooth chat in Android"!

1. Master-slave relationship of Bluetooth communication

Bluetooth technology stipulates that when Bluetooth communication is carried out between each pair of devices, one must be a master role and the other is a slave role in order to communicate. When communicating, the master must search and initiate a pairing. After the successful establishment of the chain, both parties can send and receive data. In theory, one Bluetooth master device can communicate with seven Bluetooth slave devices at the same time. A device with Bluetooth communication function can switch between two roles, usually work in slave mode, wait for other master devices to connect, and switch to master mode to make calls to other devices when needed. When a Bluetooth device initiates a call in main mode, it needs to know the other party's Bluetooth address, pairing password and other information. After the pairing is completed, the call can be initiated directly.

2. Bluetooth call process

The Bluetooth host device initiates a call, first of all, to find out the Bluetooth devices around which can be found. After the master device finds the slave Bluetooth device, it pairs with the slave Bluetooth device. At this time, it needs to enter the PIN code of the slave device, and some devices do not need to enter the PIN code. After the pairing is completed, the slave Bluetooth device records the trust information of the master device, and the master can initiate a call to the slave device, and the paired device no longer needs to be re-paired on the next call. Paired devices, as slave Bluetooth devices, can also initiate chain-building requests, but Bluetooth modules for data communication generally do not initiate calls. After the link is established successfully, two-way data or voice communication can be carried out between the master and slave ends. In the communication state, both the master and slave devices can initiate chain disconnection and disconnect the Bluetooth link.

3. Bluetooth one-to-one serial port data transmission application

In the application of Bluetooth data transmission, one-to-one serial port data communication is one of the most common applications. The Bluetooth device sets the pairing information between the two Bluetooth devices in advance before leaving the factory, and the master terminal pre-stores the PIN code and address of the slave device. both ends of the device power up to build the chain automatically, transparent serial port transmission, without the intervention of peripheral circuits. In one-to-one application, the slave device can be set to two types, one is the silent state, that is, it can only communicate with the designated master without being searched by other Bluetooth devices, and the other is the development state, which can be searched by the designated master or linked by other Bluetooth devices.

Functional Overview

Bluetooth chat function is mainly divided into the following modules: message module, friend module and personal module.

Message module

Support one-to-one, one-to-many, many-to-many real-time chat, can transfer text, expressions, pictures, files and so on. Offline messages can be sent when the other party is not online, and can be pushed in time when the other party is online. Messages support historical message storage and viewing.

Friend module

Support nearby friend addition, friend deletion, friend group display, friend online and offline reminder, friend nickname and group name modification.

Personal module

Display personal information, including nicknames, images, joining time and other information.

This module has not been realized yet. At present, the main functions are one-to-one real-time chat, transmission of text, facial expressions and files, and support for friends to add, delete and group. The following mainly introduces the Bluetooth communication process that has been realized.

Operation flow

Find paired devices (that is, friend lists)

Code implementation:

Private void findDevice () {/ / get the saved pairing device Set pairedDevices = BluetoothAdapter.getDefaultAdapter (). GetBondedDevices (); if (pairedDevices.size () > 0) {mGroupFriendListData.clear (); GroupInfo groupInfo = new GroupInfo (); groupInfo.setGroupName (BluetoothAdapter.getDefaultAdapter (). GetName ()); List friendInfoList = new ArrayList (); for (BluetoothDevice device: pairedDevices) {FriendInfo friendInfo = new FriendInfo (); friendInfo.setIdentificationName (device.getName ()); friendInfo.setDeviceAddress (device.getAddress ()) FriendInfo.setFriendNickName (device.getName ()); friendInfo.setOnline (false); friendInfo.setJoinTime (DateTime.getStringByFormat (new Date (), DateTime.DEFYMDHMS); friendInfo.setBluetoothDevice (device); friendInfoList.add (friendInfo);} groupInfo.setFriendList (friendInfoList); groupInfo.setOnlineNumber (0); mGroupFriendListData.add (groupInfo); mGroupFriendAdapter.setGroupInfoList (mGroupFriendListData);}}

Friend list example diagram:

Enable the discoverability of the device

If you want to make the local device discoverable by other devices, call the startActivityForResult (Intent, int) method of the ACTION_REQUEST_DISCOVERABLE operation intent. This method makes a request to the system setting to enable discoverable mode. By default, the discoverable mode of the device lasts for 120 seconds. You can define different durations by adding EXTRA_DISCOVERABLE_DURATION additional fields to the Intent object. The maximum duration that the application can set is 3600 seconds, and 0 means that the device is always discoverable. Any value less than 0 or greater than 3600 seconds is automatically set to 120 seconds. For example, the following code sets the duration to 300 seconds:

Intent discoverableIntent = newIntent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity (discoverableIntent)

When you apply for a user to enable discoverable mode for a device, a dialog box is displayed. If you respond to "Yes", the discoverable mode of the device will last for a specified time, and your Activity will receive a call to the onActivityResult () callback method with the result code equal to the discoverable device duration. If the user responds to "No" or an error occurs, the result code is equal to RESULT_CANCELED.

In discoverable mode, the device quietly maintains this mode for a specified period of time. If you want to be notified when the discoverable mode is changed, you can register an ACTION_SCAN_MODE_CHANGED type Intent broadcast. This Intent object contains additional fields EXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE, which will tell you the new and old scan modes, respectively. Each of their possible values is: SCAN_MODE_CONNECTABLE_DISCOVERABLE,SCAN_MODE_CONNECTABLE or SCAN_MODE_NONE, which indicates whether the device is in discoverable mode or discoverable mode but can still receive connections, or cannot receive connections in discoverable mode.

If you want to initialize a connection to a remote device, you do not need to enable the device's realizability. Discoverability needs to be enabled only if you want to use your application as a server to receive input connections, because remote devices must be able to discover it before connecting to your device.

Search for devices and match them (that is, add friends)

Simply call the startDiscovery () method to start discovering the device. The process is asynchronous, and the method immediately returns a Boolean value indicating whether the discovery process was successfully started. Usually the discovery process will query the scan for about 12 seconds, and then get the Bluetooth name of each device found by the scan.

Public class ScanBroadcastReceiver extends BroadcastReceiver {private IScanCallback scanCallback; private final Map mDeviceMap = new HashMap (); public ScanBroadcastReceiver (IScanCallback scanCallback) {this.scanCallback = scanCallback;} @ Override public void onReceive (Context context, Intent intent) {if (scanCallback = = null) {return;} if (intent.getAction (). Equals (BluetoothDevice.ACTION_FOUND)) {/ / scan to Bluetooth device BluetoothDevice bluetoothDevice = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE); if (bluetoothDevice = = null) {return } if (! mDeviceMap.containsKey (bluetoothDevice.getAddress () {mDeviceMap.put (bluetoothDevice.getAddress (), bluetoothDevice);} scanCallback.discoverDevice (bluetoothDevice);} else if (intent.getAction (). Equals (BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {/ / scanning device end final List deviceList = new ArrayList (mDeviceMap.values ()); if (deviceList! = null & & deviceList.size () > 0) {scanCallback.scanFinish (deviceList) } else {scanCallback.scanTimeout ();}

Search for friend sample figure:

Public class PairBroadcastReceiver extends BroadcastReceiver {private IPairCallback pairCallback; public PairBroadcastReceiver (IPairCallback pairCallback) {this.pairCallback = pairCallback;} @ Override public void onReceive (Context context, Intent intent) {if (intent.getAction (). Equals (BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {/ / update device list information (pairing status) BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE); if (device! = null) {resolveBondingState (device.getBondState ()) } private void resolveBondingState (final int bondState) {if (pairCallback = = null) {return;} switch (bondState) {case BluetoothDevice.BOND_BONDED:// paired pairCallback.bonded (); pairCallback.bonding () in break; case BluetoothDevice.BOND_BONDING:// pairing; break; case BluetoothDevice.BOND_NONE:// unpaired pairCallback.unBonded (); break; default: pairCallback.bondFail (); break }}}

Sample diagram of pairing information:

Sample diagram of the pairing process:

Connect the device (that is, friends to establish a communication channel)

When you want to connect two devices, one must hold an open BluetoothServerSocket object as the server. The purpose of a service socket is to listen for incoming connection requests and to provide a BluetoothSocket connection object when a connection request is received. When fetching BluetoothSocket from a BluetoothServerSocket object, BluetoothServerSocket can (and should) be discarded unless you want to receive more connections.

The following is the basic process of establishing a service socket and receiving a connection:

1. Call the listenUsingRfcommWithServiceRecord (String, UUID) method to get a BluetoothServerSocket object. The String parameter in this method is an identifiable name of your server, which is automatically written to the Service Discovery Protocol (SDP) database entity on the device (the name is arbitrary, and you can simply use the name of your application). The UUID parameter is also included in the SDP entity and is the basic protocol for connecting to the client device. That is, when a client tries to connect to a server, it carries a UUID that the server it wants to connect to can uniquely identify. The connection can be received only if these UUID match exactly.

2. Start the connection request by calling the accept () method. This is a blocking call. This method returns only if the connection is received or if an exception occurs. The connection is received only if the UUID carried by the remote device that sent the connection request matches a UUID registered by the listening service socket. When the connection succeeds, the accept () method returns a connected BluetoothSocket object.

3. Unless you want to receive other connections, call the close () method. This method releases the service socket and all the resources it consumes, but does not close the BluetoothSocket object returned by the connected accept () method. Unlike TCP/IP, only one client is allowed to connect to each RFCOMM channel at a time, so in most cases, it makes sense to call the close () method of the BluetoothServerSocket object immediately after receiving a connection socket.

The following are the listening threads implemented by the above process:

Public class AcceptThread extends Thread {private BluetoothChatHelper mHelper; private final BluetoothServerSocket mServerSocket; private String mSocketType; public AcceptThread (BluetoothChatHelper bluetoothChatHelper, boolean secure) {mHelper = bluetoothChatHelper; BluetoothServerSocket tmp = null; mSocketType = secure? "Secure": "Insecure"; try {if (secure) {tmp = mHelper.getAdapter (). ListenUsingRfcommWithServiceRecord (ChatConstant.NAME_SECURE, ChatConstant.UUID_SECURE);} else {tmp = mHelper.getAdapter (). ListenUsingInsecureRfcommWithServiceRecord (ChatConstant.NAME_INSECURE, ChatConstant.UUID_INSECURE);}} catch (IOException e) {BleLog.e ("SocketType:" + mSocketType + "listen () failed", e);} mServerSocket = tmp } public void run () {BleLog.i ("SocketType:" + mSocketType + "BEGIN mAcceptThread" + this); setName ("AcceptThread" + mSocketType); BluetoothSocket socket = null; while (mHelper.getState ()! = com.vise.basebluetooth.common.State.STATE_CONNECTED) {try {BleLog.i ("wait new socket:" + mServerSocket); socket = mServerSocket.accept () } catch (IOException e) {BleLog.e ("SocketType:" + mSocketType + "accept () failed", e); break;} if (socket! = null) {synchronized (this) {if (mHelper.getState () = = com.vise.basebluetooth.common.State.STATE_LISTEN | | mHelper.getState () = = com.vise.basebluetooth.common.State.STATE_CONNECTING) {BleLog.i ("mark CONNECTING") MHelper.connected (socket, socket.getRemoteDevice (), mSocketType);} else if (mHelper.getState () = = com.vise.basebluetooth.common.State.STATE_NONE | | mHelper.getState () = = com.vise.basebluetooth.common.State.STATE_CONNECTED) {try {socket.close ();} catch (IOException e) {BleLog.e ("Could not close unwanted socket", e) } BleLog.i ("END mAcceptThread, socket Type:" + mSocketType);} public void cancel () {BleLog.i ("SocketType" + mSocketType + "cancel" + this); try {mServerSocket.close ();} catch (IOException e) {BleLog.e ("SocketType" + mSocketType + "close () of server failed", e);}

The following is a basic connection process:

1. A BluetoothSocket object is obtained by calling the createRfcommSocketToServiceRecord (UUID) method of BluetoothDevice. This method initializes a BluetoothSocket object that connects to the BluetoothDevice object. The UUID parameter passed to this method must match the UUID that the server device uses when opening the BluetoothServerSocket object. Simply use hard code for comparison in your application, and if there is a match, the server-side and client-side code can apply the BluetoothSocket object.

2. Initialize the connection by calling the connect () method. In this call, in order to find a matching UUID, the system executes a SDP query on the remote device. If the query succeeds and the remote device receives the connection request, it shares the use of the RFCOMM channel during the connection and the connect () method returns. This method is a blocking call. If for some reason the connection fails or the connection times out (about 12 seconds later), an exception is thrown.

The following are the connection threads that implement the above process:

Public class ConnectThread extends Thread {private BluetoothChatHelper mHelper; private final BluetoothSocket mSocket; private final BluetoothDevice mDevice; private String mSocketType; public ConnectThread (BluetoothChatHelper bluetoothChatHelper, BluetoothDevice device, boolean secure) {mHelper = bluetoothChatHelper; mDevice = device; BluetoothSocket tmp = null; mSocketType = secure? "Secure": "Insecure"; try {if (secure) {tmp = device.createRfcommSocketToServiceRecord (ChatConstant.UUID_SECURE);} else {tmp = device.createInsecureRfcommSocketToServiceRecord (ChatConstant.UUID_INSECURE);}} catch (IOException e) {BleLog.e ("SocketType:" + mSocketType + "create () failed", e);} mSocket = tmp;} public void run () {BleLog.i ("BEGIN mConnectThread SocketType:" + mSocketType); setName ("ConnectThread" + mSocketType) MHelper.getAdapter (). CancelDiscovery (); try {mSocket.connect ();} catch (IOException e) {try {mSocket.close ();} catch (IOException e2) {BleLog.e ("unable to close ()" + mSocketType + "socket during connection failure", e2);} mHelper.connectionFailed (); return;} synchronized (this) {mHelper.setConnectThread (null);} mHelper.connected (mSocket, mDevice, mSocketType) } public void cancel () {try {mSocket.close ();} catch (IOException e) {BleLog.e ("close () of connect" + mSocketType + "socket failed", e);}

The cancelDiscovery () method is called before the connection is established. This method should always be called before connecting, and it is safe not to actually check whether the Bluetooth discovery process is running (call the isDiscovering () method if you want to check).

Manage connections (that is, communication between friends)

When you successfully connect two (or more) devices, each device has a connected BluetoothSocket object. This is a good start because you can share data between devices. The process of using the BluetoothSocket object to transfer arbitrary data is simple:

1. Obtain the InputStream and OutputStream objects that handle the transfer task through the socket through the getInputStream () and getOutputStream () methods, respectively

2. Use read (byte []) and write (byte []) methods to read and write data in the stream.

The following are the communication threads that implement the above process:

Public class ConnectedThread extends Thread {private final BluetoothChatHelper mHelper; private final BluetoothSocket mSocket; private final InputStream mInStream; private final OutputStream mOutStream; public ConnectedThread (BluetoothChatHelper bluetoothChatHelper, BluetoothSocket socket, String socketType) {BleLog.i ("create ConnectedThread:" + socketType); mHelper = bluetoothChatHelper; mSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try {tmpIn = socket.getInputStream (); tmpOut = socket.getOutputStream ();} catch (IOException e) {BleLog.e ("temp sockets not created", e);} mInStream = tmpIn MOutStream = tmpOut;} public void run () {BleLog.i ("BEGIN mConnectedThread"); int bytes; byte [] buffer = new byte [1024]; / / Keep listening to the InputStream while connected while (true) {try {bytes = mInStream.read (buffer); byte [] data = new byte [bytes]; System.arraycopy (buffer, 0, data, 0, data.length); mHelper.getHandler (). ObtainMessage (ChatConstant.MESSAGE_READ, bytes,-1, data). SendToTarget () } catch (IOException e) {BleLog.e ("disconnected", e); mHelper.start (false); break;} public void write (byte [] buffer) {if (mSocket.isConnected ()) {try {mOutStream.write (buffer); mHelper.getHandler (). ObtainMessage (ChatConstant.MESSAGE_WRITE,-1,-1, buffer). SendToTarget ();} catch (IOException e) {BleLog.e ("Exception during write", e) } public void cancel () {try {mSocket.close ();} catch (IOException e) {BleLog.e ("close () of connect socket failed", e);}

Sample diagram of sending messages:

Send an emoji sample diagram:

Send a file example diagram:

At this point, I believe you have a deeper understanding of "how to achieve Bluetooth chat in Android". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report