2017-08-30 39 views
0

是Android gat connect還是Android掃描(getBluetoothLeScanner),它會導致掃描請求和響應? 如果我們知道BLE設備地址,我們是否可以直接連接到BLE設備地址而無需發現服務?哪個Android API問題掃描請求和響應

回答

1

在Android的BLE掃描,對掃描請求將在你所希望的方式返回,例如

List<ScanFilter> filters = new ArrayList<ScanFilter>(); 

ScanFilter filter = new ScanFilter.Builder() 
     .setServiceUuid(uuid) 
     .setDeviceAddress(address) 
     .setDeviceName(name) 
     .build(); 
filters.add(filter); 

和掃描響應的結果將返回在

onScanResult(INT callbackType,ScanResult結果)

ScanCallBack mCallback = new ScanCallback() { 
     @Override 
     public void onScanResult(int callbackType, ScanResult result) { 
      super.onScanResult(callbackType, result); 
      if (result != null){ 
       BluetoothDevice device = result.getDevice(); 
       mDeviceList.add(device); 
       removeDuplicateWithOrder(mDeviceList); 
       adapter.notifyDataSetChanged(); 
      } 
     } 

     @Override 
     public void onBatchScanResults(List<ScanResult> results) { 
      super.onBatchScanResults(results); 
     } 

     @Override 
     public void onScanFailed(int errorCode) { 
      super.onScanFailed(errorCode); 
      Log.e("TAG", "Scan failed " + errorCode); 
     } 
    }; 

如果我們知道BLE設備地址,我們可以直接連接到BLE設備地址而無需發現服務?

答案是YES 你可以按照這個例子

public boolean connect(final String address) { 
    if (mBluetoothAdapter == null || address == null) { 
     Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); 
     return false; 
    } 

    // Previously connected device. Try to reconnect. 
    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) 
      && mBluetoothGatt != null) { 
     Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); 
     if (mBluetoothGatt.connect()) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 
    if (device == null) { 
     Log.w(TAG, "Device not found. Unable to connect."); 
     return false; 
    } 
    // We want to directly connect to the device, so we are setting the autoConnect 
    // parameter to false. 
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback); 
    Log.d(TAG, "Trying to create a new connection."); 
    mBluetoothDeviceAddress = address; 
    return true; 
} 

希望這可以幫助。

+0

第二個問題的答案有點高級。由於缺少API中的地址類型參數,如果自上次藍牙重置或已綁定以來掃描它,則只能可靠地連接到設備地址。 – Emil

+0

@Emil,在這種情況下,我可以使用另一個回調掃描並將重定向連接到設備,而無需發現服務。 'BluetoothAdapter.LeScanCallback mLeScanCallback =新的BluetoothAdapter.LeScanCallback()'。 此回調將允許我掃描並添加找到的任何設備。 –

+0

@DuyKyou如果我沒有錯LeScanCallback被使用,直到Android J和未來它是getBluetoothScanner()。startScan() – Raulp