Introduction to android bluetooth

Bluetooth is currently the most widely used wireless communication protocol, a standard for short-range wireless communication. Legend has it that there was a king in Sweden who liked to eat blueberries so much that his teeth were blue every day. During his reign, the king was very sociable, he could talk, and he had a very good relationship with neighboring countries. This invention of Bluetooth People think that the function of Bluetooth is to communicate with the surrounding devices at close range, which is very similar to this king, so it is called Bluetooth.

The default Bluetooth protocol stack provided by Android is BlueDroid, which is divided into two layers: Bluetooth embedded system (BTE) and Bluetooth application layer (BTA). The BTE layer mainly implements the core functions of Bluetooth, and the BTA layer is mainly responsible for communicating with the Anroid framework.
Android 4.2 Before, Google has been using the official Linux Bluetooth protocol stack, which is a well-known old open source
Project BlueZ. BlueZ is actually an open source project released by Qualcomm based on the GPL agreement in May 2001. The project was incorporated into the Linux kernel by Linux Torvalds, the father of Linux only one month after the release, and became the official Linux 2.4.6 kernel. Bluetooth protocol stack. With the popularity of Android devices, BlueZ has also been greatly improved and expanded. For example, the version of BlueZ in Android 4.1 is upgraded to 4.93, which supports Bluetooth Core Specification 4.0 and implements most of the Profiles. But starting from Android 4.2, namely Jelly Bean, Google has introduced BlueDroid, which it developed together with Broadcom, in the Android source code to replace BlueZ. Although due to time and maturity reasons, most mobile phone manufacturers continue to use BlueZ in Android 4.2. But BlueZ's creator, Qualcomm, will also remove BlueZ from Android reference designs based on its chips and support only BlueDroid. I don't care what the future of BlueZ is. However, BlueDroid has its own reasons for making Qualcomm change its course. Compared with BlueZ, the most commendable thing about BlueDroid is that its frame structure has become more concise and clear. In addition, with the help of HAL (Hardware Abstraction Layer, hardware abstraction layer), BlueDroid finally no longer has anything to do with dbus. (Reference)





The process of connecting a Bluetooth device is as follows:
1. Turn on Bluetooth (enable permission)
2. Find surrounding devices
3. Get the name and address of the device
4. Create a BluetoothSocket
         BluetoothSocket tmp = null;
            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
              tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
           } catch (IOException e) {
                Log.e(TAG, "create() failed", e);
          }
5 , call connect() link



Main API
1: The object of this class BuletoothAdapter
represents the local bluetooth adapter, which is equivalent to the bluetooth adapter in the mobile phone in the bluetooth work flow chart, that is to say, for example, this application is running on the mobile phone, then The bluetooth adapter on the phone is the local bluetooth adapter.

2: The object of this class BuletoothDevice
represents the remote Bluetooth device, which is equivalent to the Bluetooth adapter in the computer in the Bluetooth workflow diagram, that is to say, for example, this application is running on the mobile phone, then the BuletoothDevice represents the remote you want to connect. the bluetooth adapter on that device.


/**
     *
     * bluetooth connection thread
     *

     *
     * @author lsw
     *
     */
    private class ConnectThread extends Thread {
        String macAddress = "";

        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            mBluetoothAdapter.cancelDiscovery();
            //initSocket();
            try {
                socket = mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);
               
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                Log.e(TAG, "Socket", e);
            }            
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {               
                connectDevice();
            }
            // 重置ConnectThread
            //synchronized (BluetoothService.this) {
               //ConnectThread = null;
            //}
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }
    } Next is the connection device method     called


connectDevice():

  
protected

void connectDevice() { 
        try { 
            // Pairing before connection is established 
            if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) { 
                Method creMethod = BluetoothDevice.class 
                        .getMethod("createBond"); 
                Log.e("TAG" , "Start pairing"); 
                creMethod.invoke(mBluetoothDevice); 
            } else { 
            } 
        } catch (Exception e) { 
            // TODO: handle exception 
            //DisplayMessage("无法配对!"); 
            e.printStackTrace(); 
        } 
        mBluetoothAdapter.cancelDiscovery(); 
        try { 
            socket.connect(); 
            //DisplayMessage("连接成功!");
            //connetTime++;
            connected = true;
        } catch (IOException e) { 
            // TODO: handle exception 
            //DisplayMessage("连接失败!");
            connetTime++;
            connected = false;
            try { 
                socket.close();
                socket = null;
            } catch (IOException e2) { 
                // TODO: handle exception 
                Log.e(TAG, "Cannot close connection when connection failed"); 
            } 
        } finally {
            connecting = false;
        } 
    }




Use reflection to obtain the BluetoothSocket through the port, and then execute the connect() method.

  
Copy code

    /**
     *
     * Bluetooth connection thread
     *

     *
     * @author lsw
     *
     */
    private class ConnectThread extends Thread {
        String macAddress = "";

        public ConnectThread(String mac) {
            macAddress = mac;
        }

        public void run() {
            connecting = true;
            connected = false;
            if(mBluetoothAdapter == null){
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            }
            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
            mBluetoothAdapter.cancelDiscovery();
            initSocket();                        
            //adapter.cancelDiscovery();
            while (!connected && connetTime <= 10) {
                try {
                    socket.connect();
                    connected = true;
                } catch (IOException e1) {
                    connetTime++;
                    connected = false;
                    // 关闭 socket
                    try {
                        socket.close();
                        socket = null;
                    } catch (IOException e2) {
                        //TODO: handle exception 
                        Log.e(TAG, "Socket", e2);
                    }
                } finally {
                    connecting = false;
                }
                //connectDevice();
            }
            // Reset ConnectThread
            //synchronized (BluetoothService.this) {
               //ConnectThread = null;
            //}
        }

        public void cancel() {
            try {
                socket.close();
                socket = null;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                connecting = false;
            }
        }
    }


Next is the method to initialize and get the BluetoothSocket

  
Copy code

    /**
     * Get the BluetoothSocket
     */
    private void initSocket() {
        BluetoothSocket temp = null;
        try {           
            Method m = mBluetoothDevice.getClass().getMethod(
                    "createRfcommSocket", new Class[] { int.class });
            temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//这里端口为1           
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        socket = temp;
    }



Key points: 1. Bluetooth pairing and connection are two different things and should not be confused.

   2. The Bluetooth serial connection can be operated by two methods: port (1-30) and UUID.

   3. It is best to perform a pairing operation for Bluetooth connection through UUID.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326458208&siteId=291194637
Recommended