溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android 取消藍(lán)牙配對(duì)框?qū)崿F(xiàn)自動(dòng)配對(duì)功能

發(fā)布時(shí)間:2020-08-27 14:05:55 來源:腳本之家 閱讀:233 作者:caobai 欄目:移動(dòng)開發(fā)

我看了幾個(gè)文章,主要是接受配對(duì)廣播,然后設(shè)置pin,實(shí)現(xiàn)配對(duì),但是網(wǎng)上的大部分手機(jī)是不可以的,Android.bluetoothdevice 下 action_pair_request ,沒有定義這個(gè),開始困擾了我一點(diǎn)時(shí)間,實(shí)現(xiàn)難度:是否能進(jìn)入那個(gè)廣播響應(yīng)

定義了一個(gè)類,這個(gè)是網(wǎng)上的可以直接用

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 
{ 
  /**
   * 與設(shè)備配對(duì) 參考源碼: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(); 
  } 
  /**
   * 與設(shè)備解除配對(duì) 參考源碼: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(); 
  } 
  // 取消配對(duì) 
  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)) 
    { // 檢查藍(lán)牙地址是否有效 
      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); // 手機(jī)和藍(lán)牙采集器配對(duì) 
        ClsUtils.createBond(device.getClass(), device); 
//        remoteDevice = device; // 配對(duì)完畢就把這個(gè)設(shè)備對(duì)象傳給全局的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); // 手機(jī)和藍(lán)牙采集器配對(duì) 
        ClsUtils.createBond(device.getClass(), device); 
//        remoteDevice = device; // 如果綁定成功,就直接把這個(gè)設(shè)備對(duì)象傳給全局的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設(shè)置  
    tbtnSwitch = (ToggleButton) this.findViewById(R.id.toggleButton1);  
    tbtnSwitch.setOnClickListener(new ClickEvent()); 
    // ListView及其數(shù)據(jù)源 適配器  
    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();// 初始化本機(jī)藍(lán)牙功能  
    if (btAdapt.isEnabled()) 
      tbtnSwitch.setChecked(false);  
    else 
      tbtnSwitch.setChecked(true);   
     // 注冊(cè)Receiver來獲取藍(lán)牙設(shè)備相關(guān)的結(jié)果 
    String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST"; 
    IntentFilter intent = new IntentFilter();  
    intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver來取得搜索結(jié)果  
    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();  
      // 顯示所有收到的消息及其細(xì)節(jié)  
      for (int i = 0; i < lstName.length; i++) {  
        String keyName = lstName[i].toString();  
        Log.e(keyName, String.valueOf(b.get(keyName)));  
      }  
      BluetoothDevice device = null;  
      // 搜索設(shè)備時(shí),取得設(shè)備的MAC地址  
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {  
        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);  
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {  
          String str = "未配對(duì)|" + device.getName() + "|"  
              + device.getAddress();  
          if (lstDevices.indexOf(str) == -1)// 防止重復(fù)添加  
            lstDevices.add(str); // 獲取設(shè)備名稱和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", "正在配對(duì)......");  
          break;  
        case BluetoothDevice.BOND_BONDED:  
          Log.d("BlueToothTestActivity", "完成配對(duì)");  
          connect(device);//連接設(shè)備  
          break;  
        case BluetoothDevice.BOND_NONE:  
          Log.d("BlueToothTestActivity", "取消配對(duì)");  
        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"); // 手機(jī)和藍(lán)牙采集器配對(duì) 
          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) {  
          //利用反射方法調(diào)用BluetoothDevice.createBond(BluetoothDevice remoteDevice);  
//          Method createBondMethod = BluetoothDevice.class.getMethod("createBond");  
//          Log.d("BlueToothTestActivity", "開始配對(duì)");  
//          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)// 搜索藍(lán)牙設(shè)備,在BroadcastReceiver顯示結(jié)果  
      {  
        if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果藍(lán)牙還沒開啟  
          Toast.makeText(Demo_ad_escActivity.this, "請(qǐng)先打開藍(lán)牙", 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 = "已配對(duì)|" + device.getName() + "|"  
              + device.getAddress();  
          lstDevices.add(str); // 獲取設(shè)備名稱和mac地址  
          adtDevices.notifyDataSetChanged();  
        }  
        setTitle("本機(jī)藍(lán)牙地址:" + btAdapt.getAddress());  
        btAdapt.startDiscovery();  
      } else if (v == tbtnSwitch) {// 本機(jī)藍(lán)牙啟動(dòng)/關(guān)閉  
        if (tbtnSwitch.isChecked() == false)  
          btAdapt.enable();  
        else if (tbtnSwitch.isChecked() == true)  
          btAdapt.disable();  
      } else if (v == btnDis)// 本機(jī)可以被搜索  
      {  
        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 取消藍(lán)牙配對(duì)框?qū)崿F(xiàn)自動(dòng)配對(duì)功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI