android-蓝牙-状态和协议值总结及监听例子

Android 蓝牙完整指南:状态值、协议值总结与广播接收

一、蓝牙状态值完整总结

1.1 适配器状态值 (BluetoothAdapter)

// 开关状态

STATE_OFF = 10 // 关闭

STATE_TURNING_ON = 11 // 正在开启

STATE_ON = 12 // 已开启

STATE_TURNING_OFF = 13 // 正在关闭

ERROR = -1 // 错误

// 扫描模式

SCAN_MODE_NONE = 20 // 不可发现/连接

SCAN_MODE_CONNECTABLE = 21 // 可连接

SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23 // 可发现/连接

1.2 连接状态值 (BluetoothProfile)

STATE_DISCONNECTED = 0 // 已断开

STATE_CONNECTING = 1 // 连接中

STATE_CONNECTED = 2 // 已连接

STATE_DISCONNECTING = 3 // 断开中

1.3 绑定状态值 (BluetoothDevice)

BOND_NONE = 10 // 未绑定

BOND_BONDING = 11 // 绑定中

BOND_BONDED = 12 // 已绑定

1.4 Profile 值

音频相关 Profiles

// 音频播放和通话

int HEADSET = 1; // 耳机通话

int HEADSET_CLIENT = 16; //耳机通话 客户端可主动挂断/接听/拨号

int A2DP = 2; // 音频发送

int A2DP_SINK = 11; // 音频接收

int AVRCP_CONTROLLER = 12; // 媒体控制

int AVRCP_TARGET = 13; // 被控制端

int HEARING_AID = 21; // 助听器

int LE_AUDIO = 22; // 低功耗音频

数据传输 Profiles

// 数据同步和传输

int PAN = 5; // 网络共享

int PBAP = 6; // 电话簿

int PBAP_CLIENT = 17; // 电话簿客户端

int MAP = 9; // 消息

int MAP_CLIENT = 18; // 消息客户端

int OPP = 20; // 文件传输

int SAP = 10; // SIM卡访问

输入设备 Profiles

// 人机交互

int HID_HOST = 4; // 连接HID设备

int HID_DEVICE = 19; // 作为HID设备

BLE 相关 Profiles

// 低功耗蓝牙

int GATT = 7; // BLE客户端

int GATT_SERVER = 8; // BLE服务器

int HEALTH = 3; // 健康设备

int LE_AUDIO = 22; // LE音频

特殊用途 Profiles

连接状态值总结

// 所有 Profile 共用的连接状态

int STATE_DISCONNECTED = 0; // 已断开

int STATE_CONNECTING = 1; // 连接中

int STATE_CONNECTED = 2; // 已连接

int STATE_DISCONNECTING = 3; // 断开中

二、蓝牙协议值总结

2.1 基础协议值

// 传输层协议

PROTOCOL_L2CAP = 1 // 逻辑链路控制协议

PROTOCOL_RFCOMM = 3 // 串口仿真协议

PROTOCOL_BNEP = 15 // 蓝牙网络封装协议

PROTOCOL_AVCTP = 23 // 音频/视频控制传输

PROTOCOL_AVDTP = 25 // 音频/视频分发传输

PROTOCOL_HIDP = 17 // HID协议

PROTOCOL_ATT = 7 // 属性协议 (BLE)

PROTOCOL_SDP = 1 // 服务发现协议

2.2 协议端口/PSM值

值 协议 用途

1 SDP 服务发现

3 RFCOMM 串口通信

23 BNEP 网络传输

17 HIDP HID控制

19 AVCTP AV控制

25 AVDTP AV分发

2.3 UUID 短格式

// 常用服务UUID

UUID_HEADSET = 0x1108 // 耳机服务

UUID_HANDSFREE = 0x111E // 免提服务

UUID_A2DP_SOURCE = 0x110A // A2DP源

UUID_A2DP_SINK = 0x110B // A2DP接收

UUID_AVRCP = 0x110C // 音视频遥控

UUID_HID = 0x1124 // HID服务

UUID_PAN = 0x1115 // 个人局域网

UUID_SPP = 0x1101 // 串行端口

三、蓝牙广播接收完整示例

3.1 广播接收器实现

package com.example.bluetooth;

import android.Manifest;

import android.bluetooth.;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import java.util.
;

public class BluetoothStateReceiver extends BroadcastReceiver {

private static final String TAG = "BluetoothReceiver";

复制代码
// 监听器接口
public interface BluetoothStateListener {
    void onAdapterStateChanged(int state);
    void onDeviceFound(BluetoothDevice device, int rssi);
    void onDeviceConnected(BluetoothDevice device, int profile, int state);
    void onDeviceDisconnected(BluetoothDevice device, int profile, int state);
    void onBondStateChanged(BluetoothDevice device, int prevState, int newState);
    void onDiscoveryStarted();
    void onDiscoveryFinished();
    void onAclConnected(BluetoothDevice device);
    void onAclDisconnected(BluetoothDevice device);
    void onScanModeChanged(int mode);
    void onLocalNameChanged(String name);
    void onUuidChanged(BluetoothDevice device, ParcelUuid[] uuids);
}

private BluetoothStateListener listener;
private Context context;

public BluetoothStateReceiver(Context context, BluetoothStateListener listener) {
    this.context = context.getApplicationContext();
    this.listener = listener;
}

/**
 * 注册所有蓝牙广播
 */
public void registerAllReceivers() {
    IntentFilter filter = new IntentFilter();
    
    // 适配器相关
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
    
    // 发现相关
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_CLASS_CHANGED);
    filter.addAction(BluetoothDevice.ACTION_UUID);
    filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
    
    // 连接相关
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    
    // 绑定相关
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    
    // Profile 状态变化
    filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
    filter.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
    filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
    filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
    filter.addAction(BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED);
    filter.addAction(BluetoothPan.ACTION_CONNECTION_STATE_CHANGED);
    
    // 低功耗蓝牙相关
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        filter.addAction(BluetoothLeScanner.ACTION_SCAN_RESULT_AVAILABLE);
    }
    
    context.registerReceiver(this, filter);
    Log.d(TAG, "已注册所有蓝牙广播接收器");
}

/**
 * 注销广播接收器
 */
public void unregisterReceiver() {
    try {
        context.unregisterReceiver(this);
        Log.d(TAG, "已注销蓝牙广播接收器");
    } catch (IllegalArgumentException e) {
        Log.w(TAG, "接收器未注册或已注销");
    }
}

@Override
public void onReceive(Context context, Intent intent) {
    if (intent == null || intent.getAction() == null) {
        return;
    }
    
    String action = intent.getAction();
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    
    Log.d(TAG, "收到广播: " + action + ", 设备: " + 
        (device != null ? device.getName() : "null"));
    
    // 处理各种广播
    switch (action) {
        // 适配器状态变化
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            handleAdapterStateChanged(intent);
            break;
            
        // 扫描模式变化
        case BluetoothAdapter.ACTION_SCAN_MODE_CHANGED:
            handleScanModeChanged(intent);
            break;
            
        // 本地名称变化
        case BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED:
            handleLocalNameChanged(intent);
            break;
            
        // 发现相关
        case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
            handleDiscoveryStarted();
            break;
            
        case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
            handleDiscoveryFinished();
            break;
            
        case BluetoothDevice.ACTION_FOUND:
            handleDeviceFound(intent);
            break;
            
        // ACL 连接状态
        case BluetoothDevice.ACTION_ACL_CONNECTED:
            handleAclConnected(device);
            break;
            
        case BluetoothDevice.ACTION_ACL_DISCONNECTED:
            handleAclDisconnected(device);
            break;
            
        // 绑定状态变化
        case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
            handleBondStateChanged(intent, device);
            break;
            
        // Profile 连接状态变化
        case BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED:
        case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
        case BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED:
        case BluetoothPan.ACTION_CONNECTION_STATE_CHANGED:
            handleProfileStateChanged(action, intent, device);
            break;
            
        // 音频状态变化
        case BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED:
        case BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:
            handleAudioStateChanged(action, intent, device);
            break;
            
        // UUID 变化
        case BluetoothDevice.ACTION_UUID:
            handleUuidChanged(intent, device);
            break;
            
        // 设备类变化
        case BluetoothDevice.ACTION_CLASS_CHANGED:
            handleClassChanged(intent, device);
            break;
    }
}

// ========== 具体处理方法 ==========

private void handleAdapterStateChanged(Intent intent) {
    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 
        BluetoothAdapter.ERROR);
    int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, 
        BluetoothAdapter.ERROR);
    
    Log.i(TAG, String.format("蓝牙适配器状态变化: %s -> %s", 
        getStateName(previousState), getStateName(state)));
    
    if (listener != null) {
        listener.onAdapterStateChanged(state);
    }
}

private void handleScanModeChanged(Intent intent) {
    int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, 
        BluetoothAdapter.SCAN_MODE_NONE);
    
    Log.i(TAG, "扫描模式变化: " + getScanModeName(mode));
    
    if (listener != null) {
        listener.onScanModeChanged(mode);
    }
}

private void handleLocalNameChanged(Intent intent) {
    String name = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
    Log.i(TAG, "本地名称变化: " + name);
    
    if (listener != null) {
        listener.onLocalNameChanged(name);
    }
}

private void handleDiscoveryStarted() {
    Log.i(TAG, "开始发现设备");
    
    if (listener != null) {
        listener.onDiscoveryStarted();
    }
}

private void handleDiscoveryFinished() {
    Log.i(TAG, "设备发现完成");
    
    if (listener != null) {
        listener.onDiscoveryFinished();
    }
}

private void handleDeviceFound(Intent intent) {
    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
    
    String name = device != null ? device.getName() : "未知设备";
    String address = device != null ? device.getAddress() : "未知地址";
    
    Log.i(TAG, String.format("发现设备: %s (%s), RSSI: %d", 
        name, address, rssi));
    
    if (device != null && listener != null) {
        listener.onDeviceFound(device, rssi);
    }
}

private void handleAclConnected(BluetoothDevice device) {
    Log.i(TAG, "设备已连接: " + (device != null ? device.getName() : "未知"));
    
    if (listener != null && device != null) {
        listener.onAclConnected(device);
    }
}

private void handleAclDisconnected(BluetoothDevice device) {
    Log.i(TAG, "设备已断开: " + (device != null ? device.getName() : "未知"));
    
    if (listener != null && device != null) {
        listener.onAclDisconnected(device);
    }
}

private void handleBondStateChanged(Intent intent, BluetoothDevice device) {
    int previousState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, 
        BluetoothDevice.ERROR);
    int newState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, 
        BluetoothDevice.ERROR);
    
    Log.i(TAG, String.format("绑定状态变化: %s -> %s, 设备: %s", 
        getBondStateName(previousState), getBondStateName(newState),
        device != null ? device.getName() : "未知"));
    
    if (device != null && listener != null) {
        listener.onBondStateChanged(device, previousState, newState);
    }
}

private void handleProfileStateChanged(String action, Intent intent, BluetoothDevice device) {
    int previousState = intent.getIntExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, 
        BluetoothProfile.STATE_DISCONNECTED);
    int newState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, 
        BluetoothProfile.STATE_DISCONNECTED);
    int profile = getProfileFromAction(action);
    
    String profileName = getProfileName(profile);
    
    Log.i(TAG, String.format("Profile状态变化: %s [%s -> %s], 设备: %s", 
        profileName, getStateName(previousState), getStateName(newState),
        device != null ? device.getName() : "未知"));
    
    if (device != null && listener != null) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            listener.onDeviceConnected(device, profile, newState);
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            listener.onDeviceDisconnected(device, profile, newState);
        }
    }
}

private void handleAudioStateChanged(String action, Intent intent, BluetoothDevice device) {
    int audioState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
    String stateName = action.contains("AUDIO") ? 
        getHeadsetAudioStateName(audioState) : getA2dpPlayingStateName(audioState);
    
    Log.i(TAG, String.format("音频状态变化: %s, 设备: %s", 
        stateName, device != null ? device.getName() : "未知"));
}

private void handleUuidChanged(Intent intent, BluetoothDevice device) {
    ParcelUuid[] uuids = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID) != null ?
        Arrays.copyOf(intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID),
            intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID).length,
            ParcelUuid[].class) : new ParcelUuid[0];
    
    Log.i(TAG, "设备UUID变化: " + (device != null ? device.getName() : "未知") + 
        ", UUID数量: " + uuids.length);
    
    if (device != null && listener != null) {
        listener.onUuidChanged(device, uuids);
    }
}

private void handleClassChanged(Intent intent, BluetoothDevice device) {
    BluetoothClass bluetoothClass = intent.getParcelableExtra(BluetoothDevice.EXTRA_CLASS);
    if (bluetoothClass != null) {
        Log.i(TAG, "设备类变化: " + (device != null ? device.getName() : "未知") + 
            ", 设备类: " + bluetoothClass.getDeviceClass());
    }
}

// ========== 辅助方法 ==========

private int getProfileFromAction(String action) {
    switch (action) {
        case BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED:
            return BluetoothProfile.HEADSET;
        case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
            return BluetoothProfile.A2DP;
        case BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED:
            return BluetoothProfile.HID_HOST;
        case BluetoothPan.ACTION_CONNECTION_STATE_CHANGED:
            return BluetoothProfile.PAN;
        default:
            return -1;
    }
}

private String getStateName(int state) {
    switch (state) {
        case BluetoothAdapter.STATE_OFF: return "OFF";
        case BluetoothAdapter.STATE_TURNING_ON: return "TURNING_ON";
        case BluetoothAdapter.STATE_ON: return "ON";
        case BluetoothAdapter.STATE_TURNING_OFF: return "TURNING_OFF";
        case BluetoothProfile.STATE_DISCONNECTED: return "DISCONNECTED";
        case BluetoothProfile.STATE_CONNECTING: return "CONNECTING";
        case BluetoothProfile.STATE_CONNECTED: return "CONNECTED";
        case BluetoothProfile.STATE_DISCONNECTING: return "DISCONNECTING";
        default: return "UNKNOWN_" + state;
    }
}

private String getScanModeName(int mode) {
    switch (mode) {
        case BluetoothAdapter.SCAN_MODE_NONE: return "NONE";
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE: return "CONNECTABLE";
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: return "DISCOVERABLE";
        default: return "UNKNOWN_" + mode;
    }
}

private String getBondStateName(int state) {
    switch (state) {
        case BluetoothDevice.BOND_NONE: return "NONE";
        case BluetoothDevice.BOND_BONDING: return "BONDING";
        case BluetoothDevice.BOND_BONDED: return "BONDED";
        default: return "UNKNOWN_" + state;
    }
}

private String getProfileName(int profile) {
    switch (profile) {
        case BluetoothProfile.HEADSET: return "HEADSET";
        case BluetoothProfile.A2DP: return "A2DP";
        case BluetoothProfile.HID_HOST: return "HID_HOST";
        case BluetoothProfile.PAN: return "PAN";
        default: return "UNKNOWN_" + profile;
    }
}

private String getHeadsetAudioStateName(int state) {
    switch (state) {
        case BluetoothHeadset.STATE_AUDIO_CONNECTING: return "AUDIO_CONNECTING";
        case BluetoothHeadset.STATE_AUDIO_CONNECTED: return "AUDIO_CONNECTED";
        case BluetoothHeadset.STATE_AUDIO_DISCONNECTED: return "AUDIO_DISCONNECTED";
        default: return "UNKNOWN_" + state;
    }
}

private String getA2dpPlayingStateName(int state) {
    switch (state) {
        case BluetoothA2dp.STATE_PLAYING: return "PLAYING";
        case BluetoothA2dp.STATE_NOT_PLAYING: return "NOT_PLAYING";
        default: return "UNKNOWN_" + state;
    }
}

}

3.2 使用示例

public class MainActivity extends AppCompatActivity

implements BluetoothStateReceiver.BluetoothStateListener {

复制代码
private BluetoothStateReceiver receiver;
private BluetoothAdapter bluetoothAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    // 初始化蓝牙适配器
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    
    // 创建广播接收器
    receiver = new BluetoothStateReceiver(this, this);
    
    // 请求权限
    requestPermissions();
}

@Override
protected void onResume() {
    super.onResume();
    
    // 注册广播接收器
    if (receiver != null) {
        receiver.registerAllReceivers();
    }
    
    // 开始发现设备
    if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
        startDiscovery();
    }
}

@Override
protected void onPause() {
    super.onPause();
    
    // 注销广播接收器
    if (receiver != null) {
        receiver.unregisterReceiver();
    }
    
    // 停止发现设备
    if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    receiver = null;
}

// ========== 监听器方法实现 ==========

@Override
public void onAdapterStateChanged(int state) {
    runOnUiThread(() -> {
        TextView tvStatus = findViewById(R.id.tv_status);
        String status = "蓝牙状态: " + receiver.getStateName(state);
        tvStatus.setText(status);
        
        switch (state) {
            case BluetoothAdapter.STATE_ON:
                // 蓝牙已开启,开始发现设备
                startDiscovery();
                break;
            case BluetoothAdapter.STATE_OFF:
                // 蓝牙已关闭
                showToast("蓝牙已关闭");
                break;
        }
    });
}

@Override
public void onDeviceFound(BluetoothDevice device, int rssi) {
    runOnUiThread(() -> {
        // 添加到设备列表
        ListView listView = findViewById(R.id.lv_devices);
        ArrayAdapter<String> adapter = (ArrayAdapter<String>) listView.getAdapter();
        
        String deviceInfo = String.format("%s\n地址: %s\nRSSI: %d", 
            device.getName() != null ? device.getName() : "未知设备",
            device.getAddress(),
            rssi);
        
        adapter.add(deviceInfo);
        adapter.notifyDataSetChanged();
    });
}

@Override
public void onDeviceConnected(BluetoothDevice device, int profile, int state) {
    runOnUiThread(() -> {
        String message = String.format("设备已连接\n名称: %s\nProfile: %s", 
            device.getName() != null ? device.getName() : "未知设备",
            receiver.getProfileName(profile));
        showToast(message);
    });
}

@Override
public void onDeviceDisconnected(BluetoothDevice device, int profile, int state) {
    runOnUiThread(() -> {
        String message = String.format("设备已断开\n名称: %s\nProfile: %s", 
            device.getName() != null ? device.getName() : "未知设备",
            receiver.getProfileName(profile));
        showToast(message);
    });
}

@Override
public void onBondStateChanged(BluetoothDevice device, int prevState, int newState) {
    runOnUiThread(() -> {
        String message = String.format("绑定状态变化\n设备: %s\n状态: %s -> %s", 
            device.getName() != null ? device.getName() : "未知设备",
            receiver.getBondStateName(prevState),
            receiver.getBondStateName(newState));
        showToast(message);
    });
}

@Override
public void onDiscoveryStarted() {
    runOnUiThread(() -> {
        TextView tvDiscovery = findViewById(R.id.tv_discovery);
        tvDiscovery.setText("正在发现设备...");
    });
}

@Override
public void onDiscoveryFinished() {
    runOnUiThread(() -> {
        TextView tvDiscovery = findViewById(R.id.tv_discovery);
        tvDiscovery.setText("设备发现完成");
    });
}

@Override
public void onAclConnected(BluetoothDevice device) {
    Log.i("MainActivity", "ACL连接: " + device.getName());
}

@Override
public void onAclDisconnected(BluetoothDevice device) {
    Log.i("MainActivity", "ACL断开: " + device.getName());
}

@Override
public void onScanModeChanged(int mode) {
    Log.i("MainActivity", "扫描模式: " + receiver.getScanModeName(mode));
}

@Override
public void onLocalNameChanged(String name) {
    Log.i("MainActivity", "本地名称: " + name);
}

@Override
public void onUuidChanged(BluetoothDevice device, ParcelUuid[] uuids) {
    Log.i("MainActivity", "UUID变化: " + uuids.length);
}

// ========== 辅助方法 ==========

private void startDiscovery() {
    if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        
        // 清空列表
        ListView listView = findViewById(R.id.lv_devices);
        ArrayAdapter<String> adapter = (ArrayAdapter<String>) listView.getAdapter();
        adapter.clear();
        adapter.notifyDataSetChanged();
        
        // 开始发现
        boolean started = bluetoothAdapter.startDiscovery();
        Log.d("MainActivity", "开始发现设备: " + started);
    }
}

private void requestPermissions() {
    String[] permissions = {
        Manifest.permission.BLUETOOTH,
        Manifest.permission.BLUETOOTH_ADMIN,
        Manifest.permission.BLUETOOTH_CONNECT,
        Manifest.permission.BLUETOOTH_SCAN,
        Manifest.permission.ACCESS_FINE_LOCATION
    };
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        ActivityCompat.requestPermissions(this, permissions, 100);
    }
}

private void showToast(String message) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

}

四、权限配置

4.1 AndroidManifest.xml

五、总结表格

5.1 状态值快速参考

类别 值 描述

适配器 10-13 开关状态

连接 0-3 连接状态

绑定 10-12 绑定状态

扫描 20-23 扫描模式

5.2 协议值快速参考

协议 值 用途

RFCOMM 3 串口通信

L2CAP 1 数据链路

AVDTP 25 音频分发

ATT 7 BLE属性

SDP 1 服务发现

5.3 广播动作总结

广播动作 触发时机

ACTION_STATE_CHANGED 蓝牙开关状态变化

ACTION_FOUND 发现新设备

ACTION_BOND_STATE_CHANGED 绑定状态变化

ACTION_ACL_CONNECTED 物理连接建立

ACTION_CONNECTION_STATE_CHANGED Profile连接变化

这个完整的示例涵盖了 Android 蓝牙开发中的状态值、协议值管理和广播接收的所有重要方面。

相关推荐
徒 花2 小时前
数据库知识复习05
android·数据库
提子拌饭1334 小时前
番茄时间管理:鸿蒙Flutter 实现的高效时间管理工具
android·flutter·华为·架构·开源·harmonyos·鸿蒙
4311媒体网4 小时前
帝国CMS二次开发实战:精准实现“最新资讯”标识与高亮判断
android
BLUcoding4 小时前
Android 轻量级本地存储 SharedPreferences
android
冬奇Lab5 小时前
Camera HAL3 接口:Android 相机的真正底牌
android·音视频开发·源码阅读
sensen_kiss5 小时前
CAN302 Technologies for E-Commerce 电子商务技术 Pt.6 市场营销与SEO(搜索引擎优化)
android·学习·搜索引擎
菜鸟国国5 小时前
Compose + Koin ViewModel 实战完全手册
android
小羊子说5 小时前
Android 音频系统深度解析:从 App 到内核的完整链路
android·人工智能·性能优化·车载系统
fengci.5 小时前
php反序列化(复习)(第三章)
android·开发语言·学习·php