完整demo地址:github

1.打开蓝牙:

      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();/**如果本地蓝牙没有开启,则开启*/if (!mBluetoothAdapter.isEnabled()) {// 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择,比如用户单击了Yes开启,// 那么将会收到RESULT_OK的结果,// 如果RESULT_CANCELED则代表用户不愿意开启蓝牙Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(mIntent, ENABLE_BLUE);} else {Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();}

监听打开的结果:

    @Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == ENABLE_BLUE) {if (resultCode == RESULT_OK) {Toast.makeText(this, "蓝牙开启成功", Toast.LENGTH_SHORT).show();getBondedDevices();} else if (resultCode == RESULT_CANCELED) {Toast.makeText(this, "蓝牙开始失败", Toast.LENGTH_SHORT).show();}} else {}}

2.关闭蓝牙:

     /**关闭蓝牙*/if (mBluetoothAdapter.isEnabled()) {mBluetoothAdapter.disable();}

3.设计蓝牙为可见:

     Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 180);//180可见时间startActivity(intent);

4.收索蓝牙:

注册广播监听搜索的结果:

     /**注册搜索蓝牙receiver*/mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);mFilter.addAction(BluetoothDevice.ACTION_FOUND);mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);registerReceiver(mReceiver, mFilter);

开始的搜索:

     // 如果正在搜索,就先取消搜索if (mBluetoothAdapter.isDiscovering()) {mBluetoothAdapter.cancelDiscovery();}// 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回mBluetoothAdapter.startDiscovery();

监听搜索的结果:

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();/** 搜索到的蓝牙设备*/if (action.equals(BluetoothDevice.ACTION_FOUND)) {BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);// 搜索到的不是已经配对的蓝牙设备if (device.getBondState() != BluetoothDevice.BOND_BONDED) {BlueDevice blueDevice = new BlueDevice();blueDevice.setName(device.getName());blueDevice.setAddress(device.getAddress());blueDevice.setDevice(device);setDevices.add(blueDevice);blueAdapter.setSetDevices(setDevices);blueAdapter.notifyDataSetChanged();Log.d(MAINACTIVITY, "搜索结果......"+device.getName());}/**当绑定的状态改变时*/} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {/**搜索完成*/} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {setProgressBarIndeterminateVisibility(false);Log.d(MAINACTIVITY, "搜索完成......");hideProgressDailog();}}};

5.配对蓝牙:

配对工具类

    public class BlueUtils {public BlueUtils(BlueDevice blueDevice) {this.blueDevice = blueDevice;}/*** 配对*/public void doPair() {if(null == mOthHandler){HandlerThread handlerThread = new HandlerThread("other_thread");handlerThread.start();mOthHandler = new Handler(handlerThread.getLooper());}mOthHandler.post(new Runnable() {@Overridepublic void run() {initSocket();   //取得sockettry {socket.connect();   //请求配对//                      mAdapterManager.updateDeviceAdapter();} catch (IOException e) {e.printStackTrace();}}});}/*** 取消蓝牙配对* @param device*/public static void unpairDevice(BluetoothDevice device) {try {Method m = device.getClass().getMethod("removeBond", (Class[]) null);m.invoke(device, (Object[]) null);} catch (Exception e) {Log.d("BlueUtils", e.getMessage());}}/*** 取得BluetoothSocket*/private void initSocket() {BluetoothSocket temp = null;try {Method m = blueDevice.getDevice().getClass().getMethod("createRfcommSocket", new Class[] {int.class});temp = (BluetoothSocket) m.invoke(blueDevice.getDevice(), );//怪异错误: 直接赋值给socket,对socket操作可能出现异常,  要通过中间变量temp赋值给socket} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}socket = temp;}}

注册监听配对结果的广播(使用同上面的注册代码)

     /**注册搜索蓝牙receiver*/mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);mFilter.addAction(BluetoothDevice.ACTION_FOUND);mFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);registerReceiver(mReceiver, mFilter);

开始配对

    /*** 开始配对蓝牙设备** @param blueDevice*/private void startPariBlue(BlueDevice blueDevice) {BlueUtils blueUtils = new BlueUtils(blueDevice);blueUtils.doPair();}

监听配对结果:(使用同上面的广播接收者)

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();/** 搜索到的蓝牙设备*/if (action.equals(BluetoothDevice.ACTION_FOUND)) {...../**当绑定的状态改变时*/} else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);switch (device.getBondState()) {case BluetoothDevice.BOND_BONDING:Log.d(MAINACTIVITY, "正在配对......");break;case BluetoothDevice.BOND_BONDED:Log.d(MAINACTIVITY, "完成配对");hideProgressDailog();/**开始连接*/contectBuleDevices();break;case BluetoothDevice.BOND_NONE:Log.d(MAINACTIVITY, "取消配对");Toast.makeText(MainActivity.this,"成功取消配对",Toast.LENGTH_SHORT).show();getBondedDevices();break;default:break;}/**搜索完成*/} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {....}}};

6.使用A2DP协议连接蓝牙设备:

连接设备

    /*** 开始连接蓝牙设备*/private void contectBuleDevices() {/**使用A2DP协议连接设备*/mBluetoothAdapter.getProfileProxy(this, mProfileServiceListener, BluetoothProfile.A2DP);}

监听连接的回调

    /*** 连接蓝牙设备(通过监听蓝牙协议的服务,在连接服务的时候使用BluetoothA2dp协议)*/private BluetoothProfile.ServiceListener mProfileServiceListener = new BluetoothProfile.ServiceListener() {@Overridepublic void onServiceDisconnected(int profile) {}@Overridepublic void onServiceConnected(int profile, BluetoothProfile proxy) {try {if (profile == BluetoothProfile.HEADSET) {....} else if (profile == BluetoothProfile.A2DP) {/**使用A2DP的协议连接蓝牙设备(使用了反射技术调用连接的方法)*/a2dp = (BluetoothA2dp) proxy;if (a2dp.getConnectionState(currentBluetoothDevice) != BluetoothProfile.STATE_CONNECTED) {a2dp.getClass().getMethod("connect", BluetoothDevice.class).invoke(a2dp, currentBluetoothDevice);Toast.makeText(MainActivity.this,"请播放音乐",Toast.LENGTH_SHORT).show();getBondedDevices();}}} catch (Exception e) {e.printStackTrace();}}};

7.添加权限

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

8.打开乐库播放音乐

9.Android 6.0的系统需要动态添加权限才能搜索出蓝牙设备

Android 6.0的系统需要动态添加权限

    /**判断手机系统的版本*/if (Build.VERSION.SDK_INT >= 6.0) {//Build.VERSION.SDK_INT >= Build.VERSION_CODES.Mif(ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){/**动态添加权限:ACCESS_FINE_LOCATION*/ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSION_REQUEST_CONSTANT);}}

请求权限的回调

    /**请求权限的回调:这里判断权限是否添加成功*//**请求权限的回调:这里判断权限是否添加成功*/public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {switch (requestCode) {case MY_PERMISSION_REQUEST_CONSTANT: {if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {Log.i("main","添加权限成功");}return;}}}

Android 蓝牙音箱开发相关推荐

  1. Android 蓝牙通信开发

    Android 蓝牙通信开发 Receiver的设置 一.Receiver1(蓝牙状态的改变通过广播接收) 二.Receiver2(蓝牙搜索到设备.绑定设备(配对)通过广播接收) 服务端代码 客户端代 ...

  2. Android 蓝牙BLE开发详解

    Android 蓝牙BLE开发详解 由于年初接手了个有关蓝牙BLE的项目,开始了对蓝牙ble的学习,经过长时间的慢慢学习(学得太慢,太拖了),终于了解了该怎么写蓝牙BLE,现在就给大家分享一下. 一. ...

  3. Qt on Android 蓝牙通信开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  4. Android蓝牙BLE开发

    最近正在研究Android的蓝牙BLE开发学习,以下是自己做的个人总结 1.1何为BLE? 首先得说明什么是低功耗蓝牙BLE,BLE的全称为Bluetooth low energy(或称Blooth ...

  5. Android蓝牙手柄开发

    手柄相应的按键 摇杆监听(已连接状态) 通过google找到官方示例https://developer.android.com/training/game-controllers/controller ...

  6. Android 蓝牙Hid开发

    原文地址: https://blog.csdn.net/VNanyesheshou/article/details/61914974 Demo下载:http://www.demodashi.com/d ...

  7. Android蓝牙BLE开发(一)-基本原理

    公司有需求要做蓝牙BLE传输,经查阅后发现关于BLE开发的知识还真不多.对于BLE开发的同学来说,我的建议是先快速了解一下BLE的基本原理,磨刀不误砍柴工. 什么是BLE BLE全称Bluetooth ...

  8. android蓝牙通讯方法,Android蓝牙通信开发教程(详解版)

    Android 系统提供蓝牙 API 包 android.bluetooth,允许手机设备通过蓝牙与其他设备进行无线连接. Android 的蓝牙 API 可提供以下功能: 需要说明的是,Androi ...

  9. Android 蓝牙游戏开发(一)

    蓝牙4.0 据说是超低功耗,随之而来的是智能手表.手环.同屏对战塔防等.咱也了解了解相关的技术,做技术储备.今天需要总结的是蓝牙聊天的例子,例子来源于Android的官网.我们把关键的技术理一下. 关 ...

最新文章

  1. LeetCode-337 House Robber III
  2. roads 构筑极致用户体验_智美双极 引领旗舰 亚洲龙探索革新的高品质体验
  3. 如何自行给指定的SAP OData服务添加自定义日志记录功能
  4. 2016蓝桥杯省赛---java---B---2(生日蜡烛)
  5. 关于信噪比-draft
  6. cocos2D创建一组单选按钮菜单
  7. 【CSP201312-2】ISBN号码,字符串,简单模拟
  8. Chrome 插件PPAPI 开发(一)环境搭建
  9. Chrome DevTools 中键盘快捷键的参考。
  10. 转自汇编网: 高三老师给大一学生的一封信(感动!)
  11. wml 与服务器交互
  12. [MRCTF2020]Ez_bypass
  13. 计算机毕业设计基于asp.net网上考试报名系统——计算机毕业设计
  14. Java中使用zt-exec执行多shell/Linux命令,执行日志实时推送前端
  15. 复读机java群管脚本_JS让浏览器实现复读机的功能_js
  16. Unity移动端Input触控和Window触摸屏电脑 控制相机旋转缩放
  17. 拥抱开源,Vue Admin Work后台管理系统免费开源啦
  18. Nginx+Lua 实现灰度发布详细步骤
  19. 英特尔眼中的三大科技趋势
  20. js中的直接赋值和引用赋值

热门文章

  1. sublime text多文件夹查找关键字
  2. nginx+php+mysql环境
  3. asp.net mvc 简单文件下载
  4. @AuotoWired+@Qualifier(百度百科)
  5. 基于WinSvr2012共享文件夹的Hyper-V实时迁移之二文件服务器及迁移用虚拟机的创建...
  6. 开源 YDB 数据库
  7. 31 款轻量高效的开源 JavaScript 插件和库
  8. 50 家硅谷 IT 公司技术博客
  9. office文档 在线预览 (doc、ppt、xls)
  10. python爬知识星球付费数据_python抓取知识星球精选帖,制作为pdf文件