Android蓝牙操作笔记
蓝牙是一种支持设备短距离传输数据的无线技术。android在2.0以后提供了这方面的支持。 
从查找蓝牙设备到能够相互通信要经过几个基本步骤(本机做为服务器): 
1.设置权限 
在manifest中配置
- <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蓝牙操作笔记(转)
		
蓝牙是一种支持设备短距离传输数据的无线技术.android在2.0以后提供了这方面的支持. 从查找蓝牙设备到能够相互通信要经过几个基本步骤(本机做为服务器): 1.设置权限 在manifest中配置 ...
 - Android蓝牙学习笔记
		
一 Bluetooth基本概念 蓝牙是无线数据和语音传输的开放式标准,它将各种通信设备.计算机及其终端设备.各种数字数据系统.甚至家用电器采用无线方式联接起来.它的传输距离为10cm-10m,如果增加 ...
 - Android 蓝牙操作详解
		
1.启用蓝牙并使设备处于可发现状态 1.1 在使用BluetoothAdapter类的实例进操作之前,应启用isEnable()方法检查设备是否启用了蓝牙适配器. // 使用意图提示 ...
 - Android蓝牙操作
		
1.添加蓝牙权限 <uses-permission android:name = "android.permission.BLUETOOTH"/> <!--启用应 ...
 - Android:日常学习笔记(10)———使用LitePal操作数据库
		
Android:日常学习笔记(10)———使用LitePal操作数据库 引入LitePal 什么是LitePal LitePal是一款开源的Android数据库框架,采用了对象关系映射(ORM)的模式 ...
 - Android群英传笔记——第一章:Android体系与系统架构
		
Android群英传笔记--第一章:Android体系与系统架构 图片都是摘抄自网络 今天确实挺忙的,不过把第一章的笔记做一下还是可以的,嘿嘿 1.1 Google的生态圈 还是得从Android的起 ...
 - Android自动化学习笔记:编写MonkeyRunner脚本的几种方式
		
---------------------------------------------------------------------------------------------------- ...
 - Android自动化学习笔记之MonkeyRunner:官方介绍和简单实例
		
---------------------------------------------------------------------------------------------------- ...
 - android蓝牙打印机
		
您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受 目录视图 摘要视图 订阅 CSDN2013 ...
 
随机推荐
- java的Serialization 机制
			
基本使用方法 Serialization是指把类或者基本的数据类型持久化(persistence)到数据流(Stream)中,包括文件.字节流.网络数据流. ...
 - hdu 4502 吉哥系列故事——临时工计划(dp)
			
题目:http://acm.hdu.edu.cn/showproblem.php?pid=4502 思路:一个简单的dp ,比赛时没做出来呢..... d[i]代表 到第i天时的最大值 #includ ...
 - poj 2418 Hardwood Species  (map)
			
题目:http://poj.org/problem?id=2418 在poj 上交题总是有各种错误,再次感叹各个编译器. c++ AC代码,G++为超时,上代码: #include<cstdio ...
 - 宏HASH_DELETE
			
HASH_DELETE(buf_page_t, hash, buf_pool->page_hash, fold, bpage); NAME 可理解为 void* next /********** ...
 - 【 D3.js 进阶系列 】 进阶总结
			
进阶系列的文章从去年10月开始写的,晃眼又是4个多月了,想在年前总结一下. 首先恭祝大家新年快乐.今年是羊年吧.前段时间和朋友聊天,聊到十二生肖里为什么没猫,我张口就道:不是因为十二生肖开会的时候猫迟 ...
 - [Bhatia.Matrix Analysis.Solutions to Exercises and Problems]ExI.2.7
			
The set of all invertible matrices is a dense open subset of the set of all $n\times n$ matrices. Th ...
 - Selenium webdriver 之select 控件封装,解决onchange问题
			
使用webdriver的时候,select 控件经常会绑定onchange 事件,在selenium2.09 之前click 方法对onchange 事件有bug,2.09 以后修复了,但是根据经验也 ...
 - 【暑假】[实用数据结构]UVAlive 3942 Remember the Word
			
UVAlive 3942 Remember the Word 题目: Remember the Word Time Limit: 3000MS Memory Limit: Unknown ...
 - 2014上海网络赛 HDU 5053 the Sum of Cube
			
水 #include <stdio.h> #include <stdlib.h> #include<math.h> #include<iostream> ...
 - mysql 清空表的两种方法
			
一.Delete DELETE FROM `table`; 二.Truncate TRUNCATE `table`; 第一种方法其实就是去掉where条件,没有了条件,也就是删除掉表里面的所有记录了: ...