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

Android 取消蓝牙配对框实现自动配对功能,第1张

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

我看了几个文章,主要是接受配对广播,然后设置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); //        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(),"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 取消蓝牙配对框实现自动配对功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!

总结

以上是内存溢出为你收集整理的Android 取消蓝牙配对框实现自动配对功能全部内容,希望文章能够帮你解决Android 取消蓝牙配对框实现自动配对功能所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147003.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存