Android(蓝牙)

因近期项目需求调试了Android蓝牙通讯接口,主要是两个终端作为服务端和客户端的通信,本文将部分重要知识点记录如下。

蓝牙是短距离无线通信,通常分经典蓝牙和低功耗蓝牙(即蓝牙4.0),两类蓝牙协议各层定义上存在很多不同,因此芯片也不一样,但就Android上做应用层开发没什么差别。

蓝牙通信分为配对和数据传输两部分,两部分是独立的,一般来说是点对点,如果要组局域网需要支持LAN协议扩展,没有尝试过。

  • 配对阶段
    • 发现设备方
           
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.enable(); IntentFilter intent = new IntentFilter(); intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果 receiver = new BluetoothReceiver(); registerReceiver(receiver, intent);//注册一个广播,接收蓝牙设备发现的消息 mBluetoothAdapter.startDiscovery();
复制代码
    private class BluetoothReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action))
            {
                if(isFound == true){
                    return;
                }
                isFound = true;
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//获取这个蓝牙设备,可能存在多个
复制代码
    • 被发现方
        Intent discoveryIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoveryIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                300);//弹出一个窗口,确认本机蓝牙设备在300s内可被发现
        discoveryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(discoveryIntent);
  • 通信阶段

通信阶段基本等价于socket编程,本文不黏贴全部代码,唯一遇到的问题是不用反射方法获取设备,通信连接很不稳定,本文代码如下:

    • 服务器端
Method listenMethod = adapter.getClass().getMethod("listenUsingRfcommOn", new Class[]{int.class});
mmServerSocket = ( BluetoothServerSocket) listenMethod.invoke(adapter, Integer.valueOf(1));
socket = mmServerSocket.accept();
    • 客户端
Method method = mServerDevice.getClass().getMethod("createRfcommSocket",new Class[] { int.class });
mSocket = (BluetoothSocket) method.invoke(mServerDevice, Integer.valueOf(1));
posted @   Fredric_2013  阅读(515)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2013-07-01 需求调研与分析流程
2013-07-01 【转】MySQL性能优化的21个最佳实践
点击右上角即可分享
微信分享提示