Android如何获取连接的蓝牙设备的名称[重复]

5gfr0r5j  于 2023-06-04  发布在  Android
关注(0)|答案(2)|浏览(237)

此问题已在此处有答案

Android: How to find out name of the bluetooth device connected?(1个答案)
6年前关闭。
我想知道如何在Android中获得连接的蓝牙设备的名称这里是代码

NetworkInfo bluetooth = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_BLUETOOTH);
if(bluetooth.isConnected())
                {
                    Toast.makeText(myprofile3Context,"bluetooth is connected", Toast.LENGTH_SHORT).show();
                }

这里我检查蓝牙设备是否连接。如果蓝牙连接,我想知道如何获得连接设备的名称。

drkbr07n

drkbr07n1#

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_ACL_CONNECTED.equals(action)) {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                          //you can get name by device.getName()

        } else if (BluetoothAdapter.ACL_DISCONNECTED
                .equals(action)) {

        }
    }
 };

使用extendsBroadcastReceiver并在manifest中添加permissions

n6lpvg4x

n6lpvg4x2#

试试这个

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

相关问题