如何检查蓝牙是否启用编程?
我想检查是否在任何Android设备上定期启用蓝牙。 是否有任何意图我可以捕捉使用BroadcastReceiver这样做,还是有其他方法来做到这一点?
你去了:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth } else { if (!mBluetoothAdapter.isEnabled()) { // Bluetooth is not enable :) } }
uses-permission
<uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
在这里,我有其他的select作为这个问题的答案。
首先在你的Manifest文件中添加以下行。
<uses-feature android:name="android.hardware.BLUETOOTH" android:required="false"/>
现在,您要在哪里查看蓝牙支持,请使用以下代码。
boolean isBluetoothSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
public boolean isBluetoothEnabled() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return mBluetoothAdapter.isEnabled(); }
在清单文件中有权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
使用可以使用
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
为检查bt连接
mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED
为检查bt断开
mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_DISCONNECTED
要以编程方式检查蓝牙状态,请打开或closures:
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 }
你也可以听意向动作:
BluetoothAdapter.ACTION_STATE_CHANGED
这是我用@ xjaphx的答案做的,稍微简化了一下:
private boolean getBlueToothOn(){ BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); return btAdapter != null && btAdapter.isEnabled(); } <uses-permission android:name="android.permission.BLUETOOTH" />