2017-09-28 36 views
1

早上好, 我正在开发一个BLE应用程序,并且我为GATT连接写了一个活动。现在我遇到了一个问题,因为有时系统会识别服务和特征,而其他时间则不识别。蓝牙低功耗服务每次都没有找到

下面是我的一些代码:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_gatt); 

    peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView); 
    peripheralTextView.setMovementMethod(new ScrollingMovementMethod()); 

    scanServiceButton = (Button) findViewById(R.id.scan_service); 
    scanServiceButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      mBluetoothGatt.discoverServices(); 
     } 
    }); 

    //get the Bluetooth device which comes from mainActivity 
    BluetoothDevice bluetoothDevice = getIntent().getExtras().getParcelable("selectedDevice"); 
    String test = bluetoothDevice.getAddress(); 
    Toast toast = Toast.makeText(this, "Verbunden mit " + test, Toast.LENGTH_LONG); 
    toast.show(); 

    Log.d("GattActivity", "connectGatt()"); 
    mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback); 
} 

,这是我onServiceDiscovered那里有时我得到的服务的所有值,但很多时候它没有得到任何:

 @Override 
    public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
     //new Services discovered 
     if(status == BluetoothGatt.GATT_SUCCESS){ 
      broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); 
      displayGattServices(mBluetoothGatt.getServices()); 
     }else{ 
      Log.d("GattActivity", "onServicesDiscovered received: " + status); 
     } 
    } 

我用Google搜索很多,我认为它与Google的样本非常相似,但我不知道它为什么有时显示,有时不显示。

也许有人可以帮我

+0

也许重要的是要知道我测试过哪些设备。我使用了Samsung s5 mini和Google Nexus 5,我的广告是由OnePlus 3t通过Google的Advtertisement Sample发送的。 – Fab

回答

0

我得到了一个解决方案,现在希望它是正确的。

我做的第一件事是确保我们已经访问粗略位置启用。

if(this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){...} 

其次我忘了后,我做这两件事情它的工作原理,每次使用discoverServices()在onConnectionStateChange()

@Override 
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {.... mBluetoothGatt.discoverServices()...;} 

(测试了大约50倍希望将现在的工作) 但如果你知道一个更好的解决方案可以自由回答我