蓝牙配对-扫描-连接-状态查询
蓝牙通讯的主要操作路线 创建蓝牙适配器对象-扫描周围蓝牙设备-配对-连接完成之后通过蓝牙适配器对象通信 下一篇讲解
文章中有获取当前蓝牙设备链接状态的方法 低版本可能会出现配对没有连接成功的情况 可根据状态做出处理
首先申请权限
<uses-permission android:name="android.permission.BLUETOOTH" ></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" ></uses-permission>
创建BluetoothAdapter对象
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
扫描广播
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter1.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
intentFilter1.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(scanBlueReceiver, intentFilter1);
配对广播
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(pinBlueReceiver, intentFilter);
开启扫描
/**
- 扫描的方法 返回true 扫描成功
- 通过接收广播获取扫描到的设备
- @return
*/
public boolean scanBlue() {if (!isBlueEnable()) {Log.e("蓝牙扫描", "Bluetooth not enable!");return false;}//当前是否在扫描,如果是就取消当前的扫描,重新扫描if (mBluetoothAdapter.isDiscovering()) {// mBluetoothAdapter.cancelDiscovery();Toast.makeText(this, "正在扫描中", Toast.LENGTH_SHORT).show();} else {//tvAddress.setText("");//此方法是个异步操作,一般搜索12秒return mBluetoothAdapter.startDiscovery();}return false;
}
开始配对
/**
* 配对(配对成功与失败通过广播返回)
*
* @param device
* @return
*/
public boolean pin(BluetoothDevice device) {if (device == null) {Log.d("蓝牙", "bond device null");return false;}if (!isBlueEnable()) {Log.d("蓝牙", "Bluetooth not enable!");return false;}//配对之前把扫描关闭if (mBluetoothAdapter.isDiscovering()) {mBluetoothAdapter.cancelDiscovery();}//判断设备是否配对,没有配对在配,配对了就不需要配了if (device.getBondState() == BluetoothDevice.BOND_NONE) {
// if (recyPop != null && recyPop.isShowing()) {
// recyPop.dismiss();
// recyPop = null;
// blue_recy = null;
// }Log.d("蓝牙", "attemp to bond:" + device.getName());try {Method createBondMethod = device.getClass().getMethod("createBond");Log.e(getPackageName(), "开始配对");Boolean invoke = (Boolean) createBondMethod.invoke(device);// //1.确认配对
// setPairingConfirmation();
// //3.调用setPin方法进行配对...
// boolean ret = setPin(device.getClass(), device, "");// return invoke;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();Log.e("蓝牙", "attemp to bond fail!");}}return false;}
获取当前蓝牙连接状态 实测很好用的一个方法
if (mBluetoothAdapter == null) {Log.i("蓝牙...", "111");
} else if (mBluetoothAdapter.isEnabled()) {int a2dp = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP); //可操控蓝牙设备,如带播放暂停功能的蓝牙耳机int headset = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET); //蓝牙头戴式耳机,支持语音输入输出int health = mBluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH); //蓝牙穿戴式设备//查看是否蓝牙是否连接到三种设备的一种,以此来判断是否处于连接状态还是打开并没有连接的状态 2是连接int flag = -1;if (a2dp == BluetoothProfile.STATE_CONNECTED) {flag = a2dp;} else if (headset == BluetoothProfile.STATE_CONNECTED) {flag = headset;} else if (health == BluetoothProfile.STATE_CONNECTED) {flag = health;}//flag == -1 未连接 flag==2 表示已连接Log.i("蓝牙...", "2222..." + flag);if (flag == 2) {mApplication.BlueIsConnect = true;} else {mApplication.BlueIsConnect = false;}
} else {Log.i("蓝牙...", ".未开启..........");
}
获取所有以配对的蓝牙设备 并全部取消配对
//得到所有已配对的蓝牙适配器对象
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
if (devices.size() > 0) {for (Iterator iterator = devices.iterator(); iterator.hasNext(); ) {BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator.next();//得到远程已配对蓝牙设备的mac地址try {removeBond(bluetoothDevice.getClass(), bluetoothDevice);} catch (Exception e) {e.printStackTrace();}}//.扫描周围蓝牙设备(配对上的设备有可能扫描不出来) 扫描会弹出弹窗boolean b = scanBlue(); //解绑完扫描}
// 解绑蓝牙
public boolean removeBond(Class btClass, BluetoothDevice btDevice) throws Exception {Method removeBondMethod = btClass.getMethod("removeBond");Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);return returnValue.booleanValue();
}
下面贴出扫描和配对的广播类
/*** 扫描广播接收类* Created by zqf on 2018/7/6.*/public class ScanBlueReceiver extends BroadcastReceiver {private static final String TAG = ScanBlueReceiver.class.getName();private ScanBlueCallBack callBack;public ArrayList<DeviceBean> AddList = new ArrayList();public ScanBlueReceiver(ScanBlueCallBack callBack) {this.callBack = callBack;}//广播接收器,当远程蓝牙设备被发现时,回调函数onReceiver()会被执行@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d(TAG, "action:" + action);BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);switch (action) {case BluetoothAdapter.ACTION_DISCOVERY_STARTED:Log.d(TAG, "开始扫描...");AddList.clear();callBack.onScanStarted();break;case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:Log.d(TAG, "结束扫描...");callBack.onScanFinished();break;case BluetoothDevice.ACTION_FOUND:Log.d(TAG, "发现设备...");AddList.add(new DeviceBean(device.getName(), device.getAddress()));for (int i = 0; i < AddList.size(); i++) //外循环是循环的次数{for (int j = AddList.size() - 1; j > i; j--) //内循环是 外循环一次比较的次数{if (AddList.get(i).getAddress() == AddList.get(j).getAddress()) {AddList.remove(j);}}}addMsg.getMsg(AddList);// callBack.onScanning(device);break;}}private AddMsg addMsg;public interface AddMsg {public void getMsg(ArrayList<DeviceBean> list);}public void setMessage(AddMsg addMsg) {this.addMsg = addMsg;}
}
/**配对广播接收类* Created by zqf on 2018/7/7.*/public class PinBlueReceiver extends BroadcastReceiver {private String pin = "1111"; //此处为你要连接的蓝牙设备的初始密钥,一般为1234或0000private static final String TAG = PinBlueReceiver.class.getName();private PinBlueCallBack callBack;public PinBlueReceiver(PinBlueCallBack callBack){this.callBack = callBack;}//广播接收器,当远程蓝牙设备被发现时,回调函数onReceiver()会被执行@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();Log.d(TAG, "action:" + action);BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){Log.i("芜湖","ACTION_PAIRING_REQUEST");try {callBack.onBondRequest();//1.确认配对
// ClsUtils.setPairingConfirmation(device.getClass(), device, true);Method setPairingConfirmation = device.getClass().getDeclaredMethod("setPairingConfirmation",boolean.class);setPairingConfirmation.invoke(device,true);//2.终止有序广播Log.d("order...", "isOrderedBroadcast:"+isOrderedBroadcast()+",isInitialStickyBroadcast:"+isInitialStickyBroadcast());abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。//3.调用setPin方法进行配对...
// boolean ret = ClsUtils.setPin(device.getClass(), device, pin);Method removeBondMethod = device.getClass().getDeclaredMethod("setPin", new Class[]{byte[].class});Boolean returnValue = (Boolean) removeBondMethod.invoke(device, new Object[]{pin.getBytes()});} catch (Exception e) {// TODO Auto-generatBuletoothAdaptered catch blocke.printStackTrace();}}else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){switch (device.getBondState()) {case BluetoothDevice.BOND_NONE:// Log.d(TAG, "取消配对");callBack.onBondFail(device);break;case BluetoothDevice.BOND_BONDING:// Log.d(TAG, "配对中");callBack.onBonding(device);break;case BluetoothDevice.BOND_BONDED:// Log.d(TAG, "配对成功");callBack.onBondSuccess(device);break;}}}
}
蓝牙配对-扫描-连接-状态查询相关推荐
- win10蓝牙已配对连接不上_Win10系统蓝牙配对手机连接不成功的解决方法
Win10系统蓝牙配对手机连接不成功的解决方法.很多的Win10用户都在使用蓝牙连接手机,一些网友在连接时出现win10系统蓝牙已配对但连接不成功,出现在这样的问题怎么解决呢?下面我们来看看Win10 ...
- android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打印功能进行了封装,让你超快实现蓝牙打印功能
BluetoothPrint 项目地址:liuGuiRong18/BluetoothPrint 简介:android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打 ...
- android 蓝牙广播协议,Android蓝牙协议-蓝牙配对与连接
蓝牙设备在连接前,会先检查设备是否已经配对过,如果没有则先配对,配对完成后,再开始连接. onPreferenceTreeClick 蓝牙连接开始于设备列表 DeviceListPreferenceF ...
- 蓝牙 - 配对和连接
什么是蓝牙配对? 蓝牙配对是为了连接设备的一种信息注册方法.通过在设备之间注册设备信息(配对),它们可以连接.要使用一个蓝牙设备,你必须首先将其与另一个蓝牙设备配对.配对有点像交换电话号码.类似于你必 ...
- android蓝牙配对加连接,android – 配对设备的蓝牙自动连接
我是新来的,我已经阅读了很多你的帖子,但仍然没有找到问题的解决方案. 我正在为Android 2.2编写一个使用蓝牙连接到终端设备的应用程序. 我有一个配对设备列表,我可以将我的Android平板电脑 ...
- mysql查看历史连接数_MySQL如何查看连接数和连接状态
MySQL 是一种关联数据库管理系统,关联数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性.MySQL 所使用的 SQL 语言是用于访问数据库的最常用标准 ...
- 蓝牙的配对和连接的建立过程
蓝牙的建立过程是一个复杂的过程,即使有过相当一段工作和使用经验的人,如果不仔细去了解还是理解不全. 平时我们用蓝牙耳机听音乐,和不同的设备共享文件,打电话等,都有一个配对--连接--传输数据的过程. ...
- android bluetooth——蓝牙的开启、搜索、配对与连接
android 的blt仅仅支持api 18 android4.3以上,有的功能甚至需要api 19 android4.4: 所以我们在做blt项目之前一定要清楚可用的版本范围. 我要讲述的是打开bl ...
- Android中如何实现蓝牙的配对与连接
Android中如何实现蓝牙的配对与连接 这段时间在项目中负责做蓝牙的设置模块,蓝牙这部分不算简单,自己先是花了一些时间看系统的蓝牙设置代码,感觉有点熟了才开动的,但期间还是踩了不少坑,有些问题网上也 ...
最新文章
- redis安装过程中遇到的问题
- cortex M内核优先级设置
- Web前端开发薪资待遇及发展前景解读
- Dropout也能自动化了,谷歌Quoc Le等人利用强化学习自动找寻模型专用Dropout
- ASP.NET 2.0构建动态导航的Web应用程序(TreeView和Menu )[转载]
- 最简单DIY基于STM32F407探索者开发板的MPU6050陀螺仪姿态控制舵机程序
- iphone5信号无服务器,南京苹果维修点告诉你iPhone手机显示无信号、wifi故障该怎么处理?...
- 服务器密码机的标准和产品应用要点
- 受够了百度网盘?如何注册无限容量的Google Drive网盘
- Android Muti-Window
- IntelliJ IDEA重置配置设定
- Java+MySQL基于SSM的二手玩具交换网站
- Google Earth Engine(GEE)——NDWI水体阈值的监测
- 行业生态重塑中,新氧如何逆风翻盘
- 智能指纹锁迎来大风口,能否在三年内成为大众消费品?
- 智慧矿山 | 基于钻孔数据的三维地质模型可视化
- z490 linux raid,PC硬件与外设 篇二十三:光威弈系列Pro Z490平台装机评测(含raid模式)...
- 集美大学计算机毕业论文,集美大学毕业设计模板-
- 在线正则表达式生成器用法
- 智能集群理论优化控制_深度解析【智能集群控制技术】到底多硬核?