Reputation: 115
I am trying to implement a Bluetooth device discovery function in my app. I have implemented the proposed way to do it with a BluetoothAdapter
and a BroadcastReceiver
like so:
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();
}
}
In my manifest I have the following permissions:
<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" />
The result is me getting two toasts: "Start discovery" and 10sec later "Discovery finished". Never a device is found. I have tested on Samsung S9+, Sansumg Tab A, and Motorola something (with Bluetooth on).
Is there something I am not doing wright or is there any known problems I don't know?
Upvotes: 0
Views: 94
Reputation: 3500
Pure speculation on my end, but in case you're running on API level 23 + (and likely you are), you need to dynamically ask for permissions, not just declare them in manifest. Either use RxPermissions
or ContextCompat.checkSelfPermission
.
Upvotes: 1