




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Android BLE与终端通信(三)客户端与服务端通信过程以及实现数据通信一.蓝牙数据传输蓝牙数据传输其实跟我们的 Socket(套接字)有点类似,如果有不懂的,可以百度一下概念,我们只要知道是这么回事就可以了,在网络中使用Socket和ServerSocket控制客户端和服务端来数据读写。而蓝牙通讯也是由客户端和服务端来完成的,蓝牙客户端Socket是BluetoothSocket,蓝牙服务端Socket是BluetoothServerSocket,这两个类都在Android.bluetooth包下,而且无论是BluetoothSocket还是BluetoothServerSocket,我
2、们都需要一个UUID(标识符),这个UUID在上篇也是有提到,而且他的格式也是固定的:UUID:XXXXXXXX(8)-XXXX(4)-XXXX(4)-XXXX(4)-XXXXXXXXXXXX(12)第一段是8位,中间三段式4位,最后一段是12位,UUID相当于Socket的端口,而蓝牙地址则相当于Socket的IP1.activity_main.xml<LinearLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_heig
3、ht="match_parent" android:orientation="vertical" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="btnSearch" android:text="搜索蓝牙设备" /> <ListView android:id="+id/lvDevices&qu
4、ot; android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /></LinearLayout>2.实现步骤1.声明我们需要的东西 / 本地蓝牙适配器 private BluetoothAdapter mBluetoothAdapter; / 列表 private ListView lvDevices; / 存储搜索到的蓝牙 private List<String> bluetoo
5、thDevices = new ArrayList<String>(); / listview的adapter private ArrayAdapter<String> arrayAdapter; / UUID.randomUUID()随机获取UUID private final UUID MY_UUID = UUID .fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3"); / 连接对象的名称 private final String NAME = "LGL" / 这里本身即是服务
6、端也是客户端,需要如下类 private BluetoothSocket clientSocket; private BluetoothDevice device; / 输出流_客户端需要往服务端输出 private OutputStream os;2.初始化/ 获取本地蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); / 判断手机是否支持蓝牙 if (mBluetoothAdapter = null) Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SH
7、ORT).show(); finish(); / 判断是否打开蓝牙 if (!mBluetoothAdapter.isEnabled() / 弹出对话框提示用户是后打开 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 1); / 不做提示,强行打开 / mBluetoothAdapter.enable(); / 初始化listview lvDevices = (ListView) findViewById(R.id.lvDevices); lvD
8、evices.setOnItemClickListener(this); / 获取已经配对的设备 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter .getBondedDevices(); / 判断是否有配对过的设备 if (pairedDevices.size() > 0) for (BluetoothDevice device : pairedDevices) / 遍历到列表中 bluetoothDevices.add(device.getName() + ":" + device.getAd
9、dress() + "n"); / adapter arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothDevices); lvDevices.setAdapter(arrayAdapter); /* * 异步搜索蓝牙设备广播接收 */ / 找到设备的广播 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
10、 / 注册广播 registerReceiver(receiver, filter); / 搜索完成的广播 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); / 注册广播 registerReceiver(receiver, filter); 3.点击搜索public void btnSearch(View v) / 设置进度条 setProgressBarIndeterminateVisibility(true); setTitle("正在搜索."); / 判断是否在搜索,如果在搜
11、索,就取消搜索 if (mBluetoothAdapter.isDiscovering() mBluetoothAdapter.cancelDiscovery(); / 开始搜索 mBluetoothAdapter.startDiscovery(); 4.搜索设备private final BroadcastReceiver receiver = new BroadcastReceiver() Override public void onReceive(Context context, Intent intent) / 收到的广播类型 String action = intent.getAc
12、tion(); / 发现设备的广播 if (BluetoothDevice.ACTION_FOUND.equals(action) / 从intent中获取设备 BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); / 判断是否配对过 if (device.getBondState() != BluetoothDevice.BOND_BONDED) / 添加到列表 bluetoothDevices.add(device.getName() + ":" + devi
13、ce.getAddress() + "n"); arrayAdapter.notifyDataSetChanged(); / 搜索完成 else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED .equals(action) / 关闭进度条 setProgressBarIndeterminateVisibility(true); setTitle("搜索完成!"); ;5.客户端实现已经发送数据流 / 客户端 Override public void onItemClick(AdapterView<?&
14、gt; parent, View view, int position, long id) / 先获得蓝牙的地址和设备名 String s = arrayAdapter.getItem(position); / 单独解析地址 String address = s.substring(s.indexOf(":") + 1).trim(); / 主动连接蓝牙 try / 判断是否在搜索,如果在搜索,就取消搜索 if (mBluetoothAdapter.isDiscovering() mBluetoothAdapter.cancelDiscovery(); try / 判断是否
15、可以获得 if (device = null) / 获得远程设备 device = mBluetoothAdapter.getRemoteDevice(address); / 开始连接 if (clientSocket = null) clientSocket = device .createRfcommSocketToServiceRecord(MY_UUID); / 连接 clientSocket.connect(); / 获得输出流 os = clientSocket.getOutputStream(); catch (Exception e) / TODO: handle except
16、ion / 如果成功获得输出流 if (os != null) os.write("Hello Bluetooth!".getBytes("utf-8"); catch (Exception e) / TODO: handle exception 6.Handler服务/ 服务端,需要监听客户端的线程类 private Handler handler = new Handler() public void handleMessage(android.os.Message msg) Toast.makeText(MainActivity.this, Str
17、ing.valueOf(msg.obj), Toast.LENGTH_SHORT).show(); super.handleMessage(msg); ;7.服务端读取数据流/ 线程服务类 private class AcceptThread extends Thread private BluetoothServerSocket serverSocket; private BluetoothSocket socket; / 输入 输出流 private OutputStream os; private InputStream is; public AcceptThread() try ser
18、verSocket = mBluetoothAdapter .listenUsingRfcommWithServiceRecord(NAME, MY_UUID); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace(); Override public void run() / 截获客户端的蓝牙消息 try socket = serverSocket.accept(); / 如果阻塞了,就会一直停留在这里 is = socket.getInputStream(); os = socket.getOu
19、tputStream(); / 不断接收请求,如果客户端没有发送的话还是会阻塞 while (true) / 每次只发送128个字节 byte buffer = new byte128; / 读取 int count = is.read(); / 如果读取到了,我们就发送刚才的那个Toast Message msg = new Message(); msg.obj = new String(buffer, 0, count, "utf-8"); handler.sendMessage(msg); catch (Exception e) / TODO: handle exce
20、ption 8.开启服务首先要声明 /启动服务 ac = new AcceptThread(); ac.start();MainActivity完整代码package com.lgl.bluetoothget;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.UUID;import android.app.Ac
21、tivity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothServerSocket;import android.bluetooth.BluetoothSocket;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.conte
22、nt.IntentFilter;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAd
23、apter;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity implements OnItemClickListener / 本地蓝牙适配器 private BluetoothAdapter mBluetoothAdapter; / 列表 private ListView lvDevices; / 存储搜索到的蓝牙 pri
24、vate List<String> bluetoothDevices = new ArrayList<String>(); / listview的adapter private ArrayAdapter<String> arrayAdapter; / UUID.randomUUID()随机获取UUID private final UUID MY_UUID = UUID .fromString("db764ac8-4b08-7f25-aafe-59d03c27bae3"); / 连接对象的名称 private final String NA
25、ME = "LGL" / 这里本身即是服务端也是客户端,需要如下类 private BluetoothSocket clientSocket; private BluetoothDevice device; / 输出流_客户端需要往服务端输出 private OutputStream os; /线程类的实例 private AcceptThread ac; Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView
26、(R.layout.activity_main); initView(); private void initView() / 获取本地蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); / 判断手机是否支持蓝牙 if (mBluetoothAdapter = null) Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show(); finish(); / 判断是否打开蓝牙 if (!mBluetoothAdapter.isEnabled()
27、 / 弹出对话框提示用户是后打开 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 1); / 不做提示,强行打开 / mBluetoothAdapter.enable(); / 初始化listview lvDevices = (ListView) findViewById(R.id.lvDevices); lvDevices.setOnItemClickListener(this); / 获取已经配对的设备 Set<BluetoothDev
28、ice> pairedDevices = mBluetoothAdapter .getBondedDevices(); / 判断是否有配对过的设备 if (pairedDevices.size() > 0) for (BluetoothDevice device : pairedDevices) / 遍历到列表中 bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "n"); / adapter arrayAdapter = new ArrayAdapter&
29、lt;String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothDices); lvDevices.setAdapter(arrayAdapter); /启动服务 ac = new AcceptThread(); ac.start(); /* * 异步搜索蓝牙设备广播接收 */ / 找到设备的广播 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); / 注册广播 registerReceiver(re
30、ceiver, filter); / 搜索完成的广播 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); / 注册广播 registerReceiver(receiver, filter); public void btnSearch(View v) / 设置进度条 setProgressBarIndeterminateVisibility(true); setTitle("正在搜索."); / 判断是否在搜索,如果在搜索,就取消搜索 if (mBluetoothAdapter.isD
31、iscovering() mBluetoothAdapter.cancelDiscovery(); / 开始搜索 mBluetoothAdapter.startDiscovery(); / 广播接收器 private final BroadcastReceiver receiver = new BroadcastReceiver() Override public void onReceive(Context context, Intent intent) / 收到的广播类型 String action = intent.getAction(); / 发现设备的广播 if (Bluetooth
32、Device.ACTION_FOUND.equals(action) / 从intent中获取设备 BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); / 判断是否配对过 if (device.getBondState() != BluetoothDevice.BOND_BONDED) / 添加到列表 bluetoothDevices.add(device.getName() + ":" + device.getAddress() + "n"
33、); arrayAdapter.notifyDataSetChanged(); / 搜索完成 else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED .equals(action) / 关闭进度条 setProgressBarIndeterminateVisibility(true); setTitle("搜索完成!"); ; / 客户端 Override public void onItemClick(AdapterView<?> parent, View view, int position, long id)
34、 / 先获得蓝牙的地址和设备名 String s = arrayAdapter.getItem(position); / 单独解析地址 String address = s.substring(s.indexOf(":") + 1).trim(); / 主动连接蓝牙 try / 判断是否在搜索,如果在搜索,就取消搜索 if (mBluetoothAdapter.isDiscovering() mBluetoothAdapter.cancelDiscovery(); try / 判断是否可以获得 if (device = null) / 获得远程设备 device = mBl
35、uetoothAdapter.getRemoteDevice(address); / 开始连接 if (clientSocket = null) clientSocket = device .createRfcommSocketToServiceRecord(MY_UUID); / 连接 clientSocket.connect(); / 获得输出流 os = clientSocket.getOutputStream(); catch (Exception e) / TODO: handle exception / 如果成功获得输出流 if (os != null) os.write("Hello Bluetooth!&qu
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 西北民族大学《妇产科学床边教学》2023-2024学年第一学期期末试卷
- 汕头大学《证券市场基本法》2023-2024学年第二学期期末试卷
- 2025年益阳市数学五下期末学业水平测试试题含答案
- 小学生春季疾病防控知识
- 思维导图集训6小时找到适合你的高效学习法第1讲 思维导图在预习中的应用
- 大学生性别教育
- 上海市奉贤区2025届高三高考二模地理试卷(含答案)
- 2025《房地产经纪专业基础》备考提升核心试题库-500题
- 云南省卫生健康系统事业单位招聘-药学类近年考试真题库(含答案)
- 教育销售培训资料
- 饭店转包合同
- 人教版音乐九下第二单元《梨园风采(二)》夫妻双双把家还教案
- 执法办案和执法监督注意事项课件
- 高档汽车租赁合同书
- 小学急救知识PPT模板
- 2023年新版新汉语水平考试五级HSK真题
- 《交变电流》说课一等奖课件
- 小学英语三年级英语绘本阅读公开课Dear-zoo优质课件
- JJG 141-2013工作用贵金属热电偶
- GB/T 32161-2015生态设计产品评价通则
- GB/T 1852-2008船用法兰铸钢蒸汽减压阀
评论
0/150
提交评论