Android 11 搜索附近蓝牙设备的 Demo 实现

1. 整体流程

在实现 Android 11 中搜索附近蓝牙的功能时,我们可以按照以下步骤进行操作:

步骤 操作描述
1 配置权限
2 初始化 BluetoothAdapter
3 请求位置权限
4 扫描附近的蓝牙设备
5 显示搜索到的蓝牙设备
6 停止扫描

2. 实现每一步

接下来我们逐步了解每个步骤需要实现的代码。

步骤 1:配置权限

AndroidManifest.xml 文件中添加必要的权限。

<manifest xmlns:android="
    package="com.example.bluetoothscanner">

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/> <!-- Android 10+ -->
</manifest>

步骤 2:初始化 BluetoothAdapter

在主活动中,我们需要初始化 BluetoothAdapter

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;

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

        // 获取 BluetoothAdapter
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            finish();
        }
    }
}

步骤 3:请求位置权限

为了能够扫描 Bluetooth 设备,我们需要请求位置权限。

import android.Manifest;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;

public void checkPermissions() {
    // 检查位置权限
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // 请求权限
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    } else {
        startScanning();
    }
}

步骤 4:扫描附近的蓝牙设备

使用 startDiscovery() 来开始扫描,使用 BroadcastReceiver 来接收结果。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.widget.Toast;

public void startScanning() {
    // 注册广播接收器
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(receiver, filter);

    // 开始扫描
    bluetoothAdapter.startDiscovery();
}

// 创建广播接收器
private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 获取搜索到的设备
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            // 显示设备信息
            Toast.makeText(context, "Found device: " + deviceName + " [" + deviceAddress + "]", Toast.LENGTH_SHORT).show();
        }
    }
};

步骤 5:显示搜索到的蓝牙设备

BroadcastReceiver 中显示设备名称和地址,如上面的代码所示。

步骤 6:停止扫描

当不再需要扫描时,停止扫描。

@Override
protected void onDestroy() {
    super.onDestroy();
    // 停止扫描并注销接收器
    if (bluetoothAdapter != null) {
        bluetoothAdapter.cancelDiscovery();
    }
    unregisterReceiver(receiver);
}

3. 类图

以下是类图,描述了 MainActivity 和其使用的组件之间的关系。

classDiagram
    class MainActivity {
        +BluetoothAdapter bluetoothAdapter
        +void onCreate(Bundle savedInstanceState)
        +void checkPermissions()
        +void startScanning()
    }
    class BluetoothAdapter
    class BluetoothDevice

    MainActivity --> BluetoothAdapter
    BluetoothAdapter --> BluetoothDevice

4. 结束语

以上内容是 Android 11 系统中搜索附近蓝牙设备的完整流程与实现代码示例。通过这些简单的步骤,你可以实现基本的蓝牙设备扫描功能。请确保在设备上开启蓝牙,确保使用合适的权限,并测试你的应用。

你可以在此基础上扩展功能,比如显示可用的蓝牙设备列表及其连接功能。希望这些内容能帮助你更好地理解并实现蓝牙功能!如果有任何疑问,随时可以咨询。