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. objective-C学习笔记(四)函数成员:方法(函数)

    函数分为:  全局函数(C语言函数) 成员函数(OBJC方法):实例方法 “-” 和类方法“+”的区别 //这里要区别静态变量(类变量).全局函数.常量的区别 OBJC里面,所有方法默认为公有方法.没 ...

  2. 在C++中如何使用C

    如下代码: /*C语言头文件:Max.h*/ #ifndef _MAX_H_ #define _MAX_H_ int Max(int nA,int nB) #endif /*C语言实现文件:Max.c ...

  3. BZOJ 1207: [HNOI2004]打鼹鼠( dp )

    dp.. dp[ i ] = max( dp[ j ] + 1 ) ------------------------------------------------------------------ ...

  4. 驱动之路四------adc驱动(input设备)

    开发板:smdk6410 开发环境:Linux 突然想起一点,写这些驱动,内核需要配成支持抢占才行. 前面的博客已经将其它的基本知识都解释了,这里也就不过多的阐述了,咱就直接写代码吧 这次写的是adc ...

  5. 关于input标签的需要注意的几个小问题

    1.input元素没有结束标签,只有开始标签,即使写上结束标签也不起作用.如下 <input type="text" value="text" /> ...

  6. C++ 面向对象学习2 构造方法

    Date.h #ifndef DATE_H #define DATE_H class Date{ public: Date(,,);//自定义了构造方法 会覆盖掉默认的无参构造方法 void setD ...

  7. 射频识别技术漫谈(21)——RC系列射频芯片的天线设计

    个人感觉使用RC系列射频芯片开发卡片读写器,主要的关键点有两个,分别涉及硬件和软件.软件上的关键是如何正确设置RC系列射频芯片内部的64个寄存器,硬件上的关键则是RC系列射频芯片的天线设计.天线提供了 ...

  8. libcurl post上传文件

    #include <stdio.h>#include <string.h> #include <curl/curl.h> int main(int argc, ch ...

  9. Android JNI入门第一篇——HelloJni

    android支持使用NDK开发C程序,关于配置NDK环境问题应该不用再赘述了,这个网上有很多,这里通过一篇实例来讲述简单的JNI开发,大家可以参考这篇文章(Get Your Eclipse-Inte ...

  10. SQL 语言划分

    从功能上划分,SQL 语言能够分为DDL,DML和DCL三大类. 1. DDL(Data Definition Language)     数据定义语言,用于定义和管理 SQL 数据库中的全部对象的语 ...