前言
讲讲android对于蓝牙耳机连接技术的实现
今天涉及的内容有:
1. 流程讲解
2. 新建广播BluetoothReceiver,用于监听处理蓝牙连接过程中各状态
3. 在MainActivity中调用
4. 注意的点
5. 项目结构图和效果图
下面做以讲解
一. 流程讲解
在实现蓝牙耳机链接的时候,需要做一些前期工作,第一步,判断设备是否支持蓝牙。
1.1 设备是否支持蓝牙
/**设备是否支持蓝牙**/
public boolean isSupportBluetooth() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
return true;
}
return false;
}
若支持蓝牙,则需要判断设备蓝牙是否打开
1.2 设备蓝牙是否开启
/**蓝牙是否已经启动**/
public boolean isBluetoothOpen() {
if (mBluetoothAdapter != null) {
return mBluetoothAdapter.isEnabled();
}
return false;
}
如果蓝牙没有开启,则需要请求开启蓝牙
1.3 请求开启蓝牙
/**请求启动蓝牙**/
public void requestStartBluetooth(int requestCode,Context context) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
((MainActivity)context).startActivityForResult(enableBtIntent, requestCode);
}
当然,蓝牙还有一个强制开启的方法:
/**强制打开蓝牙**/
public void openBluetooth(){
if(isSupportBluetooth()){
mBluetoothAdapter.enable();
}
}
蓝牙开启后,接下来是查询已配对过的设备
1.3 获取配对过的设备列表
/**查询配对设备**/
public List<BluetoothDevice> checkDevices() {
List<BluetoothDevice> devices=new ArrayList<>();
if(mBluetoothAdapter!=null){
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices != null && pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
devices.add(device);
}
}
}
return devices;
}
若已配对列表中没有你的蓝牙耳机设备,则需要搜索
1.4 搜索新设备
/**发现新设备**/
public void findBluetoothDevice() {
//其实是启动了一个异步线程,该方法将立即返回一个布尔值,指示发现是否已成功启动。
// 发现过程通常涉及大约12秒的查询扫描,随后是每个找到的设备的页面扫描以检索其蓝牙名称
if(mBluetoothAdapter!=null && mBluetoothAdapter.isEnabled() && !mBluetoothAdapter.isDiscovering()){
if (mBluetoothAdapter.startDiscovery()) {
LogUtil.i("=======已成功启动寻找新设备的异步线程=======");
} else {
LogUtil.i("=======启动寻找新设备的异步线程失败=======");
}
}
}