自己的APP检测系统的蓝牙连接状态和连接的设备名字

网上关于蓝牙开发的文章实在太多了,在这种环境下,我竟然还能原创?得意一下。

网上的文章大部分都是从打开蓝牙设备---》扫描--》配对--》连接--》读取设备各种状态信息。

本身手机系统,在设置界面就可以完成这一系列的动作,而我们的需求是在自己开发的APP上面不需要经过打开,扫描,连接等动作,就可以获取到目前系统的蓝牙连接状态?

我这个经验的限制在于必须指定一个具体的profile(你也可以设置其他profile):HEADSET。


首先,获得系统的蓝牙句柄:

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

然后向系统注册这个profile的句柄,或者说获得这个服务控制器,这是肯定可以成功的(系统支持的情况下):

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        if (profile == BluetoothProfile.HEADSET) {
            Log.d(TAG,"headset profile connected");
            mBluetoothHeadset = (BluetoothHeadset) proxy;
        }
    }
    public void onServiceDisconnected(int profile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null;
        }
    }
};
mBluetoothAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);


最后,获得HEADSET 是否连接上了,连接上了,再去获得远程设备的句柄:

int cnt = mBluetoothAdapter.getProfileConnectionState(HEADSET);
Log.d(TAG,"connection state: "+cnt);

if((cnt==2) &&(mBluetoothHeadset!=null)) {
    devices = mBluetoothHeadset.getConnectedDevices();
    Log.d(TAG,"connected no= "+devices.size());

    for ( final BluetoothDevice dev : devices ) {
        Log.d(TAG,"connected name= "+dev.getName());
    }
}

That's all!!!

句柄的叫法,主要以前做Linux的缘故。。。!!!


你可能感兴趣的:(安卓应用开发)