蓝牙配对无法正常工作

时间:2016-10-24 07:20:10

标签: android bluetooth

我正在努力解决与我的设备(三星Galaxy S6)中的蓝牙配对相关的问题。我有list-view,我在其中填充我的BLE设备名称,如下图enter image description here

当用户点击任何BLE时,它应与该BLE配对。我的代码工作如下:

  1. 用于呼叫广播接收器(哄骗BLE名称)

    // Quick permission check
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    int permissionCheck = getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
    permissionCheck += getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
    if (permissionCheck != 0) {
    
    this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
    }
    }
    
    getActivity().registerReceiver(FoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    getActivity().registerReceiver(FoundReceiver, filter);
    
    mBluetoothAdapter.startDiscovery();
    
    1. 为了填充BLE列表,下面的代码工作正常。

      private final BroadcastReceiver FoundReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
      
      String action = intent.getAction();
      
      // When discovery finds a new device
      if (BluetoothDevice.ACTION_FOUND.equals(action)) {
          // Get the BluetoothDevice object from the Intent
          BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
          if (!bleName.contains(device)) {
              if(device.getName() != null){
                  bleName.add(device.getName());
              }
              Toast.makeText(getActivity(), "name: " + device.getName() + " " + device.getAddress(), Toast.LENGTH_LONG).show();
              bedListADPT = new BleList(context, bleName);
              listView.setAdapter(bedListADPT);
              if(!dvcNameBle.containsKey(device.getName())) {
                  dvcNameBle.put(device.getName(), device);
              }
              bedListADPT.notifyDataSetChanged();
          }
      
      }
      // When discovery cycle finished
      if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
          if (bleName == null || bleName.isEmpty()) {
              Toast.makeText(getActivity(), "No Devices", Toast.LENGTH_LONG).show();
          }
      }
      }
      };
      
  2. 现在,当用户点击列表项时,它应该与该BLE名称配对。

    1. 点击列表项目的活动

      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1,
                              int position, long arg3) {
          Toast.makeText(getActivity(),bedListADPT.getItem(position).toString(),Toast.LENGTH_LONG).show();
      
          IntentFilter filter = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
      
         /**
           * Registering a new BTBroadcast receiver from the Main Activity context
           * with pairing request event
           */
          selectedDevice = bedListADPT.getItem(position).toString();
          getActivity().registerReceiver(new PairingRequest(dvcNameBle,selectedDevice), filter);
          Toast.makeText(getActivity(),""+dvcNameBle.size(),Toast.LENGTH_LONG).show();
      
      }
      });
      
    2. 下面的广播接收器与BLE配对

      public  class PairingRequest extends BroadcastReceiver {
          private static HashMap<String, BluetoothDevice> mdvcNameBle = new HashMap<String, BluetoothDevice>();
          private static String mselectedDevice = "";
          public PairingRequest() {
              super();
          }
      
          public PairingRequest(HashMap<String, BluetoothDevice> dvcNameBle, String mselectedDevice){
              super();
              this.mdvcNameBle = dvcNameBle;
              this.mselectedDevice = mselectedDevice;
          }
      
          @Override
          public void onReceive(Context context, Intent intent) {
              if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
                  try {
                      BluetoothDevice device = mdvcNameBle.get(mselectedDevice);
      
                      int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                      //the pin in case you need to accept for an specific pin
                      Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0));
                      //maybe you look for a name or address
                      Log.d("Bonded", device.getName());
                      byte[] pinBytes;
                      pinBytes = (""+pin).getBytes("UTF-8");
                      device.setPin(pinBytes);
                      //setPairing confirmation if neeeded
                      device.setPairingConfirmation(true);
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          }
      }
      

      在清单文件中,我已经声明了广播接收器和应用程序所需的权限

      <receiver android:name=".PairingRequest">
              <intent-filter>
                  <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
              </intent-filter>
      </receiver>
      
      <uses-permission android:name="android.permission.BLUETOOTH"  android:label="BLUETOOTH"/>
      <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      

      当我打电话时

        

      PairingRequest

      没有发生任何事情;这意味着没有例外没有配对。

      任何帮助都会非常明显。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我得到了答案

public boolean createBond(BluetoothDevice btDevice)
        throws Exception {
    Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
    Method createBondMethod = class1.getMethod("createBond");
    Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
    return returnValue.booleanValue();
}

如果上面的代码在API 23中不起作用,那么请快速检查Android权限。

    // Quick permission check
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        int permissionCheck = getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        permissionCheck += getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        if (permissionCheck != 0) {

            this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
        }
    }