Я пытаюсь реализовать функцию обнаружения устройства Bluetooth в моем приложении.Я реализовал предложенный способ сделать это с BluetoothAdapter
и BroadcastReceiver
следующим образом:
My Activity (discover() is called in onCreate):
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
BluetoothAdapter mBluetoothAdapter;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
testDevice("Start discover");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
testDevice("Discovery finished");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
testDevice("Found device " + device.getName());
}
}
};
public void discover() {
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
public void testDevice(String msg) {
Toast.makeText(this, msg,
Toast.LENGTH_LONG).show();
}
}
В моем манифесте у меня есть следующие разрешения:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
В результате я получил два тоста: «Начать обнаружение» и 10 секунд спустя «Обнаружение завершено».Никогда устройство не найдено.Я проверил что-то на Samsung S9 +, Sansumg Tab A и Motorola (с включенным Bluetooth).
Есть что-то, что я не так делаю, или есть известные проблемы, о которых я не знаю?