Android Bluetooth蓝牙开发:Bluetooth蓝牙设备配对Paired Bluetooth Devices(2)
Android Bluetooth蓝牙开发:Bluetooth蓝牙设备配对Paired Bluetooth Devices(2)
不同的Bluetooth进行配对时候,通常会显示如图所示的配对提示(前提是已经打开蓝牙设备且已经互相发现对方):
手机端:
电脑端:
图中所示例子是一个Android设备和一个PC(笔记本电脑)在进行蓝牙配对时候的对话。蓝牙设备在配对过程中,Android代码无法掌控,需要拥有该设备的用户手动操作完成配对过程。在配对完成后,Android上层Java代码即可遍历所有和当前设备已经配对的周围蓝牙设备。遍历代码比较简单:
package zhangphil.bluetooth;
import java.util.Set;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends ListActivity {
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 获得和当前Android已经配对的蓝牙设备。
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// 遍历
for (BluetoothDevice device : pairedDevices) {
// 把已经取得配对的蓝牙设备名字和地址打印出来。
Log.d("已经配对的蓝牙设备", device.getName() + " : " + device.getAddress());
}
}
}
}
配对完成,遍历已经配对的蓝牙设备,目的之一就是为了获得配对集合Set中的BluetoothDevice们,从中选取某一特定BluetoothDevice,从BluetoothDevice获得BluetoothSocket,取出输入输出流,进而进行数据传输。
从蓝牙配对集合中获取某一特定的BluetoothDevice进行数据传输,是Android蓝牙通信编程实现的其中一条途径,但并不是唯一途径。
蓝牙的权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
附录文章:
1,《Android Bluetooth蓝牙开发:发现Bluetooth蓝牙设备(1)》链接地址:http://blog.csdn.net/zhangphil/article/details/50524809
2,Android Bluetooth蓝牙开发Google官方文档链接地址:http://developer.android.com/intl/zh-cn/guide/topics/connectivity/bluetooth.html
还没有评论,来说两句吧...