Marc Ledesma Chivite
Marc Ledesma Chivite

Reputation: 21

Android 10: How to get the rssi value of a non connected bluetooth device

I have a button and a TextView in my layout.

I am trying to get signal strength value of a BLE device, the goal is to find where is the desired devices without need to be connected, and for this I need to get the RSSI of all devices near me. I wrote the following code based on other posts.

The problem is that my device never enters the ScanCallback function, and I don't know why. Can someone give a guide on how to solve the problem? Thanks!

import ...

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private ScanCallback mScanCallback;
    private Button mButton;
    private TextView mTextView;

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

        mButton = findViewById(R.id.button1);
        mTextView = findViewById(R.id.textView1);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        mScanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);
                int rssi = result.getRssi();
                mTextView.setText("RSSI: " + rssi);
            }
        };

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {return;}
                mBluetoothLeScanner.startScan(mScanCallback);
            }
        });

    }
}

Upvotes: 2

Views: 628

Answers (1)

Amin Keshavarzian
Amin Keshavarzian

Reputation: 3963

You can search for devices like this:

bluetoothAdapter.bluetoothLeScanner?.startScan(emptyList(), scanSetting, callback)

and use this scan callback:

    callback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult?) {
            timber.d("device found name: ${result.device?.name} address: ${result.device?.address}")
            val rssi = result.rssi
        }

        override fun onScanFailed(errorCode: Int) {
            onError("BLE scan failed with error code: $errorCode", errorCode)
        }
    }

Upvotes: 0

Related Questions