国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android 藍牙自動匹配PIN碼跳過用戶交互示例

2019-10-23 18:27:16
字體:
來源:轉載
供稿:網友

近期項目中需要連接藍牙設備,起初只是設置藍牙列表界面讓用戶點擊然后輸入默認PIN碼,后來改需求了 = = ,要求自動連接指定設備并不需要用戶手動輸入PIN碼,作為Android 小白的我是拒絕的,但是拒絕有什么用~

首先說一下之后會用到的關于藍牙方面的東西:

  1. 斷開藍牙已配對的設備
  2. 搜索附近藍牙設備
  3. 攔截用戶交互頁面,使用代碼輸入
  4. 由于在最后連接的時候使用的是設備的SDK所以在這里就不介紹了

1.斷開已配對設備

最后在項目中發現沒有用。這里就先記錄一下。

  //得到配對的設備列表,清除已配對的設備  public void removePairDevice() {    if (mBluetoothAdapter != null) {      //mBluetoothAdapter初始化方式 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();      //這個就是獲取已配對藍牙列表的方法      Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();      for (BluetoothDevice device : bondedDevices) {        //這里可以通過device.getName() device.getAddress()來判斷是否是自己需要斷開的設備        unpairDevice(device);      }    }  }  //反射來調用BluetoothDevice.removeBond取消設備的配對  private void unpairDevice(BluetoothDevice device) {    try {      Method m = device.getClass().getMethod("removeBond", (Class[]) null);      m.invoke(device, (Object[]) null);    } catch (Exception e) {      Log.e("mate", e.getMessage());    }  }

2.搜索附近藍牙

首先我們需要注冊兩個廣播,第一個為正在搜索時的,第二個為搜索完成的。

    // Register for broadcasts when a device is discovered    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);    this.registerReceiver(mFindBlueToothReceiver, filter);    // Register for broadcasts when discovery has finished    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);    this.registerReceiver(mFindBlueToothReceiver, filter);    //需要時開始搜索    if (mBluetoothAdapter.isDiscovering()) {          mBluetoothAdapter.cancelDiscovery();     }    mBluetoothAdapter.startDiscovery();

然后對廣播進行處理。這里要說明一下ClsUtils.createBond()這個方法如果連接設備SDK中有配對的方法,建議把這個方法去掉,我這里是去掉的,加上的話偶爾會Toast出無法配對。

 private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {    @Override    public void onReceive(Context context, Intent intent) {      String action = intent.getAction();      // When discovery finds a device      if (BluetoothDevice.ACTION_FOUND.equals(action)) {        //TODO 開始搜索        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);       //  if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//判斷藍牙狀態,是否是已配對          //TODO 可以在這判斷名字 如果搜索結束后沒有,再到已配對中尋找          String BTName[] = device.getName().split("-");          if (BTName[0].equals("xxx")) {             //在這連接設備 一般需要藍牙地址 device.getAddress();             try {               ClsUtils.createBond(device.getClass(), device);             } catch (Exception e) {               // TODO Auto-generated catch block               e.printStackTrace();             }          }       // }      } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {        //TODO 搜索結束        Toast.makeText(context, "搜索結束",Toast.LENGTH_SHORT).show();      }    }  };

這里在Activity結束時記得取消注冊和取消搜索

unregisterReceiver(mFindBlueToothReceiver); if (mBluetoothAdapter != null) {     mBluetoothAdapter.cancelDiscovery(); }

3.攔截用戶交互頁面

通過廣播可以監聽到輸入PIN碼的那個頁面將要彈出

    <receiver android:name=".BluetoothConnectActivityReceiver" >      <intent-filter android:priority="1000">        <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />      </intent-filter>    </receiver>

廣播中需要做的事情,注意一定要調用abortBroadcast(),不然交互頁面還是會出現一下然后消失。就是這個方法找了一天(╯‵□′)╯︵┴─┴。。。

public class BluetoothConnectActivityReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {    if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {      BluetoothDevice mBluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);      try {        //(三星)4.3版本測試手機還是會彈出用戶交互頁面(閃一下),如果不注釋掉下面這句頁面不會取消但可以配對成功。(中興,魅族4(Flyme 6))5.1版本手機兩中情況下都正常        //ClsUtils.setPairingConfirmation(mBluetoothDevice.getClass(), mBluetoothDevice, true);        abortBroadcast();//如果沒有將廣播終止,則會出現一個一閃而過的配對框。        //3.調用setPin方法進行配對...        boolean ret = ClsUtils.setPin(mBluetoothDevice.getClass(), mBluetoothDevice, "你需要設置的PIN碼");      } catch (Exception e) {        e.printStackTrace();      }    }  }}

然后只要在搜索到自己需要的設備后連接進行操作就可以了!!!一定要記得加權限~

 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" />

在Android6.0之后還需要一個模糊定位的權限

 

復制代碼 代碼如下:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

 

最后把ClsUtils類奉上,網上有很多的。

/**************** 藍牙配對函數 ***************/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<? extends BluetoothDevice> 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(btClass, device);    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();  }  //確認配對  static public void setPairingConfirmation(Class<?> btClass, BluetoothDevice device, boolean isConfirm) throws Exception {    Method setPairingConfirmation = btClass.getDeclaredMethod("setPairingConfirmation", boolean.class);    setPairingConfirmation.invoke(device, isConfirm);  }  /**   *   * @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();    }  }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜宁县| 浮山县| 沈阳市| 青神县| 固始县| 青海省| 大安市| 麻城市| 蒲江县| 桑植县| 嘉义县| 达州市| 泰和县| 郎溪县| 西林县| 二连浩特市| 博湖县| 民权县| 宁德市| 安阳市| 商水县| 南丹县| 南澳县| 林芝县| 两当县| 五常市| 雷山县| 安康市| 麻城市| 京山县| 靖安县| 泰和县| 巴林左旗| 纳雍县| 孟村| 孟州市| 墨玉县| 邛崃市| 芦溪县| 资中县| 商河县|