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

What is the method of simple development of android Bluetooth?

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

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what is the method of simple development of android Bluetooth". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Overview

Some time ago, I learned some knowledge of Bluetooth development, and recorded the simple development of Bluetooth in Android. Here are the two most important classes.

BluetoothAdapter: Bluetooth adapter, use getDefaultAdapter () to get an instance. If the device does not support Bluetooth, it returns a null object that enables you to turn on and off Bluetooth, scan the device, and create a socket channel to the specified device.

BluetoothDevice: represents a device object through which you can get the device's name, address, type, etc., create matches, establish socket channels, and so on.

1. Apply for permission to use Bluetooth. Use the permission to scan and set Bluetooth (to declare this permission, you must declare the above permission).

Android6 or above, location permission is also required to scan other Bluetooth.

/ / versions below Android 9 / / Android 9 and above 2, open Bluetooth mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter (); / / if the device does not support Bluetooth if (mBluetoothAdapter = = null) {return;} / / the device supports Bluetooth, call startActivityForResult to launch Bluetooth if (! mBluetoothAdapter.isEnabled ()) {startBlueTooth.launch (new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE));}

The Bluetooth function is enabled through startActivity, but the startActivity function has expired, so I use the officially recommended Activity Result instead.

ActivityResultLauncher startBlueTooth = registerForActivityResult (new ActivityResultContracts.StartActivityForResult (), new ActivityResultCallback () {@ Override public void onActivityResult (ActivityResult result) {if (result==null) {Toast.makeText (BlueToothActivity.this, "open failed", Toast.LENGTH_SHORT). Show () } else {if (result.getResultCode () = = RESULT_CANCELED) {Toast.makeText (BlueToothActivity.this, "user cancel", Toast.LENGTH_SHORT);}); 3. Receive changes in Bluetooth status

Receive a change in Bluetooth status through a broadcast

Class BluetoothStateChangeReceiver extends BroadcastReceiver {public int DEFAULT_VALUE_BLUETOOTH = 1000; @ Override public void onReceive (Context context, Intent intent) {String action = intent.getAction (); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals (action)) {int state = intent.getIntExtra (BluetoothAdapter.EXTRA_STATE,DEFAULT_VALUE_BLUETOOTH) Switch (state) {case BluetoothAdapter.STATE_ON: Log.d (TAG, "onReceive: open"); break; case BluetoothAdapter.STATE_OFF: Log.d (TAG, "onReceive: off"); break Case BluetoothAdapter.STATE_TURNING_ON: Log.d (TAG, "onReceive: opening"); break; case BluetoothAdapter.STATE_TURNING_OFF: Log.d (TAG, "onReceive: shutting down"); break;}

Don't forget the registration and registration of the broadcast

IntentFilter filter = new IntentFilter (BluetoothAdapter.ACTION_STATE_CHANGED); stateReceiver = new BluetoothStateChangeReceiver (); registerReceiver (stateReceiver,filter); 4. Scan other devices

Also received through the broadcast, action is BluetoothDevice.ACTION_FOUND

Class MyReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {String action = intent.getAction (); if (BluetoothDevice.ACTION_FOUND.equals (action)) {/ / get Bluetooth device information from the intent object BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE) / / add if (device.getBondState ()! = BluetoothDevice.BOND_BONDED) {blueNames.add (device.getName () + "\ t" + device.getAddress ());} blueAdpater.notifyDataSetChanged () when it is found that the new device does not exist in the matching list Log.d (TAG, "onReceive:" + device.getName ());}}

Dynamically register broadcast

IntentFilter filter = new IntentFilter (BluetoothDevice.ACTION_FOUND); registerReceiver (mReceiver,filter)

Turn on scanning

MBluetoothAdapter.startDiscovery (); 5. Bluetooth pairing public class BondReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals (intent.getAction () {BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE) Switch (device.getBondState ()) {case BluetoothDevice.BOND_BONDED: Log.d (TAG, "onReceive: matching completed"); break; case BluetoothDevice.BOND_BONDING: Log.d (TAG, "onReceive: matching") Break; case BluetoothDevice.BOND_NONE: Log.d (TAG, "onReceive: unpairing"); break;}} 6. Get the devices that have been paired.

Paired devices will be stored and accessed directly through BluetoothAdpater

Set paireDevices = mBluetoothAdapter.getBondedDevices (); if (paireDevices.size () > 0) {for (BluetoothDevice pairedDevice: pairedDevices) {blueNames.add (pairedDevice.getName () + "+ pairedDevice.getAddress ()); Log.d (TAG," onClick: "+ pairedDevice.getName ());}} 7, connect the device

If you want to create a connection between two devices, you must implement the client and server mechanisms. They use the socket mechanism to connect, the server opens the server socket, and the client initiates the connection to the server through the MAC address. The client and the server obtain the BluetoothSocket in different ways. When the client and the server have connected BluetoothSocket on the same RFCOMM channel, they are regarded as connected to each other, so each device gets input and output streaming and starts to transmit data.

Connection technology

One implementation technique is to automatically prepare each device as a server, so that each device opens a service socket and listens for a connection, in which case any device can initiate a connection to another device and call it a client.

Server

To set up the server socket and accept the connection, follow these steps

1, call listenUsingRfcommWithServiceRecord () to get a BluetoothServerSocket, the function requires two parameters, the first is the name of the server, you can take one, and the second is UUID, which is used to identify the uniqueness of the information. We can generate one randomly from many UUID generators on the network, and then use UUID.fromString (String) to initialize a UUID.

2. Start listening for connection requests through the accept () function

The server will accept the request only if the UUID in the connection request sent by the remote device matches the UUID registered using this socket, and the accept function returns the connected BluetoothSocket

3. After a successful connection, call close () to close BluetoothSocket.

Private class AcceptThread extends Thread {private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread (boolean secure) {BluetoothServerSocket tmp = null; mSocketType = secure? "secure": "Insercure"; try {if (secure) {tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord (NAME_SECURE,MY_UUID_SECURE);} else {tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord (NAME_INSECURE,MY_UUID_INSECURE) } catch (IOException e) {Log.e (TAG, "socket type" + mSocketType + "listen () failed", e);} mmServerSocket = tmp;} @ Override public void run () {Log.d (TAG, "SocketType:" + mSocketType + "BEGIN mAcceptThread" + this) SetName ("AcceptThread" + mSocketType); BluetoothSocket socket = null; Log.d (TAG, "run: start listening"); while (true) {try {socket = mmServerSocket.accept (); Log.d ("acceptThread", "run: connection successful") Connected (socket,socket.getRemoteDevice (), mSocketType);} catch (IOException e) {Log.e (TAG, "SocketType:" + mSocketType + "accept () failed", e); break;}} Log.i (TAG, "END mAcceptThread, socket Type:" + mSocketType) } public void cancel () {Log.d (TAG, "SocketType" + mSocketType + "cancel" + this); try {mmServerSocket.close ();} catch (IOException e) {Log.e (TAG, "SocketType" + mSocketType + "close () of server failed", e);}

The secure and Insecure above just use different UUID.

Client

After the remote device turns on snooping, we initiate a connection to this device. We must first obtain the BluetoothDevice object of the remote device, and then obtain the BluetoothSocket initiated connection.

The basic steps are as follows

1. Use BluetoothDevice to get BluetoothSocket by calling createRfcommSocketToServiceRecord (UUID).

2. Initiate a connection through connect

Private class ConnectThread extends Thread {private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; public ConnectThread (BluetoothDevice device, boolean secure) {mmDevice = device; BluetoothSocket tmp = null; mSocketType = secure? "Secure": "Insecure"; try {if (secure) {tmp = device.createRfcommSocketToServiceRecord (MY_UUID_SECURE);} else {tmp = device.createRfcommSocketToServiceRecord (MY_UUID_INSECURE) } catch (IOException e) {Log.e (TAG, "SocketType:" + mSocketType + "create () failed", e);} mmSocket = tmp;} @ Override public void run () {Log.i (TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName ("ConnectThred" + mSocketType) / / always cancel discovery because it slows down the connection bluetoothAdapter.cancelDiscovery (); / / connect / / Make a connection to the BluetoothSocket try {/ / This is a blocking call and will only return on a / / successful connection or an exception mmSocket.connect () Log.d (TAG, "run: socket connection succeeded");} catch (IOException e) {/ / Close the socket Log.d (TAG, "run: turn off socket"); try {mmSocket.close () } catch (IOException e2) {Log.e (TAG, "unable to close ()" + mSocketType + "socket during connection failure", e2);} return;} connected (mmSocket,mmDevice,mSocketType) } public void cancel () {try {mmSocket.close ();} catch (IOException e) {Log.e (TAG, "close () of connect" + mSocketType + "socket failed", e);}

Send data

After the connection is successful, we can send data through socket. The Socket object on the client side is BluetoothSocket and the socket on the server side is BluetoothServerSocket. Be careful not to confuse it. Use getInputStream and getOutputStream to get InputStream and OutputStream for data transmission through socket processing, respectively. Writing data is easy, but reading data requires a separate thread to listen all the time.

Private class ConnectedThread extends Thread {private final BluetoothSocket mmSocket; private InputStream mmInStream; private OutputStream mmOutStream; public ConnectedThread (BluetoothSocket socket, String socketType) throws IOException {Log.d (TAG, "create ConnectedThread:" + socketType); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try {tmpIn = socket.getInputStream () TmpOut = socket.getOutputStream (); if (socket! = null) {tmpOut.write (new String ("hello") .getBytes ()); Log.d (TAG, "ConnectedThread: socket is not null") } catch (IOException e) {Log.e (TAG, "temp socket not created", e);} mmInStream = tmpIn; mmOutStream = tmpOut; / / mmOutStream.write (new String ("hello") .getBytes ()) } @ RequiresApi (api = Build.VERSION_CODES.KITKAT) @ Override public void run () {Log.i (TAG, "BEGIN mConnectedThread"); byte [] buffer = new byte [1024]; int bytes; while (true) {try {bytes = mmInStream.read (buffer) / / send the bytes to the ui Activity String text = encodeByteToString (buffer,bytes); Log.d (TAG, "run: received message:" + text); chatItems.add (text); mHandler.sendMessage (mHandler.obtainMessage ()) } catch (IOException e) {Log.d (TAG, "run: no message received"); e.printStackTrace (); break;} public String encodeByteToString (byte [] data,int length) {byte [] temp = new byte [length] For (int I = 0; I < length; iTunes +) {temp [I] = data [I];} try {return new String (temp, "utf-8");} catch (UnsupportedEncodingException e) {return "" }} public void write (byte [] buffer) {try {mmOutStream.write (buffer); / / mHandler.obtainMessage (Constants.MESSAGE_WRITE,-1,-1,buffer). SendToTarget ();} catch (IOException e) {e.printStackTrace () }} public void cancel () {try {mmSocket.close (); Log.d (TAG, "cancel: connectedThread");} catch (IOException e) {Log.e (TAG, "close () of connect socket failed", e) This is the end of the content of "what is the method of simple development of android Bluetooth". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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