Android BLE扫描程序权限异常

时间:2018-06-12 18:22:43

标签: android bluetooth-lowenergy scanning

我无法从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);
    }
};

1 个答案:

答案 0 :(得分:1)

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

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