2017-11-12 22 views
0

Android Studio(java)を使用してBLEデバイスをスキャンし、接続してデータを送信しています。BLEはデバイスを見つけても接続していません

これまではBLEデバイスを検出できる機能的なスキャナを作成しましたが、デバイス名、MACアドレス、RSSI値を呼び出すことはできますが、接続することはできません。私はMACアドレスを持っていることを考えると、コードの単純な小さなセグメントではないのですか?

私はcreateBond()を使用しようとしましたが、これはデバッグセクションで応答しますが、何もしません。

実際のスキャンのMACアドレスがありますが、そのアドレスから直接接続できる方法はありますか?私は同じBLEモジュールにしか接続しないので、それは私の目的にも役立ちます。ここで

あなたは私が持っているものを見ることができますので、私のコードですBLE周辺機器に接続するの

public class BluetoothConnect extends AppCompatActivity { 

    BluetoothManager btManager; 
    BluetoothAdapter btAdapter; 
    BluetoothLeScanner btScanner; 
    Button startScanningButton; 
    Button stopScanningButton; 
    TextView peripheralTextView; 
    private final static int REQUEST_ENABLE_BT = 1; 
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1; 
    final Intent startMainActivity = new Intent(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.scan_and_connect); 

     controlTankScreen(); 

     //sets us the window for devices to be listed 
     peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView); 
     peripheralTextView.setMovementMethod(new ScrollingMovementMethod()); 

     //button id 6 is start scanning 
     startScanningButton = findViewById(R.id.button6); 
     startScanningButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       startScanning(); 
      } 
     }); 
     //button id 7 is stop scanning 
     stopScanningButton = findViewById(R.id.button7); 
     stopScanningButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       stopScanning(); 
      } 
     }); 

     //enables bluetooth, Adapter refers to the local device, in this case, my smart phone 
     btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE); 
     btAdapter = btManager.getAdapter(); 
     btScanner = btAdapter.getBluetoothLeScanner(); 


     if (btAdapter != null && !btAdapter.isEnabled()) { 
      Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
      startActivityForResult(enableIntent,REQUEST_ENABLE_BT); 

     } 

    // Make sure we have access coarse location enabled, if not, prompt the user to enable it 
    if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setTitle("This app needs location access"); 
     builder.setMessage("Please grant location access so this app can detect peripherals."); 
     builder.setPositiveButton(android.R.string.ok, null); 
     builder.setOnDismissListener(new DialogInterface.OnDismissListener() { 
      @Override 
      public void onDismiss(DialogInterface dialog) { 
       requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); 
      } 
     }); 
     builder.show(); 
    } 
} 


// this will scan for devices, displaying the device name, the mac address, and the RSSI, recieved signal strength indicator 
public ScanCallback leScanCallback = new ScanCallback() { 
    @Override 
    public void onScanResult(int callbackType, ScanResult result) { 
     peripheralTextView.append("Device Name: " + result.getDevice().getName() +"Mac Address: "+ result.getDevice().getAddress() +" rssi: " + result.getRssi() + "\n"); 
     String deviceName = result.getDevice().getName(); 
     String deviceAddress = result.getDevice().getAddress(); 
     result.getDevice().createBond(); 

     // auto scroll for text view 
     final int scrollAmount = peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount()) - peripheralTextView.getHeight(); 
     // if there is no need to scroll, scrollAmount will be <=0 
     if (scrollAmount > 0) 
      peripheralTextView.scrollTo(0, scrollAmount); 
    } 
}; 



@Override 
//This makes sure that Bluetooth and correct permissions are allowed 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case PERMISSION_REQUEST_COARSE_LOCATION: { 
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       System.out.println("coarse location permission granted"); 
      } else { 
       final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
       builder.setTitle("Functionality limited"); 
       builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background."); 
       builder.setPositiveButton(android.R.string.ok, null); 
       builder.setOnDismissListener(new DialogInterface.OnDismissListener() { 

        @Override 
        public void onDismiss(DialogInterface dialog) { 
        } 

       }); 
       builder.show(); 
      } 
      return; 
     } 
    } 
} 
//ran when button id 6, start scan is pressed 
public void startScanning() { 
    System.out.println("start scanning"); 
    peripheralTextView.setText("Started Scanning"); 
    //startScanningButton.setVisibility(View.INVISIBLE); 
    //stopScanningButton.setVisibility(View.VISIBLE); 
    AsyncTask.execute(new Runnable() { 
     @Override 
     public void run() { 
      btScanner.startScan(leScanCallback); 
     } 
    }); 
} 
//ran when button id 7, stop scan is pressed 
public void stopScanning() { 
    System.out.println("stopping scanning"); 
    peripheralTextView.append("Stopped Scanning"); 
    //startScanningButton.setVisibility(View.VISIBLE); 
    //stopScanningButton.setVisibility(View.INVISIBLE); 
    AsyncTask.execute(new Runnable() { 
     @Override 
     public void run() { 
      btScanner.stopScan(leScanCallback); 
     } 
    }); 
} 
//ran from onCreate on app boot up, just sets the app up to control the tank 
public void controlTankScreen() { 
    startMainActivity.setComponent(new ComponentName("smiths.tankcontroller", "smiths.tankcontroller.MainActivity")); 

    final Button button = findViewById(R.id.button5); 
    button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      startActivity(startMainActivity); 
      setContentView(R.layout.activity_main); 

      //what to do when the button is pressed 
      finish(); 

     } 
    }); 
} 



IntentFilter intent = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 


private final BroadcastReceiver bluetoothParingReciever = new BroadcastReceiver() { 
    public void onReceive(Context context, Intent intent) { 
     String action = intent.getAction(); 

     if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { 
      final int state  = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); 
      final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); 

      if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { 
       System.out.println("Paired"); 
      } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){ 
       System.out.println("Unpaired"); 
      } 

     } 
    } 
}; 

public void pairDevice(BluetoothDevice device) { 
    try { 
     Method method = device.getClass().getMethod("createBond", (Class[]) null); 
     method.invoke(device, (Object[]) null); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
} 
+0

古典的なBluetooth(?)のためだけに 'createBond()'はありません。 Bluetooth LEでは、接続するデバイスは「GATTサーバ」なので、[Bluetooth LEのAndroidドキュメント](https://developer.android.com/guide/topics/connectivity/bluetooth-le .html)。 –

答えて

0

正しい方法で機能しているすべては:

final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 

mBluetoothGatt = device.connectGatt(this, false, mGattCallback); 

特性のいずれかが暗号化が必要な場合読み取り/書き込み結果「BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION」を処理して再試行する必要があります。

+0

私は実際にはその部分を理解していないので、私はhavent bluetoothGattシステムのいずれかを使用して、主に。私はそれなしで機能するスキャナを作成したので、私はそれなしで接続できませんか?私はそれを読んで見ることができますから、私はBluetoothGattを使用するコードの半分を変更する必要があります – user8927659

関連する問題