蓝牙BLE连接到Gatt服务器不能正常工作

时间:2018-02-22 18:13:50

标签: android bluetooth-lowenergy gatt bluetooth-gatt

我有一个连接到配对设备的Android应用程序。问题是,如果我在应用程序启动之前没有启用此设备,它将无法运行。

唯一可行的情况是当设备打开然后我启动应用程序。如果我启动应用程序并启动设备,它就永远不会连接。

以下是代码:

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

    // Check if the system supports Bluetooth Low Energy
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "BLE Not Supported", Toast.LENGTH_SHORT).show();
        finish();
    }

    // Take the system BLE adapter
    bleAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter();

    // Enable Bluetooth in case it's off.
    if (bleAdapter == null || !bleAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }

    start_microbit();
}

private void start_microbit() {

    // Get paired devices.
    Set<BluetoothDevice> pairedDevices = bleAdapter.getBondedDevices();

    for (BluetoothDevice device : pairedDevices) {

        // Connect to Micro:Bit (the only one paired device)
        device.connectGatt(this, true, new BluetoothGattCallback() {

            // Check if it connects or disconnects from the Micro:Bit
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
                super.onConnectionStateChange(gatt, status, newState);

                switch (newState) {
                    case BluetoothProfile.STATE_CONNECTED:
                        runOnUiThread(new Runnable() {
                            public void run() {
                                ((TextView) findViewById(R.id.state)).setText("Connected to Micro:Bit");
                                ((TextView) findViewById(R.id.state)).setTextColor(Color.GREEN);
                            }
                        });

                        gatt.discoverServices();
                        break;

                    case BluetoothProfile.STATE_DISCONNECTED:
                        runOnUiThread(new Runnable() {
                            public void run() {
                                ((TextView) findViewById(R.id.state)).setText("Not connected");
                                ((TextView) findViewById(R.id.state)).setTextColor(Color.RED);
                            }
                        });

                        gatt.disconnect();
                        break;
                }
            }
        });
    }
}

0 个答案:

没有答案