dch*_*lle 77 android android-bluetooth
我知道如何获得配对设备列表,但我怎么知道它们是否已连接?
它必须是可能的,因为我看到它们列在我手机的蓝牙设备列表中,并说明了它们的连接状态.
Sky*_*ton 139
使用intent过滤器来侦听ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECT_REQUESTED和ACTION_ACL_DISCONNECTED广播:
<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)
几点说明:
job*_*ert 23
在我的使用案例中,我只想查看是否为VoIP应用程序连接了蓝牙耳机.以下解决方案适合我:
public static boolean isBluetoothHeadsetConnected() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
}
Run Code Online (Sandbox Code Playgroud)
当然你需要蓝牙许可:
<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)
pmo*_*ont 11
非常感谢Skylarsutton的回答.我发布此作为对他的回复,但因为我发布的代码我无法回复评论.我已经提出了他的答案,所以我不是在寻找任何积分.只需支付它.
由于某些原因,Android Studio无法解析BluetoothAdapter.ACTION_ACL_CONNECTED.也许它在Android 4.2.2中被弃用了?这是他的代码的修改.注册码是一样的; 接收者代码稍有不同.我在一个服务中使用它来更新应用程序的其他部分引用的蓝牙连接标志.
public void onCreate() {
//...
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
}
//else if...
}
};
Run Code Online (Sandbox Code Playgroud)
小智 8
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java中的BluetoothDevice 系统API 中有一个isConnected函数。
如果您想知道当前是否连接了有界(配对)设备,以下功能对我来说很好用:
public static boolean isConnected(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("isConnected", (Class[]) null);
boolean connected = (boolean) m.invoke(device, (Object[]) null);
return connected;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
108188 次 |
最近记录: |