2017-08-30 4 views

答えて

1

スキャン、スキャン要求に対する結果は、あなたが望む方法で返されます、例えば

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デバイスのアドレスがわかっている場合、サービスを検出せずに直接接続できますか?

答えは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

2番目の質問に対する回答はもう少し進んでいます。 APIのアドレスタイプパラメータが不足しているため、最後のBluetoothリセットまたはボンディングされてからスキャンした場合にのみ、確実にデバイスアドレスに接続できます。 – Emil

+0

@Emilその場合、別のコールバックを使用して、サービスを検出せずにデバイスにリダイレクトしてスキャンして接続することができます。 'BluetoothAdapter.LeScanCallback mLeScanCallback =新しいBluetoothAdapter.LeScanCallback()'。 このコールバックを使用すると、見つかったデバイスをスキャンして追加できます。 –

+0

@DuyKyou私が間違っていない場合LeScanCallbackはAndroid Jまで使用されていますが、将来はgetBluetoothScanner()ですstartScan() – Raulp

関連する問題