1 /*
<lambda>null2  * Copyright (C) 2023 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.datausage.lib
18 
19 import android.content.Context
20 import android.content.pm.PackageManager
21 import android.os.UserHandle
22 import android.util.IconDrawableFactory
23 import androidx.preference.Preference
24 
25 class AppPreferenceRepository(
26     private val context: Context,
27     private val iconDrawableFactory: IconDrawableFactory = IconDrawableFactory.newInstance(context),
28 ) {
29     private val packageManager = context.packageManager
30 
31     fun loadAppPreferences(uids: List<Int>): List<Preference> = uids.flatMap { uid ->
32         val userId = UserHandle.getUserId(uid)
33         getPackagesForUid(uid).mapNotNull { packageName ->
34             getPreference(packageName, userId)
35         }
36     }
37 
38     private fun getPackagesForUid(uid: Int): Array<String> =
39         packageManager.getPackagesForUid(uid) ?: emptyArray()
40 
41     private fun getPreference(packageName: String, userId: Int): Preference? = try {
42         val app = packageManager.getApplicationInfoAsUser(packageName, 0, userId)
43         Preference(context).apply {
44             icon = iconDrawableFactory.getBadgedIcon(app)
45             title = app.loadLabel(packageManager)
46             isSelectable = false
47         }
48     } catch (e: PackageManager.NameNotFoundException) {
49         null
50     }
51 }
52