如何在 Android 11 后台查看蓝牙的状态开/关?

问题描述

您好 Android 开发者社区,

让我问一个 Android 应用程序如何检查蓝牙在后台状态中是关闭还是打开。这个是在Android 11的环境下问的,我知道在Android 10下怎么查。

我正在寻找当我们的应用程序在 Android 11 后台运行时如何检查蓝牙状态栏的开/关。

还有,请参考这个。 build.gradle 的 targetSdk 版本为 30。

如果答案很快就会到来,任何人都非常受欢迎。

以下不适用于 Android 11,但适用于 Android 10。

<uses-permission android:name="android.permission.BLUetoOTH" />
<uses-permission android:name="android.permission.BLUetoOTH_ADMIN" />
<receiver
            android:name=".service.BluetoothStatebroadcastReceiver"
            android:enabled="true"
            android:exported="true"
            >
            <intent-filter>
                <action android:name="android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED" />
                <action android:name="android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED" />
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
                <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
                <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
                <action android:name="android.bluetooth.device.action.ACL_disCONNECTED" />
            </intent-filter>
        </receiver>
class BluetoothStatebroadcastReceiver : broadcastReceiver() {
    override fun onReceive(context: Context,intent: Intent) {
        Timber.d("## ${intent.action}")
        val blAdapter = BluetoothAdapter.getDefaultAdapter()
        when (intent.action) {
            BluetoothAdapter.ACTION_STATE_CHANGED -> {
                when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,BluetoothAdapter.ERROR)) {
                    BluetoothAdapter.STATE_OFF,BluetoothAdapter.STATE_TURNING_OFF -> {
                        if (blAdapter?.isEnabled == false) {
                            blAdapter.enable()
                        }
                    }
                }
            }
            LocationManager.PROVIDERS_CHANGED_ACTION -> {
                ContextCompat.getSystemService(context,LocationManager::class.java)
                    ?.let { lm ->
                        val isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
                        val isNetworkEnabled =
                            lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

                        if ((!isGpsEnabled || !isNetworkEnabled)) {
                            context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS))
                        }
                    } ?: Timber.e("Can't get LocationManager")
            }
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)