Reputation: 4723
GOAL
Discovering all the available bluetooth devices such as my iPad with bluetooth ON (Discoverable).
ANDROID VERSION
6.0
PROBLEM
Cannot Discover any bluetooth devices.
CODE
// Permission
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
public BroadcastReceiver mReceiver;
public IntentFilter filter;
private boolean discover_AvailableBluetoothDevice() {
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive Called");
String action = intent.getAction();
// When discovery finds a device
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.d(TAG, "ACTION_DISCOVERY_STARTED");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d(TAG, "ACTION_DISCOVERY_FINISHED");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Log.d(TAG, "ACTION_FOUND");
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
String str = device.getName() + "\n( " + device.getAddress() + " )";
adapter.add(str);
}
}
};
filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
boolean isSuccessDiscovery = mBluetoothAdapter.startDiscovery();
return isSuccessDiscovery;
}
EXECUTION RESULT (logcat)
02-02 01:17:26.142 7194-7194/eie.imt.smartswitch D/†MainActivity: This device support Bluetooth.
02-02 01:17:55.052 7194-7194/eie.imt.smartswitch D/†ConnectSwitchActivity: isSuccessDiscovery=true
02-02 01:17:55.147 7194-7194/eie.imt.smartswitch D/†ConnectSwitchActivity: onReceive Called
02-02 01:17:55.147 7194-7194/eie.imt.smartswitch D/†ConnectSwitchActivity: ACTION_DISCOVERY_STARTED
02-02 01:18:07.909 7194-7194/eie.imt.smartswitch D/†ConnectSwitchActivity: onReceive Called
02-02 01:18:07.910 7194-7194/eie.imt.smartswitch D/†ConnectSwitchActivity: ACTION_DISCOVERY_FINISHED
I see the program does not enter the condition block of ACTION_FOUND but my iPad's bluetooth is ON, where does the problem come from?
Upvotes: 4
Views: 2345
Reputation: 5781
If you use Android 6, add one of the following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCTION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
And turn on the Location service (GPS):
And turn on the Location permission:
Google now requires ACCESS_FINE_LOCTION
or ACCESS_COARCE_LOCATION
permissions to be able to scan for Bluetooth or Wifi devices. It's weird behavior but Google says it's how it should work from now on.
Upvotes: 11