Мне нужно приложение для Android, которое считывает частоту пульса. Первым делом необходимо просканировать устройства и подключиться к выбранному. У меня есть код, но он не работает. BLE активен, другие приложения могут подключаться и отображать частоту пульса, но в этом случае я получаю только «Начало сканирования» и ничего больше.
Знаете, что не так?
BR,
Марцин
Вот мой код.
package com.example.edgetest1;
import static androidx.core.location.LocationManagerCompat.isLocationEnabled;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
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.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeScanner bluetoothLeScanner;
private ListView bleList;
private TextView pulse;
private BluetoothGatt bluetoothGatt;
private List bleDevices = new ArrayList();
private ArrayAdapter bleListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pulse = findViewById(R.id.pulse);
bleList = findViewById(R.id.bleList);
Button findBleButton = findViewById(R.id.findBle);
Button connectForceButton = findViewById(R.id.forceConnect);
Button connectButton = findViewById(R.id.connect);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
bleListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
bleList.setAdapter(bleListAdapter);
findBleButton.setOnClickListener(v -> startBleScan());
connectForceButton.setOnClickListener( v -> {
}
);
connectButton.setOnClickListener(v -> {
int position = bleList.getCheckedItemPosition();
if (position != ListView.INVALID_POSITION) {
BluetoothDevice device = bleDevices.get(position);
connectToDevice(device);
} else {
msg("Please select a device to connect");
}
});
}
private void startBleScan() {
if (bluetoothLeScanner != null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
msg("No SCAN permission 1");
return;
}
bluetoothLeScanner.stopScan(scanCallback); // Stop any ongoing scan
bleDevices.clear();
bleListAdapter.clear();
// Check if Bluetooth is enabled
if (!bluetoothAdapter.isEnabled()) {
msg("Please enable Bluetooth");
return;
}
// Check if location services are enabled
if (!isLocationEnabled()) {
msg("Please enable location services");
return;
}
bluetoothLeScanner.startScan(scanCallback); // Start a new scan
msg("Starting scan...");
}
}
private boolean isLocationEnabled() {
/* Check if location services are enabled */
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
};
private final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
msg("Have the results...");
BluetoothDevice device = result.getDevice();
if (!bleDevices.contains(device)) {
bleDevices.add(device);
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 1");
return;
}
bleListAdapter.add(device.getName() + " (" + device.getAddress() + ")");
bleListAdapter.notifyDataSetChanged();
}
}
@Override
public void onBatchScanResults(List results) {
msg("Have the bath results...");
for (ScanResult result : results) {
onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, result);
}
}
@Override
public void onScanFailed(int errorCode) {
msg("BLE scan failed with error code: " + errorCode);
}
};
private void connectToDevice(BluetoothDevice device) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 2");
return;
}
msg("Trying to connect");
bluetoothGatt = device.connectGatt(this, false, gattCallback);
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
msg("Connection state changed");
// Handle connection state changes
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
BluetoothGattService service = gatt.getService(UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb"));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"));
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 3");
return;
}
gatt.setCharacteristicNotification(characteristic, true);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
int value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
runOnUiThread(() -> pulse.setText("Pulse: " + value));
}
};
public void msg(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
Полагаю, все разрешения имеются.
Подробнее здесь: https://stackoverflow.com/questions/793 ... ng-android
Сканирование устройств BLE — Android ⇐ JAVA
Программисты JAVA общаются здесь
1736105908
Anonymous
Мне нужно приложение для Android, которое считывает частоту пульса. Первым делом необходимо просканировать устройства и подключиться к выбранному. У меня есть код, но он не работает. BLE активен, другие приложения могут подключаться и отображать частоту пульса, но в этом случае я получаю только «Начало сканирования» и ничего больше.
Знаете, что не так?
BR,
Марцин
Вот мой код.
package com.example.edgetest1;
import static androidx.core.location.LocationManagerCompat.isLocationEnabled;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
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.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeScanner bluetoothLeScanner;
private ListView bleList;
private TextView pulse;
private BluetoothGatt bluetoothGatt;
private List bleDevices = new ArrayList();
private ArrayAdapter bleListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pulse = findViewById(R.id.pulse);
bleList = findViewById(R.id.bleList);
Button findBleButton = findViewById(R.id.findBle);
Button connectForceButton = findViewById(R.id.forceConnect);
Button connectButton = findViewById(R.id.connect);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
bleListAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
bleList.setAdapter(bleListAdapter);
findBleButton.setOnClickListener(v -> startBleScan());
connectForceButton.setOnClickListener( v -> {
}
);
connectButton.setOnClickListener(v -> {
int position = bleList.getCheckedItemPosition();
if (position != ListView.INVALID_POSITION) {
BluetoothDevice device = bleDevices.get(position);
connectToDevice(device);
} else {
msg("Please select a device to connect");
}
});
}
private void startBleScan() {
if (bluetoothLeScanner != null) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
msg("No SCAN permission 1");
return;
}
bluetoothLeScanner.stopScan(scanCallback); // Stop any ongoing scan
bleDevices.clear();
bleListAdapter.clear();
// Check if Bluetooth is enabled
if (!bluetoothAdapter.isEnabled()) {
msg("Please enable Bluetooth");
return;
}
// Check if location services are enabled
if (!isLocationEnabled()) {
msg("Please enable location services");
return;
}
bluetoothLeScanner.startScan(scanCallback); // Start a new scan
msg("Starting scan...");
}
}
private boolean isLocationEnabled() {
/* Check if location services are enabled */
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
};
private final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
msg("Have the results...");
BluetoothDevice device = result.getDevice();
if (!bleDevices.contains(device)) {
bleDevices.add(device);
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 1");
return;
}
bleListAdapter.add(device.getName() + " (" + device.getAddress() + ")");
bleListAdapter.notifyDataSetChanged();
}
}
@Override
public void onBatchScanResults(List results) {
msg("Have the bath results...");
for (ScanResult result : results) {
onScanResult(ScanSettings.CALLBACK_TYPE_ALL_MATCHES, result);
}
}
@Override
public void onScanFailed(int errorCode) {
msg("BLE scan failed with error code: " + errorCode);
}
};
private void connectToDevice(BluetoothDevice device) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 2");
return;
}
msg("Trying to connect");
bluetoothGatt = device.connectGatt(this, false, gattCallback);
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
msg("Connection state changed");
// Handle connection state changes
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
BluetoothGattService service = gatt.getService(UUID.fromString("0000180d-0000-1000-8000-00805f9b34fb"));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"));
if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
msg("No CONNECT permission 3");
return;
}
gatt.setCharacteristicNotification(characteristic, true);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
int value = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
runOnUiThread(() -> pulse.setText("Pulse: " + value));
}
};
public void msg(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
Полагаю, все разрешения имеются.
Подробнее здесь: [url]https://stackoverflow.com/questions/79331423/ble-devices-scanning-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия