欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-20 15:59:22
我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,android.bluetoothdevice 下 action_pair_r...

我看了几个文章,主要是接受配对广播,然后设置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 取消蓝牙配对框实现自动配对功能,希望对大家有所帮助

上一篇:

下一篇: