Android 蓝牙开发详解与实战:基于 BluetoothChat 示例的完整解析
摘要摘要本文深入解析 Android SDK 中的经典蓝牙通信示例 BluetoothChat从项目结构、核心代码到布局文件进行完整剖析。通过主界面 Activity、后台服务、设备列表、权限配置等模块的详细讲解帮助开发者快速掌握 Android 蓝牙开发的核心流程与关键技术实现设备间的稳定数据传输。1. 引言Android 蓝牙开发是移动设备间进行短距离无线通信的重要技术。Google 在 Android SDK 中提供了 BluetoothChat 这一经典示例它完整展示了蓝牙设备的发现、配对、连接以及双向数据传输的全过程。本文将对该示例进行系统性解析帮助开发者理解 Android 蓝牙开发的核心架构与实现细节。2. 项目概述与结构BluetoothChat 是一个简单的蓝牙聊天应用主要包含以下核心组件BluetoothChat主 Activity负责 UI 展示、消息发送与接收显示。BluetoothChatService核心服务类处理蓝牙连接、数据传输等后台逻辑。DeviceListActivity设备列表界面用于搜索和选择要连接的蓝牙设备。布局文件包括主界面、消息项、设备列表等界面布局。资源文件字符串、菜单等资源配置。应用通过经典的客户端-服务器模式工作一个设备作为服务器监听连接另一个设备作为客户端发起连接建立连接后即可进行双向数据传输。3. 主界面 Activity 详解主 ActivityBluetoothChat是整个应用的入口和用户交互界面主要职责包括初始化蓝牙适配器并检查设备支持管理应用生命周期onCreate、onStart、onResume 等处理用户界面事件发送消息、菜单操作与 BluetoothChatService 通信更新 UI 状态3.1 关键代码分析以下是 BluetoothChat Activity 的核心代码结构已根据原文整理public class BluetoothChat extends Activity { // 调试标签 private static final String TAG BluetoothChat; private static final boolean D true; // 消息类型常量 public static final int MESSAGE_STATE_CHANGE 1; public static final int MESSAGE_READ 2; public static final int MESSAGE_WRITE 3; public static final int MESSAGE_DEVICE_NAME 4; public static final int MESSAGE_TOAST 5; // 关键名称常量 public static final String DEVICE_NAME device_name; public static final String TOAST toast; // Intent 请求码 private static final int REQUEST_CONNECT_DEVICE 1; private static final int REQUEST_ENABLE_BT 2; // 界面控件 private TextView mTitle; private ListView mConversationView; private EditText mOutEditText; private Button mSendButton; // 连接设备名称 private String mConnectedDeviceName null; // 消息列表适配器 private ArrayAdapterString mConversationArrayAdapter; // 输出消息缓冲区 private StringBuffer mOutStringBuffer; // 蓝牙适配器 private BluetoothAdapter mBluetoothAdapter null; // 聊天服务 private BluetoothChatService mChatService null; Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(D) Log.e(TAG, ON CREATE ); // 设置窗口布局 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); // 设置自定义标题 mTitle (TextView) findViewById(R.id.title_left_text); mTitle.setText(R.string.app_name); mTitle (TextView) findViewById(R.id.title_right_text); // 获取本地蓝牙适配器 mBluetoothAdapter BluetoothAdapter.getDefaultAdapter(); // 如果适配器为 null说明设备不支持蓝牙 if (mBluetoothAdapter null) { Toast.makeText(this, Bluetooth is not available, Toast.LENGTH_LONG).show(); finish(); return; } } Override public void onStart() { super.onStart(); if(D) Log.e(TAG, ON START ); // 如果蓝牙未开启请求开启 if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } else { // 否则初始化聊天会话 if (mChatService null) setupChat(); } } // 初始化聊天界面 private void setupChat() { Log.d(TAG, setupChat()); // 初始化消息列表适配器 mConversationArrayAdapter new ArrayAdapterString(this, R.layout.message); mConversationView (ListView) findViewById(R.id.in); mConversationView.setAdapter(mConversationArrayAdapter); // 初始化消息输入框 mOutEditText (EditText) findViewById(R.id.edit_text_out); mOutEditText.setOnEditorActionListener(mWriteListener); // 初始化发送按钮 mSendButton (Button) findViewById(R.id.button_send); mSendButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { TextView view (TextView) findViewById(R.id.edit_text_out); String message view.getText().toString(); sendMessage(message); } }); // 初始化蓝牙聊天服务 mChatService new BluetoothChatService(this, mHandler); // 初始化输出缓冲区 mOutStringBuffer new StringBuffer(); } // 发送消息 private void sendMessage(String message) { // 检查连接状态 if (mChatService.getState() ! BluetoothChatService.STATE_CONNECTED) { Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show(); return; } // 检查消息内容 if (message.length() 0) { byte[] send message.getBytes(); mChatService.write(send); // 发送消息 // 清空输入框 mOutStringBuffer.setLength(0); mOutEditText.setText(mOutStringBuffer); } } // Handler 处理来自 BluetoothChatService 的消息 private final Handler mHandler new Handler() { Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_STATE_CHANGE: // 处理连接状态变化 switch (msg.arg1) { case BluetoothChatService.STATE_CONNECTED: mTitle.setText(R.string.title_connected_to); mTitle.append(mConnectedDeviceName); mConversationArrayAdapter.clear(); break; case BluetoothChatService.STATE_CONNECTING: mTitle.setText(R.string.title_connecting); break; case BluetoothChatService.STATE_LISTEN: case BluetoothChatService.STATE_NONE: mTitle.setText(R.string.title_not_connected); break; } break; case MESSAGE_WRITE: // 处理发送的消息 byte[] writeBuf (byte[]) msg.obj; String writeMessage new String(writeBuf); mConversationArrayAdapter.add(Me: writeMessage); break; case MESSAGE_READ: // 处理接收的消息 byte[] readBuf (byte[]) msg.obj; String readMessage new String(readBuf, 0, msg.arg1); mConversationArrayAdapter.add(mConnectedDeviceName : readMessage); break; case MESSAGE_DEVICE_NAME: // 保存连接的设备名称 mConnectedDeviceName msg.getData().getString(DEVICE_NAME); Toast.makeText(getApplicationContext(), Connected to mConnectedDeviceName, Toast.LENGTH_SHORT).show(); break; case MESSAGE_TOAST: // 显示提示信息 Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show(); break; } } }; }3.2 关键功能点解析1. 蓝牙适配器初始化通过BluetoothAdapter.getDefaultAdapter()获取设备蓝牙适配器如果返回null则表示设备不支持蓝牙。2. 蓝牙启用检查在onStart()中检查蓝牙是否启用如果未启用则通过ACTION_REQUEST_ENABLE请求用户开启。3. 消息发送机制用户输入消息后通过BluetoothChatService.write()方法发送字节数据同时更新本地消息列表显示“Me:”前缀。4. 消息接收处理通过 Handler 机制接收来自BluetoothChatService的消息根据消息类型更新 UI 状态或显示接收到的消息。4. 蓝牙服务类详解BluetoothChatService是应用的核心服务类负责所有蓝牙通信的底层操作。它采用多线程架构包含三个主要线程AcceptThread服务器线程监听传入的连接请求ConnectThread客户端线程主动连接远程设备ConnectedThread连接线程处理已建立连接的数据传输4.1 服务类核心结构public class BluetoothChatService { // 调试信息 private static final String TAG BluetoothChatService; private static final boolean D true; // SDP 记录名称 private static final String NAME BluetoothChat; // 应用唯一 UUID private static final UUID MY_UUID UUID.fromString(fa87c0d0-afac-11de-8a39-0800200c9a66); // 成员变量 private final BluetoothAdapter mAdapter; private final Handler mHandler; private AcceptThread mAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; // 连接状态常量 public static final int STATE_NONE 0; // 未连接 public static final int STATE_LISTEN 1; // 监听传入连接 public static final int STATE_CONNECTING 2; // 正在连接 public static final int STATE_CONNECTED 3; // 已连接 // 构造函数 public BluetoothChatService(Context context, Handler handler) { mAdapter BluetoothAdapter.getDefaultAdapter(); mState STATE_NONE; mHandler handler; } // 设置当前状态并通知 UI private synchronized void setState(int state) { if (D) Log.d(TAG, setState() mState - state); mState state; mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } // 获取当前状态 public synchronized int getState() { return mState; } // 启动服务开始监听 public synchronized void start() { if (D) Log.d(TAG, start); // 取消任何正在运行的线程 if (mConnectThread ! null) { mConnectThread.cancel(); mConnectThread null; } if (mConnectedThread ! null) { mConnectedThread.cancel(); mConnectedThread null; } if (mAcceptThread ! null) { mAcceptThread.cancel(); mAcceptThread null; } // 启动监听线程 setState(STATE_LISTEN); mAcceptThread new AcceptThread(); mAcceptThread.start(); } // 连接到指定设备 public synchronized void connect(BluetoothDevice device) { if (D) Log.d(TAG, connect to: device); // 取消任何正在尝试的连接或运行的线程 if (mState STATE_CONNECTING) { if (mConnectThread ! null) { mConnectThread.cancel(); mConnectThread null; } } if (mConnectedThread ! null) { mConnectedThread.cancel(); mConnectedThread null; } // 启动连接线程 mConnectThread new ConnectThread(device); mConnectThread.start(); setState(STATE_CONNECTING); } // 停止所有线程 public synchronized void stop() { if (D) Log.d(TAG, stop); if (mConnectThread ! null) { mConnectThread.cancel(); mConnectThread null; } if (mConnectedThread ! null) { mConnectedThread.cancel(); mConnectedThread null; } if (mAcceptThread ! null) { mAcceptThread.cancel(); mAcceptThread null; } setState(STATE_NONE); } // 写入数据到连接线程 public void write(byte[] out) { ConnectedThread r; synchronized (this) { if (mState ! STATE_CONNECTED) return; r mConnectedThread; } r.write(out); } }4.2 三个核心线程类AcceptThread服务器线程通过BluetoothServerSocket监听传入连接使用固定的 UUID 创建 RFCOMM 服务当有设备连接时创建ConnectedThread处理数据传输ConnectThread客户端线程通过BluetoothSocket主动连接远程设备使用与服务器相同的 UUID连接成功后创建ConnectedThreadConnectedThread数据传输线程通过InputStream和OutputStream进行双向数据传输持续读取数据并通过 Handler 发送到 UI 线程提供write()方法发送数据5. 设备列表 ActivityDeviceListActivity负责显示已配对和可发现的蓝牙设备用户可以选择设备进行连接。主要功能包括显示已配对设备列表启动设备发现并显示新设备处理设备点击事件返回设备地址给主 Activity5.1 关键实现代码public class DeviceListActivity extends Activity { // 调试标签 private static final String TAG DeviceListActivity; private static final boolean D true; // 返回 Intent 的额外数据键 public static final String EXTRA_DEVICE_ADDRESS device_address; // 成员变量 private BluetoothAdapter mBtAdapter; private ArrayAdapterString mPairedDevicesArrayAdapter; private ArrayAdapterString mNewDevicesArrayAdapter; Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.device_list); // 设置结果为取消用户按返回键时 setResult(Activity.RESULT_CANCELED); // 初始化数组适配器 mPairedDevicesArrayAdapter new ArrayAdapterString(this, R.layout.device_name); mNewDevicesArrayAdapter new ArrayAdapterString(this, R.layout.device_name); // 设置已配对设备列表 ListView pairedListView (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // 设置新设备列表 ListView newDevicesListView (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // 注册广播接收器 IntentFilter filter new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); filter new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // 获取本地蓝牙适配器 mBtAdapter BluetoothAdapter.getDefaultAdapter(); // 获取已配对设备集合并添加到列表 SetBluetoothDevice pairedDevices mBtAdapter.getBondedDevices(); if (pairedDevices.size() 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() \n device.getAddress()); } } else { String noDevices getResources().getText(R.string.none_paired).toString();

相关新闻

LoadRunner 自定义函数的使用方法

LoadRunner 自定义函数的使用方法

以前写程序时,不管是什么语言都支持函数。现在在学loadrunner ,不知道loadrunner是否支持自定义函数,于是做了个实验证明了一下,loadrunner也可以自定义函数。在下面的程序中,自定义函数max()放…

2026/11/17 5:57:35 阅读更多 →
3分钟上手:OBS AI背景移除插件完整使用指南

3分钟上手:OBS AI背景移除插件完整使用指南

3分钟上手:OBS AI背景移除插件完整使用指南 【免费下载链接】obs-backgroundremoval An OBS plugin for removing background in portrait images (video), making it easy to replace the background when recording or streaming. 项目地址: https://gitcode.co…

2026/11/17 6:08:47 阅读更多 →
卡美德生物科普:SAA1(血清淀粉样蛋白 A1)炎症相关靶点解析

卡美德生物科普:SAA1(血清淀粉样蛋白 A1)炎症相关靶点解析

SAA1 全称 Serum Amyloid A1,中文常称为血清淀粉样蛋白 A1,是机体炎症反应与免疫激活过程中具有代表性的分泌型蛋白分子,也是感染、炎症、组织损伤相关研究中常见的检测靶点。本文从分子基础、表达调控、检测意义与实验研究方向展开梳理&…

2026/11/17 6:08:14 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/11/17 8:22:52 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/11/17 12:46:04 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/11/17 12:46:04 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/11/17 11:26:33 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/11/17 12:46:05 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/11/17 12:46:05 阅读更多 →

日新闻

周新闻

月新闻