Android学习之蓝牙操作
BluetoothAdapter 用法
蓝牙运行原理:通过BluetoothAdapter 蓝牙适配器处理任务,如果蓝牙被启动之后,系统会自动去搜索其它设备,如果匹配到附近的设备就发送一个广播,BroadcastRecevier的onReceive被调用一次,我们只需要在onReceive中处理自己的操作即可。
- <uses-permission android:name="android.permission.BLUETOOTH"/>
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
2.启动蓝牙 首先要查看本机是否支持蓝牙,获取BluetoothAdapter蓝牙适配器对象
- BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if(mBluetoothAdapter == null){
- //表明此手机不支持蓝牙
- return;
- }
- if(!mBluetoothAdapter.isEnabled()){ //蓝牙未开启,则开启蓝牙
- Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
- }
- //......
- public void onActivityResult(int requestCode, int resultCode, Intent data){
- if(requestCode == REQUEST_ENABLE_BT){
- if(requestCode == RESULT_OK){
- //蓝牙已经开启
- }
- }
- }
3。发现蓝牙设备 这里可以细分为几个方面 (1)使本机蓝牙处于可见(即处于易被搜索到状态),便于其他设备发现本机蓝牙
- //使本机蓝牙在300秒内可被搜索
- private void ensureDiscoverable() {
- if (mBluetoothAdapter.getScanMode() !=
- BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
- Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
- discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
- startActivity(discoverableIntent);
- }
- }
(2)查找已经配对的蓝牙设备,即以前已经配对过的设备
- Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
- if (pairedDevices.size() > 0) {
- findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
- for (BluetoothDevice device : pairedDevices) {
- //device.getName() +" "+ device.getAddress());
- }
- } else {
- mPairedDevicesArrayAdapter.add("没有找到已匹对的设备");
- }
(3)通过mBluetoothAdapter.startDiscovery();搜索设备,要获得此搜索的结果需要注册 一个BroadcastReceiver来获取。先注册再获取信息,然后处理
- //注册,当一个设备被发现时调用onReceive
- IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
- this.registerReceiver(mReceiver, filter);
- //当搜索结束后调用onReceive
- filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
- this.registerReceiver(mReceiver, filter);
- //.......
- private BroadcastReceiver mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if(BluetoothDevice.ACTION_FOUND.equals(action)){
- BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
- // 已经配对的则跳过
- if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
- mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); //保存设备地址与名字
- }
- }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //搜索结束
- if (mNewDevicesArrayAdapter.getCount() == 0) {
- mNewDevicesArrayAdapter.add("没有搜索到设备");
- }
- }
- }
- };
4.建立连接 查找到设备 后,则需要建立本机与其他设备之间的连接。 一般用本机搜索其他蓝牙设备时,本机可以作为一个服务端,接收其他设备的连接。 启动一个服务器端的线程,死循环等待客户端的连接,这与ServerSocket极为相似。 这个线程在准备连接之前启动
- //UUID可以看做一个端口号
- private static final UUID MY_UUID =
- UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
- //像一个服务器一样时刻监听是否有连接建立
- private class AcceptThread extends Thread{
- private BluetoothServerSocket serverSocket;
- public AcceptThread(boolean secure){
- BluetoothServerSocket temp = null;
- try {
- temp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
- NAME_INSECURE, MY_UUID);
- } catch (IOException e) {
- Log.e("app", "listen() failed", e);
- }
- serverSocket = temp;
- }
- public void run(){
- BluetoothSocket socket=null;
- while(true){
- try {
- socket = serverSocket.accept();
- } catch (IOException e) {
- Log.e("app", "accept() failed", e);
- break;
- }
- }
- if(socket!=null){
- //此时可以新建一个数据交换线程,把此socket传进去
- }
- }
- //取消监听
- public void cancel(){
- try {
- serverSocket.close();
- } catch (IOException e) {
- Log.e("app", "Socket Type" + socketType + "close() of server failed", e);
- }
- }
- }
搜索到设备后可以获取设备的地址,通过此地址获取一个BluetoothDeviced对象,可以看做客户端,通过此对象device.createRfcommSocketToServiceRecord(MY_UUID);同一个UUID可与服务器建立连接获取另一个socket对象,由此服务端与客户端各有一个socket对象,此时 他们可以互相交换数据了。 创立客户端socket可建立线程
- //另一个设备去连接本机,相当于客户端
- private class ConnectThread extends Thread{
- private BluetoothSocket socket;
- private BluetoothDevice device;
- public ConnectThread(BluetoothDevice device,boolean secure){
- this.device = device;
- BluetoothSocket tmp = null;
- try {
- tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
- } catch (IOException e) {
- Log.e("app", "create() failed", e);
- }
- }
- public void run(){
- mBluetoothAdapter.cancelDiscovery(); //取消设备查找
- try {
- socket.connect();
- } catch (IOException e) {
- try {
- socket.close();
- } catch (IOException e1) {
- Log.e("app", "unable to close() "+
- " socket during connection failure", e1);
- }
- connetionFailed(); //连接失败
- return;
- }
- //此时可以新建一个数据交换线程,把此socket传进去
- }
- public void cancel() {
- try {
- socket.close();
- } catch (IOException e) {
- Log.e("app", "close() of connect socket failed", e);
- }
- }
- }
5.建立数据通信线程,进行读取数据
- //建立连接后,进行数据通信的线程
- private class ConnectedThread extends Thread{
- private BluetoothSocket socket;
- private InputStream inStream;
- private OutputStream outStream;
- public ConnectedThread(BluetoothSocket socket){
- this.socket = socket;
- try {
- //获得输入输出流
- inStream = socket.getInputStream();
- outStream = socket.getOutputStream();
- } catch (IOException e) {
- Log.e("app", "temp sockets not created", e);
- }
- }
- public void run(){
- byte[] buff = new byte[1024];
- int len=0;
- //读数据需不断监听,写不需要
- while(true){
- try {
- len = inStream.read(buff);
- //把读取到的数据发送给UI进行显示
- Message msg = handler.obtainMessage(BluetoothChat.MESSAGE_READ,
- len, -1, buff);
- msg.sendToTarget();
- } catch (IOException e) {
- Log.e("app", "disconnected", e);
- connectionLost(); //失去连接
- start(); //重新启动服务器
- break;
- }
- }
- }
- public void write(byte[] buffer) {
- try {
- outStream.write(buffer);
- // Share the sent message back to the UI Activity
- handler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
- .sendToTarget();
- } catch (IOException e) {
- Log.e("app", "Exception during write", e);
- }
- }
- public void cancel() {
- try {
- socket.close();
- } catch (IOException e) {
- Log.e("app", "close() of connect socket failed", e);
- }
- }
- }
到这里,蓝牙通信的基本操作已经全部完成。
Android学习之蓝牙操作的更多相关文章
- android学习日记09--BitMap操作
Bitmap android里的图像处理重要的类,支持jpg.png.bmp等格式的图像,BitmapDrawable是封装Bitmap的一个对象,Bitmap实现在android.graphics包 ...
- Android学习之Image操作及时间日期选择器
一.基础学习 1.ImageView是图片容器,就相当于RadioGroup是RadioButton的容器一样,是View的直接子类. 1: <ImageView 2: android:id=& ...
- 转载 ----Android学习笔记 - 蓝牙篇 (Bluetooth)
1.什么是蓝牙 Bluetooth是目前使用的最广泛的无线通讯协议之一 主要针对短距离设备通讯(10米) 常用于连接耳机.鼠标和移动通讯设备等 2.发现周围蓝牙设备 BluetoothAd ...
- 九、Android学习第八天——广播机制与WIFI网络操作(转)
(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 九.Android学习第八天——广播机制与WIFI网络操作 今天熟悉了An ...
- Android – 学习操作NFC – 2
在<Android – 学习操作NFC – 1>说明了Android在处理NFC tag的机制.tag dispatch system的运作流程,以及三种ACTION_NDEF_DISCO ...
- Android端简易蓝牙聊天通讯App(原创)
欢迎转载,但请注明出处!谢谢.http://www.cnblogs.com/weizhxa/p/5792775.html 最近公司在做一个蓝牙串口通讯的App,有一个固定的蓝牙设备,需要实现手机连接相 ...
- Android 学习笔记之网络通信基础+WebView....
PS:加快学习进度...下周一完成Android网络通信...然后正式进入实战... 学习内容: 1.Android中Http基础... 2.Android中的Socket基础... 3.Androi ...
- 最全的android学习资料
一.开发环境搭建 (已完成) 负责人:kris 状态:已完成 所整理标签为:搭建 SDK JDK NDK Eclipse ADT 模拟器 AVD 调试器(DEBUG) DDMS 测试 日志 Logca ...
- Android学习——windows下搭建NDK_r9环境
1. NDK(Native Development Kit) 1.1 NDK简介 Android NDK是一套允许开发人员使用本地代码(如C/C++)进行Android APP功能开发的工具,通过这个 ...
随机推荐
- c递归程序
递归 long recursin(int); void main() { int n; long result; printf("input a integer number: \n&quo ...
- 使用Eclipse的JUnit实例
在本节中,我们将展示使用JUnit的一个完整的例子.我们将详细了解如何创建和运行测试,我们将展示如何使用特定的注释和JUnit断言. 1. 初始步骤 让我们创建一个名为 JUnitGuide 的Jav ...
- jpa无外键配置
在用jpa这种orm框架时,有时我们实体对象存在关联关系,但实际的业务场景可能不需要用jpa来控制数据库创建数据表之间的关联约束,这时我们就需要消除掉数据库表与表之间的外键关联.但jpa在处理建立外键 ...
- LAMP一体环境快速安装
(一)安装Apache 1.下载安装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 yum install zlib-devel -y wget http://m ...
- js 去掉重复数组
js去掉重复数组 重点一:字符串转数组 strArr.join(',') 重点二:做循环数组删除的时候,每次循环就把color[i] 去对比i之前所有数组color组合起来的字符串 比如 : i=1 ...
- 本文将详细介绍oracle 10g OEM常规错误
本文将详细介绍oracle 10g OEM常规错误-------Unknown host specified解决方法,需要了解的朋友可以参考下 详细出处参考:http://www.jb51.net/a ...
- Java编程思想学习笔记——字符串
前言 字符串操作是计算机程序设计中最常见的行为. 不可变String String对象是不可变的 重载"+"与StringBuilder String对象是不可变的,可以给Stri ...
- 分页功能实现之通过ajax实现表单内容刷新
拿代码来说话 我们的需求就是点击翻页功能,实现表格内容局部刷新且能够翻到对应的页面上,不明白? 那么就看看下面的图,需要达到的效果如下所示: 现在要实现的功能就是把红线框起来的表单内容 在点击翻页的时 ...
- Sublime text2插件
Sublime插件: Sublime有好几种安装插件的方法,但是最好用也是最长用的是ctrl+shift+p. 第一步: 使用ctrl+` 调出Sublime控制台,在控制台中输入 import ur ...
- [mysql] Incorrect string value: '\xE4\xBC\x9A\xE5\x91\x98' for column 'name' at row 1
数据库字符集错误, 修改为UTF8/utf8mb4字符集即可.