Bluetooth module of android uses hexadecimal data to send

Posted by jwmessiah on Mon, 01 Jul 2019 21:48:19 +0200

A Bluetooth module looks small, but it's still a bit complicated. I found a sample code from the Internet, http://blog.csdn.net/vnanyesheshou/article/details/51554852, but it can't be used directly. It needs to be read, understood and modified by myself before it can be used.

First paste a homemade uml map:


It is not difficult to see from the diagram that there are many classes in the design, which can be roughly divided into three steps: device initialization, connection establishment and message sending. The code on the Internet is encapsulated into a practical class of Bluetooth ChatUtil, which is responsible for establishing communication and sending messages, and then displaying the acquired data in the interface by means of messages. BroadcastReceiver is responsible for receiving devices acquired during Bluetooth scanning. Because the target Bluetooth in the project is already bound, it uses the getBondedDevices() function of Bluetooth Adapter class directly to get the bound Bluetooth devices, and then connects them by setting a name or address.

The steps to add a Bluetooth module to an existing project are as follows (simply from the code):

(1) Increase member variables:

// Handler for getting messages

Handler mHandler;

// Bluetooth module

// Bluetooth Name to Connect

         publicstatic final String BLUETOOTH_NAME = "XXXX";

// Connect msg

         publicstatic final String OPEN_BLUE_HEX_STRING = "00 00 00 00 ";

// Turn off msg

         publicstatic final String CLOSE_BLUE_HEX_STRING = "FF FF FF FF";

// Bluetooth address to be connected

         privateString mBluetoothAddress = "XX:XX:XX:XX:XX:XX";

    boolean hasregister = false;

    private ProgressDialog mProgressDialog;

// Bluetooth Communication Module

         privateBluetoothChatUtil mBlthChatUtil;

// Handles to the current activity

         privateContext mContext;

         privateint REQUEST_ENABLE_BT = 1;

(2) Initialization in onCreate:

mContext = this;

         mProgressDialog= new ProgressDialog(this);

Capture several messages in handleMessage(Message msg):

// Successful connection

 caseBluetoothChatUtil.STATE_CONNECTED:

                 if(mProgressDialog.isShowing()){

                        mProgressDialog.dismiss();

                 }

                 StringdeviceName = msg.getData().getString(BluetoothChatUtil.DEVICE_NAME);

// mBtnBluetoothConnect.setText("Connected to Device Successfully" + deviceName);

Toast. makeText (getApplication Context (), "Successful Connection:" +deviceName, Toast.LENGTH_SHORT).show();

// Send the message you need to send after the connection

                 sendBluetoothMessage(OPEN_BLUE_HEX_STRING);

                  break;      

// Connection failed

         caseBluetoothChatUtil.STATAE_CONNECT_FAILURE:

                 if(mProgressDialog.isShowing()){

                  mProgressDialog.dismiss();

                  }

Toast. makeText (getApplication Context (), "Connection Failure", Toast.LENGTH_SHORT).show();

          break;

// Disconnect

      caseBluetoothChatUtil.MESSAGE_DISCONNECTED:

                 if(mProgressDialog.isShowing()){

                        mProgressDialog.dismiss();

                 }

// mBtnBluetooth Connect. setText ("disconnect from device");

                break;

// Receive the message

        caseBluetoothChatUtil.MESSAGE_READ:

                byte[]buf = msg.getData().getByteArray(BluetoothChatUtil.READ_MSG);

                Stringstr = new String(buf,0,buf.length);

Toast. makeText (getApplication Context (), "Read Successfully" + str, Toast.LENGTH_SHORT).show();

                break;

Instantiate the communication module and connect Bluetooth:

// Bluetooth module

                   mBlthChatUtil= BluetoothChatUtil.getInstance(mContext);

                   mBlthChatUtil.registerHandler(mHandler);

                   initBluetooth();

// Choose scanners according to your needs

        //mBluetoothAdapter.startDiscovery();

// Connecting equipment

        connect();

        if (mBlthChatUtil.getState() == BluetoothChatUtil.STATE_NONE) {

// Start Bluetooth Chat Service

                            mBlthChatUtil.start();

                  }

Bluetooth initialization functions initBluetooth() and connect functions:

private void initBluetooth() {

                      mBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();

If (mBluetooth Adapter == null) {// Device does not support Bluetooth

Toast. makeText (getApplication Context (), "Devices do not support Bluetooth", "Toast.LENGTH_LONG).show();

                            finish();

                            return;

                   }

// Judging whether Bluetooth is on or off

If (! MBluetooth Adapter. isEnabled (){// Bluetooth is not turned on

                            IntentenableIntent = new Intent(

                                               BluetoothAdapter.ACTION_REQUEST_ENABLE);

                            startActivityForResult(enableIntent,REQUEST_ENABLE_BT);

// Turn Bluetooth on

                            mBluetoothAdapter.enable();

                   }                          

                   //

                   IntentFilterfilter = new IntentFilter();

                   filter.addAction(BluetoothDevice.ACTION_FOUND);

                   filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

                   //registerReceiver(mBluetoothReceiver,filter);

                   //hasregister= true;

                   if(mBluetoothAdapter.isEnabled()) {

                            intnMode = mBluetoothAdapter.getScanMode();

                            if(nMode== BluetoothAdapter.SCAN_MODE_CONNECTABLE){

                                     Log.e(TAG_BLUE,"getScanMode= SCAN_MODE_CONNECTABLE");

                            }

                            if(nMode== BluetoothAdapter.SCAN_MODE_NONE){

                                     Log.e(TAG_BLUE,"getScanMode= SCAN_MODE_NONE");

                            }

                            if(nMode== BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){

                                     Log.e(TAG_BLUE,"getScanMode= SCAN_MODE_CONNECTABLE_DISCOVERABLE");

                            }

                         //if(nMode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {

                         //     IntentdiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

                         //        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);

                         //       startActivity(discoverableIntent);

                         //}

                   }

// Name and address of Bluetooth itself

                   Stringname = mBluetoothAdapter.getName();

                   Stringaddress = mBluetoothAdapter.getAddress();

                   Log.d(TAG_BLUE,"bluetoothname ="+name+" address ="+address);

         }

 

         publicvoid connect() {

                   Set<BluetoothDevice>device = mBluetoothAdapter.getBondedDevices(); 

       

If (device. size () > 0) {// There are already paired Bluetooth devices

           for(Iterator<BluetoothDevice>it=device.iterator();it.hasNext();){ 

                BluetoothDevicebtd=it.next(); 

                String name = btd.getName();

                String address =btd.getAddress();

                String nameString =btd.getName()+'\n'+btd.getAddress(); 

               Log.e(TAG_BLUE,"getBondedDevices :" + nameString);

                //if(name != null &&name.equals(BLUETOOTH_NAME)){

                if(address != null &&address.equals(mBluetoothAddress)){

                         mBlthChatUtil.connect(btd);

                         break;

// Toast.makeText(mContext, "Connect Successfully", Toast.LENGTH_SHORT).show();

                }

           } 

} Other {// No paired Bluetooth devices exist

                Log.e(TAG,"No can bematched to use bluetooth"); 

       } 

}

Hexadecimal data conversion HexCommandtoByte and message sending function sendBluetoothMessage:

// Converting hexadecimal strings to byte arrays

    public static byte[]HexCommandtoByte(byte[] data) { 

            if (data == null) { 

                return null; 

            } 

            int nLength = data.length;  

              

            String strTemString = new String(data, 0, nLength); 

            String[] strings = strTemString.split(" "); 

            nLength = strings.length; 

            data = new byte[nLength];            

            for (int i = 0; i < nLength; i++) { 

                if (strings[i].length() != 2) { 

                     data[i] = 00; 

                     continue; 

                } 

                try { 

                     data[i] =(byte)Integer.parseInt(strings[i], 16); 

                } catch (Exception e) { 

                     data[i] = 00; 

                     continue; 

                } 

            } 

            return data; 

         }

         public void sendBluetoothMessage(Stringmessagesend){

                   Log.e(TAG_BLUE,"sendmessage : " + messagesend);

                   byte[] sendByte =HexCommandtoByte(messagesend.getBytes());

                   //mBlthChatUtil.write(messagesend.getBytes());

                   mBlthChatUtil.write(sendByte);

         }

 

(3) Send off Bluetooth message back to onBackPressed() or onDestroy() and cancel Bluetooth:

// Closing

       sendBluetoothMessage(CLOSE_BLUE_HEX_STRING);

        if(mBluetoothAdapter!=null &&mBluetoothAdapter.isDiscovering()){ 

                 mBluetoothAdapter.cancelDiscovery(); 

        } 

       

        if (mBlthChatUtil.getState() !=BluetoothChatUtil.STATE_CONNECTED) {

Toast.makeText(mContext, "Bluetooth is not connected", Toast.LENGTH_SHORT).show();

                   }else {

                            mBlthChatUtil.stop();

                   }

Bluetooth ChatUtil. Java is as follows:

package XXX;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 This type does all the work, builds and manages Bluetooth.
*Connect other devices. It has a thread to listen on
*Input connection, threaded connection device, and one
*When performing data transmission line connection.
 */
public class BluetoothChatUtil {
    // debugging
    private static final String TAG = "BluetoothChatService";
    private static final boolean D = true;

    // SPD Records When Creating Server Sockets
    private static final String NAME = "BluetoothChat";
    									 				
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	public static StringBuffer hexString = new StringBuffer();
    // Adapter member
    private final BluetoothAdapter mAdapter;
    private Handler mHandler;
    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;
	private static BluetoothChatUtil mBluetoothChatUtil;
	private BluetoothDevice mConnectedBluetoothDevice;
    //Constant, indicating the current connection status
    public static final int STATE_NONE = 0;       // No connection is currently available
    public static final int STATE_LISTEN = 1;     // Now listen for incoming connections
    public static final int STATE_CONNECTING = 2; // Now we're starting to get out of touch.
    public static final int STATE_CONNECTED = 3;  // Now connect to remote devices
    public static final int STATAE_CONNECT_FAILURE = 4;
    public static boolean bRun = true;
    public static final int MESSAGE_DISCONNECTED = 5;
    public static final int STATE_CHANGE = 6;
    public static final String DEVICE_NAME = "device_name";
    public static final int MESSAGE_READ = 7;
    public static final int MESSAGE_WRITE= 8;
    public static final String READ_MSG = "read_msg";
    /**
     * Constructor. Prepare a new Bluetooth chat session.
     * @param context  Background of User Interface Activities
     */
    private BluetoothChatUtil(Context context) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;       
    }

    public static BluetoothChatUtil getInstance(Context c){
    	if(null == mBluetoothChatUtil){
    		mBluetoothChatUtil = new BluetoothChatUtil(c);
    	}
    	return mBluetoothChatUtil;
    }
    public void registerHandler(Handler handler){
    	mHandler = handler;
    }
    
    public void unregisterHandler(){
    	mHandler = null;
    }
    /**
     * Set the current status of the chat connection
     * @param state  Integer defines the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;
        // For new state handlers, the interface activity can be updated
        mHandler.obtainMessage(STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Returns the current connection status. */
    public synchronized int getState() {
        return mState;
    }
    
    public BluetoothDevice getConnectedDevice(){
    	return mConnectedBluetoothDevice;
    }
    /**
     * Start chat service. Special acceptthread begins
     * Session Hearing (Server) mode. So-called activity onresume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "start");
        //Cancel any thread to attempt to establish a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        // Cancel any threads running connections
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        // Start the thread to listen to a Bluetooth server socket
        if (mAcceptThread == null) {
            mAcceptThread = new AcceptThread();
            mAcceptThread.start();
        }
        setState(STATE_LISTEN);
    }
   
    //Connection key response function
    /**
     * Start connecting threads to connect to remote devices.
     * @param Bluetooth devices connected by devices
     */
    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(TAG, "connect to: " + device);
        // Cancel any thread to attempt to establish a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }
        // Cancel any threads running connections
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        //Devices that start thread connections
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start Connected thread and start managing a Bluetooth connection
     * @param bluetoothsocket The socket is connected.
     * @param Bluetooth Device Connected by Device
     */
    @SuppressWarnings("unused")
	public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
        if (D) Log.d(TAG, "connected");
        // Cancel Threads to Complete Connections
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        //Cancel any threads running connections
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Cancel acceptance threads only because we want to connect to a device
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}

        // Start Thread Management Connection and Transfer
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();
        //Connect the name of the device to Activity
        mConnectedBluetoothDevice =  device;
        Message msg = mHandler.obtainMessage(STATE_CONNECTED);
        Bundle bundle = new Bundle();
        bundle.putString(DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        setState(STATE_CONNECTED);
       }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
        if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
        setState(STATE_NONE);
        //start();
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        //Create temporary objects
        ConnectedThread r;
        // Connected thread for synchronous replicas
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform write synchronization
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        setState(STATE_LISTEN);
        // Send failed messages back to the activity
        Message msg = mHandler.obtainMessage(STATAE_CONNECT_FAILURE);
        mHandler.sendMessage(msg);
        mConnectedBluetoothDevice = null;
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        setState(STATE_LISTEN);
        // Send a failed message back to Activity
        Message msg = mHandler.obtainMessage(MESSAGE_DISCONNECTED);
        mHandler.sendMessage(msg);
        mConnectedBluetoothDevice = null;
        stop();
    }

    /**
    *The local line listens for incoming connections at the same time. Its behavior
    *Like a server-side client. It runs until the connection is accepted
    *(Or cancel.
     */
    private class AcceptThread extends Thread {
        // Local server socket
        private final BluetoothServerSocket mServerSocket;
        public AcceptThread() {       	
            BluetoothServerSocket tmp = null;
            // Create a new listening server socket
            try {
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "listen() failed", e);
            }
            mServerSocket = tmp;
        }

        public void run() {
            if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
            setName("AcceptThread");
            BluetoothSocket socket = null;
            // Loop until the connection succeeds
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return one
                    // Successful connections or exceptions
                    socket = mServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "accept() failed", e);
                    break;
                }
                // If the connection is accepted
                if (socket != null) {
                    synchronized (BluetoothChatUtil.this) {
                        switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Normal condition. Start connection thread.
                            connected(socket, socket.getRemoteDevice());
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Not ready or connected. New socket terminated.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D) Log.i(TAG, "END mAcceptThread");
        }

        public void cancel() {
            if (D) Log.d(TAG, "cancel " + this);
            try {
                mServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of server failed", e);
            }
        }
    }


    /**
     * This line is trying to make outgoing connections.
     *With equipment. It goes straight through the connection; or
     *Success or failure.
     */
    private class ConnectThread extends Thread {
        private BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            // Get a Bluetooth socket
            try {
            	mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
                mmSocket = null;
            }
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread");
            setName("ConnectThread");
            mAdapter.cancelDiscovery();
            // Connect a Bluetooth socket
            try {
                // socket connection
                mmSocket.connect();
            } catch (IOException e) {
                connectionFailed();
                //Close the socket
                try {
                    mmSocket.close();
                } catch (IOException e2) {
                    Log.e(TAG, "unable to close() socket during connection failure", e2);
                }
                // Start the service and restart the listening mode
                BluetoothChatUtil.this.start();
                return;
            }
            // Because we did the connectthread reset
            synchronized (BluetoothChatUtil.this) {
                mConnectThread = null;
            }
            // Start connection threads
            connected(mmSocket, mmDevice);
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

    /**
     * This line is connected with remote devices.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        
        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "create ConnectedThread");
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            // Obtain input and output streams of Bluetooth socket
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "No temporary creation sockets", e);
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }  
       
        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            int bytes;
            // Continue listening to InputStream and connect at the same time
            while (true) {
                try {
                	 byte[] buffer = new byte[1024];
                    // Read input stream
                    bytes = mmInStream.read(buffer);

                    // User Interface for Sending Obtained Bytes
                    Message msg = mHandler.obtainMessage(MESSAGE_READ);
                    Bundle bundle = new Bundle();
                    bundle.putByteArray(READ_MSG, buffer);
                    msg.setData(bundle);
                    mHandler.sendMessage(msg);          
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
       }
        /**
         * Write output connections.
         * @param buffer  This is a byte stream.
         */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);
                // Share the information sent to Activity
                mHandler.obtainMessage(MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
            }
            
        }
 
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }
}


The modified code download address is: http://download.csdn.net/detail/u200814342a/9839396, remember to change the Bluetooth address or name of the connection!

Topics: socket Android Java Session