Android实现蓝牙耳机连接

矫情吗;* 2022-05-12 08:26 639阅读 0赞

代码地址如下:
http://www.demodashi.com/demo/13259.html

前言

讲讲android对于蓝牙耳机连接技术的实现

今天涉及的内容有:

  1. 流程讲解
  2. 新建广播BluetoothReceiver,用于监听处理蓝牙连接过程中各状态
  3. 在MainActivity中调用
  4. 注意的点
  5. 项目结构图和效果图

下面做以讲解

一. 流程讲解

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

1.1 设备是否支持蓝牙
  1. /**设备是否支持蓝牙**/
  2. public boolean isSupportBluetooth() {
  3. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  4. if (mBluetoothAdapter != null) {
  5. return true;
  6. }
  7. return false;
  8. }

若支持蓝牙,则需要判断设备蓝牙是否打开

1.2 设备蓝牙是否开启
  1. /**蓝牙是否已经启动**/
  2. public boolean isBluetoothOpen() {
  3. if (mBluetoothAdapter != null) {
  4. return mBluetoothAdapter.isEnabled();
  5. }
  6. return false;
  7. }

如果蓝牙没有开启,则需要请求开启蓝牙

1.3 请求开启蓝牙
  1. /**请求启动蓝牙**/
  2. public void requestStartBluetooth(int requestCode,Context context) {
  3. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  4. ((MainActivity)context).startActivityForResult(enableBtIntent, requestCode);
  5. }

当然,蓝牙还有一个强制开启的方法:

  1. /**强制打开蓝牙**/
  2. public void openBluetooth(){
  3. if(isSupportBluetooth()){
  4. mBluetoothAdapter.enable();
  5. }
  6. }

蓝牙开启后,接下来是查询已配对过的设备

1.3 获取配对过的设备列表
  1. /**查询配对设备**/
  2. public List<BluetoothDevice> checkDevices() {
  3. List<BluetoothDevice> devices=new ArrayList<>();
  4. if(mBluetoothAdapter!=null){
  5. Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
  6. if (pairedDevices != null && pairedDevices.size() > 0) {
  7. for (BluetoothDevice device : pairedDevices) {
  8. devices.add(device);
  9. }
  10. }
  11. }
  12. return devices;
  13. }

若已配对列表中没有你的蓝牙耳机设备,则需要搜索

1.4 搜索新设备
  1. /**发现新设备**/
  2. public void findBluetoothDevice() {
  3. //其实是启动了一个异步线程,该方法将立即返回一个布尔值,指示发现是否已成功启动。
  4. // 发现过程通常涉及大约12秒的查询扫描,随后是每个找到的设备的页面扫描以检索其蓝牙名称
  5. if(mBluetoothAdapter!=null && mBluetoothAdapter.isEnabled() && !mBluetoothAdapter.isDiscovering()){
  6. if (mBluetoothAdapter.startDiscovery()) {
  7. LogUtil.i("=======已成功启动寻找新设备的异步线程=======");
  8. } else {
  9. LogUtil.i("=======启动寻找新设备的异步线程失败=======");
  10. }
  11. }
  12. }

然后便是进行蓝牙耳机的配对,连接。
以上基本的蓝牙方法,我已经封装到BluetoothManager类中。
在蓝牙耳机的搜索,配对,连接等过程中,我们需要新建一个广播,对各个过程做一个监听。

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

下面给出BluetoothReceiver中主要代码:

  1. @Override
  2. public void onReceive(Context context, Intent intent){
  3. LogUtil.i("=========蓝牙接收处理广播========"+intent.getAction());
  4. BluetoothDevice device;
  5. switch (intent.getAction()) {
  6. case BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED:
  7. switch (intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1)) {
  8. case BluetoothA2dp.STATE_CONNECTING:
  9. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  10. LogUtil.i("device: " + device.getName() +" connecting");
  11. break;
  12. case BluetoothA2dp.STATE_CONNECTED:
  13. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  14. LogUtil.i("device: " + device.getName() +" connected");
  15. mOnBluetoothListener.deviceConnected(device);
  16. break;
  17. case BluetoothA2dp.STATE_DISCONNECTING:
  18. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  19. LogUtil.i("device: " + device.getName() +" disconnecting");
  20. break;
  21. case BluetoothA2dp.STATE_DISCONNECTED:
  22. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  23. LogUtil.i("device: " + device.getName() +" disconnected");
  24. break;
  25. default:
  26. break;
  27. }
  28. break;
  29. case BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED:
  30. int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1);
  31. switch (state) {
  32. case BluetoothA2dp.STATE_PLAYING:
  33. LogUtil.i("state: playing.");
  34. break;
  35. case BluetoothA2dp.STATE_NOT_PLAYING:
  36. LogUtil.i("state: not playing");
  37. break;
  38. default:
  39. LogUtil.i("state: unkown");
  40. break;
  41. }
  42. break;
  43. case BluetoothDevice.ACTION_FOUND:
  44. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  45. int deviceClassType = device.getBluetoothClass().getDeviceClass();
  46. //找到指定的蓝牙设备
  47. if (deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET
  48. || deviceClassType == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES) {
  49. LogUtil.i("Found device:" + device.getName()+" address:"+device.getAddress());
  50. if(StringUtil.isNotEmpty(device.getName())){
  51. //添加到设备列表
  52. mOnBluetoothListener.deviceFound(device);
  53. }
  54. }else{//找到可用蓝牙
  55. if(StringUtil.isNotEmpty(device.getName())){
  56. LogUtil.i("=====Found device====11===" + device.getName()+" address:"+device.getAddress());
  57. //添加到设备列表
  58. mOnBluetoothListener.deviceFound(device);
  59. }
  60. }
  61. break;
  62. case BluetoothDevice.ACTION_BOND_STATE_CHANGED:
  63. int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
  64. device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  65. switch (bondState){
  66. case BluetoothDevice.BOND_BONDED: //配对成功
  67. LogUtil.i("Device:"+device.getName()+" bonded.");
  68. //取消搜索,连接蓝牙设备
  69. mOnBluetoothListener.deviceBonded(device);
  70. break;
  71. case BluetoothDevice.BOND_BONDING:
  72. LogUtil.i("Device:"+device.getName()+" bonding.");
  73. break;
  74. case BluetoothDevice.BOND_NONE:
  75. LogUtil.i("Device:"+device.getName()+" not bonded.");
  76. //不知道是蓝牙耳机的关系还是什么原因,经常配对不成功
  77. //配对不成功的话,重新尝试配对
  78. mOnBluetoothListener.deviceBondNone(device);
  79. break;
  80. default:
  81. break;
  82. }
  83. break;
  84. case BluetoothAdapter.ACTION_STATE_CHANGED:
  85. state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
  86. switch (state) {
  87. case BluetoothAdapter.STATE_TURNING_ON:
  88. LogUtil.i("BluetoothAdapter is turning on.");
  89. break;
  90. case BluetoothAdapter.STATE_ON:
  91. LogUtil.i("BluetoothAdapter is on.");
  92. // //蓝牙已打开,开始搜索并连接service
  93. // findBluetoothDevice();
  94. // getBluetoothA2DP();
  95. mOnBluetoothListener.blootoothStateOn();
  96. break;
  97. case BluetoothAdapter.STATE_TURNING_OFF:
  98. LogUtil.i("BluetoothAdapter is turning off.");
  99. break;
  100. case BluetoothAdapter.STATE_OFF:
  101. LogUtil.i("BluetoothAdapter is off.");
  102. break;
  103. }
  104. break;
  105. default:
  106. break;
  107. }
  108. }

三. 在MainActivity中调用

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

  1. //注册广播
  2. registerReceiver();
  3. //初始化设备列表
  4. initDeviceList();
  5. //发现新设备
  6. findDevices();

其中registerReceiver方法为:

  1. /**注册广播**/
  2. private void registerReceiver(){
  3. mBluetoothReceiver=new BluetoothReceiver();
  4. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  5. filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
  6. filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
  7. filter.addAction(BluetoothDevice.ACTION_FOUND);
  8. filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
  9. filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  10. mContext.registerReceiver(mBluetoothReceiver, filter);
  11. }

findDevices方法为:

  1. /**发现新设备**/
  2. private void findDevices(){
  3. if(BluetoothManager.getInstance().isSupportBluetooth()&&BluetoothManager.getInstance().isBluetoothOpen()){
  4. //强制打开蓝牙
  5. BluetoothManager.getInstance().openBluetooth();
  6. List<BluetoothDevice>list=BluetoothManager.getInstance().checkDevices();
  7. LogUtil.i("====list=====list=="+list.size());
  8. Iterator<BluetoothDevice> it = list.iterator();
  9. while (it.hasNext()) {
  10. BluetoothDevice device = it.next();
  11. if (device != null&& StringUtil.isEmpty(device.getName())) {
  12. it.remove();
  13. }
  14. }
  15. mDevices.addAll(list);
  16. myAdapter.notifyDataSetChanged();
  17. }
  18. }

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

  1. myAdapter.setOnRecyclerItemClickListener(new MyAdapter.OnRecyclerItemClickListener() {
  2. @Override
  3. public void onRecyclerClick(View view, int position) {
  4. BluetoothDevice device= mDevices.get(position);
  5. if(!BluetoothManager.getInstance().isSupportBluetooth()){
  6. ToastUtil.showShortToast(mContext,"本设备不支持蓝牙");
  7. return;
  8. }
  9. if(!BluetoothManager.getInstance().isBluetoothOpen()){
  10. //去启动蓝牙
  11. BluetoothManager.getInstance().requestStartBluetooth(REQUEST_ENABLE_BT,mContext);
  12. }else{
  13. LogUtil.i("====开始配对=======");
  14. //绑定BluetoothA2DP,获得service
  15. BluetoothManager.getInstance().getBluetoothA2DP(mContext);
  16. //开始配对
  17. BluetoothManager.getInstance().createBond(device);
  18. }
  19. }
  20. });

3.3 关闭资源

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

  1. //注销蓝牙链接
  2. BluetoothManager.getInstance().disableAdapter();

注销广播

  1. //注销广播
  2. if(mBluetoothReceiver!=null){
  3. mContext.unregisterReceiver(mBluetoothReceiver);
  4. }

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

  1. //关闭蓝牙
  2. BluetoothManager.getInstance().closeBluetooth();

四. 注意的点

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

  1. <uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

五. 项目结构图和效果图

项目结构图

6aEWsXpPLUg7mUke8Sy.png

运行效果图

o6eMLucno0cB3a7Hbc6.gif
Android实现蓝牙耳机连接

代码地址如下:
http://www.demodashi.com/demo/13259.html

注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

发表评论

表情:
评论列表 (有 0 条评论,639人围观)

还没有评论,来说两句吧...

相关阅读