如何检测如果蓝牙设备连接 [英] How to detect if bluetooth device is connected

查看:117
本文介绍了如何检测如果蓝牙设备连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在安卓怎么我的活动将了解是否支持A2DP蓝牙设备连接到我的设备。
是否有广播接收器是什么?
如何写这个广播接收器?

In android how can my Activity will get to know if a Bluetooth A2DP device is connected to my device.
Is there any broadcast receiver for that?
How to write this broadcast receiver?

推荐答案

从API 11(的Andr​​oid 3.0),可以使用<启动href="http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html">BluetoothAdapter发现连接到特定的蓝牙简档的设备。我用下面的code发现设备通过其名称:

Starting from API 11 (Android 3.0) you can use BluetoothAdapter to discover devices connected to a specific bluetooth profile. I used the code below to discover a device by its name:

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的指南。

You can do that for every bluetooth profile. Take a look at Working with profiles in Android's guide.

不过,正如写在其他的答案,你可以注册一个BroadcastReceiver来听连接事件(当你工作在Android&LT类; 3.0)。

However, as written in other answers, you can register a BroadcastReceiver to listen to connection events (like when you're working on android < 3.0).

这篇关于如何检测如果蓝牙设备连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆