蓝牙通信的简要设计与开发(附加题)

  • 蓝牙通信简介
    • 什么是蓝牙通信
    • 蓝牙通信的过程
  • 代码如下
    • 客户端代码
    • 服务端代码
    • 共同处理通讯处理类代码
    • Constant常量类代码
    • BlueToothController蓝牙控制类代码
    • 蓝牙设备adaptor代码DeviceAdapter
  • 运行结果截图

蓝牙通信简介

什么是蓝牙通信

首先要知道几个类,BluetoothAdapter,BluetoothGatt,BluetoothDevice,BluetoothCattService,BluetoothCattCharacteristic。
BluetoothAdapter是蓝牙设配器,对蓝牙的操作都需要用到它,很重要,BluetoothGatt作为中央来使用和处理数据,使用时有一个回调方法BluetoothGattCallback返回中央的状态和周边提供的数据,BluetoothCattService作为周边来提供数据;BluetoothGattServerCallback返回周边的状态。BluetoothDevice是蓝牙设备,BluetoothCattCharacteristic是蓝牙设备的特征。
Android 平台包含蓝牙网络堆栈支持,此支持能让设备以无线方式与其他蓝牙设备交换数据。应用框架提供通过 Android Bluetooth API 访问蓝牙功能的权限。这些 API 允许应用以无线方式连接到其他蓝牙设备,从而实现点到点和多点无线功能。
原理:蓝牙通信和socket通信原理基本上是一致的

蓝牙通信的过程

1.首先开启蓝牙
2.搜索可用设备
3.创建蓝牙socket,获取输入输出流
4.读取和写入数据
5.断开连接关闭蓝牙

代码如下

客户端代码

package com.example.blue.connect;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;import java.io.IOException;
import java.util.UUID;public class ConnectThread extends Thread {private static final UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUID);private final BluetoothSocket mmSocket;private final BluetoothDevice mmDevice;private BluetoothAdapter mBluetoothAdapter;private final Handler mHandler;private ConnectedThread mConnectedThread;public ConnectThread(BluetoothDevice device, BluetoothAdapter adapter, Handler handler) {BluetoothSocket tmp = null;mmDevice = device;mBluetoothAdapter = adapter;mHandler = handler;try {tmp = device.createRfcommSocketToServiceRecord(MY_UUID);} catch (IOException e) { }mmSocket = tmp;}public void run() {mBluetoothAdapter.cancelDiscovery();try {mmSocket.connect();} catch (Exception connectException) {mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, connectException));try {mmSocket.close();} catch (IOException closeException) { }return;}manageConnectedSocket(mmSocket);}private void manageConnectedSocket(BluetoothSocket mmSocket) {mHandler.sendEmptyMessage(Constant.MSG_CONNECTED_TO_SERVER);mConnectedThread = new ConnectedThread(mmSocket, mHandler);mConnectedThread.start();}public void cancel() {try {mmSocket.close();} catch (IOException e) { }}public void sendData(byte[] data) {if( mConnectedThread!=null){mConnectedThread.write(data);}}
}

服务端代码

package com.example.blue.connect;import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;import java.io.IOException;
import java.util.UUID;//服务器端线程
public class AcceptThread extends Thread {private static final String NAME = "BlueToothClass";private static final UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUID);private final BluetoothServerSocket mmServerSocket;private final BluetoothAdapter mBluetoothAdapter;private final Handler mHandler;private ConnectedThread mConnectedThread;public AcceptThread(BluetoothAdapter adapter, Handler handler) {mBluetoothAdapter = adapter;mHandler = handler;BluetoothServerSocket tmp = null;try {tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);} catch (IOException e) { }mmServerSocket = tmp;}public void run() {BluetoothSocket socket = null;while (true) {try {mHandler.sendEmptyMessage(Constant.MSG_START_LISTENING);socket = mmServerSocket.accept();} catch (IOException e) {mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, e));break;}if (socket != null) {manageConnectedSocket(socket);try {mmServerSocket.close();mHandler.sendEmptyMessage(Constant.MSG_FINISH_LISTENING);} catch (IOException e) {e.printStackTrace();}break;}}}private void manageConnectedSocket(BluetoothSocket socket) {//只支持同时处理一个连接if( mConnectedThread != null) {mConnectedThread.cancel();}mHandler.sendEmptyMessage(Constant.MSG_GOT_A_CLINET);mConnectedThread = new ConnectedThread(socket, mHandler);mConnectedThread.start();}public void cancel() {try {mmServerSocket.close();mHandler.sendEmptyMessage(Constant.MSG_FINISH_LISTENING);} catch (IOException e) { }}public void sendData(byte[] data) {if( mConnectedThread!=null){mConnectedThread.write(data);}}
}

共同处理通讯处理类代码

package com.example.blue.connect;import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;public class ConnectedThread extends Thread {private final BluetoothSocket mmSocket;private final InputStream mmInStream;private final OutputStream mmOutStream;private final Handler mHandler;public ConnectedThread(BluetoothSocket socket, Handler handler) {mmSocket = socket;InputStream tmpIn = null;OutputStream tmpOut = null;mHandler = handler;try {tmpIn = socket.getInputStream();tmpOut = socket.getOutputStream();} catch (IOException e) { }mmInStream = tmpIn;mmOutStream = tmpOut;}public void run() {byte[] buffer = new byte[1024]; int bytes;//一直读数据while (true) {try {bytes = mmInStream.read(buffer);if( bytes >0) {Message message = mHandler.obtainMessage(Constant.MSG_GOT_DATA, new String(buffer, 0, bytes, "utf-8"));mHandler.sendMessage(message);}Log.d("GOTMSG", "message size" + bytes);} catch (IOException e) {mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_ERROR, e));break;}}}//发送数据public void write(byte[] bytes) {try {mmOutStream.write(bytes);} catch (IOException e) { }}public void cancel() {try {mmSocket.close();} catch (IOException e) { }}
}

Constant常量类代码

public class Constant {public static final String CONNECTTION_UUID = "00001101-0000-1000-8000-00805F9B34FB";/*** 开始监听*/public static final int MSG_START_LISTENING = 1;/*** 结束监听*/public static final int MSG_FINISH_LISTENING = 2;/*** 有客户端连接*/public static final int MSG_GOT_A_CLINET = 3;/*** 连接到服务器*/public static final int MSG_CONNECTED_TO_SERVER = 4;/*** 获取到数据*/public static final int MSG_GOT_DATA = 5;/*** 出错*/public static final int MSG_ERROR = -1;}

BlueToothController蓝牙控制类代码

public class BlueToothController {private BluetoothAdapter mAapter;public BlueToothController() {mAapter = BluetoothAdapter.getDefaultAdapter();}public BluetoothAdapter getAdapter() {return mAapter;}/*** 打开蓝牙* @param activity* @param requestCode*/public void turnOnBlueTooth(Activity activity, int requestCode) {Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);activity.startActivityForResult(intent, requestCode);
//        mAdapter.enable();}/*** 打开蓝牙可见性* @param context*/public void enableVisibly(Context context) {Intent discoverableIntent = newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);context.startActivity(discoverableIntent);}/*** 查找设备*/public void findDevice() {assert (mAapter != null);mAapter.startDiscovery();}/*** 获取绑定设备* @return*/public List<BluetoothDevice> getBondedDeviceList() {return new ArrayList<>(mAapter.getBondedDevices());}
}

蓝牙设备adaptor代码DeviceAdapter

public class DeviceAdapter extends BaseAdapter {private Context mContext;private List<BluetoothDevice> mDate;public DeviceAdapter(List<BluetoothDevice> Date, Context context){mDate = Date;mContext = context;}@Overridepublic int getCount() {return mDate.size();}@Overridepublic Object getItem(int position) {return mDate.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {ViewHolder viewHolder = null;if(convertView==null){viewHolder = new ViewHolder();convertView = LayoutInflater.from(mContext).inflate(R.layout.deviceadapter_layout,null);viewHolder.textView1 = (TextView)convertView.findViewById(R.id.textview1);viewHolder.textView2 = (TextView)convertView.findViewById(R.id.textview2);convertView.setTag(viewHolder);}else{viewHolder = (ViewHolder) convertView.getTag();}//获取蓝牙设备BluetoothDevice bluetoothDevice = (BluetoothDevice) getItem(position);viewHolder.textView1.setText("Name="+bluetoothDevice.getName());viewHolder.textView2.setText("Address"+bluetoothDevice.getAddress());return convertView;}public class ViewHolder{public TextView textView1;public  TextView textView2;}public void refresh(List<BluetoothDevice> data){mDate = data;notifyDataSetChanged();}
}

运行结果截图


蓝牙通信的简要设计与开发(附加题)相关推荐

  1. 蓝牙通信的简要设计与开发

    蓝牙通信的简要设计与开发 基础知识 蓝牙权限 蓝牙进行通信的四大必需任务 一:设置蓝牙 二:查找设备 三:连接设备 四:管理连接 相关java类代码 结果截图(两台真机运行) 基础知识 为了让支持蓝牙 ...

  2. 移动开发作业6——蓝牙通信的简要设计与开发

    一.蓝牙通信原理介绍 Android 平台包含蓝牙网络堆栈支持,此支持能让设备以无线方式与其他蓝牙设备交换数据.应用框架提供通过 Android Bluetooth API 访问蓝牙功能的权限.这些 ...

  3. 基于Android Studio的蓝牙通信的简单应用与开发

    实现基于Android Studio的蓝牙通信的简单应用与开发 实现蓝牙通信 界面展示 核心文件 部分代码展示 总结 实现蓝牙通信 通过权限申请与代码实现,完成蓝牙通信的简单应用与开发. 界面展示 核 ...

  4. ”WinForm上位机+OV7670摄像头+STM32+蓝牙“图像采集系统(二)PC-MCU蓝牙通信及WinForm上位机开发

    上篇Blog谈了一下stm32驱动ov7670进行图像采集,这一篇谈一下后续的几个步骤: 1.图像处理 因为对图像质量要求不高,而且串口蓝牙通信速度局限于波特率.所以决定只传输灰度图像,简单地用了RG ...

  5. AndroidStudio蓝牙通信

    文章目录 一.功能需求 二.页面布局设置 1. 中间列表list_item.xml布局 2. activity_main.xml 三.页面跳转控制(java文件) 1. MainActivity.ja ...

  6. 基于java的信访项目_基于web系统的信访设计与开发.doc

    基于web系统的信访设计与开发 毕业设计 题 目 基于web系统的信访设计与开发 英文题目 Design and Development of visit Website 学生姓名: 学 号: 专 业 ...

  7. STM32CubeIDE开发(二十五), 物联网应用之stm32的蓝牙通信设计

    一.蓝牙通信技术 蓝牙技术是一种点对点点对面的网络构架,他可以在限制的范围内以很快的速度传输网络数据,在物联网应用中,支持网状网络的物联网短距离无线通信.目前它还被广泛用于智能可穿戴设备.智能门锁.智 ...

  8. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  9. Android Studio开发之蓝牙通信

    安卓开发-蓝牙通信 功能需求:在微信程序的第一子项中完成"蓝牙聊天功能" 开发步骤: 配置文件注册 设计界面布局 编写用于蓝牙会话的服务组件ChatService 分别建立供主Ac ...

  10. 蓝牙聊天App设计3:Android Studio制作蓝牙聊天通讯软件(完结,蓝牙连接聊天,结合生活情景进行蓝牙通信的通俗讲解,以及代码功能实现,内容详细,讲解通俗易懂)

    前言:蓝牙聊天App设计全部有三篇文章(一.UI界面设计,二.蓝牙搜索配对连接实现,三.蓝牙连接聊天),这篇文章是:三.蓝牙连接聊天. 课程1:Android Studio小白安装教程,以及第一个An ...

最新文章

  1. 阿里古谦:阿里互联网架构的6大最佳实践-博客-云栖社区-阿里云
  2. python3.7安装pip问题_python3.7安装, 解决pip is configured with locations that require TLS/SSL问题...
  3. 互动整合营销_今天,我们谈谈展会的整合营销!
  4. ie 9 渐变背景色兼容问题
  5. vb鼠标涂鸦板的制作
  6. mysql 设计两个主键都不可重复_18个MySQL面试题剖析(答案解析),听说身为程序员的你还没掌握...
  7. python 常用包_Python常用指引
  8. VS Tools for AI全攻略
  9. python生成pdf文档_使用Python生成pdf文件
  10. 颜值实力派—打造MySQL运行监控环境
  11. 关于 iOS 证书,你必须了解的知识
  12. 【clickhouse】clickhouse 解析器
  13. docker centos7 安装ssh
  14. 还在纠结是否入手M1 macbook?看完这篇文章再做决定也不迟!
  15. Delphi接入科大讯飞语音合成SDK
  16. 深入浅出 Python Decorators
  17. 小学五年级计算机课评课,小学生信息技术课《复制与变换》评课稿
  18. python 完全背包问题_完全背包问题及Python代码实现
  19. proteus仿真微型计算机,微机原理与接口技术——基于8086和Proteus仿真(第3版)...
  20. windows无法访问指定设备路径或文件

热门文章

  1. 九种常见的数据分析模型
  2. 【机器学习】课程设计布置:某闯关类手游用户流失预测
  3. 电路交换、报文交换、分组交换、异步传输模式等通信交换技术的区别
  4. SFDC Lightning Performance Tuning
  5. Java_定义一个圆类,提供输出面积和周长的方法,定义一个测试类使用
  6. java实现pdf 转 高清图片
  7. #10064. 「一本通 3.1 例 1」黑暗城堡
  8. 深度学习之美(张玉宏)——第三章 机器学习三重门
  9. 实现网站的-浏览器的favicon.ico
  10. 多个excel工作簿合并_Microsoft Excel如何快速合并多个工作簿至一个工作簿中?