1 /* <lambda>null2 * Copyright (C) 2019 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.permissioncontroller.permission.data 18 19 import android.app.Application 20 import android.content.pm.PackageManager 21 import com.android.permissioncontroller.PermissionControllerApplication 22 23 /** Serves as a single shared Permission Change Listener for all AppPermissionGroupLiveDatas. */ 24 object PermissionListenerMultiplexer : PackageManager.OnPermissionsChangedListener { 25 26 private val app: Application = PermissionControllerApplication.get() 27 /** 28 * Map<UID, list of PermissionChangeCallbacks that wish to be informed when permissions are 29 * updated for that UID> 30 */ 31 private val callbacks = mutableMapOf<Int, MutableList<PermissionChangeCallback>>() 32 private val pm = app.applicationContext.packageManager 33 34 override fun onPermissionsChanged(uid: Int) { 35 callbacks[uid]?.toList()?.forEach { callback -> callback.onPermissionChange() } 36 } 37 38 fun addOrReplaceCallback(oldUid: Int?, newUid: Int, callback: PermissionChangeCallback) { 39 if (oldUid != null) { 40 removeCallback(oldUid, callback) 41 } 42 addCallback(newUid, callback) 43 } 44 45 fun addCallback(uid: Int, callback: PermissionChangeCallback) { 46 val wasEmpty = callbacks.isEmpty() 47 48 callbacks.getOrPut(uid, { mutableListOf() }).add(callback) 49 50 if (wasEmpty) { 51 pm.addOnPermissionsChangeListener(this) 52 } 53 } 54 55 fun removeCallback(uid: Int, callback: PermissionChangeCallback) { 56 if (!callbacks.contains(uid)) { 57 return 58 } 59 60 if (!callbacks[uid]!!.remove(callback)) { 61 return 62 } 63 64 if (callbacks[uid]!!.isEmpty()) { 65 callbacks.remove(uid) 66 } 67 68 if (callbacks.isEmpty()) { 69 pm.removeOnPermissionsChangeListener(this) 70 } 71 } 72 73 interface PermissionChangeCallback { 74 fun onPermissionChange() 75 } 76 } 77