如何检查蓝牙是否以编程方式启用?

and*_*oob 67 android bluetooth

我想检查是否定期在任何Android设备上启用蓝牙.有没有使用BroadcastReceiver可以捕获的意图,还是有其他方法可以做到这一点?

Pet*_*ton 157

你去:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth
} else if (!mBluetoothAdapter.isEnabled()) {
    // Bluetooth is not enabled :)
} else {
    // Bluetooth is enabled 
}
Run Code Online (Sandbox Code Playgroud)

uses-permission

 <uses-permission android:name="android.permission.BLUETOOTH" android:required="false" />
Run Code Online (Sandbox Code Playgroud)

  • 如果只需要蓝牙权限进行此检测,请不要忘记将其设置为不需要:<uses-feature android:name ="android.hardware.bluetooth"android:required ="false"/> (8认同)
  • 不,你不需要互联网来检查蓝牙状态.好吧,除了从这个SO帖子获取代码;) (4认同)

小智 8

在这里,我有其他选择作为这个问题的答案.

首先在清单文件中添加以下行.

<uses-feature android:name="android.hardware.BLUETOOTH" android:required="false"/>
Run Code Online (Sandbox Code Playgroud)

现在,您要检查蓝牙支持性,请使用以下代码.

boolean isBluetoothSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
Run Code Online (Sandbox Code Playgroud)


Aru*_*mar 6

public boolean isBluetoothEnabled()
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        return mBluetoothAdapter.isEnabled();

    }
Run Code Online (Sandbox Code Playgroud)

使用清单文件中的权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)


小智 5

要以编程方式检查蓝牙状态(打开或关闭):

    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
       }
Run Code Online (Sandbox Code Playgroud)

您还可以听取Intent操作:

蓝牙适配器。ACTION_STATE_CHANGED