最近时间比较宽裕,觉得自己可以写一些东西来总结一下工作,索性就写一篇关于安卓蓝牙的开发总结吧
安卓蓝牙开发其实也就是socket的开发,同时分为服务端和客户端,下面我就按照我的开发流程来降整个的安卓蓝牙2.0开发叙述一下,蓝牙4.0BLE我也会在之后给大家更新
首先,我们要注册蓝牙相关的广播并在manifest中给出相应的权限(安卓6.0之后由于相应的底层改变,注册权限的时候不仅要给蓝牙的权限,还要给相应的位置权限),我在这里只为大家提供相应的广播,权限自己百度吧哈哈:
if
(BluetoothDevice.
ACTION_FOUND
.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.
EXTRA_DEVICE
);
//额外的设备
if
(BluetoothAdapter.
ACTION_DISCOVERY_FINISHED
.equals(action)) {
setSupportProgressBarIndeterminateVisibility(
false
);
setTitle(
"请选择要连接的设备"
);
if
(
mPairedDevicesArrayAdapter
.getCount() ==
0
) {
String noDevices = getResources().getText(R.string.
none_found
).toString();
mPairedDevicesArrayAdapter
.add(noDevices);//当没有设备的时候
pairedListView
.setEnabled(
false
);
}
}
之后我们需要获得蓝牙模块的mac地址和模块名,所以我们要进行蓝牙设备的查找,在查找界面中 我们使用BluetoothAdapter这个适配器来存储我们搜索的设备,使用Set集合来降获得的设备进行存储通过for循环来循环出手机搜索到的所有设备,代码如下
Set
<BluetoothDevice> pairedDevices =
mBtAdapter
.getBondedDevices();
得到的设备名称和设备地址
for
(BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter
.add(device.getName() +
"( "
+ getResources().getText(R.string.
has
) +
" )"
+
"
\n
"
+ device.getAddress());
}
之后我们会将得到的设备传递到我们的主界面当中,传递使用Intent(感觉是废话)代码如下: