BLE 扫描不起作用

问题描述 投票:0回答:3

我是一名使用 Google 示例代码开发 BLE 扫描仪的初学者:https://github.com/googlesamples/android-BluetoothLeGatt

目前,代码无法检测到任何设备。 这篇文章说这是因为位置服务被禁用或在运行时没有明确要求。我已经在我的清单中包含了所需的权限。

我添加了几行代码,我认为应该可以工作。

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle(R.string.title_devices);
        mHandler = new Handler();


        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }



    // Quick permission check
        int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        if (permissionCheck != 0) {

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

    }

我认为我添加的快速权限检查应该可以工作,但该应用程序似乎仍然没有检测到任何设备。

android bluetooth-lowenergy
3个回答
2
投票

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

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

如果这不是您问题的正确答案,请回复我的答案,我会立即删除。


0
投票

扫描仪注册状态=133

这可能是因为以下原因。

1)申请中未给出位置许可。

2)连接到设备时停止扫描,然后连接到设备。

3)当我们向设备读取/写入数据时,不应进行扫描。 确保扫描已停止

4)如果开始第一次扫描,请等待扫描完成,然后开始第二次扫描。

5)多次扫描而不等待上一次扫描完成可能会导致找不到扫描回调。

尝试快速 BLE 库它比可用的 Google BLE 库更有效。


0
投票

我知道这个问题已经很老了,但我认为有人可能仍然觉得它有用。如果您发现扫描功能运行了几次然后停止,那么您可能做得对。

Starting from Android 7
,对于蓝牙 LE,Android 将设备扫描数量限制为
5 times every 30 seconds
。如果超过此限制,它将自动停止,并且您将不再接收任何数据。

© www.soinside.com 2019 - 2024. All rights reserved.