android - Android BLE 与 MAC 地址连接
问题描述
我尝试将 Arduino 和 Android 手机与 BLE 连接。
但它不起作用。
我希望应用程序与具有特定名称和 MAC 地址的特定设备连接。
我声明Mac地址
private static String Adr = "D4:36:39:6F:7F:0E";
等等
private BluetoothGattCharacteristic characteristic;
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
private SharedPreferences setting;
并做了一些课程。
部分分类是
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("callbackType", String.valueOf(callbackType));
Log.i("result", result.toString());
btDevice = result.getDevice();
if (btDevice != null && btDevice.getName() != null && btDevice.getName().contains("Device"))
connectToDevice(btDevice);
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.i("ScanResult - Results", sr.toString());
}
}
@Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("onLeScan", device.toString());
connectToDevice(device);
}
});
}
};
我搜索了互联网并修改了
public void connectToDevice(BluetoothDevice device) {
if (mGatt == null) {
btDevice = mBluetoothAdapter.getRemoteDevice(CantusAdr);
mGatt = device.connectGatt(this, false, gattCallback);
}
}
与 arduino 设备连接。
和
private ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("callbackType", String.valueOf(callbackType));
Log.i("result", result.toString());
btDevice = result.getDevice();
if (btDevice != null && btDevice.getName() != null && btDevice.getName().contains("Device"))
connectToDevice(btDevice);
}
此代码用于连接具有 MAC 地址“D4:36:39:6F:7F:0E”的命名“设备”
应用程序正在运行。
它与一台设备连接,但不与“设备”“D4~~~”连接。
我该如何解决?
请帮我。
解决方案
如果您已经知道要连接的设备的地址,则无需进行蓝牙 LE 扫描。这应该足够了:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("D4:36:39:6F:7F:0E");
device.connectGatt(this, false, gattCallback);
推荐阅读
- javascript - 使用 POST 表单发送 Blob 对象
- python - 恢复张量流模型
- powershell - 如果基于 DNS 名称解析的逻辑导致 Powershell
- python - 上传/下载到 S3 的奇怪 mime 类型的对象
- c++ - c ++ 11 chrono创建日期,时间和毫秒格式的时间戳字符串
- json - 如何序列化/反序列化 Kotlin 密封类?
- scala - Scala - Swagger:使用特征作为@Apiresponse 的响应类型
- jenkins - 带有 Jenkins 环境变量的 Artifactory API AQL
- javascript - JQuery datepicker on click on label
- sql - etl:我们可以聚合动态行数并添加 datedynamic using-talend-open-studio