在Android中,我的Activity如何知道蓝牙A2DP设备是否连接到我的设备?
是否有相应的广播接收器?
如何编写此广播接收器?
在Android中,我的Activity如何知道蓝牙A2DP设备是否连接到我的设备?
是否有相应的广播接收器?
如何编写此广播接收器?
从API 11(Android 3.0)开始,您可以使用BluetoothAdapter来发现连接到特定蓝牙配置文件的设备。我使用下面的代码通过其名称来发现设备:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
public void onServiceConnected(int profile, BluetoothProfile proxy) {
if (profile == BluetoothProfile.A2DP) {
boolean deviceConnected = false;
BluetoothA2dp btA2dp = (BluetoothA2dp) proxy;
List<BluetoothDevice> a2dpConnectedDevices = btA2dp.getConnectedDevices();
if (a2dpConnectedDevices.size() != 0) {
for (BluetoothDevice device : a2dpConnectedDevices) {
if (device.getName().contains("DEVICE_NAME")) {
deviceConnected = true;
}
}
}
if (!deviceConnected) {
Toast.makeText(getActivity(), "DEVICE NOT CONNECTED", Toast.LENGTH_SHORT).show();
}
mBluetoothAdapter.closeProfileProxy(BluetoothProfile.A2DP, btA2dp);
}
}
public void onServiceDisconnected(int profile) {
// TODO
}
};
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.A2DP);
您可以为每个蓝牙配置文件执行此操作。请参阅Android指南中的“与配置文件一起使用”页面:http://developer.android.com/guide/topics/connectivity/bluetooth.html#Profiles。通过调用任何API都无法获取已连接设备的列表。 相反,您需要监听ACTION_ACL_CONNECTED、ACTION_ACL_DISCONNECTED意图通知有关已连接或断开连接设备的信息。 无法获取初始已连接设备列表。
我在我的应用程序中遇到了这个问题,我处理方式是(没有找到更好的方法...)在应用程序启动时打开/关闭蓝牙,以确保以一个空的连接设备列表开始,然后监听上述意图。
// Create a BroadcastReceiver for ACTION_FOUND
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
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy