Dimitri Williams
Dimitri Williams

Reputation: 732

How does scanCallback work for BluetoothDevices?

I am following this tutorial. https://medium.com/@avigezerit/bluetooth-low-energy-on-android-22bc7310387a

Trying to understand LeScancallBacks

I am also following the documentation and the sample for Bluetooth devices from google

BluetoothAdapter.LeScanCallback scanCallback =
                new BluetoothAdapter.LeScanCallback() {};

  bluetoothAdapter.startLeScan(scanCallback);

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
        byte[] scanRecord) {
            if(device.address == HR_SENSOR_ADDRESS){
                myDevice = device;
            }
        }

My Code gives me the following error:

"Class 'Anonymous class derived from LeScanCallback' must either be declared abstract or implement abstract method 'onLeScan(BluetoothDevice, int, byte[])' in 'LeScanCallback'"

When I compare it with the code from google.

 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                intentAction = ACTION_GATT_CONNECTED;
                mConnectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                Log.i(TAG, "Connected to GATT server.");
                // Attempts to discover services after successful connection.
                Log.i(TAG, "Attempting to start service discovery:" +
                        mBluetoothGatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                intentAction = ACTION_GATT_DISCONNECTED;
                mConnectionState = STATE_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                broadcastUpdate(intentAction);
            }
        }

This is the only other Callback I can find, is it possible that someone can help? I tried to program this project, alone for some time.

Upvotes: 1

Views: 521

Answers (1)

PGMacDesign
PGMacDesign

Reputation: 6302

When you define that scanCallback object, you need to add in the required method like so:

    BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                //do stuff here
            }
    };

You can then handle the response in that onLeScan method.

In Java, an abstract class requires that any instantiation of it must implement the required methods, which is the error you were getting.

Upvotes: 1

Related Questions