59. Android平台的蓝牙编程在编程之前,需要在AndroidMainfest.xml中加入操作权限,代码如下:
1、获取本地蓝牙:
必须确定你的设备支持蓝牙,并保证他可以用。如果你的设备支持蓝牙,将它使能。当然,有两种方法,一种是在你的系统设置里开启蓝牙,另外一中是在你的应用程序里启动蓝牙功能,第一种方法就不讲了,具体讲一个第二种方法:
首先通过调用静态方法getDefaultAdapter()获取蓝牙适配器bluetoothadapter,以后你就可以使用该对象了。如果返回为空,则说明设备不支持蓝牙功能。
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}第七章 Android网络通信
60. Android平台的蓝牙编程 其次,调用isEnabled()来查询当前蓝牙设备的状态,如果返回为false,则表示蓝牙设备没有开启,接下来你需要封装一个ACTION_REQUEST_ENABLE请求到intent里面。例如:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
至此,如不出意外,恭喜你的蓝牙设备已经开启了,接下来需要查找周边可能存在的蓝牙设备了。第七章 Android网络通信
62. Android平台的蓝牙编程怎么查询匹配好的设备:
在建立连接之前你必须先查询配对好了的蓝牙设备集(你周围的蓝牙设备可能不止一个),以便你选取哪一个设备进行通信,例如你可以查询所有配对的蓝牙设备,并使用一个数组适配器将其打印显示出来:
SetpairedDevices=mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
建立一个蓝牙连接只需要MAC地址就已经足够了。第七章 Android网络通信