【发布时间】:2018-05-08 21:51:52
【问题描述】:
我现在正在尝试在一个简单的 Android 应用程序中实现一个 BLE 扫描仪。 我一直在关注: startLeScan replacement to current api 和 https://developer.android.com/guide/topics/connectivity/bluetooth-le
不幸的是,我的 BLEScanCallback 类的回调函数似乎没有被调用。我一直在尝试使用 Log.e 来查看是否有人调用了它们。
我调试了应用程序,应用程序进入了 bluetoothLeScanner.stopScan(scanCallback);在 run() 函数中。
我已将 BLUETOOTH、BLUETOOTH_ADMIN 和 ACCESS_COARSE_LOCATION 添加到清单中。
我不确定我在这里做错了什么。对此的任何帮助将不胜感激。
谢谢
相关代码如下:
public class DiscoverActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private boolean scanning;
private Handler handler;
static int REQUEST_ENABLE_BT = 1001;
private static final long SCAN_PERIOD = 10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
handler = new Handler();
scanning = false;
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean ret;
int id = item.getItemId();
switch (id){
case R.id.scan:
Log.e("test", "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
scanBLEDevices(true);
ret = true;
break;
default:
ret = super.onOptionsItemSelected(item);
}
return ret;
}
private void scanBLEDevices(final boolean enable){
final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
final BLEScanCallback scanCallback = new BLEScanCallback();
if (enable){
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
@Override
public void run() {
scanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}, SCAN_PERIOD);
scanning = true;
bluetoothLeScanner.startScan(scanCallback);
}else{
scanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}
public class BLEScanCallback extends ScanCallback{
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.e("Scan Success", "Scan Success");
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.e("Scan Success", "Scan Success Batch");
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("Scan Failed", "Error Code: " + errorCode);
}
}
}
【问题讨论】:
-
你有权限吗?
-
我在清单中添加了 BLUETOOTH、BLUETOOTH_ADMIN 和 ACCESS_COARSE_LOCATION 权限。
标签: java android callback bluetooth-lowenergy