蓝牙设备
一.蓝牙介绍:
二.蓝牙的作用:
三 .蓝牙工作原理以及涉及到的类:
四.蓝牙客户端代码:
五.蓝牙服务端代码:
一.蓝牙介绍:
是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换,我们主要掌握这几项技能:
添加权限:
打开蓝牙并设置允许被搜索
//调用系统开关蓝牙弹窗->用户手动允许
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);//开启蓝
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);//允许蓝牙被搜索
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);//设置允许被搜索时间200s内可以被搜索到
startActivityForResult(intent,100);
关闭蓝牙
bluetoothAdapter.disable();//强制关闭蓝牙
搜索附近的蓝牙
bluetoothAdapter.startDiscovery();//搜索
配对蓝牙:
bluetoothDevice.createBond();//发起配对
获得已经配对的蓝牙设备:
- adapter.getBondedDevices();
使用蓝牙传输数据:socket和ServerSocket传输数据
//1.获得客户端Socket
BluetoothSocket socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
socket.connect();
//2.获得服务端Socket
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(bluetoothAdapter.getName(),uuid);
serverSocket.accpet();
二.蓝牙的作用:
三 .蓝牙工作原理以及涉及到的类:
BluetoothManager 蓝牙管理类,管理BluetoothAdapter。主要负责管理蓝牙的本地连接。
BluetoothAdapter 蓝牙适配器类:代表本蓝牙设备
BluetoothDevice 蓝牙设备,配对后的远程蓝牙设备.
BluetoothServiceSocket 服务端连接类
BluetoothSocket:客户端连接类
UUID(universal unique identifier , 全局唯一标识符)
格式如下:UUID格式一般是”xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,可到http://www.uuidgenerator.com 申请。UUID分为5段,是一个8-4-4-4-12的字符串,这个字符串要求永不重复。蓝牙建立连接时双方必须使用固定的UUID
例如:文件传输服务
OBEXFileTransferServiceClass_UUID = ‘{00001106-0000-1000-8000-00805F9B34FB}’
四.蓝牙客户端代码:
如何区分客户端和服务端?如果设备A连接设备B 那么A就是客户端,B就是服务端。
客户端功能:打开蓝牙/关闭蓝牙/搜索附近蓝牙设备/点击其中一个建立连接
(0)添加权限:
1 (1)MainActivity代码:public class MainActivity extends AppCompatActivity implements View.OnClickListener,MainAdapter.OnItemClick{
private Button mStart,mStop,mSearch;