问题描述
- 安卓设备如何监听蓝牙的连接状态
-
如题,在我的APP中,成功将手机连接上了一个蓝牙串口,现在想监听它们之间的连接状态。在网上找到的方式都是用BroadcastReceiver来监听蓝牙状态改变的广播,于是我实现了这种方式,代码部分如下: private void registerBoradcastReceiver() { IntentFilter stateChangeFilter = new IntentFilter( BluetoothAdapter.ACTION_STATE_CHANGED); IntentFilter connectedFilter = new IntentFilter( BluetoothDevice.ACTION_ACL_CONNECTED); IntentFilter disConnectedFilter = new IntentFilter( BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(stateChangeReceiver, stateChangeFilter); registerReceiver(stateChangeReceiver, connectedFilter); registerReceiver(stateChangeReceiver, disConnectedFilter); } private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_ACL_CONNECTED == action) { showchange(action); } if (BluetoothDevice.ACTION_ACL_DISCONNECTED == action) { showchange(action); } if (BluetoothAdapter.ACTION_STATE_CHANGED == action) { showchange(action); } } }; 但是调试的时候并没有监听到任何的状态变化,求指教。
解决方案
将IntentFilter connectedFilter = new IntentFilter(
BluetoothDevice.ACTION_ACL_CONNECTED);
换成IntentFilter connectedFilter = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);再试下
同时,注意加上蓝牙的相关权限
解决方案二:
这个太难了,无法回答你
解决方案三:
你试试把==action换成equals(action)
解决方案四:
楼主,太谢谢你了,帮我解决了一个问题!
时间: 2024-12-22 15:49:58