【问题标题】:Finding the nearest Bluetooth device寻找最近的蓝牙设备
【发布时间】:2018-07-06 21:19:39
【问题描述】:

我正在尝试构建一个 android 应用程序来查找最近的蓝牙设备,我正在使用带有广播接收器的蓝牙适配器来查找附近的设备并根据它们的 RSSI 值过滤找到的设备。我面临的问题是发现设备需要很长时间,如果我尝试在短时间内运行发现,它不会找到所有必要的设备,例如,如果我有两个设备并保留靠近我的 android 手机的设备之一,有时它不会被检测到,但远离手机的设备会被检测到。

【问题讨论】:

    标签: android bluetooth


    【解决方案1】:

    这是一个完全由 Android 管理的异步进程。 AFAIK,不幸的是,您无法“改进”它,或者无论如何“强制”它(可能除了以 root 身份运行并自己编写 BT 堆栈)。

    更新:我最初没有想到的一件事是尝试关闭/打开蓝牙功能。

    private static BroadcastReceiver btReceiver = null;
    
    // ..
    
    void toggleRefreshBluetooth ()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter ();
    
        if (mBluetoothAdapter.isEnabled ())
        {
            mBluetoothAdapter.disable ();
        }
    }
    
    
    // ... in onCreate
    
    btReceiver = new BroadcastReceiver ()
    {
        @Override
        public void onReceive (Context context, Intent intent)
        {
            if (intent != null && BluetoothAdapter.ACTION_STATE_CHANGED.equals (intent.getAction ()))
            {
                    final int state = intent.getIntExtra (BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
                    switch (state)
                    {
                        case BluetoothAdapter.STATE_OFF:
                            // Bluetooth has been turned off
                            mBluetoothAdapter.enable ();
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            // Bluetooth is turning off
                            break;
                        case BluetoothAdapter.STATE_ON:
                            // Bluetooth has been on
                            break;
                        case BluetoothAdapter.STATE_TURNING_ON:
                            // Bluetooth is turning on
                            break;
                    }
             }
        }
    };
    
    final IntentFilter filter = new IntentFilter ();
    filter.addAction (BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver (btReceiver, filter);
    

    调用toggleRefreshBluetooth 可能会强制重新扫描。试一试,除非在您的情况下不方便。

    它不要求应用程序是系统应用程序,您不必root手机。您唯一需要的是Manifest.permission.BLUETOOTH_ADMIN 权限。

    【讨论】:

    • 我希望有办法,但还是谢谢。
    • 我在帖子中添加了一个可能的解决方案(可能的解决方法)。
    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多