我的布局中有一个按钮和一个 TextView。
我正在尝试获取BLE设备的信号强度值,目标是找到不需要连接的所需设备在哪里,为此我需要获取我附近所有设备的RSSI。我根据其他帖子编写了以下代码。
问题是我的设备从来没有进入ScanCallback函数,我不知道为什么。 有人可以指导如何解决问题吗?谢谢!
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);
}
});
}
}
您可以这样搜索设备:
bluetoothAdapter.bluetoothLeScanner?.startScan(emptyList(), scanSetting, 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)
}
}