繁体   English   中英

android-如何检查设备是否与蓝牙连接

[英]android - how to check if device is connected with Bluetooth

我有以下功能在启动时运行并完美运行。

我想在其他功能中添加条件,以检查设备是否仍处于连接状态。

这是代码

private final  Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case BluetoothService.MESSAGE_STATE_CHANGE:
            switch (msg.arg1) {
            case BluetoothService.STATE_CONNECTED:   
                Toast.makeText(getApplicationContext(), "Connect successful",
                        Toast.LENGTH_SHORT).show();
                btnClose.setEnabled(true);
                btnSend.setEnabled(true);
                btnSendDraw.setEnabled(true);
                break;
            case BluetoothService.STATE_CONNECTING:  
                Log.d("À¶ÑÀµ÷ÊÔ","ÕýÔÚÁ¬½Ó.....");
                break;
            case BluetoothService.STATE_LISTEN:     
            case BluetoothService.STATE_NONE:
                Log.d("À¶ÑÀµ÷ÊÔ","µÈ´ýÁ¬½Ó.....");
                break;
            }
            break;
        case BluetoothService.MESSAGE_CONNECTION_LOST: 
            Toast.makeText(getApplicationContext(), "Device connection was lost",
                           Toast.LENGTH_SHORT).show();
            btnClose.setEnabled(false);
            btnSend.setEnabled(false);
            btnSendDraw.setEnabled(false);
            break;
        case BluetoothService.MESSAGE_UNABLE_CONNECT:  
            Toast.makeText(getApplicationContext(), "Unable to connect device",
                    Toast.LENGTH_SHORT).show();
            break;
        }
    }

};

其他功能是这样启动的

     @Override
     protected void onPostExecute(String result){

请帮我!!

谢谢

我从经验中学到,ACL_CONNECTED / DISCONNECTED并不完全可靠,因为在设备连接期间可能会多次发生这种情况(例如,如果需要引脚,则将“连接”,如果提供了超时/错误的引脚,则将“断开”) (这不一定表示连接正确)。 这表示较低层的连接。

如果要使用广播接收器,最好使用特定于您使用的配置文件的广播(例如A2DP)。 每个人都有自己的广播。 您可以听的另一件事是来自ConnectivityManager的Connectivity_state_changed,类型为BLUETOOTH(还没有尝试过)。

同样,在没有广播接收器的情况下检查它是否已连接的方法,例如,当您要在更新活动之前在后台检查时,将通过以下方式获取配置文件对象:

mBluetoothAdapter.getProfileProxy(mContext, mA2DPProfileListener, BluetoothProfile.A2DP);

其中mA2DPProfileListenerServiceListener对象:

<code>
private ServiceListener mA2DPProfileListener = new ServiceListener(){
//anonymous inner type. etc.
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        //cast the BluetoothProfile object to the profile you need, say 
        //BluetoothA2DP proxyA2DP = (BluetoothA2DP) proxy;
        int currentState = proxyA2DP.getConnectionState(mDevice);
        //mDevice is the BluetoothDevice object you can get from
        //BluetoothAdapter.getRemote...
    }

    public void onServiceDisconnected(int profile) {
    }
}
</code>

您可以检查currentState指向什么,并确定设备是否已连接/断开/正在连接等。

HTH,Sreedevi。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM