1 /* 2 * Copyright 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 // @file:JvmName("BleScanSettingListener") 18 19 package com.android.server.bluetooth 20 21 import android.content.ContentResolver 22 import android.database.ContentObserver 23 import android.os.Handler 24 import android.os.Looper 25 import android.provider.Settings 26 27 private const val TAG = "BleScanSettingListener" 28 29 object BleScanSettingListener { 30 // Must match Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE but cannot depend on the variable 31 const val BLE_SCAN_ALWAYS_AVAILABLE = "ble_scan_always_enabled" 32 33 @JvmStatic 34 var isScanAllowed = false 35 private set 36 37 /** 38 * Listen on Ble Scan setting and trigger the callback when scanning is no longer enabled 39 * 40 * @param callback: The callback to trigger when there is a mode change, pass new mode as 41 * parameter 42 * @return The initial value of the radio 43 */ 44 @JvmStatic initializenull45 fun initialize(looper: Looper, resolver: ContentResolver, callback: () -> Unit) { 46 val notifyForDescendants = false 47 48 resolver.registerContentObserver( 49 Settings.Global.getUriFor(BLE_SCAN_ALWAYS_AVAILABLE), 50 notifyForDescendants, 51 object : ContentObserver(Handler(looper)) { 52 override fun onChange(selfChange: Boolean) { 53 val previousValue = isScanAllowed 54 isScanAllowed = getScanSettingValue(resolver) 55 if (isScanAllowed) { 56 Log.i(TAG, "Ble Scan mode is now allowed. Nothing to do") 57 return 58 } else if (previousValue == isScanAllowed) { 59 Log.i(TAG, "Ble Scan mode was already considered as false. Discarding") 60 return 61 } else { 62 Log.i(TAG, "Trigger callback to disable BLE_ONLY mode") 63 callback() 64 } 65 } 66 } 67 ) 68 isScanAllowed = getScanSettingValue(resolver) 69 } 70 71 /** 72 * Check if Bluetooth is impacted by the radio and fetch global mode status 73 * 74 * @return whether Bluetooth should consider this radio or not 75 */ getScanSettingValuenull76 private fun getScanSettingValue(resolver: ContentResolver): Boolean { 77 try { 78 return Settings.Global.getInt(resolver, BLE_SCAN_ALWAYS_AVAILABLE) != 0 79 } catch (e: Settings.SettingNotFoundException) { 80 Log.i(TAG, "Settings not found. Default to false") 81 return false 82 } 83 } 84 } 85