列出已连接的蓝牙设备?

发布于 2024-09-27 02:53:10 字数 44 浏览 0 评论 0原文

如何列出 Android 上所有已连接的蓝牙设备?

谢谢!

How can I list all connected bluetooth devices on android ?

thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

捂风挽笑 2024-10-04 02:53:10
public void checkConnected()
{
  // true == headset connected && connected headset is support hands free
  int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
  if (state != BluetoothProfile.STATE_CONNECTED)
    return;

  try
  {
    BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET);
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }
}

private ServiceListener serviceListener = new ServiceListener()
{
  @Override
  public void onServiceDisconnected(int profile)
  {

  }

  @Override
  public void onServiceConnected(int profile, BluetoothProfile proxy)
  {
    for (BluetoothDevice device : proxy.getConnectedDevices())
    {
      Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
          + BluetoothProfile.STATE_CONNECTED + ")");
    }

    BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
  }
};
public void checkConnected()
{
  // true == headset connected && connected headset is support hands free
  int state = BluetoothAdapter.getDefaultAdapter().getProfileConnectionState(BluetoothProfile.HEADSET);
  if (state != BluetoothProfile.STATE_CONNECTED)
    return;

  try
  {
    BluetoothAdapter.getDefaultAdapter().getProfileProxy(_context, serviceListener, BluetoothProfile.HEADSET);
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }
}

private ServiceListener serviceListener = new ServiceListener()
{
  @Override
  public void onServiceDisconnected(int profile)
  {

  }

  @Override
  public void onServiceConnected(int profile, BluetoothProfile proxy)
  {
    for (BluetoothDevice device : proxy.getConnectedDevices())
    {
      Log.i("onServiceConnected", "|" + device.getName() + " | " + device.getAddress() + " | " + proxy.getConnectionState(device) + "(connected = "
          + BluetoothProfile.STATE_CONNECTED + ")");
    }

    BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy);
  }
};
请恋爱 2024-10-04 02:53:10

从 API 14(Ice Cream)开始,Android 有一些新的 BluetoothAdapter 方法,包括:

public int getProfileConnectionState (int profile)

其中 profile 是 HEALTH、HEADSET、A2DP

检查响应,如果不是 STATE_DISCONNECTED,则说明您有实时连接。

以下是适用于任何 API 设备的代码示例:

BluetoothAdapter mAdapter;

/**
 * Check if a headset type device is currently connected. 
 * 
 * Always returns false prior to API 14
 * 
 * @return true if connected
 */
public boolean isVoiceConnected() {
    boolean retval = false;
    try {
        Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class);
        // retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
        retval = (Integer)method.invoke(mAdapter, 1) != 0;
    } catch (Exception exc) {
        // nothing to do
    }
    return retval;
}

As of API 14 (Ice Cream), Android has a some new BluetoothAdapter methods including:

public int getProfileConnectionState (int profile)

where profile is one of HEALTH, HEADSET, A2DP

Check response, if it's not STATE_DISCONNECTED you know you have a live connection.

Here is code example that will work on any API device:

BluetoothAdapter mAdapter;

/**
 * Check if a headset type device is currently connected. 
 * 
 * Always returns false prior to API 14
 * 
 * @return true if connected
 */
public boolean isVoiceConnected() {
    boolean retval = false;
    try {
        Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class);
        // retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
        retval = (Integer)method.invoke(mAdapter, 1) != 0;
    } catch (Exception exc) {
        // nothing to do
    }
    return retval;
}
您的好友蓝忘机已上羡 2024-10-04 02:53:10
  • 首先,您需要检索 BluetoothAdapter

最终的蓝牙适配器 btAdapter =
BluetoothAdapter.getDefaultAdapter();

  • 其次,您需要确保蓝牙可用并已打开:

if (btAdapter != null && btAdapter.isEnabled()) // null 表示否
蓝牙!

如果蓝牙未打开,您可以使用文档中不推荐的 btAdapter.enable() 或要求用户执行此操作:以编程方式在 Android 上启用蓝牙

  • 第三,您需要定义一个状态数组(以过滤掉
    未连接的设备):

final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED,
蓝牙配置文件.STATE_CONNECTING};

  • 第四,您创建一个BluetoothProfile.ServiceListener,其中
    包含连接服务时触发的两个回调
    断开连接:

    最终的BluetoothProfile.ServiceListener监听器=新的BluetoothProfile.ServiceListener() {
        @覆盖
        公共无效onServiceConnected(int配置文件,BluetoothProfile代理){
        }
    
        @覆盖
        公共无效onServiceDisconnected(int配置文件){
        }
    };
    

现在您必须重复查询 Android SDK 中所有可用蓝牙配置文件的过程 (A2Dp、GATT、GATT_SERVER、手机、健康、SAP),您应该按以下步骤操作:

onServiceConnected 中,放置一个条件来检查当前是什么配置文件,以便我们将找到的设备添加到正确的集合中,然后使用:proxy.getDevicesMatchingConnectionStates(states)来过滤掉未连接的设备:

switch (profile) {
    case BluetoothProfile.A2DP:
        ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
        gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
        gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEADSET: 
        headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
        healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
        sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
}

最后,最后要做的事情是开始查询过程:

btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !

source :https://stackoverflow.com/a/34790442/2715054

  • First you need to retrieve the BluetoothAdapter:

final BluetoothAdapter btAdapter =
BluetoothAdapter.getDefaultAdapter();

  • Second you need to make sure Bluetooth is available and turned on :

if (btAdapter != null && btAdapter.isEnabled()) // null means no
Bluetooth!

If the Bluetooth is not turned out you can either use btAdapter.enable() which is not recommended in the documentation or ask the user to do it : Programmatically enabling bluetooth on Android

  • Third you need to define an array of states (to filter out
    unconnected devices):

final int[] states = new int[] {BluetoothProfile.STATE_CONNECTED,
BluetoothProfile.STATE_CONNECTING};

  • Fourth, you create a BluetoothProfile.ServiceListener which
    contains two callbacks triggered when a service is connected and
    disconnected :

    final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() {
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy) {
        }
    
        @Override
        public void onServiceDisconnected(int profile) {
        }
    };
    

Now since you have to repeat the querying process for all available Bluetooth Profiles in the Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) you should proceed as follow :

In onServiceConnected, place a condition that check what is the current profile so that we add the found devices into the correct collection and we use : proxy.getDevicesMatchingConnectionStates(states) to filter out unconnected devices:

switch (profile) {
    case BluetoothProfile.A2DP:
        ad2dpDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT: // NOTE ! Requires SDK 18 !
        gattDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.GATT_SERVER: // NOTE ! Requires SDK 18 !
        gattServerDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEADSET: 
        headsetDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.HEALTH: // NOTE ! Requires SDK 14 !
        healthDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
    case BluetoothProfile.SAP: // NOTE ! Requires SDK 23 !
        sapDevices.addAll(proxy.getDevicesMatchingConnectionStates(states));
        break;
}

And finally, the last thing to do is start the querying process :

btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET);
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 !
btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 !

source: https://stackoverflow.com/a/34790442/2715054

吖咩 2024-10-04 02:53:10

这样您就可以获得配对设备的列表。

 BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();


    for (BluetoothDevice pairedDevice : pairedDevicesList) {
    Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
    Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());

    saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());

}

So you get the list of paired devices.

 BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevicesList = btAdapter.getBondedDevices();


    for (BluetoothDevice pairedDevice : pairedDevicesList) {
    Log.d("BT", "pairedDevice.getName(): " + pairedDevice.getName());
    Log.d("BT", "pairedDevice.getAddress(): " + pairedDevice.getAddress());

    saveValuePreference(getApplicationContext(), pairedDevice.getName(), pairedDevice.getAddress());

}
美人如玉 2024-10-04 02:53:10

Android 系统不允许您查询所有“当前”连接的设备。但是,您可以查询配对的设备。您将需要使用广播接收器来侦听 ACTION_ACL_{CONNECTED|DISCONNECTED} 事件以及 STATE_BONDED 事件,以更新应用程序状态以跟踪当前连接的内容。

Android system doesn't let you query for all "currently" connected devices. It however, you can query for paired devices. You will need to use a broadcast receiver to listen to ACTION_ACL_{CONNECTED|DISCONNECTED} events along with STATE_BONDED event to update your application states to track what's currently connected.

高速公鹿 2024-10-04 02:53:10

我找到了一个解决方案,它适用于 android 10

Kotlin

private val serviceListener: ServiceListener = object : ServiceListener {
    var name: String? = null
    var address: String? = null
    var threadName: String? = null
    override fun onServiceDisconnected(profile: Int) {}
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        for (device in proxy.connectedDevices) {
            name = device.name
            address = device.address
            threadName = Thread.currentThread().name
            Toast.makeText(
                this@MainActivity,
                "$name $address$threadName",
                Toast.LENGTH_SHORT
            ).show()
            Log.i(
                "onServiceConnected",
                "|" + device.name + " | " + device.address + " | " + proxy.getConnectionState(
                    device
                ) + "(connected = "
                        + BluetoothProfile.STATE_CONNECTED + ")"
            )
        }
        BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
    }
}

中调用此方法

BluetoothAdapter.getDefaultAdapter()
            .getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET)

在主线程Java

原始代码

I found a solution and it works on android 10

Kotlin

private val serviceListener: ServiceListener = object : ServiceListener {
    var name: String? = null
    var address: String? = null
    var threadName: String? = null
    override fun onServiceDisconnected(profile: Int) {}
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        for (device in proxy.connectedDevices) {
            name = device.name
            address = device.address
            threadName = Thread.currentThread().name
            Toast.makeText(
                this@MainActivity,
                "$name $address$threadName",
                Toast.LENGTH_SHORT
            ).show()
            Log.i(
                "onServiceConnected",
                "|" + device.name + " | " + device.address + " | " + proxy.getConnectionState(
                    device
                ) + "(connected = "
                        + BluetoothProfile.STATE_CONNECTED + ")"
            )
        }
        BluetoothAdapter.getDefaultAdapter().closeProfileProxy(profile, proxy)
    }
}

Call this method in main thread

BluetoothAdapter.getDefaultAdapter()
            .getProfileProxy(this, serviceListener, BluetoothProfile.HEADSET)

Java

original code

记忆里有你的影子 2024-10-04 02:53:10

请分析此类

在这里您将了解如何发现所有已连接(配对)的蓝牙设备。

Please analyze this class online.

Here you will find how to discover all connected (paired) Bluetooth devices.

北恋 2024-10-04 02:53:10

步骤如下:

  1. 首先,您开始意图发现设备

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. 为其注册一个广播接收器:

    registerReceiver(mReceiver, filter);

  3. 关于mReceiver的定义:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        公共无效onReceive(上下文上下文,意图意图){
        字符串操作=intent.getAction();
        // 当发现发现设备时
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            // 从Intent中获取BluetoothDevice对象
            蓝牙设备设备 = Intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 将名称和地址添加到数组适配器以显示在 ListView 中
            arrayadapter.add(device.getName())//arrayadapter 类型为 ArrayAdapter;
            lv.setAdapter(数组适配器); //lv是列表视图 
            arrayadapter.notifyDataSetChanged();
        }
    }
    

并且在发现新设备时会自动填充该列表。

Well here are the steps:

  1. First, you start intent to discover devices

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

  2. Register a broadcast reciver for it:

    registerReceiver(mReceiver, filter);

  3. On the definition of mReceiver:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        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);
            // Add the name and address to an array adapter to show in a ListView
            arrayadapter.add(device.getName())//arrayadapter is of type ArrayAdapter<String>
            lv.setAdapter(arrayadapter); //lv is the list view 
            arrayadapter.notifyDataSetChanged();
        }
    }
    

and the list will be automatically populated on new device discovery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文