Android 6.0 蓝牙程序无法发现任何可用的蓝牙设备

Android 6.0 Bluetooth Program Cannot Discover Any Available Bluetooth Devices

目标

正在发现所有可用的蓝牙设备,例如我的 iPad 蓝牙开启(可发现)。

ANDROID 版本

6.0

问题

无法发现任何蓝牙设备。

代码

// 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;
    }



执行结果(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

我看到程序没有进入ACTION_FOUND的条件块,但是我的iPad的蓝牙是ON的,问题出在哪里?

如果使用Android6,添加以下权限之一:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCTION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

并打开定位服务 (GPS):

并开启定位权限:

Google 现在需要 ACCESS_FINE_LOCTIONACCESS_COARCE_LOCATION 权限才能扫描蓝牙或 Wifi 设备。这是一种奇怪的行为,但 Google 说从现在开始它应该如何工作。

Link to AndroidDev about this