当前位置: 首页 > news >正文

如何实现android蓝牙开发 自动配对连接,并不弹出提示框

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

如何实现android蓝牙开发 自动配对连接,并不弹出提示框

之前做一个android版的蓝牙,遇到最大的难题就是自动配对.

上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了

我就开始查找怎么关闭这个蓝牙配对提示框,后面还是伟大的android源码帮助了我。

在源码 BluetoothDevice 类中还有两个隐藏方法

cancelBondProcess()和cancelPairingUserInput()

这两个方法一个是取消配对进程一个是取消用户输入

下面是自动配对的代码

Mainfest,xml注册

<receiver android:name=".BluetoothConnectActivityReceiver" >
    <intent-filter>
        <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
    </intent-filter>
</receiver>

自己在收到广播时处理并将预先输入的密码设置进去
public class BluetoothConnectActivityReceiver extends BroadcastReceiver
{

	String strPsw = "0";

	@Override
	public void onReceive(Context context, Intent intent)
	{
		// TODO Auto-generated method stub
		if (intent.getAction().equals(
				"android.bluetooth.device.action.PAIRING_REQUEST"))
		{
			BluetoothDevice btDevice = intent
					.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

			// byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
			// device.setPin(pinBytes);
			Log.i("tag11111", "ddd");
			try
			{
				ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手机和蓝牙采集器配对
				ClsUtils.createBond(btDevice.getClass(), btDevice);
				ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}
}
<b>/************************************ 蓝牙配对函数 * **************/
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils
{

	/**
	 * 与设备配对 参考源码:platform/packages/apps/Settings.git
	 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
	 */
	static public boolean createBond(Class btClass, BluetoothDevice btDevice)
			throws Exception
	{
		Method createBondMethod = btClass.getMethod("createBond");
		Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
		return returnValue.booleanValue();
	}

	/**
	 * 与设备解除配对 参考源码:platform/packages/apps/Settings.git
	 * /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
	 */
	static public boolean removeBond(Class btClass, BluetoothDevice btDevice)
			throws Exception
	{
		Method removeBondMethod = btClass.getMethod("removeBond");
		Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
		return returnValue.booleanValue();
	}

	static public boolean setPin(Class btClass, BluetoothDevice btDevice,
			String str) throws Exception
	{
		try
		{
			Method removeBondMethod = btClass.getDeclaredMethod("setPin",
					new Class[]
					{byte[].class});
			Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
					new Object[]
					{str.getBytes()});
			Log.e("returnValue", "" + returnValue);
		}
		catch (SecurityException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;

	}

	// 取消用户输入
	static public boolean cancelPairingUserInput(Class btClass,
			BluetoothDevice device)

	throws Exception
	{
		Method createBondMethod = btClass.getMethod("cancelPairingUserInput");
		// cancelBondProcess()
		Boolean returnValue = (Boolean) createBondMethod.invoke(device);
		return returnValue.booleanValue();
	}

	// 取消配对
	static public boolean cancelBondProcess(Class btClass,
			BluetoothDevice device)

	throws Exception
	{
		Method createBondMethod = btClass.getMethod("cancelBondProcess");
		Boolean returnValue = (Boolean) createBondMethod.invoke(device);
		return returnValue.booleanValue();
	}

	/**
	 * 
	 * @param clsShow
	 */
	static public void printAllInform(Class clsShow)
	{
		try
		{
			// 取得所有方法
			Method[] hideMethod = clsShow.getMethods();
			int i = 0;
			for (; i < hideMethod.length; i++)
			{
				Log.e("method name", hideMethod[i].getName() + ";and the i is:"
						+ i);
			}
			// 取得所有常量
			Field[] allFields = clsShow.getFields();
			for (i = 0; i < allFields.length; i++)
			{
				Log.e("Field name", allFields[i].getName());
			}
		}
		catch (SecurityException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			// throw new RuntimeException(e.getMessage());
			e.printStackTrace();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}</b>
<b>public static boolean pair(String strAddr, String strPsw)
	{
		boolean result = false;
		BluetoothAdapter bluetoothAdapter = BluetoothAdapter
				.getDefaultAdapter();

		bluetoothAdapter.cancelDiscovery();

		if (!bluetoothAdapter.isEnabled())
		{
			bluetoothAdapter.enable();
		}

		if (!BluetoothAdapter.checkBluetoothAddress(strAddr))
		{ // 检查蓝牙地址是否有效

			Log.d("mylog", "devAdd un effient!");
		}

		BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);

		if (device.getBondState() != BluetoothDevice.BOND_BONDED)
		{
			try
			{
				Log.d("mylog", "NOT BOND_BONDED");
				ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
				ClsUtils.createBond(device.getClass(), device);
				remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice
				result = true;
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block

				Log.d("mylog", "setPiN failed!");
				e.printStackTrace();
			} //

		}
		else
		{
			Log.d("mylog", "HAS BOND_BONDED");
			try
			{
				ClsUtils.createBond(device.getClass(), device);
				ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
				ClsUtils.createBond(device.getClass(), device);
				remoteDevice = device; // 如果绑定成功,就直接把这个设备对象传给全局的remoteDevice
				result = true;
			}
			catch (Exception e)
			{
				// TODO Auto-generated catch block
				Log.d("mylog", "setPiN failed!");
				e.printStackTrace();
			}
		}
		return result;
	}</b>
转自

转载于:https://my.oschina.net/u/582827/blog/505436

相关文章:

  • JFreeChart绘制XY折线图(工具类设计)
  • ORACLE数据库笔记之PL/SQL
  • ByteTCC 0.5.0-ALPHA1 发布,基于 TCC 的分布式事务管理器
  • 马哥-51CTO-Linux培训-0901-linux文件系统
  • 【译】Cloudera Manager(CDH)入门系列之四 (管理员控制台)
  • 程序猿常识--OJ系统和ACM测试考试大全
  • linux-命令行快捷方式使用
  • mac 关闭dashboard 开机更快
  • 队列queue
  • SEO优化:为什么要关注“网站抓取频率”?
  • Nginx配置error_page 404错误页面
  • pycharm安装以及简单使用教程
  • Android 多渠道打包
  • shell计算工具源码
  • JavaScript之闭包
  • 收藏网友的 源程序下载网
  • Cookie 在前端中的实践
  • ES6系统学习----从Apollo Client看解构赋值
  • JavaScript DOM 10 - 滚动
  • magento 货币换算
  • mysql 5.6 原生Online DDL解析
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • orm2 中文文档 3.1 模型属性
  • Python中eval与exec的使用及区别
  • React16时代,该用什么姿势写 React ?
  • springMvc学习笔记(2)
  • spring学习第二天
  • Vue小说阅读器(仿追书神器)
  • 回流、重绘及其优化
  • 数据可视化之 Sankey 桑基图的实现
  • 探索 JS 中的模块化
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • # centos7下FFmpeg环境部署记录
  • (2.2w字)前端单元测试之Jest详解篇
  • (9)STL算法之逆转旋转
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (一)C语言之入门:使用Visual Studio Community 2022运行hello world
  • (已解决)报错:Could not load the Qt platform plugin “xcb“
  • .Net 4.0并行库实用性演练
  • .net 4.0发布后不能正常显示图片问题
  • .net framework profiles /.net framework 配置
  • .net 无限分类
  • .net开发时的诡异问题,button的onclick事件无效
  • .Net转前端开发-启航篇,如何定制博客园主题
  • @Autowired 与@Resource的区别
  • @ModelAttribute注解使用
  • @RunWith注解作用
  • @Transactional 竟也能解决分布式事务?
  • [ 2222 ]http://e.eqxiu.com/s/wJMf15Ku
  • []sim300 GPRS数据收发程序
  • [100天算法】-实现 strStr()(day 52)
  • [AutoSar]BSW_Com02 PDU详解
  • [C#基础知识系列]专题十七:深入理解动态类型
  • [C++从入门到精通] 14.虚函数、纯虚函数和虚析构(virtual)