1 /*
2  * Copyright (C) 2021 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.service
18 
19 import android.content.BroadcastReceiver
20 import android.content.Context
21 import android.content.Intent
22 import android.os.Process
23 import androidx.annotation.VisibleForTesting
24 import com.android.permissioncontroller.DumpableLog
25 import com.android.permissioncontroller.permission.data.PermissionEvent
26 import kotlinx.coroutines.CoroutineDispatcher
27 import kotlinx.coroutines.Dispatchers
28 import kotlinx.coroutines.GlobalScope
29 import kotlinx.coroutines.launch
30 
31 /**
32  * [BroadcastReceiver] to clear user decision information when a package has its data cleared or is
33  * fully removed.
34  */
35 class PersistedStoragePackageUninstalledReceiver(
36     @VisibleForTesting
37     private val storages: List<PermissionEventStorage<out PermissionEvent>> =
38         PermissionEventStorageImpls.getInstance(),
39     private val dispatcher: CoroutineDispatcher = Dispatchers.IO
40 ) : BroadcastReceiver() {
41 
42     companion object {
43         private const val LOG_TAG = "PersistedStoragePackageUninstalledReceiver"
44     }
45 
onReceivenull46     override fun onReceive(context: Context, intent: Intent) {
47         if (storages.isEmpty()) {
48             return
49         }
50         val action = intent.action
51         if (
52             !(action == Intent.ACTION_PACKAGE_DATA_CLEARED ||
53                 action == Intent.ACTION_PACKAGE_FULLY_REMOVED)
54         ) {
55             return
56         }
57         intent.data?.let {
58             val packageName = it.schemeSpecificPart
59             val userId = Process.myUserHandle().identifier
60             DumpableLog.d(LOG_TAG, "Received $action for $packageName for u$userId")
61 
62             GlobalScope.launch(dispatcher) {
63                 for (storage in storages) {
64                     storage.removeEventsForPackage(packageName)
65                 }
66             }
67         }
68     }
69 }
70