Android蓝牙通信的完整指南

Android设备可以通过蓝牙和其他设备进行通信,包括其他Android设备和外部设备,如蓝牙耳机、打印机和传感器等。在本指南中,我们将详细介绍如何使用Android蓝牙API建立和管理蓝牙连接。

一、检查设备是否支持蓝牙

首先,我们需要检查当前设备是否支持蓝牙功能。

    private boolean isBluetoothSupported() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter != null;
    }

使用上述代码可以检查设备是否支持蓝牙功能。如果返回true,则设备支持蓝牙功能。

二、开启蓝牙

在使用蓝牙功能之前,需要确保蓝牙已经开启。

    private boolean isBluetoothEnabled() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled();
    }

    private void enableBluetooth(Activity activity) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "蓝牙已打开", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "无法打开蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

使用上述代码可以检查蓝牙是否已开启。如果返回true,则蓝牙已经开启。如果返回false,则需要启动启用蓝牙对话框以请求开启蓝牙。

三、搜索设备

在与其他设备进行通信之前,需要搜索周围的设备。在搜索设备之前,需要确保蓝牙已经开启。

    private void startDiscovery() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        bluetoothAdapter.startDiscovery();
        Toast.makeText(this, "搜索设备中...", Toast.LENGTH_SHORT).show();
    }

    private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d(TAG, "发现设备:" + device.getName() + " - " + device.getAddress());
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(discoveryReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(discoveryReceiver);
    }

使用上述代码可以开始搜索设备。当找到设备时,会收到广播,并且在日志中打印设备名称和地址。如果找不到设备,可以尝试重新启动搜索或检查设备是否打开蓝牙。

四、连接设备

当找到要连接的设备时,需要建立连接。建立连接前,需要确保蓝牙已经开启。

    private void connect(String address) {
        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
        BluetoothSocket socket = null;
        try {
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            Log.d(TAG, "连接成功:" + device.getName());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

使用上述代码可以连接指定地址的设备。如果连接成功,则会在日志中打印设备名称。如果连接失败,则会抛出IOException。

五、数据传输

连接建立后,可以开始在设备之间传输数据。以下代码演示如何发送和接收文本数据。

    private void send(String message) {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            return;
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
        BluetoothSocket socket = null;
        OutputStream outputStream = null;
        try {
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            outputStream = socket.getOutputStream();
            outputStream.write(message.getBytes());
            Log.d(TAG, "消息发送成功:" + message);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private final BroadcastReceiver receiveReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                Log.d(TAG, "连接成功");
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                Log.d(TAG, "连接断开");
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
                Log.d(TAG, "断开请求");
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiveReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiveReceiver);
    }

使用上述代码可以在设备之间传输文本数据。发送消息时,使用OutputStream将文本字符串转换为字节,并通过BluetoothSocket发送。在接收消息时,使用BroadcastReceiver监听连接的状态,并根据状态更新UI或执行其他操作。

六、总结

本指南中介绍了如何使用Android蓝牙API建立和管理蓝牙连接。需要注意的是,在使用蓝牙功能之前,需要确保蓝牙已经开启,并且在连接设备之前,需要确保已经搜索到要连接的设备。为了传输数据,可以使用OutputStream将文本转换为字节并发送。在接收数据时,可以使用BroadcastReceiver监听连接状态并执行操作。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/186240.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-11-27 05:45
下一篇 2024-11-27 05:45

相关推荐

  • Java JsonPath 效率优化指南

    本篇文章将深入探讨Java JsonPath的效率问题,并提供一些优化方案。 一、JsonPath 简介 JsonPath是一个可用于从JSON数据中获取信息的库。它提供了一种DS…

    编程 2025-04-29
  • 运维Python和GO应用实践指南

    本文将从多个角度详细阐述运维Python和GO的实际应用,包括监控、管理、自动化、部署、持续集成等方面。 一、监控 运维中的监控是保证系统稳定性的重要手段。Python和GO都有强…

    编程 2025-04-29
  • Python应用程序的全面指南

    Python是一种功能强大而简单易学的编程语言,适用于多种应用场景。本篇文章将从多个方面介绍Python如何应用于开发应用程序。 一、Web应用程序 目前,基于Python的Web…

    编程 2025-04-29
  • Python wordcloud入门指南

    如何在Python中使用wordcloud库生成文字云? 一、安装和导入wordcloud库 在使用wordcloud前,需要保证库已经安装并导入: !pip install wo…

    编程 2025-04-29
  • Python字符转列表指南

    Python是一个极为流行的脚本语言,在数据处理、数据分析、人工智能等领域广泛应用。在很多场景下需要将字符串转换为列表,以便于操作和处理,本篇文章将从多个方面对Python字符转列…

    编程 2025-04-29
  • 打造照片漫画生成器的完整指南

    本文将分享如何使用Python编写一个简单的照片漫画生成器,本文所提到的所有代码和技术都适用于初学者。 一、环境准备 在开始编写代码之前,我们需要准备一些必要的环境。 首先,需要安…

    编程 2025-04-29
  • 如何在Java中拼接OBJ格式的文件并生成完整的图像

    OBJ格式是一种用于表示3D对象的标准格式,通常由一组顶点、面和纹理映射坐标组成。在本文中,我们将讨论如何将多个OBJ文件拼接在一起,生成一个完整的3D模型。 一、读取OBJ文件 …

    编程 2025-04-29
  • Python小波分解入门指南

    本文将介绍Python小波分解的概念、基本原理和实现方法,帮助初学者掌握相关技能。 一、小波变换概述 小波分解是一种广泛应用于数字信号处理和图像处理的方法,可以将信号分解成多个具有…

    编程 2025-04-29
  • Python初学者指南:第一个Python程序安装步骤

    在本篇指南中,我们将通过以下方式来详细讲解第一个Python程序安装步骤: Python的安装和环境配置 在命令行中编写和运行第一个Python程序 使用IDE编写和运行第一个Py…

    编程 2025-04-29
  • Python起笔落笔全能开发指南

    Python起笔落笔是指在编写Python代码时的编写习惯。一个好的起笔落笔习惯可以提高代码的可读性、可维护性和可扩展性,本文将从多个方面进行详细阐述。 一、变量命名 变量命名是起…

    编程 2025-04-29

发表回复

登录后才能评论