以下是一个使用Android的BluetoothLeScanner类进行BLE设备扫描的简单示例代码:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
public class MainActivity extends Activity {
private static final String TAG = "BLEScanner";
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private ScanCallback mScanCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取BluetoothAdapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 检查设备是否支持BLE
if (mBluetoothAdapter == null || !mBluetoothAdapter.isMultipleAdvertisementSupported()) {
Log.e(TAG, "设备不支持BLE");
return;
}
// 获取BluetoothLeScanner
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
// 设置扫描回调
mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
Log.d(TAG, "发现设备: " + device.getName() + ", " + device.getAddress());
}
@Override
public void onBatchScanResults(List results) {
for (ScanResult result : results) {
BluetoothDevice device = result.getDevice();
Log.d(TAG, "发现设备: " + device.getName() + ", " + device.getAddress());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e(TAG, "扫描失败: " + errorCode);
}
};
// 设置扫描参数
ScanSettings scanSettings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
// 开始扫描
mBluetoothLeScanner.startScan(null, scanSettings, mScanCallback);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 停止扫描
mBluetoothLeScanner.stopScan(mScanCallback);
}
}
要注意的是,为了进行BLE扫描,需要在AndroidManifest.xml
文件中添加以下权限:
希望这个示例能帮助到你!
下一篇:BLE扫描时出现错误代码2