【问题标题】:connect to device with Bluetooth address on String使用 String 上的蓝牙地址连接到设备
【发布时间】:2013-05-29 22:39:18
【问题描述】:

我正在做一个 Android 应用程序,我将另一台设备的 MAC 作为字符串(17 个字符长)并且需要使用该 MAC 来连接到该设备(启动蓝牙连接的线程)。 我整个下午都在玩它,不知道该怎么做。问题是它不允许我将 BluetoothDevice 设置为等于字符串。 有没有办法可以/必须这样做?

(决定不把我的任何尝试作为代码放在这里,看看它们是如何充满错​​误的)

它必须与另一台运行完全相同的应用程序的平板电脑进行通信。我之前浏览了this 页面,我的大部分应用程序都基于此。我的主要问题是使用 ConnectThread 示例时,

我有一个带有 MAC 地址的字符串,如何连接到那个 MAC?

任何帮助将不胜感激,

【问题讨论】:

  • 您使用的是什么蓝牙配置文件? 17 个字符的设备名称可能只是设备的 MAC 地址。
  • 是的,对不起。表示 MAC 地址...

标签: android string sockets bluetooth


【解决方案1】:

如果我理解正确,您有一个 MAC 地址作为字符串,并且您想连接到设备,对吗?这应该有效:

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BluetoothSocket tmp = null;
BluetoothSocket mmSocket = null;

// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
    tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (IOException e) {
    Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;

【讨论】:

  • 先生,我可以将我自己的蓝牙地址保存在一个字符串中吗???如果可能怎么办?
【解决方案2】:

将字符串值转换为蓝牙设备。

BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothDevice mBluetoothDevice = bluetoothManager.getAdapter() .getRemoteDevice("deviceAddress");

【讨论】:

  • 我可以将状态中显示的蓝牙地址保存在字符串中吗?如果是的话可以帮助我!
【解决方案3】:

首先,您必须找出蓝牙设备支持的配置文件,例如,它可能是可以使用 HDP 配置文件的医疗设备,也可能是通过蓝牙使用简单的 RS232。在开始编写代码之前,了解如何为各种配置文件建立蓝牙连接非常重要。

这是一个很好的开始链接。 Android SDK 还附带一些基本示例,您可以开始使用。

http://developer.android.com/guide/topics/connectivity/bluetooth.html

编辑:

如果您的设备配对成功,您将在配对设备列表中看到 MAC 地址。例如,您可以这样做来查找与您设备的 MAC 地址匹配的设备:

  Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                    .getBondedDevices();
            if (pairedDevices.isEmpty()) {
                Log.e(TAG,
                        "No devices paired...");
                return ;
            }

    for (BluetoothDevice device : pairedDevices) {
                Log.d(TAG, "Device : address : " + device.getAddress() + " name :"
                        + device.getName());
            if (MY_MAC_ADDR.equals(device.getAddress())) {
                mDevice = device;
                break;
            }
    }

希望对您有所帮助。

【讨论】:

  • 对不起,我没有指定。它必须与另一台运行完全相同的应用程序的平板电脑进行通信。我之前浏览了该页面,我的大部分应用程序都是基于该页面的。我的主要问题是在使用 ConnectThread 示例时,我不知道如何输入 MAC 地址(字符串)= mmDevice 谢谢您的回答,
  • 编辑了我的回复以回答您的问题。
  • 我可以将我的蓝牙地址保存在一个字符串值中吗?如果是,请帮助我一些方法
猜你喜欢
  • 1970-01-01
  • 2012-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
相关资源
最近更新 更多