Android蓝牙开发深入解析

1. 使用蓝牙的响应权限

代码如下:

<uses-permission android:name="android.permission.BLUETOOTH" />

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2. 配置本机蓝牙模块

在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter

代码如下:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

//直接打开系统的蓝牙设置面板

Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(intent, 0x1);

//直接打开蓝牙 adapter.enable();

//关闭蓝牙 adapter.disable();

//打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)

Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);

//设置持续时间(最多300秒)

3.搜索蓝牙设备

使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备

startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。

请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:

ACTION_DISCOVERY_START:开始搜索

ACTION_DISCOVERY_FINISHED:搜索结束

ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。

我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能

代码如下:

// 创建一个接收ACTION_FOUND广播的

BroadcastReceiver

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

// 发现设备

if (BluetoothDevice.ACTION_FOUND.equals(action)) {

// 从Intent中获取设备对象

BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

// 将设备名称和地址放入array adapter,以便在ListView中显示

mArrayAdapter.add(device.getName() + "\n" + device.getAddress());

}

}

};

// 注册BroadcastReceiver

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定

4. 蓝牙Socket通信

如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。

服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incoming connection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMM channel来获取的。

服务器端的实现

通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)

调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)

如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket)

代码如下:

private class AcceptThread extends Thread {

private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {

// Use a temporary object that is later assigned to mmServerSocket,

// because mmServerSocket is final

BluetoothServerSocket tmp = null;

try {

// MY_UUID is the app‘s UUID string, also used by the client code

tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);

} catch (IOException e) { }

mmServerSocket = tmp;

}

public void run() {

BluetoothSocket socket = null;

// Keep listening until exception occurs or a socket is returned

while (true) {

try {

socket = mmServerSocket.accept();

} catch (IOException e) {

break;

}

// If a connection was accepted

if (socket != null) {

// Do work to manage the connection (in a separate thread)

manageConnectedSocket(socket);

mmServerSocket.close();

break;

}

}

}

/** Will cancel the listening socket, and cause the thread to finish */

public void cancel() {

try {

mmServerSocket.close();

} catch (IOException e) { }

}

}

客户端的实现 通过搜索得到服务器端的BluetoothService

调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)

调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回

注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败

代码如下:

private class ConnectThread extends Thread {

private final BluetoothSocket mmSocket;

private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {

// Use a temporary object that is later assigned to mmSocket,

// because mmSocket is final

BluetoothSocket tmp = null;

mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice

try {

// MY_UUID is the app‘s UUID string, also used by the server code

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

} catch (IOException e) { }

mmSocket = tmp;

}

public void run() {

// Cancel discovery because it will slow down the connection

mBluetoothAdapter.cancelDiscovery();

try {

// Connect the device through the socket. This will block

// until it succeeds or throws an exception

mmSocket.connect();

} catch (IOException connectException) {

// Unable to connect; close the socket and get out

try {

mmSocket.close();

} catch (IOException closeException) { }

return;

}

// Do work to manage the connection (in a separate thread)

manageConnectedSocket(mmSocket);

}

/** Will cancel an in-progress connection, and close the socket */

public void cancel() {

try {

mmSocket.close();

} catch (IOException e) { }

}

}

连接管理(数据通信)
分别通过BluetoothSocket的getInputStream()和getOutputStream()方法获取InputStream和OutputStream

使用read(bytes[])和write(bytes[])方法分别进行读写操作

注意:read(bytes[])方法会一直block,知道从流中读取到信息,而write(bytes[])方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)

代码如下:

private class ConnectedThread extends Thread {

private final BluetoothSocket mmSocket;

private final InputStream mmInStream;

private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {

mmSocket = socket;

InputStream tmpIn = null;

OutputStream tmpOut = null;

// Get the input and output streams, using temp objects because

// member streams are final

try {

tmpIn = socket.getInputStream();

tmpOut = socket.getOutputStream();

} catch (IOException e) { }

mmInStream = tmpIn;

mmOutStream = tmpOut;

}

public void run() {

byte[] buffer = new byte[1024];

// buffer store for the stream

int bytes;

// bytes returned from read()

// Keep listening to the InputStream until an exception occurs

while (true) {

try {                 // Read from the InputStream

bytes = mmInStream.read(buffer);

// Send the obtained bytes to the UI Activity

mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget();

} catch (IOException e) {

break;

}

}

}

/* Call this from the main Activity to send data to the remote device */

public void write(byte[] bytes) {

try {

mmOutStream.write(bytes);

} catch (IOException e) { }

}

/* Call this from the main Activity to shutdown the connection */

public void cancel() {

try {

mmSocket.close();

} catch (IOException e) { }

}

}

时间: 2024-08-25 11:10:13

Android蓝牙开发深入解析的相关文章

如何实现android蓝牙开发 自动配对连接,并不弹出提示框

如何实现android蓝牙开发 自动配对连接,并不弹出提示框 之前做一个android版的蓝牙,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就开始查找怎么关闭这个蓝牙配对提示框,后面还是伟大的android源码帮助了我. 在源码 BluetoothDevice 类中还有两个隐藏方法 cancelBondProcess()和cancelPairingUserInput() 这两个方法一个是取消配对进

Android蓝牙开发的一些经验

转载请注明来自:http://blog.csdn.net/icyfox_bupt/article/details/25487125 最近在实验室做项目,使用了Android的蓝牙开发,这里面有好多坑..所以还是希望能记下来这些东西和大家分享,不要再走我的老路了. 先说一下背景,我是开发手机与带蓝牙的智能设备(蓝牙血压计.血糖仪.手环等)设备对接的APP.也就是说,在设备端没有什么可以操作的,手机负责发起数据传输. 蓝牙连接,不需要配对 由于被曾经使用蓝牙的思路所误导,一直以为使用蓝牙是必须一个配

Android蓝牙开发

Android蓝牙开发 近期做蓝牙小车,须要Android端来控制小车的运动.以此文记录开发过程. 使用HC-06无线蓝牙串口透传模块.对于其它的蓝牙设备本文相同适用. 蓝牙开发的流程: 获取本地蓝牙适配器    -->     打开蓝牙    -->    搜索设备  -->   连接设备  -->   发送信息 首先为了避免以往我们先写入蓝牙权限: <uses-permission android:name="android.permission.BLUETOO

Android蓝牙开发入门

目录: 1. 蓝牙简史,现状 2. 蓝牙的应用场景 3. 蓝牙相关概念 4. Android蓝牙开发 1. 蓝牙简史: 蓝牙( Bluetooth)是一种无线技术标准,可以实现短距离(通常是几米范围之内)的无线通信.蓝牙技术始于1994年,迄今已经发展了超过20年.本质上它和其它几种射频通信技术类似,比如手机移动通信,近场通信技术(NFC),都是通过电磁波来实现不同设备的信息交换.区别在于无线电波的频率和发射功率不一样,从而传输距离也不一样. 2. 蓝牙的应用场景: l 移动电话和免提设备之间的

Android蓝牙开发,报BluetoothAdapter﹕ Can&#39;t create handler inside thread that has not called Looper.prepare

这个错误翻译的意思是:不能在没有Looper.prepare的线程里面创建handler. 起初我很疑惑,我根本没有用到工作线程,也没有创建handler.报错的代码如下: // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final Blu

Android蓝牙开发开源框架 代码案例

这篇文章我早早就想写了,一直忘记了.之前一开始开发Android就搞蓝牙开发,好头大!研究了半个月才能搞定.现在自己整理出了蓝牙开发框架,这框架比较简单,不过希望能帮助蓝牙开发的朋友们.当然个人技术很菜,不足之处请指导. 蓝牙开步骤: 1.了解,蓝牙API共有五个类,其中需要撑握三个类: BluetoothAdapter(蓝牙适配器):该类主要获取蓝牙信息,比较打开蓝牙.获取本机mac地址.配对的蓝牙信息.等等; BluetoothDevice(蓝牙设备):如果连接非安卓设备,该类主要是初始服务

Android 蓝牙开发

此例子基于 Android demo 对于一般的软件开发人员来说,蓝牙是很少用到的,尤其是Android的蓝牙开发,国内的例子很少     Android对于蓝牙开发从2.0版本的sdk才开始支持,而且模拟器不支持,测试至少需要两部手机,所以制约了很多技术人员的开发:    鉴于很多开发人员现在也有蓝牙开发的需求,也为了大家少走些弯路,先将我积攒的一点点在Android蓝牙开发经验与大家分享一下! 首先,要操作蓝牙,先要在AndroidManifest.xml里加入权限 <uses-permis

Android 蓝牙开发之搜索、配对、连接、通信大全

        蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最多可以同时和7个其它蓝牙设备建立连接,进 行通信,当然并不是每一个蓝牙都可以达到最大值.下面,我们从蓝牙的基本概念开始,一步一步开始了解蓝牙. 基本概念: 安卓平台提供对蓝牙的通讯栈的支持,允许设别和其他的设备进行无线传输数据.应用程序层通过安卓API来调用蓝牙的相关功 能,这些API使程序无线连接

【转】android蓝牙开发---与蓝牙模块进行通信--不错

原文网址:http://www.cnblogs.com/wenjiang/p/3200138.html 近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝牙模块进行通信.开头的进展很顺利,但因为蓝牙模块不在我这里,所以只能用手机测试.一开头就发现手机的蓝牙不能用,为了证明这点,我刷了四次不同不同系统的官方包,正式宣布手机的蓝牙报销了,于是和朋友换手机.在测试的过程中也是非常痛苦,放假了,同学都几乎回家了,剩下的同学中竟然80%都是用非android手机!我和我的小伙伴都吓呆了!!就算