我想检查是否定期在任何Android设备上启用了蓝牙。使用BroadcastReceiver可以捕捉到任何意图吗,还是有其他方法可以做到?
Answers:
你去了:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
} else if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled :)
} else {
// Bluetooth is enabled
}
用 uses-permission
<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
在这里,我有其他选择作为该问题的答案。
首先在清单文件中添加以下行。
<uses-feature android:name="android.hardware.BLUETOOTH" android:required="false"/>
现在,要检查蓝牙支持能力,请使用以下代码。
boolean isBluetoothSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
要以编程方式检查蓝牙状态(打开或关闭):
BluetoothAdapter btAdapter = ((Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1)
?((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter()
:(BluetoothAdapter.getDefaultAdapter()));
if(btAdapter==null){
return;
}
if(btAdapter.getState()==BluetoothAdapter.STATE_ON){
//Bluetooth is ON
}
您还可以听取Intent操作:
蓝牙适配器。ACTION_STATE_CHANGED
使用可以使用
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
用于检查bt连接
mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED
用于检查bt断开连接
mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_DISCONNECTED
这是我在@xjaphx的答案(略有简化的版本)的帮助下完成的:
private boolean getBlueToothOn(){
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
return btAdapter != null && btAdapter.isEnabled();
}
<uses-permission android:name="android.permission.BLUETOOTH" />