Не удается подключиться к устройству BLE. SetItemOnClickListener - PullRequest
0 голосов
/ 07 сентября 2018

Я создал фоновый сервис для устройства для подключения и чтения рекламных пакетов.Устройства, которые я получаю после сканирования Bluetooth Low Energy Scanner, отображаются в виде списка.Но всякий раз, когда я нажимаю на элемент ListView, устройство не подключается, несмотря на запуск службы после получения адреса.для подключения устройства я использую этот метод

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()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }

        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.w(TAG, "Device not found.  Unable to connect.");
            Toast.makeText(this, "Unable to connect", Toast.LENGTH_SHORT).show();
            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;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

Метод, из которого я пытаюсь получить доступ к этому методу, - как стипендиаты.в DeviceActivity

Intent gattServiceIntent = new Intent(this, LeBluetoothService.class);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Toast.makeText(context, "you clicked", Toast.LENGTH_SHORT).show();

                device = mLeDeviceListAdapter.getDevice(position);
                mDeviceAddress = device.getAddress();

                bindService(gattServiceIntent, mServiceConnection, BIND_ABOVE_CLIENT);




                mScanning = false;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    mBluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
                } else {

                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                }
                invalidateOptionsMenu();


//                mLeBluetoothService.connect(mDeviceAddress);


                //   Toast.makeText(context, "connected to: "+mDeviceAddress, Toast.LENGTH_SHORT).show();

            }
        });

Для соединения с автоматической службой я использую следующий код:

 private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mLeBluetoothService = ((LeBluetoothService.LocalBinder) service).getService();
            if (!mLeBluetoothService.initialize()) {
                Toast.makeText(context, "Unable to initialize Bluetooth", Toast.LENGTH_SHORT).show();
                finish();

            }
            mLeBluetoothService.connect(mDeviceAddress);
            Toast.makeText(context, "Connected to " + mDeviceAddress, Toast.LENGTH_SHORT).show();


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mLeBluetoothService = null;
        }
    };

Когда я пытаюсь подключиться напрямую из списка, он дает мне нулевой указательИсключение.

1 Ответ

0 голосов
/ 12 сентября 2018

попробуйте эту библиотеку https://github.com/Jasonchenlijian/FastBle это дает вам простые методы

...