4. 扫描蓝牙设备

任务说明

本案例要求实现经典蓝牙(BR/EDR)设备的扫描功能,并在界面上展示扫描到的设备列表。核心任务包括:申请蓝牙权限、检查蓝牙状态、启动扫描、接收扫描结果并更新UI。需要说明的是,本案例聚焦于经典蓝牙扫描,不涉及BLE(低功耗蓝牙)的扫描回调。

实现方案

采用Android标准蓝牙API完成扫描。使用BroadcastReceiver监听ACTION_FOUND和ACTION_DISCOVERY_FINISHED广播,前者获取扫描到的设备,后者判断扫描结束。UI层使用ListView展示设备名称和MAC地址。为保证Android 12+兼容性,需在Manifest中声明BLUETOOTH_SCAN权限并运行时请求。

代码实现


// AndroidManifest.xml 关键权限声明
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30"/>

// MainActivity.java 核心代码
public class MainActivity extends AppCompatActivity {
    private BluetoothAdapter bluetoothAdapter;
    private ArrayAdapter<String> deviceListAdapter;
    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 deviceInfo = device.getName() + "\n" + device.getAddress();
                if (!deviceListAdapter.getPosition(deviceInfo) >= 0) {
                    deviceListAdapter.add(deviceInfo);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                findViewById(R.id.btn_scan).setEnabled(true);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        deviceListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        ListView listView = findViewById(R.id.list_devices);
        listView.setAdapter(deviceListAdapter);
        findViewById(R.id.btn_scan).setOnClickListener(v -> startScan());
        checkPermissions();
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= 31) {
            requestPermissions(new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT}, 1);
        } else {
            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }

    private void startScan() {
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!bluetoothAdapter.isEnabled()) {
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 2);
            return;
        }
        deviceListAdapter.clear();
        findViewById(R.id.btn_scan).setEnabled(false);
        bluetoothAdapter.startDiscovery();
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }
}

布局文件


<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btn_scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="开始扫描"/>
    <ListView
        android:id="@+id/list_devices"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

验证方法

在真机上运行应用(模拟器不支持蓝牙),点击“开始扫描”按钮。观察ListView是否出现附近经典蓝牙设备(如蓝牙音箱、耳机)的名称和MAC地址。扫描结束后按钮恢复可点击状态。若设备未开启蓝牙,系统会弹出开启请求。判定标准:能列出至少一个真实存在的蓝牙设备,且设备信息与系统蓝牙设置中显示的一致。

蓝牙扫描时序与数据流 MainActivity BluetoothAdapter 系统蓝牙服务 1. 请求权限 2. isEnabled() 3. 返回true/false 4. startDiscovery() 5. 执行扫描 6. 广播ACTION_FOUND 7. 更新ListView 调用/返回 异步广播

关键说明

扫描结果通过广播异步返回,每次发现设备都会触发一次ACTION_FOUND。代码中通过deviceListAdapter.getPosition()检查重复设备,避免同一设备多次添加。Android 12及以上系统要求扫描时声明BLUETOOTH_SCAN权限,且无需位置权限;Android 11及以下需要ACCESS_FINE_LOCATION权限。扫描过程中建议在onPause中取消扫描以节省资源。