Android BLE 扫描仪权限异常

Android BLE Scanner Permissions Exception

我在从 BLE 扫描仪获取扫描结果时遇到了问题。我在我的 AndroidManifest.xml 中拥有适当的权限 (ACCESS_COARSE_LOCATION),如下所述,但出现异常表明我需要我拥有的权限。毫不奇怪,从未调用扫描器回调。

W/Binder: Caught a RuntimeException from the binder stub implementation.
          java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results.  I'm not sure why the exception is thrown but I certianly DON'T get scan call backs.


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


ScanCallback btScanCallback = new ScanCallback()
{
    @Override
    public void onScanResult(int callbackType, final ScanResult result)
    {
        BluetoothDevice btDevice = result.getDevice();
        Log.d(LOGTAG, "Found BLE device: " + btDevice.getName());


        // Remove the device from the scanner select view if its there already
        for( int i=0; i<btDeviceNameList.size(); i++)
        {
            String aDevice = btDeviceNameList.get(i);

            if(aDevice.equalsIgnoreCase(btDevice.getName()))
            {
                btDeviceNameList.remove(i);
                btDeviceList.remove(i);
                break;
            }
       }

        // Add the device to the scanner select view
        btDeviceList.add(btDevice);
        btDeviceNameList.add(btDevice.getName());

        btListAdapter.notifyDataSetChanged();
    }


    @Override
    public void onScanFailed(int errorCode)
    {
        Log.e(LOGTAG, "BT scan error: " + errorCode);
    }
};

我遇到过和你一样的情况。如果您使用的是 android 6.0 或更高版本。您必须在 运行 时请求位置许可。获取蓝牙适配器后,让我们插入如下代码行以请求位置权限。当您的应用程序 运行 时,将显示一个对话框询问您是否同意共享您的位置。

ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);