BluetoothConnectActivityReceiver.java:监听蓝牙配对的广播

代码:

package com.imte.Broadcast;

import com.imte.utils.ClsUtils;
import com.itme.ActivityClass.R; import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast; public class BluetoothConnectActivityReceiver extends BroadcastReceiver { String strPsw = "123456"; @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);
try {
ClsUtils.setPin(btDevice.getClass(), btDevice, strPsw); // 手机和蓝牙采集器配对
ClsUtils.createBond(btDevice.getClass(), btDevice);
ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
Toast.makeText(
context,
context.getResources().getString(
R.string.bluetooth_connect_success),
Toast.LENGTH_SHORT);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// Thread thread=new Thread(strPsw);
// thread.
}
} }
} ClsUtils.java? package com.imte.utils; /************************************ 蓝牙配对函数 * **************/
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();
}
}
} 最后就是MainActivity,用一个按钮来实现自动配对,代码如下: package com.itme.ActivityClass; import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; import com.imte.utils.ClsUtils; public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private static BluetoothDevice remoteDevice=null;
private Button btn_autopair=null;
final static String ACTION_BLUETOOTHBC="android.bluetooth.device.action.PAIRING_REQUEST";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_autopair=(Button)findViewById(R.id.btn_autopair);
btn_autopair.setOnClickListener(this);
}
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);
// ClsUtils.cancelPairingUserInput(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这个类的的以下静态方法都是通过反射机制得到需要的方法
ClsUtils.createBond(device.getClass(), device);//创建绑定
ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
ClsUtils.createBond(device.getClass(), device);
// ClsUtils.cancelPairingUserInput(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;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_autopair:
if (pair("94:DB:46:2B:A1:82", "123456")) {//pair的第一个参数是要配对的蓝牙地址,第二个参数是配对时预先设置的密钥 Log.i("aaron", remoteDevice.getAddress());
}
break; default:
break;
}
}
} 叮咚..如题的功能就实现了。。。 项目源代码下载地址: http://download.csdn.net/detail/huangrangg12/4578242

android 实现蓝牙自动配对连接的更多相关文章

  1. Android蓝牙自动配对Demo,亲测好使!!!

    蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...

  2. Android蓝牙自动配对Demo,亲测好使!!!(转)

    蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details ...

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

    之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就 ...

  4. android开发之蓝牙配对连接的方法

    最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结. 在做android蓝牙串口连接的时候一般会使用 ? 1 2 3 4 5 ...

  5. Android-蓝牙自动配对与隐藏对话框

    一.概述 本次分析是基于Android7.0的源码. 二.自动配对分析过程 首先,我们分析一下源码的自动配对过程,packages/apps/Settings/src/com/android/sett ...

  6. ubuntu16.04连接android手机蓝牙共享网络热点

    最近的想要用android手机蓝牙共享wifi网络给ubuntu16.04系统用,查了好多资料,发现网上很少有有用的.自己实践后分享如下. 第一步:手机与电脑配对:         该步骤比较简单,网 ...

  7. Android 开发 蓝牙开发

    前言 蓝牙开发其实分2个部分,一个是正常蓝牙功能的开发(比如Android蓝牙的互相连接.读取蓝牙列表.文件传输.蓝牙耳机等等).另外一个是BLE蓝牙开发(属于低功耗蓝牙设备,设备大多是血糖仪.蓝牙手 ...

  8. Android Studio 蓝牙开发实例——基于Android 6.0

    因项目需要做一个Android 的蓝牙app来通过手机蓝牙传输数据以及控制飞行器,在此,我对这段时间里写的蓝牙app的代码进行知识梳理和出现错误的总结. 该应用的Compile Sdk Version ...

  9. Android ble 蓝牙4.0 总结

    本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦 ...

随机推荐

  1. zoj 3706 Break Standard Weight

    /*题意:将两个砝码中的其中一个分成两块,三块组合最多有几种情况(可以只有一块,或者两块). 组合情况 i j m 三块砝码 (i+j)-m=m-(i+j) i+j i-j=j-i  i j m (i ...

  2. JavaMail收发邮件的一般流程与主要方法

    1.Properties属性类 Properties p = new Properties(); p.put(key, value); key -| mail.smtp.host -| mail.sm ...

  3. 【转】CoreData以及MagicalRecord (二)

    3. 运行时类与对象 NSManagedObject Managed Object 表示数据文件中的一条记录,每一个Managed Object在内存中对应的实体(Entity)的一个数据表示.Man ...

  4. jquery的extend()函数

    extend()是在写插件的过程中常用的方法,该方法有一些重载原型. 1.该方法的原型是: extend(dest,src1,src2,src3...); 它的含义是将src1,src2,src3.. ...

  5. phplib系统开发经验总结

    数据库设计: 数据库的设计一定要在了解整个系统需求的情况下,把数据库设计,及ER图画出来,数据库字典也要及时把握,只有掌握了这些才能下手开始设计界面,后期如果有需要,可以在数据库中添加数据,但要及时更 ...

  6. Tomcat embed

    http://www.iflym.com/index.php/code/use-embeded-tomcat-to-javaee-start-tomcat.html http://java.dzone ...

  7. 在VC6中基于dll开发插件用于各种图片显示(BMP/TGA/JPG/GIF/PNG/TIF/ICO/WMF/EMF/...)

    一.图片显示 图片显示的方法: 1.  直接写程序 2.  第3方库 3.  调用COM组件的IPicture接口 4.  使用MFC的CPictureHolder类 5.  使用GDI+的CImag ...

  8. Microsoft SQL Server 混合云博客系列

    Microsoft 云操作系统愿景的核心支柱之一就是借助我们的混合云基础结构改造数据中心.在 Windows Azure 基础结构服务正式发布后的几个月里,我们一直在发布博客,介绍 Windows A ...

  9. 将MFC Grid control封装为DLL的做法及其在DLL中的使用方法

    MFCGrid control是一款非常优秀的网格控件,支持非常丰富的界面元素,如下图: 因而在数据库程序及报表程序应用较为广泛,其源码可以在下面下载到: MFC Grid control2.27源码 ...

  10. 1148 - Mad Counting(数学)

    1148 - Mad Counting   PDF (English) Statistics Forum Time Limit: 0.5 second(s) Memory Limit: 32 MB M ...