Android對于藍(lán)牙開發(fā)從2.0版本的sdk才開始支持,而且模擬器不支持,測試至少需要兩部手機(jī),所以制約了很多技術(shù)人員的開發(fā)。
1. 首先,要操作藍(lán)牙,先要在AndroidManifest.xml里加入權(quán)限
// 管理藍(lán)牙設(shè)備的權(quán)限
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" />
// 使用藍(lán)牙設(shè)備的權(quán)限
<uses-permissionandroid:name="android.permission.BLUETOOTH" />
2.打開藍(lán)牙
獲得藍(lán)牙適配器(android.bluetooth.BluetoothAdapter),檢查該設(shè)備是否支持藍(lán)牙,如果支持,就打開藍(lán)牙。
[java]
// 檢查設(shè)備是否支持藍(lán)牙
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null)
{
// 設(shè)備不支持藍(lán)牙
}
// 打開藍(lán)牙
if (!adapter.isEnabled())
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 設(shè)置藍(lán)牙可見性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(intent);
}
// 檢查設(shè)備是否支持藍(lán)牙
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null)
{
// 設(shè)備不支持藍(lán)牙
}
// 打開藍(lán)牙
if (!adapter.isEnabled())
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 設(shè)置藍(lán)牙可見性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
context.startActivity(intent);
}
3.獲取已配對的藍(lán)牙設(shè)備(android.bluetooth.BluetoothDevice)
首次連接某藍(lán)牙設(shè)備需要先配對,一旦配對成功,該設(shè)備的信息會被保存,以后連接時(shí)無需再配對,所以已配對的設(shè)備不一定是能連接的。
[java]
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for(int i=0; i<devices.size(); i++)
{
BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
System.out.println(device.getName());
}
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for(int i=0; i<devices.size(); i++)
{
BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
System.out.println(device.getName());
}
4.搜索周圍的藍(lán)牙設(shè)備
適配器搜索藍(lán)牙設(shè)備后將結(jié)果以廣播形式傳出去,所以需要自定義一個(gè)繼承廣播的類,在onReceive方法中獲得并處理藍(lán)牙設(shè)備的搜索結(jié)果。
[java]
// 設(shè)置廣播信息過濾
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注冊廣播接收器,接收并處理搜索結(jié)果
context.registerReceiver(receiver, intentFilter);
// 尋找藍(lán)牙設(shè)備,android會將查找到的設(shè)備以廣播形式發(fā)出去
adapter.startDiscovery();
// 設(shè)置廣播信息過濾
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注冊廣播接收器,接收并處理搜索結(jié)果
context.registerReceiver(receiver, intentFilter);
// 尋找藍(lán)牙設(shè)備,android會將查找到的設(shè)備以廣播形式發(fā)出去
adapter.startDiscovery(); 自定義廣播類
[java]
private BroadcastReceiver receiver = 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);
System.out.println(device.getName());
}
}
}
private BroadcastReceiver receiver = 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);
System.out.println(device.getName());
}
}
}
5.藍(lán)牙設(shè)備的配對和狀態(tài)監(jiān)視
[java]
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 獲取查找到的藍(lán)牙設(shè)備
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
// 如果查找到的設(shè)備符合要連接的設(shè)備,處理
if (device.getName().equalsIgnoreCase(name)) {
// 搜索藍(lán)牙設(shè)備的過程占用資源比較多,一旦找到需要連接的設(shè)備后需要及時(shí)關(guān)閉搜索
adapter.cancelDiscovery();
// 獲取藍(lán)牙設(shè)備的連接狀態(tài)
connectState = device.getBondState();
switch (connectState) {
// 未配對
case BluetoothDevice.BOND_NONE:
// 配對
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配對
case BluetoothDevice.BOND_BONDED:
try {
// 連接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 狀態(tài)改變的廣播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equalsIgnoreCase(name)) {
connectState = device.getBondState();
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
try {
// 連接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 獲取查找到的藍(lán)牙設(shè)備
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println(device.getName());
// 如果查找到的設(shè)備符合要連接的設(shè)備,處理
if (device.getName().equalsIgnoreCase(name)) {
// 搜索藍(lán)牙設(shè)備的過程占用資源比較多,一旦找到需要連接的設(shè)備后需要及時(shí)關(guān)閉搜索
adapter.cancelDiscovery();
// 獲取藍(lán)牙設(shè)備的連接狀態(tài)
connectState = device.getBondState();
switch (connectState) {
// 未配對
case BluetoothDevice.BOND_NONE:
// 配對
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配對
case BluetoothDevice.BOND_BONDED:
try {
// 連接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 狀態(tài)改變的廣播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equalsIgnoreCase(name)) {
connectState = device.getBondState();
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
try {
// 連接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
} 6.藍(lán)牙設(shè)備的連接
[java]
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}
本篇文章來源于 Linux公社網(wǎng)站(www.linuxidc.com) 原文鏈接:http://www.linuxidc.com/Linux/2011-12/48374.htm
1.BluetoothAdapter 顧名思義,藍(lán)牙適配器,直到我們建立bluetoothSocket連接之前,都要不斷操作它
BluetoothAdapter里的方法很多,常用的有以下幾個(gè):
cancelDiscovery() 根據(jù)字面意思,是取消發(fā)現(xiàn),也就是說當(dāng)我們正在搜索設(shè)備的時(shí)候調(diào)用這個(gè)方法將不再繼續(xù)搜索
disable()關(guān)閉藍(lán)牙
enable()打開藍(lán)牙,這個(gè)方法打開藍(lán)牙不會彈出提示,更多的時(shí)候我們需要問下用戶是否打開,一下這兩行代碼同樣是打開藍(lán)牙,不過會提示用戶:
Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler,reCode);//同startActivity(enabler);
getAddress()獲取本地藍(lán)牙地址
getDefaultAdapter()獲取默認(rèn)BluetoothAdapter,實(shí)際上,也只有這一種方法獲取BluetoothAdapter
getName()獲取本地藍(lán)牙名稱
getRemoteDevice(String address)根據(jù)藍(lán)牙地址獲取遠(yuǎn)程藍(lán)牙設(shè)備
getState()獲取本地藍(lán)牙適配器當(dāng)前狀態(tài)(感覺可能調(diào)試的時(shí)候更需要)
isDiscovering()判斷當(dāng)前是否正在查找設(shè)備,是返回true
isEnabled()判斷藍(lán)牙是否打開,已打開返回true,否則,返回false
listenUsingRfcommWithServiceRecord(String name,UUID uuid)根據(jù)名稱,UUID創(chuàng)建并返回BluetoothServerSocket,這是創(chuàng)建BluetoothSocket服務(wù)器端的第一步
startDiscovery()開始搜索,這是搜索的第一步
2.BluetoothDevice看名字就知道,這個(gè)類描述了一個(gè)藍(lán)牙設(shè)備
createRfcommSocketToServiceRecord(UUIDuuid)根據(jù)UUID創(chuàng)建并返回一個(gè)BluetoothSocket
這個(gè)方法也是我們獲取BluetoothDevice的目的——?jiǎng)?chuàng)建BluetoothSocket
這個(gè)類其他的方法,如getAddress(),getName(),同BluetoothAdapter
3.BluetoothServerSocket如果去除了Bluetooth相信大家一定再熟悉不過了,既然是Socket,方法就應(yīng)該都差不多,
這個(gè)類一種只有三個(gè)方法
兩個(gè)重載的accept(),accept(inttimeout)兩者的區(qū)別在于后面的方法指定了過時(shí)時(shí)間,需要注意的是,執(zhí)行這兩個(gè)方法的時(shí)候,直到接收到了客戶端的請求(或是過期之后),都會阻塞線程,應(yīng)該放在新線程里運(yùn)行!
還有一點(diǎn)需要注意的是,這兩個(gè)方法都返回一個(gè)BluetoothSocket,最后的連接也是服務(wù)器端與客戶端的兩個(gè)BluetoothSocket的連接
close()這個(gè)就不用說了吧,翻譯一下——關(guān)閉!
4.BluetoothSocket,跟BluetoothServerSocket相對,是客戶端
一共5個(gè)方法,不出意外,都會用到
close(),關(guān)閉
connect()連接
getInptuStream()獲取輸入流
getOutputStream()獲取輸出流
getRemoteDevice()獲取遠(yuǎn)程設(shè)備,這里指的是獲取bluetoothSocket指定連接的那個(gè)遠(yuǎn)程藍(lán)牙設(shè)備