1 /* 2 * Copyright (C) 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 package com.android.settings.restriction 18 19 import android.content.Context 20 import com.android.settingslib.datastore.HandlerExecutor 21 import com.android.settingslib.datastore.KeyedObserver 22 import com.android.settingslib.metadata.PreferenceChangeReason 23 import com.android.settingslib.preference.PreferenceScreenBindingHelper 24 25 /** Helper to rebind preference immediately when user restriction is changed. */ 26 class UserRestrictionBindingHelper( 27 private val context: Context, 28 private val screenBindingHelper: PreferenceScreenBindingHelper, 29 ) : KeyedObserver<String>, AutoCloseable { 30 private val restrictionKeysToPreferenceKeys: Map<String, MutableSet<String>> = 31 mutableMapOf<String, MutableSet<String>>() <lambda>null32 .apply { 33 screenBindingHelper.forEachRecursively { 34 val metadata = it.metadata 35 if (metadata is PreferenceRestrictionMixin) { 36 for (restrictionKey in metadata.restrictionKeys) { 37 getOrPut(restrictionKey) { mutableSetOf() }.add(metadata.key) 38 } 39 } 40 } 41 } 42 .toMap() 43 44 init { 45 val restrictionKeys = restrictionKeysToPreferenceKeys.keys 46 if (restrictionKeys.isNotEmpty()) { 47 val userRestrictions = UserRestrictions.get(context) 48 val executor = HandlerExecutor.main 49 for (restrictionKey in restrictionKeys) { 50 userRestrictions.addObserver(restrictionKey, this, executor) 51 } 52 } 53 } 54 onKeyChangednull55 override fun onKeyChanged(restrictionKey: String, reason: Int) { 56 val keys = restrictionKeysToPreferenceKeys[restrictionKey] ?: return 57 for (key in keys) screenBindingHelper.notifyChange(key, PreferenceChangeReason.STATE) 58 } 59 closenull60 override fun close() { 61 val restrictionKeys = restrictionKeysToPreferenceKeys.keys 62 if (restrictionKeys.isNotEmpty()) { 63 val userRestrictions = UserRestrictions.get(context) 64 for (restrictionKey in restrictionKeys) { 65 userRestrictions.removeObserver(restrictionKey, this) 66 } 67 } 68 } 69 } 70