前言

最近看了下蓝牙耳机连接的问题,查阅了相关资料,再此做一个总结。

本文参考以下链接:

Android实现主动连接蓝牙耳机

再次对作者表示感谢。

今天涉及的内容有:

流程讲解

新建广播BluetoothReceiver,用于监听处理蓝牙连接过程中各状态

在MainActivity中调用

注意的点

效果图

下面做以讲解

一. 流程讲解

在实现蓝牙耳机链接的时候,需要做一些前期工作,第一步,判断设备是否支持蓝牙。

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 checkDevices() {

List devices=new ArrayList<>();

if(mBluetoothAdapter!=null){

Set 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("=======启动寻找新设备的异步线程失败=======");

}

}

}

然后便是进行蓝牙耳机的配对,连接。

以上基本的蓝牙方法,我已经封装到BluetoothManager类中。

在蓝牙耳机的搜索,配对,连接等过程中,我们需要新建一个广播,对各个过程做一个监听。

二. 新建广播BluetoothReceiver,用于监听处理蓝牙连接过程中各状态

下面给出BluetoothReceiver中主要代码:

@Override

public void onReceive(Context context, Intent intent){

LogUtil.i("=========蓝牙接收处理广播========"+intent.getAction());

BluetoothDevice device;

switch (intent.getAction()) {

case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:

switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {

case BluetoothA2dp.STATE_CONNECTING:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

LogUtil.i("device: " + device.getName() +" connecting");

break;

case BluetoothA2dp.STATE_CONNECTED:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

LogUtil.i("device: " + device.getName() +" connected");

mOnBluetoothListener.deviceConnected(device);

break;

case BluetoothA2dp.STATE_DISCONNECTING:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

LogUtil.i("device: " + device.getName() +" disconnecting");

break;

case BluetoothA2dp.STATE_DISCONNECTED:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

LogUtil.i("device: " + device.getName() +" disconnected");

break;

default:

break;

}

break;

case BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:

int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1);

switch (state) {

case BluetoothA2dp.STATE_PLAYING:

LogUtil.i("state: playing.");

break;

case BluetoothA2dp.STATE_NOT_PLAYING:

LogUtil.i("state: not playing");

break;

default:

LogUtil.i("state: unkown");

break;

}

break;

case BluetoothDevice.ACTION_FOUND:

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

int deviceClassType = device.getBluetoothClass().getDeviceClass();

//找到指定的蓝牙设备

if (deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET

|| deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES) {

LogUtil.i("Found device:" + device.getName()+" address:"+device.getAddress());

if(StringUtil.isNotEmpty(device.getName())){

//添加到设备列表

mOnBluetoothListener.deviceFound(device);

}

}else{//找到可用蓝牙

if(StringUtil.isNotEmpty(device.getName())){

LogUtil.i("=====Found device====11===" + device.getName()+" address:"+device.getAddress());

//添加到设备列表

mOnBluetoothListener.deviceFound(device);

}

}

break;

case BluetoothDevice.ACTION_BOND_STATE_CHANGED:

int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);

device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

switch (bondState){

case BluetoothDevice.BOND_BONDED: //配对成功

LogUtil.i("Device:"+device.getName()+" bonded.");

//取消搜索,连接蓝牙设备

mOnBluetoothListener.deviceBonded(device);

break;

case BluetoothDevice.BOND_BONDING:

LogUtil.i("Device:"+device.getName()+" bonding.");

break;

case BluetoothDevice.BOND_NONE:

LogUtil.i("Device:"+device.getName()+" not bonded.");

//不知道是蓝牙耳机的关系还是什么原因,经常配对不成功

//配对不成功的话,重新尝试配对

mOnBluetoothListener.deviceBondNone(device);

break;

default:

break;

}

break;

case BluetoothAdapter.ACTION_STATE_CHANGED:

state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);

switch (state) {

case BluetoothAdapter.STATE_TURNING_ON:

LogUtil.i("BluetoothAdapter is turning on.");

break;

case BluetoothAdapter.STATE_ON:

LogUtil.i("BluetoothAdapter is on.");

// //蓝牙已打开,开始搜索并连接service

// findBluetoothDevice();

// getBluetoothA2DP();

mOnBluetoothListener.blootoothStateOn();

break;

case BluetoothAdapter.STATE_TURNING_OFF:

LogUtil.i("BluetoothAdapter is turning off.");

break;

case BluetoothAdapter.STATE_OFF:

LogUtil.i("BluetoothAdapter is off.");

break;

}

break;

default:

break;

}

}

三. 在MainActivity中调用

3.1 初始化时注册广播,扫描设备列表

//注册广播

registerReceiver();

//初始化设备列表

initDeviceList();

//发现新设备

findDevices();

其中registerReceiver方法为:

/**注册广播**/

private void registerReceiver(){

mBluetoothReceiver=new BluetoothReceiver();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);

filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);

filter.addAction(BluetoothDevice.ACTION_FOUND);

filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

mContext.registerReceiver(mBluetoothReceiver, filter);

}

findDevices方法为:

/**发现新设备**/

private void findDevices(){

if(BluetoothManager.getInstance().isSupportBluetooth()&&BluetoothManager.getInstance().isBluetoothOpen()){

//强制打开蓝牙

BluetoothManager.getInstance().openBluetooth();

Listlist=BluetoothManager.getInstance().checkDevices();

LogUtil.i("====list=====list=="+list.size());

Iterator it = list.iterator();

while (it.hasNext()) {

BluetoothDevice device = it.next();

if (device != null&& StringUtil.isEmpty(device.getName())) {

it.remove();

}

}

mDevices.addAll(list);

myAdapter.notifyDataSetChanged();

}

}

3.2 点击设备列表去连接蓝牙耳机或者开启蓝牙扫描

myAdapter.setOnRecyclerItemClickListener(new MyAdapter.OnRecyclerItemClickListener() {

@Override

public void onRecyclerClick(View view, int position) {

BluetoothDevice device= mDevices.get(position);

if(!BluetoothManager.getInstance().isSupportBluetooth()){

ToastUtil.showShortToast(mContext,"本设备不支持蓝牙");

return;

}

if(!BluetoothManager.getInstance().isBluetoothOpen()){

//去启动蓝牙

BluetoothManager.getInstance().requestStartBluetooth(REQUEST_ENABLE_BT,mContext);

}else{

LogUtil.i("====开始配对=======");

//绑定BluetoothA2DP,获得service

BluetoothManager.getInstance().getBluetoothA2DP(mContext);

//开始配对

BluetoothManager.getInstance().createBond(device);

}

}

});

3.3 关闭资源

退出app的时候需要关闭蓝牙耳机连接

//注销蓝牙链接

BluetoothManager.getInstance().disableAdapter();

注销广播

//注销广播

if(mBluetoothReceiver!=null){

mContext.unregisterReceiver(mBluetoothReceiver);

}

当然,你还可以考虑是否需要关闭蓝牙

//关闭蓝牙

BluetoothManager.getInstance().closeBluetooth();

四. 注意的点

蓝牙耳机的连接需要蓝牙权限,所以你得在你的mainfast.xml中以下权限设置:

五. 效果图

5.gif

ok,今天的内容就讲到这里,谢谢。

android 蓝牙耳机 判断,Android实现蓝牙耳机连接相关推荐

  1. android 连接蓝牙耳机 播放音乐,android 手机怎么实现和蓝牙耳机建立连接,连接之后可以听音乐...

    如题,手机和蓝牙耳机配对之后,怎么建立连接 解决方案 20 BluetoothA2dpService是底层的Service类,你可以通过BluetoothA2dp类来使用它 android.bluet ...

  2. android 连接已配对蓝牙耳机,连接/配对蓝牙耳机和Android

    我想创建一个简单的程序,扫描蓝牙耳机(我正在测试一个PS3耳机),然后连接到它.我正在使用bluetooth chat program example中的代码.但是我无法将它连接到任何东西.当它到达c ...

  3. Android Audio和耳机,蓝牙耳机等音频外设

    文章目录 Android Audio和耳机,蓝牙耳机等音频外设 蓝牙连接处理 广播接收 AudioManager接口 Listener监听 蓝牙耳机和AudioService的交互 蓝牙的状态 A2D ...

  4. android 蓝牙耳机 sco,Android:通过Sco蓝牙耳机播放声音

    在过去的几天里,我一直试图从我的Android手机上播放我的sco蓝牙耳机上的任何声音 . 我这个项目的最终目标是最终制作一个车库门开启器,但首先我需要能够通过耳机播放声音 . 这是我正在使用的当前代 ...

  5. android中怎么网络判断,Android中判断网络是否连接实例详解

    Android中判断网络是否连接实例详解 在android中,如何监测网络的状态呢,这个有的时候也是十分重要的,方法如下: public class ConnectionDetector { priv ...

  6. Android之判断网络状态(网络的连接,改变,和判断2G/3G/4G)

    现在app大多都需要从网络上获得数据.所以访问网络是在所难免.但是再访问网络之前,我们应该先做一下网络的状态判断.其实在访问网络之前我们要做一些状态判断,对应一些状态判断来做处理,并不是直接使用Htt ...

  7. Android之判断设备网络连接状态,并判断连接方式

    在Android开发过程中,对于一个需要连接网络的Android设备,对设备的网络状态检测是很有必要的!有很多的App都需要连接网络.判断设备是否已经连接网络,并且在连接网络的状态下判断是wifi无线 ...

  8. android进入wifi权限,判断android设备wifi连接状态,判断android设备wifi,添加访问权限(Andro...

    判断android设备wifi连接状态,判断android设备wifi,添加访问权限(Andro 添加访问权限(AndroidManifest.xml文件里) ```Java代码(MainActivi ...

  9. android 耳机 录音,Android 蓝牙耳机录音以及蓝牙耳机播放

    此文是借鉴于CSDN 某大牛博客改进之后的代码 首先, 要保证蓝牙设备的链接,可用手机直接蓝牙设备进行连接,连接的代码不写了 如蓝牙耳机已开启则直接运行以下步骤 1. 实例化 录音对象Recorder ...

最新文章

  1. mysql union 优化_mysql 5.7.3 对union all 的优化
  2. 一次 sql 优化经历,太有趣了!
  3. 【LeetCode】0938. 二叉搜索树的范围和(二叉树的遍历)
  4. SpringBoot中@EventListener注解的使用
  5. 解决This picacion faied to trt becuse t could, not find or load the Qt platform plugin “windows““问题
  6. 关于动态修改定时器的时间间隔
  7. 力扣——寻找两个有序数组的中位数
  8. python可选参数定义_c#教程之定义可选参数
  9. java 时间序列预测_基于spark的时间序列预测包Sparkts._的使用
  10. java mm_Java网络编程-你是GG还是MM?
  11. python之生成器-generator
  12. 不做etl sql 怎么直接取_我们可以不再使用ETL了吗?
  13. ArcGis for JavaScript 4.23版本接入国家天地矢量地图
  14. 前端常见开发英语单词大全
  15. 所有小米机型 解BT+刷Magisk并ROOT+躲避应用ROOT环境检查教程
  16. Linux中的preempt_count
  17. 怎么在windows笔记本使用html,笔记本上快捷键用不了 笔记本电脑上音量键用不了了...
  18. Python 斐波那契数列 及 杨辉三角
  19. [转载]NFC功能介绍
  20. Maven项目自动更新/修复Javadoc

热门文章

  1. mysql oracle 查询语句执行顺序_MySQL sql语句执行顺序
  2. pandas DataFrame isin
  3. es python demo
  4. 用scikit-learn学习K-Means聚类
  5. java set 包含_关于Java的Set的集合是否包括问题,如下为什么不包括?
  6. 77. Leetcode 1439. 有序矩阵中的第 k 个最小数组和 (堆-技巧二-多路归并)
  7. Leetcode 322. 零钱兑换 (每日一题 20210824)
  8. toch_geometric 笔记:message passing GCNConv
  9. tableau可视化数据分析60讲(十七)-tableau常用可视化视图(凹凸图甘特图直方图)
  10. Python编程基础:第五十一节 将函数赋值给变量Assign Functions to Variables