如何获得蓝牙配对设备的设备名称?

时间:2019-05-20 18:59:42

标签: java android bluetooth

我在获取蓝牙设备名称时遇到一些麻烦。

我正在连接名称为MTP-3的蓝牙打印机(此名称采用硬编码),但是我想连接另一台具有其他名称的蓝牙打印机,因此我更改了第二台打印机的名称在设置中的“操作系统配对设备”列表中,但不起作用。

此外,如果我将第一台打印机的名称更改为MTP-3以外的其他名称,则打印机仍与我的应用程序连接。

我正在寻找某种方法,即使我使用Opereting System更改名称,该方法也能为我提供与Android配对的设备的确切名称。

  Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();

            if (pairedDevice.size() > 0) {
                for (BluetoothDevice pairedDev : pairedDevice) {

    if(pairedDev.getName.equals("MTP-3")){
          bluetoothDevice = pairedDev;
          Toast.makeText(getApplicationContext(), "found it", Toast.LENGTH_SHORT).show();
          break;
    }
}
}

2 个答案:

答案 0 :(得分:0)

您可以从返回的集合中获取它:

BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

答案 1 :(得分:0)

下面的代码将获取蓝牙名称,如果没有名称,它将返回地址。

public String getDeviceName(){
    if(mBluetoothAdapter == null){
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }
    String name = mBluetoothAdapter.getName();
    if(name == null){
        System.out.println("Name is null!");
        name = mBluetoothAdapter.getAddress();
    }
    return name;
}