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.BroadcastReceiver 20 import android.content.Context 21 import android.content.Intent 22 import android.content.IntentFilter 23 import android.os.UserManager 24 import com.android.settingslib.datastore.AbstractKeyedDataObservable 25 import com.android.settingslib.datastore.DataChangeReason 26 import com.android.settingslib.datastore.KeyedObserver 27 import com.android.settingslib.metadata.PreferenceChangeReason 28 import java.util.concurrent.Executor 29 30 /** Helper class to monitor user restriction changes. */ 31 class UserRestrictions private constructor(private val applicationContext: Context) { 32 33 private val observable = 34 object : AbstractKeyedDataObservable<String>() { onFirstObserverAddednull35 override fun onFirstObserverAdded() { 36 val intentFilter = IntentFilter() 37 intentFilter.addAction(UserManager.ACTION_USER_RESTRICTIONS_CHANGED) 38 applicationContext.registerReceiver(broadcastReceiver, intentFilter) 39 } 40 onLastObserverRemovednull41 override fun onLastObserverRemoved() { 42 applicationContext.unregisterReceiver(broadcastReceiver) 43 } 44 } 45 46 private val broadcastReceiver: BroadcastReceiver = 47 object : BroadcastReceiver() { onReceivenull48 override fun onReceive(context: Context, intent: Intent) { 49 // there is no way to get the changed keys, just notify all observers 50 observable.notifyChange(PreferenceChangeReason.STATE) 51 } 52 } 53 addObservernull54 fun addObserver(observer: KeyedObserver<String?>, executor: Executor) = 55 observable.addObserver(observer, executor) 56 57 fun addObserver(key: String, observer: KeyedObserver<String>, executor: Executor) = 58 observable.addObserver(key, observer, executor) 59 60 fun removeObserver(observer: KeyedObserver<String?>) = observable.removeObserver(observer) 61 62 fun removeObserver(key: String, observer: KeyedObserver<String>) = 63 observable.removeObserver(key, observer) 64 65 companion object { 66 @Volatile private var instance: UserRestrictions? = null 67 68 fun get(context: Context) = 69 instance 70 ?: synchronized(this) { 71 instance ?: UserRestrictions(context.applicationContext).also { instance = it } 72 } 73 } 74 } 75