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. spring+hibernate基础

    把数据库的配置信息写在一个文件中 jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc\:mysql\://localhost\:3306/ ...

  2. 浅谈JSP(一)

    一.JSP引言 JSP全名为Java Server Pages,中文名叫java服务器页面,其根本是一个简化的Servlet设计.它是在传统的网页HTML文件(*.htm,*.html)中插入Java ...

  3. UVA1471( LIS变形)

    这是LIS的变形,题意是求一个序列中去掉某个连续的序列后,能得到的最长连续递增序列的长度. 用DP的解法是:吧这个序列用数组a来记录,再分别用两个数组f记录以i结尾的最长连续递增序列的长度,g[i]记 ...

  4. php如何开启GD库

    GD库是干什么用的呢!它是php处理图形的扩展库,GD库提供了一系列用来处理图片的API,使用GD库可以处理图片,或者生成图片.GD库在php中默认是没有开启的,如果想让它支持图片处理功能,那么就要手 ...

  5. nrf51 SDK自带例程的解读

    简单的pwm电机控制示例 simple_pwm_motor_control_example 其实就是pwm控制led的亮度 1.首先设置gpiote 设置初始为高电平2.接着设置ppi 定时器time ...

  6. phome_ecms_news 数据表字段解释(新闻系统模型-主表)

    http://www.phome.net/doc/manual/extend/html/dbdoc/index.html 字段名 类型 解释 附加说明 id int(11) 信息ID   classi ...

  7. 卡特兰数(Catalan)简介

    Catalan序列是一个整数序列,其通项公式是 h(n)=C(2n,n)/(n+1) (n=0,1,2,...) 其前几项为 : 1, 1, 2, 5, 14, 42, 132, 429, 1430, ...

  8. haproxy 超时机制

    <pre name="code" class="python">option redispatch option redispatch 是否允许重新 ...

  9. [转]chrome技术文档列表

    chrome窗口焦点管理系统 http://www.douban.com/note/32607279/ chrome之TabContents http://www.douban.com/note/32 ...

  10. 过河(bfs)

    Problem 2188 过河I Accept: 112    Submit: 277 Time Limit: 3000 mSec    Memory Limit : 32768 KB  Proble ...