向蓝牙设备传输数据显示到设备上完整用例

时间: 2023-10-08 21:09:32 浏览: 44
好的,这里是一个基于Android平台向蓝牙设备传输数据并显示到设备上的完整用例: 1. 首先,需要在AndroidManifest.xml文件中添加以下权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ``` 2. 在MainActivity中创建一个蓝牙适配器(BluetoothAdapter)的实例,并启用蓝牙: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // 设备不支持蓝牙 return; } if (!bluetoothAdapter.isEnabled()) { // 启用蓝牙 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } ``` 3. 搜索周围的蓝牙设备,并选择要连接的设备: ```java Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { // 找到已配对的设备 for (BluetoothDevice device : pairedDevices) { if (device.getName().equals("设备名称")) { // 连接设备 ConnectThread connectThread = new ConnectThread(device); connectThread.start(); break; } } } else { // 没有已配对的设备,搜索新设备 Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION); startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_BT); } ``` 其中,ConnectThread是自定义的一个线程类,用于连接蓝牙设备: ```java private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmSocket // because mmSocket is final. BluetoothSocket tmp = null; mmDevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice. try { // MY_UUID is the app's UUID string, also used in the server code. tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "Socket's create() method failed", e); } mmSocket = tmp; } public void run() { // Cancel discovery because it otherwise slows down the connection. bluetoothAdapter.cancelDiscovery(); try { // Connect to the remote device through the socket. This call blocks // until it succeeds or throws an exception. mmSocket.connect(); } catch (IOException connectException) { // Unable to connect; close the socket and return. try { mmSocket.close(); } catch (IOException closeException) { Log.e(TAG, "Could not close the client socket", closeException); } return; } // The connection attempt succeeded. Perform work associated with // the connection in a separate thread. ConnectedThread connectedThread = new ConnectedThread(mmSocket); connectedThread.start(); } // Closes the client socket and causes the thread to finish. public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "Could not close the client socket", e); } } } ``` 4. 建立数据通道并发送数据: ```java private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) { mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the input and output streams; using temp objects because // member streams are final. try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "Error occurred when creating input/output stream", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } public void run() { byte[] buffer = new byte[1024]; int numBytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs. while (true) { try { // Read from the InputStream. numBytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity. Message readMsg = mHandler.obtainMessage( MESSAGE_READ, numBytes, -1, buffer); readMsg.sendToTarget(); } catch (IOException e) { Log.d(TAG, "Input stream was disconnected", e); break; } } } // Call this method from the main activity to send data to the remote device. public void write(byte[] bytes) { try { mmOutStream.write(bytes); // Share the sent message with the UI activity. Message writtenMsg = mHandler.obtainMessage( MESSAGE_WRITE, -1, -1, bytes); writtenMsg.sendToTarget(); } catch (IOException e) { Log.e(TAG, "Error occurred when sending data", e); // Send a failure message back to the activity. Message writeErrorMsg = mHandler.obtainMessage(MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString("toast", "Couldn't send data to the other device"); writeErrorMsg.setData(bundle); mHandler.sendMessage(writeErrorMsg); } } // Call this method from the main activity to shut down the connection. public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "Could not close the connect socket", e); } } } ``` 5. 在UI线程中发送数据: ```java // 向蓝牙设备发送数据 byte[] bytes = "Hello, world!".getBytes(); connectedThread.write(bytes); ``` 6. 最后,将接收到的数据显示到设备上: ```java private final Handler mHandler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case MESSAGE_READ: byte[] readBuf = (byte[]) msg.obj; // 将接收到的数据显示在UI上 String readMessage = new String(readBuf, 0, msg.arg1); textView.setText(readMessage); break; // ... } return true; } }); ``` 以上就是一个完整的向蓝牙设备传输数据并显示到设备上的Android应用程序的实现过程。

相关推荐

最新推荐

recommend-type

史上最详细的测试用例的设计方法及案例

思路:输入的集合是无穷的,不能全部都覆盖到等价类:依据需求将输入划分为若干个等价类,从等价类中选出一个测试用例,如果这个测试用例测试通过,则认为所代表的整个等价类测试通过,这样就可以通过较少的测试用例达到...
recommend-type

功能测试用例大全1500条

测试用例的分类 3 文本框需求 4 字段为特殊代码校验: 4 文本框为数值型 4 文本框为日期型 5 文本框为时间型 6 密码框 返回目录 6 单选按钮 7 组合列表框/下拉列表 7 数码框(up-down)控件 8 搜索框填充域测试 8 复...
recommend-type

史上最全的测试用例设计方法总结

是把所有可能的输入数据,即程序的输入域划分成若干部分(子集),然后从每一个子集中选取少数具有代表性的数据作为测试用例。该方法是一种重要的,常用的黑盒测试用例设计方法。 2.划分等价类: 等价类是指某个...
recommend-type

软件测试用例模板一详细用例(经典).doc

软件测试用例模板一详细用例(经典) - 用例编号 项目名称 模块名称 项目承担部门 用例作者 完成日期 本文档使用部门 评审负责人 审核日期 TestCase_LinkWorks_WorkEv...
recommend-type

testlink安装加手把手教你创建测试用例.docx

testlink安装教程+手把手创建测试用例 testlink安装教程 创建测试用例 本人小白,也是第一次学习,所以写的比较详细,然后大家可以根据我写的来一步一步的跟着做,基于知识产权,再加上写了好久,所以大家花个积分来...
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

云原生架构与soa架构区别?

云原生架构和SOA架构是两种不同的架构模式,主要有以下区别: 1. 设计理念不同: 云原生架构的设计理念是“设计为云”,注重应用程序的可移植性、可伸缩性、弹性和高可用性等特点。而SOA架构的设计理念是“面向服务”,注重实现业务逻辑的解耦和复用,提高系统的灵活性和可维护性。 2. 技术实现不同: 云原生架构的实现技术包括Docker、Kubernetes、Service Mesh等,注重容器化、自动化、微服务等技术。而SOA架构的实现技术包括Web Services、消息队列等,注重服务化、异步通信等技术。 3. 应用场景不同: 云原生架构适用于云计算环境下的应用场景,如容器化部署、微服务
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。