Как автоматически подключиться ко всем обнаруживаемым устройствам через Bluetooth, которые находятся в диапазоне n RSSI Android

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Как автоматически подключиться ко всем обнаруживаемым устройствам через Bluetooth, которые находятся в диапазоне n RSSI

Сообщение Anonymous »

Я создаю приложение для Android, которое автоматически подключается к другим устройствам, на которых работает то же приложение, через Bluetooth (например, без каких-либо запросов) в пределах диапазона n RSSI. Затем он приступает к отправке файла.
В настоящее время у меня устройства успешно «рекламируют» и «обнаруживают» одновременно, но приложение не обнаруживает себя и никогда не подключается. Вот класс, который я использую для его вызова.

Код: Выделить всё

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothServerSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class BluetoothConnectionManager {

private static final String TAG = "BluetoothConnManager";
private static final UUID APP_UUID = UUID.fromString("29f9fac1-db57-4a3f-b91e-98f2a1139a16"); // Generate a unique UUID
private static final String APP_NAME = "MyBluetoothApp"; // Your app name

private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private BluetoothServerSocket serverSocket;
private Context context;

public BluetoothConnectionManager(Context context) {
this.context = context;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Register for Bluetooth scan results (for RSSI)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(receiver, filter);
}

// Start discovering devices
public void startDeviceDiscovery() {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
bluetoothAdapter.startDiscovery();
Toast toast = Toast.makeText(context, "Discovery Started", Toast.LENGTH_SHORT);
toast.show();
}
}

// BroadcastReceiver to handle discovered devices and RSSI
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice and RSSI
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

Log.d(TAG, "Device found: " + device.getName() + " RSSI: " + rssi);

// Check the RSSI and if it's strong enough, attempt to connect
if(rssi > -75) {
connectToDevice(device);
BluetoothFileTransfer bluetoothFileTransfer = new BluetoothFileTransfer(bluetoothSocket, context);
File fileToSend = new File(context.getFilesDir(), "contact.json");
File fileToRecieve = new File(context.getFilesDir(), "recievedContact.json");
bluetoothFileTransfer.startFileTransfer(fileToSend,fileToRecieve);
try {
wait(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
closeConnection();
cleanup();
}
}
}
};

// Establish connection with a device
private void connectToDevice(BluetoothDevice device) {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(APP_UUID);
bluetoothAdapter.cancelDiscovery(); // Cancel discovery as it impacts performance

// Try to connect
bluetoothSocket.connect();
Log.d(TAG, "Connected to " + device.getName());
Toast toast = Toast.makeText(context, "Connected to device", Toast.LENGTH_SHORT);
toast.show();
} catch (IOException e) {
Log.e(TAG, "Connection failed", e);
closeConnection();
}
}

// Close connection if any
public void closeConnection() {
try {
if (bluetoothSocket != null) {
bluetoothSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "Failed to close connection", e);
}
}

// Set up server socket to listen for connections
public void startServer() {
new Thread(() ->  {
try {
serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord(APP_NAME, APP_UUID);
Log.d(TAG, "Server started");
bluetoothSocket = serverSocket.accept(); // Blocking call
Log.d(TAG, "Server accepted connection");

} catch (IOException e) {
Log.e(TAG, "Failed to start server", e);
}
}).start();
}

// Stop discovery and unregister receiver
public void cleanup() {
bluetoothAdapter.cancelDiscovery();
try {
serverSocket.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
context.unregisterReceiver(receiver);
}
}

Я еще не понял, что соединение не происходит, поскольку оба сервера успешно запускаются и останавливаются, а устройства доступны для обнаружения. Я полностью признаю, что существует один подобный пост. Однако этот пост, похоже, не соответствует моему вопросу, поскольку он ставит под сомнение только метод подключения, а не рекламу.

Подробнее здесь: https://stackoverflow.com/questions/791 ... oth-that-a
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Android 10: как получить значение rssi неподключенного устройства Bluetooth
    Гость » » в форуме JAVA
    0 Ответы
    33 Просмотры
    Последнее сообщение Гость
  • Android 10: как получить значение rssi неподключенного устройства Bluetooth
    Гость » » в форуме Android
    0 Ответы
    34 Просмотры
    Последнее сообщение Гость
  • Как получить доступ к устройствам Bluetooth (BLE) в приложении Dockerized Flask в Windows с помощью WSL2?
    Anonymous » » в форуме Python
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • Подключение / отключение к устройствам Bluetooth программно в приложениях Android
    Anonymous » » в форуме Android
    0 Ответы
    1 Просмотры
    Последнее сообщение Anonymous
  • Как подключиться к нескольким устройствам одновременно
    Anonymous » » в форуме Android
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Android»