【问题标题】:Can automatically connect to paired bluetooth device when in range?在范围内可以自动连接到配对的蓝牙设备吗?
【发布时间】:2016-12-18 05:07:39
【问题描述】:

我有两部 Android 手机。我想通过蓝牙在它们之间建立自动连接。例如,

我的安卓手机与另一个蓝牙配对。当我把这些手机放在一起时,它们需要检测蓝牙设备,并自动连接到选定的安卓手机(已知地址/MAC/之前配对)。我不需要再次连接它。我希望在我的 Android 应用程序中实现这种连接。

我谷歌并找到了一些相关的参考,但他们还没有解决问题。我认为我需要创建一个线程/服务以在蓝牙处于范围内时自动连接它们。但是,我无法实现它。如果您有好的解决方案,请告诉我。谢谢

Automatically connect to paired bluetooth device when in range

Find already paired bluetooth devices automatically, when they are in range

   /**
     * The BroadcastReceiver that listens for discovered devices and changes the title when
     * discovery is finished
     */
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
            // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            setProgressBarIndeterminateVisibility(false);
            setTitle(R.string.select_device);
            if (mNewDevicesArrayAdapter.getCount() == 0) {
                String noDevices = getResources().getText(R.string.none_found).toString();
                mNewDevicesArrayAdapter.add(noDevices);
            }
        }
    }
};

【问题讨论】:

    标签: android bluetooth android-service android-bluetooth android-broadcastreceiver


    【解决方案1】:

    这些广播接收器仅在发现过程运行后才会触发。

    可以通过两种方式启动发现:在蓝牙设置中手动启动,或通过调用BluetoothAdapter#startDiscovery() 以编程方式启动。但是,文档指出:

    设备发现是一个重量级的过程。在发现过程中,不应尝试与远程蓝牙设备建立新连接,现有连接将遇到带宽有限和高延迟的问题。使用cancelDiscovery() 取消正在进行的发现。 Discovery 不由 Activity 管理,而是作为系统服务运行,因此应用程序应始终调用cancelDiscovery(),即使它没有直接请求发现。

    这意味着发现应该作为一次性过程完成,而不是在后台持续运行 - 除了减慢其他蓝牙连接之外,它会很快耗尽电池。

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多