摘要
摘要:本文深入解析 Android SDK 中的经典蓝牙通信示例 BluetoothChat,从项目结构、核心代码到布局文件进行完整剖析。通过主界面 Activity、后台服务、设备列表、权限配置等模块的详细讲解,帮助开发者快速掌握 Android 蓝牙开发的核心流程与关键技术,实现设备间的稳定数据传输。
1. 引言
Android 蓝牙开发是移动设备间进行短距离无线通信的重要技术。Google 在 Android SDK 中提供了 BluetoothChat 这一经典示例,它完整展示了蓝牙设备的发现、配对、连接以及双向数据传输的全过程。本文将对该示例进行系统性解析,帮助开发者理解 Android 蓝牙开发的核心架构与实现细节。
2. 项目概述与结构
BluetoothChat 是一个简单的蓝牙聊天应用,主要包含以下核心组件:
- BluetoothChat(主 Activity):负责 UI 展示、消息发送与接收显示。
- BluetoothChatService:核心服务类,处理蓝牙连接、数据传输等后台逻辑。
- DeviceListActivity:设备列表界面,用于搜索和选择要连接的蓝牙设备。
- 布局文件:包括主界面、消息项、设备列表等界面布局。
- 资源文件:字符串、菜单等资源配置。
应用通过经典的客户端-服务器模式工作:一个设备作为服务器监听连接,另一个设备作为客户端发起连接,建立连接后即可进行双向数据传输。
3. 主界面 Activity 详解
主 Activity(BluetoothChat)是整个应用的入口和用户交互界面,主要职责包括:
- 初始化蓝牙适配器并检查设备支持
- 管理应用生命周期(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 ArrayAdapter<String> 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 ArrayAdapter<String>(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
- 连接成功后创建
ConnectedThread
ConnectedThread(数据传输线程):
- 通过
InputStream和OutputStream进行双向数据传输 - 持续读取数据并通过 Handler 发送到 UI 线程
- 提供
write()方法发送数据
5. 设备列表 Activity
DeviceListActivity负责显示已配对和可发现的蓝牙设备,用户可以选择设备进行连接。主要功能包括:
- 显示已配对设备列表
- 启动设备发现并显示新设备
- 处理设备点击事件,返回设备地址给主 Activity
5.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 ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.device_list); // 设置结果为取消(用户按返回键时) setResult(Activity.RESULT_CANCELED); // 初始化数组适配器 mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter<String>(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(); // 获取已配对设备集合并添加到列表 Set<BluetoothDevice> 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();