Android Bluetooth Development (1)

Introduction to Bluetooth

Bluetooth (Bluetooth) is a wireless technology standard that enables data exchange and communication between devices within a short distance. Bluetooth technology was originally developed by Sweden's Ericsson in 1994. Its name comes from the translated name "Harald Bluetooth" of Danish King Harald Brutt, who once unified Scandinavia.

Bluetooth technology is based on radio frequency technology, the operating frequency is 2.4GHz, and can support up to 8 devices to connect at the same time. Bluetooth technology is widely used, including mobile phones, computers, audio equipment, bracelets, smart homes and other fields, and can realize functions such as data transmission, audio transmission, remote control and positioning. The advantages of Bluetooth technology include low power consumption, low cost, ease of use, and high reliability, making it an integral part of modern communications.

foreword

Bluetooth is a short-range wireless communication technology. The short-distance communication technologies for mobile devices that we are relatively familiar with include NFC , infrared , and Bluetooth;

NFC: Mainly used for simple operation and instant corresponding card swiping

Infrared: Mainly used in the need for button control, such as home appliance remote control

Bluetooth: It is mainly used for complex and massive data transmission between two devices (here it is divided into low-power Bluetooth and classic Bluetooth ). Today I will share with you the classic Bluetooth

Android Bluetooth development steps

1. Check if the device supports Bluetooth

In the application, you need to first check if the device supports bluetooth. You can declare the required Bluetooth permissions in the AndroidManifest.xml file and use the BluetoothAdapter class to query whether the device supports Bluetooth

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // 该设备不支持蓝牙
} else {
    // 该设备支持蓝牙
}

2. Turn on Bluetooth

In your application, you need to guide the user to turn on their Bluetooth. You can provide a request using the ACTION_REQUEST_ENABLE event

if (!bluetoothAdapter.isEnabled()) {
    //如果该设备蓝牙未开启

    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

3. Scan for available Bluetooth devices

Once Bluetooth is enabled, you can start scanning for devices. You can perform scan operations using the BluetoothAdapter class and the BluetoothDevice class

bluetoothAdapter.startDiscovery();

You can use the BroadcastReceiver class to receive scan results:

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //该设备成功搜索到蓝牙设备
        }
    }
};

4. Select Bluetooth and successfully pair with it

Through the BluetoothAdapter object, you can perform Bluetooth pairing. You need to instantiate the BluetoothDevice class and use its connect() method to establish a connection

BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
device.createBond();

 5. Select Bluetooth and establish a connection with it

Through the BluetoothDevice object, you can use the BluetoothSocket class to establish a Bluetooth connection. You need to instantiate the BluetoothSocket class and use its connect() method to establish a connection

BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();

6. Data transmission

Once the Bluetooth connection has been established, you can use the BluetoothSocket's getInputStream() and getOutputStream() methods to send and receive data

InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();

The above is the basic process of Android Bluetooth development. It should be noted that in actual development, complex situations such as disconnection of Bluetooth connection and multi-device connection need to be dealt with.

7. Disconnect the Bluetooth connection and turn off Bluetooth

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable(); //关闭蓝牙

Note: Android provides the Bluetooth module management tool BluetoothAdapter (Bluetooth adapter)

Some common method descriptions of the BluetoothAdapter class:

1. enable() - turn on bluetooth

2. disable() - turn off bluetooth

3. startDiscovery() - start searching for devices

4. cancelDiscovery() - cancel the discovery of the device

5. getBondedDevices() - Get the list of paired devices

6. getRemoteDevice(String address) - get remote device object

7. setState(int state) - set bluetooth state

8. setScanMode(int mode) - set scan mode

9. getScanMode() - get scan mode

10. getName() - get the local bluetooth device name

11. setName(String name) - set the local bluetooth device name

12. getAddress() - get the local bluetooth device address

13. isDiscovering: Determine whether it is searching for surrounding Bluetooth devices

14. getBluetoothLeScanner() - Get the BluetoothLeScanner object

15. getProfileProxy(Context context, BluetoothProfile.ServiceListener listener, int profile) - 获取BluetoothProfile对象

16. closeProfileProxy(int profile, BluetoothProfile proxy) - close the connection of the BluetoothProfile object

Demonstration of Android Bluetooth development effect

1. Declare Bluetooth permissions

Create a new Android project, and then declare the relevant permissions in the AndroidManifest manifest file

2. Dynamically obtain location permission

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //判断是否有访问位置的权限,没有权限,直接申请位置权限
        isPermission();
    }

    //动态获取位置权限
    @SuppressLint("NewApi")
    private void isPermission(){
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
    }
}

running result:

3. Determine whether the device supports Bluetooth function

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        if (isBluetoothSupport()){
            Toast.makeText(MainActivity.this, "该设备支持蓝牙功能", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(MainActivity.this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
        }
    }


    //判断该设备是否支持蓝牙功能
    private Boolean isBluetoothSupport(){
        if(mBluetoothAdapter == null){
            return false;
        }else {
            return true;
        }
    }
}

running result:

4. Determine whether the machine is enabled with Bluetooth

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


            //判断蓝牙是否打开
            if(!isBluetoothEnabled()){
                //如果蓝牙未开启,则申请打开蓝牙
                Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetoothIntent, RESULT_CANCELED);
            }else {

            }

    }




    /**
     * 检查该设备蓝牙是否开启
     */
    private boolean isBluetoothEnabled(){
        if(mBluetoothAdapter.isEnabled()){
            return true;
        }else {
            return false;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CANCELED) {
            if (resultCode == RESULT_OK) {
                // 蓝牙已成功开启
                Toast.makeText(MainActivity.this, "用户已开启蓝牙", Toast.LENGTH_SHORT).show();
            } else {
                // 用户取消了蓝牙开启请求
                Toast.makeText(MainActivity.this, "用户已拒绝开启蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

running result:

5. Get the Bluetooth device that the device has been paired with

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;


    @SuppressLint({"MissingPermission", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //判断是否有访问位置的权限,没有权限,直接申请位置权限
        isPermission();


        getPairedDevices();
    }

    //动态获取位置权限
    @SuppressLint("NewApi")
    private void isPermission(){
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
    }

    
    @SuppressLint("MissingPermission")
    private void getPairedDevices() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress();
                Log.d("MainActivity","设备名:"+deviceName+'\n'+"地址:"+deviceHardwareAddress);
            }
        }
    }


}

running result:

6. Search for Bluetooth devices

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;


    @SuppressLint({"MissingPermission", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //判断是否有访问位置的权限,没有权限,直接申请位置权限
        isPermission();


        mBluetoothAdapter.startDiscovery();
        registerBluetoothReceiver();
    }

    //动态获取位置权限
    @SuppressLint("NewApi")
    private void isPermission(){
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
    }

  

    private void registerBluetoothReceiver(){
        //filter注册广播接收器
        IntentFilter filter = new IntentFilter();


        //蓝牙当前状态
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);


        //开始扫描蓝牙设备广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

        //找到蓝牙设备广播
        filter.addAction(BluetoothDevice.ACTION_FOUND);

        //扫描蓝牙设备结束广播
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        //蓝牙设备配对状态改变广播
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        //设备扫描模式改变广播
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);

        registerReceiver(receiver, filter);
    }


    //处理找到蓝牙设备和搜索完成的广播消息
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            //开始查找设备
            if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                Log.d("","开始查找");
            }
            //找到蓝牙设备
            else if(BluetoothDevice.ACTION_FOUND.equals(action)){
                //搜到蓝牙设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //把搜索到的设备添加到已找到列表中,显示它的信息
                Log.d("","设备名:"+device.getName()+'\n'+"地址:"+device.getAddress());

            }
            //查找设备结束
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                //搜索完毕
                Toast.makeText(MainActivity.this, "选择要配对的蓝牙设备", Toast.LENGTH_SHORT).show();
                Log.d("","查找结束");
            }

        }
    };


}

running result:

7. Pair Bluetooth devices

package com.example.bluetoothdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter mBluetoothAdapter;


    @SuppressLint({"MissingPermission", "MissingInflatedId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //判断是否有访问位置的权限,没有权限,直接申请位置权限
        isPermission();


        getPairedDevices();

    }

    //动态获取位置权限
    @SuppressLint("NewApi")
    private void isPermission(){
        if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                || (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 200);
        }
    }

   

    @SuppressLint("MissingPermission")
    private void getPairedDevices() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            int i=0;
            for (BluetoothDevice device : pairedDevices) {
                i++;
                if(i==pairedDevices.size()){
                    device.createBond();
                    Log.d("","本机与另一个蓝牙设备"+device.getName()+"成功配对");
                }
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress();
                Log.d("","设备名:"+deviceName+'\n'+"地址:"+deviceHardwareAddress);
            }
        }
    }


}

running result:

This article will be shared here first, and you can copy the code to run it; in the next article, I will share with you the actual usage of the Bluetooth project

Notes on Android Bluetooth development:

  1. Make sure your device supports Bluetooth: Before developing, make sure your device supports Bluetooth. Most modern smartphones and tablets support Bluetooth.

  2. Obtain the necessary permissions: Before developing Bluetooth applications, you need to obtain the appropriate permissions. For example, you need to request the "android.permission.BLUETOOTH" permission so that your application can use Bluetooth.

  3. Determine the type of Bluetooth profile you need: Android provides two different types of Bluetooth profiles: Classic Bluetooth and Bluetooth Low Energy. Using Bluetooth Low Energy can extend device battery life, but requires Android 4.3 (API level 18) or higher.

  4. Make sure your app is compatible with other apps: Before using Bluetooth in your app, make sure it's compatible with other apps. If your application and other applications use Bluetooth at the same time, it may cause conflicts and erratic behavior.

  5. Use the correct Bluetooth protocol: When developing a Bluetooth application, you need to make sure that you are using the correct Bluetooth protocol. Different devices and applications may use different Bluetooth protocols, so you need to determine which protocols your application needs to use.

  6. Handling errors and exceptions: When using Bluetooth, errors and exceptions may occur. Make sure your application has proper error handling and exception handling code to ensure that it properly handles the Bluetooth connection if something goes wrong.

  7. Debug your application: When developing your Bluetooth application, make sure to use appropriate debugging tools. Android Studio provides some built-in debugging tools for diagnosing and fixing Bluetooth connection problems.

  8. Avoid known bugs with Bluetooth: There are many known bugs that can occur when using Bluetooth. To avoid these errors, write appropriate code to ensure that your application handles these errors correctly.

It should be noted that Bluetooth development requires special attention to power and performance issues. For frequent Bluetooth searches, connections, and data transmission operations, it should be minimized or optimized to avoid excessive impact on device power and performance.

Guess you like

Origin blog.csdn.net/Ai1114/article/details/132270959