android 实现蓝牙自动配对连接

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    
时间: 2024-08-04 12:15:17

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

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

如何实现android蓝牙开发 自动配对连接,并不弹出提示框 之前做一个android版的蓝牙,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就开始查找怎么关闭这个蓝牙配对提示框,后面还是伟大的android源码帮助了我. 在源码 BluetoothDevice 类中还有两个隐藏方法 cancelBondProcess()和cancelPairingUserInput() 这两个方法一个是取消配对进

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

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details/52400782 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙设备,注意修改相关名字以及修改设备初试pin值. 2.将Demo安装在Android手机上,点击按钮,可以实现与目标蓝牙设备的自动

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

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details/52400782 源码下载地址:https://github.com/chaohuangtianjie994/BlueTooth-AutoPair 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙

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

最近在做蓝牙开锁的小项目,手机去连接单片机总是出现问题,和手机的连接也不稳定,看了不少蓝牙方面的文档,做了个关于蓝牙连接的小结. 在做android蓝牙串口连接的时候一般会使用 ? 1 2 3 4 5 6 7 8 BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try {          tmp = device.createRfcom

Android ble 蓝牙4.0 总结一

本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦. 首先发一下官方的demo,有兴趣的可以过去看看:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html.android系统4.3以上,手机支持蓝牙4.0,具有搜索,配对,连接,发现服务及特征值,断开连接等功能,下载地

Android ble 蓝牙4.0 总结

本文介绍Android ble 蓝牙4.0,也就是说API level >= 18,且支持蓝牙4.0的手机才可以使用,如果手机系统版本API level < 18,也是用不了蓝牙4.0的哦. 首先发一下官方的demo,有兴趣的可以过去看看:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html.android系统4.3以上,手机支持蓝牙4.0,具有搜索,配对,连接,发现服务及特征值,断开连接等功能,下载地

Android 蓝牙设备的查找和连接

1.权限使用蓝牙设备需要先在Manifest中开放权限,位置如下. [html] view plaincopy <manifest ...> <application ...> ... </application> // 使用蓝牙设备的权限 <uses-permission android:name="android.permission.BLUETOOTH" /> // 管理蓝牙设备的权限 <uses-permission and

Android BLE蓝牙详细解读

代码地址如下:http://www.demodashi.com/demo/15062.html 随着物联网时代的到来,越来越多的智能硬件设备开始流行起来,比如智能手环.心率检测仪.以及各式各样的智能家具和玩具类产品.安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备.查询服务和读写特性.相比传统的蓝牙,BLE更显著的特点是低功耗.本文主要讲解Android低功耗蓝牙的api使用以及蓝牙扫描.连接.发送数据.接收数据等一系列操作,并主要介绍本人封装的Ble

Android 低功耗蓝牙BLE 开发注意事项

基本概念和问题 1.蓝牙设计范式? 当手机通过扫描低功耗蓝牙设备并连接上后,手机与蓝牙设备构成了客户端-服务端架构.手机通过连接蓝牙设备,可以读取蓝牙设备上的信息.手机就是客户端,蓝牙设备是服务端. 手机做为客户端可以连接多个蓝牙设备,所以手机又可以叫中心设备(Central),蓝牙设备叫外围设备(Peripheral). 还有另外一个称谓:手机叫主设备(Master),蓝牙设备叫从设备(Slave). Android4.3 开始支持低功耗蓝牙,此版本只支持单模式:同时只能工作在中心设备模式或者