Bluetooth for Android Mobile Phone

Posted by carefree on Wed, 15 May 2019 01:35:49 +0200

Bluetooth 1 for Android Mobile Phone (Ordinary Bluetooth)

hello, you haven't updated your blog for a long time. There are so many things that I want to write that I feel unable to write when I lift my pen. Maybe this is a rookie! Okay, no more nonsense, get to the point.
This article is about Bluetooth on Android mobile phone, which is divided into two parts. (All written in kotlin)
1: Ordinary Bluetooth (communication between mobile phones)
2: Low Power Bluetooth (Mobile Phone to Device)

Ordinary Bluetooth

First of all, we need to understand some steps or things when we use Bluetooth.
1:Two Mobile Phones Supporting Bluetooth Modules
2: One serves as a server and the other serves as a client. (The client will actively connect to the server; the server will monitor whether there is a client connection)
3: According to the pre-determined uuid, the server creates the service with this uuid, and the client connects.
4: After the channel is successfully established, the server and client monitor the data sent by the other party.

ok Gets to the Topic

First step
We need to get the Bluetooth module inside the mobile phone.

Bluetooth Adapter So what is this class? The best teacher is the source code.

The annotations in the red box have shown that this class is a Bluetooth adapter for local devices. It can be used to do some saucy operations on Bluetooth, such as boot, query binding and so on.

We need to get this class

 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

Note: This is kotlin
After getting the Bluetooth Adapter, you need to decide whether it is null or not. If null means that the mobile phone does not support Bluetooth module, you can turn it off by yourself.
We get what we need, and then we need to create a server and a client (because a mobile phone is both a server and a client). Here we use threads to create a server and a client separately.

The second step

Server AcceptThread function: Waiting for remote Bluetooth connection after opening (waiting for client connection)

We need to get a Bluetooth Server Socket to manage our connection

The annotations have shown that Bluetooth Server Socket can listen for incoming connection requests, and that it is blocked.

 mBluetoothServerSocket = mBluetoothAdapter!!.listenUsingRfcommWithServiceRecord(BLUE_SOCKET_NAME,BLUE_UUID)
            Log.d(NAME,"Start Waiting for Bluetooth Connection...")
            mBluetoothSocket = mBluetoothServerSocket!!.accept()
            Log.d(NAME,"Remote Bluetooth Connection Successful!!")

The listenUsingRfcommWithService Record method needs to be addressed
There are two ways to create Bluetooth Server Socket
1: listen UsingRfcommWithService Record
2: listen UsingInsecureRfcommWithService Record
The parentheses after the two differences give us the first one.
Listen UsingRfcommWithService Record has a number of parameters, a name and a uuid
Name: The name of the service you created
uuid: This is the uuid you specified (note: uuid must be consistent or not connected)

Once the connection is successful, you need to get the successful device information through getRemoteDevice() in Bluetooth Server Socket.

Is it very simple to listen to the client at the server here?

The third step

Create ConnectedThread to listen for data sent by clients
The code is simple enough to convert the byte array passed in to the data we need.

 var buf : ByteArray
        var size :Int
        var msg : String? = null
        while (!isStop){
            size = 0
            buf = ByteArray(1024)
            try {
                inputStream = mBluetoothSocket!!.inputStream
                Log.d(NAME,"Waiting data")
                size = inputStream!!.read(buf)
                msg = String(buf,0,size)
                Log.d(NAME,"Read the data once :"+msg)
            }catch (e :IOException){
                e.printStackTrace()
                isStop = true
            }

            if(size>0){
                //Send the read data out
                sendMessage(msg!!)
            }

You can see that we use mBluetooth Socket to retrieve the information from the stream, read out the information from the stream, and then return to our ui thread for data display.
ok server we have finished, and then the client.

The fourth step
Let's create a client ConnectThread function: Actively connect services that are open on the server side
Before we create ConnectThread, we first need to determine which Bluetooth service our client wants to connect to. At this time, we need to find the specified Bluetooth service we want to connect to, otherwise the connection is unsuccessful.
The process we need to go through to find the specified equipment is as follows:

1: Scan Bluetooth devices visible around
2: Find the specified Bluetooth connection (here's why we created Connect Thread)

So we need a scan.
Remember the mBluetooth Adapter we created in the first step? This is what scans do.

  //If you are currently searching, cancel the search first
        if (mBluetoothAdapter!!.isDiscovering) {
            mBluetoothAdapter!!.cancelDiscovery()
        }
        //Open search
        mBluetoothAdapter!!.startDiscovery()

Yeah, you didn't read it wrong. It's just these lines of code that can scan the surrounding devices.
So the question arises. Where can we know the result of the scan? (Manual Funny)
We need to register a broadcast to know the scan results.

 mReceiver = object :BroadcastReceiver(){
            @SuppressLint("MissingPermission")
            override fun onReceive(context: Context?, intent: Intent?) {
                when( intent!!.action){
                //Find equipment
                    BluetoothDevice.ACTION_FOUND -> {
                        var device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

                        Log.d(NAME,"found device :" +device.name)
                    }
                //In search
                    BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                        Log.d(NAME,"start found device ")

                    }
                //Search end
                    BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                        Log.d(NAME,"finished found device ")

                    }

                //Bluetooth disconnection
                    BluetoothDevice.ACTION_ACL_DISCONNECTED ->{
                        mBlueSockt = null

                    }
                }
            }



//Dynamic Registered Broadcasting

val filter1 = IntentFilter(BluetoothDevice.ACTION_FOUND)
        val filter2 = IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        val filter3 = IntentFilter(
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        val filter4 = IntentFilter(
                BluetoothDevice.ACTION_ACL_DISCONNECTED)
        val filter5 = IntentFilter(
                BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)

        mContext!!.registerReceiver(mReceiver, filter1)
        mContext!!.registerReceiver(mReceiver, filter2)
        mContext!!.registerReceiver(mReceiver, filter3)
        mContext!!.registerReceiver(mReceiver, filter4)
        mContext!!.registerReceiver(mReceiver, filter5)

The above code is some basic operations, nothing to say.

var device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
Through this code, we can get the Bluetooth device scanned by the mobile phone.

Now create Connect Thread

mSocket = device!!.createInsecureRfcommSocketToServiceRecord(BLUE_UUID)

mSocket is Bluetooth Socket.
BLUE_UUID is the uuid specified when our server creates a service.
Here's what I want to say.
device creates Bluetooth Socket in two ways
1: Create Insecure Rf commSocket To Service Record (2.3 or more)
2: CreateRfcommSocketToService Record (Android 2.3 and below)
Let's use the first one.

After getting the socket, we call her connect method and the connection succeeds.

When the connection is successful, the next step is to send data to each other.

It's easy to send data.
Call the getOutputStream() method in Bluetooth Socket to get the output stream

  outputStream = mBluetoothSocket!!.outputStream
            outputStream!!.write(buf)

buf is the byte array you passed in

At this point, all the successful partners have succeeded. Thank you for seeing this. Thank you for the low power section.

Demo I don't upload csdn for free. Now it's all about charging so. You know, now it's on git.
Enclosed Demo address

END

Topics: socket Mobile Android git