Мне нужно создать приложение для Android, которое использует BLE для одновременного подключения к нескольким устройствам.
Поэтому я создал этот код в классе основной деятельности:
public class SensorService extends IntentService {
public static final String tag = "Ssensors";
private static final String ACTION_FOO = "it.eresult.silvermountain.service.action.FOO";
private static final String ACTION_BAZ = "it.eresult.silvermountain.service.action.BAZ";
// TODO: Rename parameters
private static final String EXTRA_PARAM1 = "it.eresult.silvermountain.service.extra.PARAM1";
private static final String EXTRA_PARAM2 = "it.eresult.silvermountain.service.extra.PARAM2";
public long dosimeterScanningTime;
private Context mContext;
private String macAddress;
private int mStatus;
//private BluetoothDevice mDevice;
List listaSensori = new ArrayList();
public SensorService() {
super("SensorService");
}
// TODO: Customize helper method
public static void startActionFoo(Context context, String param1, String param2) {
Intent intent = new Intent(context, SensorService.class);
intent.setAction(ACTION_FOO);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
// TODO: Customize helper method
public static void startActionBaz(Context context, String param1, String param2) {
Intent intent = new Intent(context, SensorService.class);
intent.setAction(ACTION_BAZ);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(tag, "ON HANDLE INTENT");
Bundle extras = intent.getExtras();
if (extras == null) {
Log.d(tag, "No macAddress configuration");
}
else {
String firstMacAddress = (String) extras.get("firstDevice");
String secondMacAddress = (String) extras.get("secondDevice");
//questa parte di codice va rivista
if (intent != null) {
String action = intent.getStringExtra(PreferenceHandler.ACTION);
Log.d(tag, action != null ? action : "no action");
if (action != null && action.equals(PreferenceHandler.ACTION_CHANGE_SCANNING_ROTATION_TIME)) {
Log.d(tag, "modifico il servizio");
//todo questa parte va rivista
int rTime = 10;
int sTime = 10;
dosimeterScanningTime = sTime;
Log.d(tag, "val new " + dosimeterScanningTime);
//provo a vedere se la modifica ha risolto qualcosa
return;
} else if (action != null && action.equals(PreferenceHandler.ACTION_STOP)) {
Log.d(tag, "fermo il servizio");
dosimeterScanningTime = 0;
//provo a vedere se la modifica ha risolto qualcosa
return;
}
}
mContext = this;
dosimeterScanningTime = 100;
SensorModel s = new SensorModel();
s.setMacAddress(firstMacAddress);
listaSensori.add(s);
s = new SensorModel();
s.setMacAddress(secondMacAddress);
listaSensori.add(s);
for(int i=0;i< listaSensori.size();i++) {
connectDevice(i, listaSensori.get(i).getMacAddress());
}
}
}
private void connectDevice(int tagDevice, String mac) {
listaSensori.get(tagDevice).setConnectionState(0);//connecting
macAddress = mac;
// Toast.makeText(getApplicationContext(), "Dosimeter connected", Toast.LENGTH_LONG).show();
Log.d(tag, "Try to connect device: "+mac);
mStatus = BluetoothProfile.STATE_DISCONNECTED;
if( listaSensori.get(tagDevice).getmConnGatt()==null){
Log.w(tag, "new connect :: "+ listaSensori.get(tagDevice).getMacAddress());
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac);
if (device == null) {
Log.w(tag, "Device not found. Unable to connect.");
return;
}
try {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
Log.d(tag, "Missing bluetooth permission");
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return;
}
BluetoothGatt mConnGatt = device.connectGatt(mContext, true, mGattCallback);
mConnGatt.connect();
mConnGatt.discoverServices();
listaSensori.get(tagDevice).setmConnGatt(mConnGatt);
}
catch (Exception e)
{
//e.printStackTrace();
Log.d(tag,"ConnectGatt exception caught " + e.getMessage());
}
}
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
Log.d(tag, gatt.getDevice().getAddress()+ " onConnectionStateChange, status " +status+" newState: " + newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
Log.d(tag, gatt.getDevice().getAddress()+" onServicesDiscovered");
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {
Log.d(tag, gatt.getDevice().getAddress()+" onCharacteristicRead");
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
Log.d(tag,gatt.getDevice().getAddress()+ " >>onCharacteristicWrite");
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
Log.d(tag,">>onCharacteristicChanged");
}
};
}
Теперь, если я попытаюсь запустить свой код, служба запустится, приложение подключится к двум устройствам BLE и будет вызван метод «onConnectionStateChange». Это журнал
Мне нужно создать приложение для Android, которое использует BLE для одновременного подключения к нескольким устройствам. Поэтому я создал этот код в классе основной деятельности: [code]protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkPermissions(true);
EdgeToEdge.enable(this); setContentView(R.layout.activity_background_ble); ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); Intent sensorService = new Intent(getApplicationContext(),SensorService.class); sensorService.putExtra("firstDevice", "10:7C:61:27:5C:56"); sensorService.putExtra("secondDevice", "10:7C:61:27:5C:64"); startService(sensorService); } [/code] Как вы можете видеть, я создаю экземпляр службы, передающей две строки, это Mac-адрес подключаемых устройств BLE. Это класс SensorService: [code]public class SensorService extends IntentService { public static final String tag = "Ssensors"; private static final String ACTION_FOO = "it.eresult.silvermountain.service.action.FOO"; private static final String ACTION_BAZ = "it.eresult.silvermountain.service.action.BAZ";
// TODO: Rename parameters private static final String EXTRA_PARAM1 = "it.eresult.silvermountain.service.extra.PARAM1"; private static final String EXTRA_PARAM2 = "it.eresult.silvermountain.service.extra.PARAM2";
public long dosimeterScanningTime; private Context mContext; private String macAddress; private int mStatus; //private BluetoothDevice mDevice;
List listaSensori = new ArrayList();
public SensorService() { super("SensorService"); }
//questa parte di codice va rivista if (intent != null) { String action = intent.getStringExtra(PreferenceHandler.ACTION);
Log.d(tag, action != null ? action : "no action"); if (action != null && action.equals(PreferenceHandler.ACTION_CHANGE_SCANNING_ROTATION_TIME)) { Log.d(tag, "modifico il servizio"); //todo questa parte va rivista int rTime = 10; int sTime = 10; dosimeterScanningTime = sTime; Log.d(tag, "val new " + dosimeterScanningTime); //provo a vedere se la modifica ha risolto qualcosa return; } else if (action != null && action.equals(PreferenceHandler.ACTION_STOP)) { Log.d(tag, "fermo il servizio"); dosimeterScanningTime = 0;
//provo a vedere se la modifica ha risolto qualcosa return; } } mContext = this; dosimeterScanningTime = 100; SensorModel s = new SensorModel(); s.setMacAddress(firstMacAddress); listaSensori.add(s); s = new SensorModel(); s.setMacAddress(secondMacAddress); listaSensori.add(s); for(int i=0;i< listaSensori.size();i++) { connectDevice(i, listaSensori.get(i).getMacAddress()); } } }
private void connectDevice(int tagDevice, String mac) { listaSensori.get(tagDevice).setConnectionState(0);//connecting macAddress = mac; // Toast.makeText(getApplicationContext(), "Dosimeter connected", Toast.LENGTH_LONG).show(); Log.d(tag, "Try to connect device: "+mac); mStatus = BluetoothProfile.STATE_DISCONNECTED; if( listaSensori.get(tagDevice).getmConnGatt()==null){ Log.w(tag, "new connect :: "+ listaSensori.get(tagDevice).getMacAddress()); BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(mac); if (device == null) { Log.w(tag, "Device not found. Unable to connect."); return; } try { if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { Log.d(tag, "Missing bluetooth permission"); // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. //return; } BluetoothGatt mConnGatt = device.connectGatt(mContext, true, mGattCallback); mConnGatt.connect(); mConnGatt.discoverServices(); listaSensori.get(tagDevice).setmConnGatt(mConnGatt); } catch (Exception e) { //e.printStackTrace(); Log.d(tag,"ConnectGatt exception caught " + e.getMessage()); } }
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { Log.d(tag, gatt.getDevice().getAddress()+ " onConnectionStateChange, status " +status+" newState: " + newState);
}
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { Log.d(tag, gatt.getDevice().getAddress()+" onServicesDiscovered");
} @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); Log.d(tag,gatt.getDevice().getAddress()+ " >>onCharacteristicWrite");
} @Override public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) { Log.d(tag,">>onCharacteristicChanged"); } }; } [/code] Теперь, если я попытаюсь запустить свой код, служба запустится, приложение подключится к двум устройствам BLE и будет вызван метод «onConnectionStateChange». Это журнал [code]10:7C:61:27:5C:56 onConnectionStateChange, status 133 newState: 0 [/code] Поэтому я не могу подключиться к устройству BLE и прочитать его характеристики.
Я пытаюсь создать пароль на используя следующие параметры:
Подтверждение пользователя: обязательно. Обнаруживаемые учетные данные: обязательно. Вложение: поддерживаются все Подтверждение: нет
Я использую веб-сайт на Windows 11 23H2 (также...
Я создаю приложение для Android, которое автоматически подключается к другим устройствам, на которых работает то же приложение, через Bluetooth (например, без каких-либо запросов) в пределах диапазона n RSSI. Затем он приступает к отправке файла.
В...
В настоящее время я занимаюсь разработкой программы регистрации устройств (DEP) и столкнулся с проблемой рабочего процесса. Каждый раз, когда через конфигуратор добавляется новый iPhone, мне нужно вручную вызвать API, указанный в документации...
Я пытаюсь подключить телефон Android к
плате Arduino, но забыл заказать USB-кабель «гнездо-гнездо», но в любом случае хотел бы отслеживать общение между ними. Я могу подключить обоих к своему Linux-компьютеру, но мне нужна утилита, которая позволит...
Я пытаюсь подключить телефон Android к
плате Arduino, но забыл заказать USB-кабель «гнездо-гнездо», но в любом случае хотел бы отслеживать общение между ними. Я могу подключить обоих к своему Linux-компьютеру, но мне нужна утилита, которая позволит...