列出连接的蓝牙设备?

时间:2010-10-14 10:32:17

标签: android bluetooth

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

谢谢!

8 个答案:

答案 0 :(得分:3)

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

public int getProfileConnectionState (int 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;
}

答案 1 :(得分:2)

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);
  }
};

答案 2 :(得分:0)

以下是步骤:

  1. 首先,您开始尝试发现设备

    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

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

    registerReceiver(mReceiver, filter);

  3. 关于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();
        }
    }
    
  4. 并在新设备发现时自动填充列表。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

  • 首先,您需要检索BluetoothAdapter
  

最终BluetoothAdapter btAdapter =   BluetoothAdapter.getDefaultAdapter();

  • 第二,您需要确保蓝牙可用并打开:
  

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

如果未关闭蓝牙,则可以使用文档中不推荐的btAdapter.enable()或要求用户这样做:Programmatically enabling bluetooth on Android

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

最终的int []状态=新的int [] {BluetoothProfile.STATE_CONNECTED,   BluetoothProfile.STATE_CONNECTING};

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

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

现在,由于您必须对Android SDK(A2Dp, GATT, GATT_SERVER, Handset, Health, 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 !

来源:https://stackoverflow.com/a/34790442/2715054

答案 5 :(得分:0)

因此您会获得已配对设备的列表。

 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());

}

答案 6 :(得分:0)

我找到了一个解决方案,它可以在android 10上运行

科特林

Roles

在主线程中调用此方法

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)
    }
}

Java

original code

答案 7 :(得分:-1)

请在线分析this class

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