Android 取消蓝牙配对框实现自动配对功能

我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,Android.bluetoothdevice 下 action_pair_request ,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应

定义了一个类,这个是网上的可以直接用

package zicox.esc;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import android.bluetooth.BluetoothAdapter;
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 www.jb51.net
  {
    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();
    }
  }
  static public 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;
  }
}
//================================================================================================================================

还有一部分 activity

//================================================================================================================================

package zicox.esc;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Demo_ad_escActivity extends Activity
{
  //---------------------------------------------------
  public static String ErrorMessage;
  Button btnSearch, btnDis, btnExit;
  ToggleButton tbtnSwitch;
  ListView lvBTDevices;
  ArrayAdapter<String> adtDevices;
  List<String> lstDevices = new ArrayList<String>();
  BluetoothAdapter btAdapt;
  public static BluetoothSocket btSocket;
  //---------------------------------------------------
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
   // if(!ListBluetoothDevice())finish();
    Button Button1 = (Button) findViewById(R.id.button1);
    ErrorMessage = "";
    //---------------------------------------------------
    btnSearch = (Button) this.findViewById(R.id.btnSearch);
    btnSearch.setOnClickListener(new ClickEvent());
    btnExit = (Button) this.findViewById(R.id.btnExit);
    btnExit.setOnClickListener(new ClickEvent());
    btnDis = (Button) this.findViewById(R.id.btnDis);
    btnDis.setOnClickListener(new ClickEvent());
    // ToogleButton设置
    tbtnSwitch = (ToggleButton) this.findViewById(R.id.toggleButton1);
    tbtnSwitch.setOnClickListener(new ClickEvent());
    // ListView及其数据源 适配器
    lvBTDevices = (ListView) this.findViewById(R.id.listView1);
    adtDevices = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, lstDevices);
    lvBTDevices.setAdapter(adtDevices);
    lvBTDevices.setOnItemClickListener(new ItemClickEvent());
    btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
    if (btAdapt.isEnabled())
      tbtnSwitch.setChecked(false);
    else
      tbtnSwitch.setChecked(true);
     // 注册Receiver来获取蓝牙设备相关的结果
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
    IntentFilter intent = new IntentFilter();
    intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
    intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    intent.addAction(ACTION_PAIRING_REQUEST);
    intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(searchDevices, intent);
    Button1.setOnClickListener(new Button.OnClickListener()
    {
      public void onClick(View arg0)
      {
  //     Print1(SelectedBDAddress);
      }
    });
  }
//---------------------------------------------------
  private BroadcastReceiver searchDevices = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      Bundle b = intent.getExtras();
      Object[] lstName = b.keySet().toArray();
      // 显示所有收到的消息及其细节
      for (int i = 0; i < lstName.length; i++) {
        String keyName = lstName[i].toString();
        Log.e(keyName, String.valueOf(b.get(keyName)));
      }
      BluetoothDevice device = null;
      // 搜索设备时,取得设备的MAC地址
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {
        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
          String str = "未配对|" + device.getName() + "|"
              + device.getAddress();
          if (lstDevices.indexOf(str) == -1)// 防止重复添加
            lstDevices.add(str); // 获取设备名称和mac地址
          adtDevices.notifyDataSetChanged();
          try {
            ClsUtils.setPin(device.getClass(),device,"0000");
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          try {
            ClsUtils.cancelPairingUserInput(device.getClass(), device);
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        switch (device.getBondState()) {
        case BluetoothDevice.BOND_BONDING:
          Log.d("BlueToothTestActivity", "正在配对......");
          break;
        case BluetoothDevice.BOND_BONDED:
          Log.d("BlueToothTestActivity", "完成配对");
          connect(device);//连接设备
          break;
        case BluetoothDevice.BOND_NONE:
          Log.d("BlueToothTestActivity", "取消配对");
        default:
          break;
        }
      }
      if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST"))
      {
        Log.e("tag11111111111111111111111", "ddd");
        BluetoothDevice btDevice = intent
            .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234");
        // device.setPin(pinBytes);
        try
        {
          ClsUtils.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对
          ClsUtils.createBond(btDevice.getClass(), btDevice);
          ClsUtils.cancelPairingUserInput(btDevice.getClass(), btDevice);
        }
        catch (Exception e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  };
  class ItemClickEvent implements AdapterView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {
      if(btAdapt.isDiscovering())btAdapt.cancelDiscovery();
      String str = lstDevices.get(arg2);
      String[] values = str.split("\\|");
      String address = values[2];
      Log.e("address", values[2]);
      BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
      try {
        Boolean returnValue = false;
        if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
          //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);
//          Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
//          Log.d("BlueToothTestActivity", "开始配对");
//          returnValue = (Boolean) createBondMethod.invoke(btDev);
          ClsUtils.pair(address, "0000");
          showMessage("here");
        }else if(btDev.getBondState() == BluetoothDevice.BOND_BONDED){
          connect(btDev);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  private void connect(BluetoothDevice btDev) {
    final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    UUID uuid = SPP_UUID;
    try {
      btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
      Log.d("BlueToothTestActivity", "开始连接...");
      btSocket.connect();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  class ClickEvent implements View.OnClickListener {
    @Override
    public void onClick(View v) {
      if (v == btnSearch)// 搜索蓝牙设备,在BroadcastReceiver显示结果
      {
        if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
          Toast.makeText(Demo_ad_escActivity.this, "请先打开蓝牙", 1000).show();          return;
        }
        if (btAdapt.isDiscovering())
          btAdapt.cancelDiscovery();
        lstDevices.clear();
        Object[] lstDevice = btAdapt.getBondedDevices().toArray();
        for (int i = 0; i < lstDevice.length; i++) {
          BluetoothDevice device = (BluetoothDevice) lstDevice[i];
          String str = "已配对|" + device.getName() + "|"
              + device.getAddress();
          lstDevices.add(str); // 获取设备名称和mac地址
          adtDevices.notifyDataSetChanged();
        }
        setTitle("本机蓝牙地址:" + btAdapt.getAddress());
        btAdapt.startDiscovery();
      } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭
        if (tbtnSwitch.isChecked() == false)
          btAdapt.enable();
        else if (tbtnSwitch.isChecked() == true)
          btAdapt.disable();
      } else if (v == btnDis)// 本机可以被搜索
      {
        Intent discoverableIntent = new Intent(
            BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(
            BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);
      } else if (v == btnExit) {
        try {
          if (btSocket != null)
            btSocket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        Demo_ad_escActivity.this.finish();
      }
    }
  }
  @Override
  protected void onDestroy() {
    this.unregisterReceiver(searchDevices);
    super.onDestroy();
    android.os.Process.killProcess(android.os.Process.myPid());
  }
  public void showMessage(String str)
  {
    Toast.makeText(this,str, Toast.LENGTH_LONG).show();
  }
}

以上所述是小编给大家介绍的Android 取消蓝牙配对框实现自动配对功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • android接收到蓝牙配对请求时如何点亮屏幕具体实现

    file: BluetoothEventLoop.java GB/GB2/GB3: 1. import android.os.PowerManager; 2. 变量申明:private PowerManager.WakeLock mWakeLock; 3. BluetoothEventLoop(){} 构造函数里面添加定义: PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); mWake

  • Android 取消蓝牙配对框实现自动配对功能

    我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,Android.bluetoothdevice 下 action_pair_request ,没有定义这个,开始困扰了我一点时间,实现难度:是否能进入那个广播响应 定义了一个类,这个是网上的可以直接用 package zicox.esc; import java.lang.reflect.Method; import java.lang.reflect.Field; import android.blu

  • JavaScript实现搜索框的自动完成功能(一)

    在很多需要搜索的网站, 都会有一个自动完成的搜索框. 方便用户查找他们想要的搜索词. 帮助用户快速找到自己想要的结果. 这种方式是比较友好的. 所以是比较提倡使用的. 先给大家展示下效果图: 实现这个功能需要服务端配合.客户端通过脚本来展示从服务端取得的数据. 先看客户端的HTML: 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DT

  • 使用Ajax模仿百度搜索框的自动提示功能实例

    啊啊,熬夜了.今天学习了ajax给我的感觉就是,"哇塞"ajax好酷炫哦,(额...后端狗,接触到了大前端的魅力了),这么晚了还是直奔主题把.Let's go! 百度搜索提示框,我想大家都很熟悉了把,是什么样子我也就不再赘述.直接看代码 来我们写一个简陋的jsp页面 Look! 是这个样子的 下面是代码: <%@ page language="java" contentType="text/html; charset=UTF-8" page

  • Android实现短信验证码获取自动填写功能(详细版)

    现在的应用在注册登录或者修改密码中都用到了短信验证码,那在android中是如何实现获取短信验证码并自动填写的呢? 首先,需要要在manifest中注册接收和读取短信的权限: <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_

  • easyUI实现类似搜索框关键词自动提示功能示例代码

    在一个DataGrid里面,搜索行所在位置 实现的效果如下: 在搜索框中输入部分列名关键字,即可匹配到行的位置. EasyUI的SearchBox组件只提供了静态搜索框,我们可以使用ComboBox来实现动态的自动关键匹配效果,并且不需要加载远程数据.当前页面的DataGrid的数据我们可以直接在本地获取之. 代码如下: setp1.创建combobox <div style="text-align: left;background-color: #E0ECFF;padding-left:

  • Android 8.0实现蓝牙遥控器自动配对

    本文要实现的是在 android 8.0 的平台上,蓝牙遥控器与TV自动配对,具体就是在TV端打开配对界面,TV端开始搜索远程蓝牙设备,按下遥控器按键让蓝牙遥控器进入对码模式,此时蓝牙遥控器就能作为一个远程蓝牙设备被发现,TV端扫描到这个远程蓝牙设备(蓝牙遥控器),就会自动进行配对连接. 话不多说,直接上代码分析. public class RcConnectActivity extends Activity {         private static final String TAG =

  • Android实现获取短信验证码并自动填写功能

    本文实例为大家分享了Android短信验证码获取并自动填写功能的具体代码,供大家参考,具体内容如下 代码如下: MainActivity public class MainActivity extends AppCompatActivity { public static TextView mText; private SmsContent content; @Override protected void onCreate(Bundle savedInstanceState) { super.

  • Android自动文本框输入识别提示功能代码

    自动提示文本框(AutoCompleteTextView)可以加强用户体验,缩短用户的输入时间(百度的搜索框就是这个效果). 相信大家都熟悉自动识别提示吧,在我们的生活中随处可见,今天就让我为大家简单介绍一下它是如何设计的. 所谓自动识别输入即是根据用户输入的已有信息,为用户提示可能的值,方便用户完成输入.在Android设备上这种功能分为:AutoCompleteTextView和MultiAutoCompleteTextView,前者为单个的自动识别,类似与搜索引擎的输入框提示:后者为多个值

  • Android Bluetooth蓝牙技术使用流程详解

    在上篇文章给大家介绍了Android Bluetooth蓝牙技术初体验相关内容,感兴趣的朋友可以点击了解详情. 一:蓝牙设备之间的通信主要包括了四个步骤 设置蓝牙设备 寻找局域网内可能或者匹配的设备 连接设备 设备之间的数据传输 二:具体编程实现 1. 启动蓝牙功能 首先通过调用静态方法getDefaultAdapter()获取蓝牙适配器BluetoothAdapter,如果返回为空,则无法继续执行了.例如: BluetoothAdapter mBluetoothAdapter = Blueto

  • Android实现蓝牙(BlueTooth)设备检测连接

    无论是WIFI还是4G网络,建立网络连接后都是访问互联网资源,并不能直接访问局域网资源.比如两个人在一起,A要把手机上的视频传给B,通常情况是打开手机QQ,通过QQ传送文件给对方.不过上传视频很耗流量,如果现场没有可用的WIFI,手机的数据流量又不足,那又该怎么办呢?为了解决这种邻近传输文件的问题,蓝牙技术应运而生.蓝牙技术是一种无线技术标准,可实现设备之间的短距离数据交换. Android为蓝牙技术提供了4个工具类,分别是蓝牙适配器BluetoothAdapter.蓝牙设备BluetoothD

随机推荐