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.permissioncontroller.pm.data.repository.v31 18 19 import android.app.Application 20 import android.content.pm.PackageManager 21 import android.os.UserHandle 22 import android.util.Log 23 import com.android.permissioncontroller.permission.utils.Utils 24 import com.android.permissioncontroller.pm.data.model.v31.PackageInfoModel 25 import kotlin.concurrent.Volatile 26 import kotlinx.coroutines.CoroutineDispatcher 27 import kotlinx.coroutines.Dispatchers 28 import kotlinx.coroutines.withContext 29 30 /** 31 * Repository to access package info data exposed by [PackageManager]. Domain and view layer 32 * shouldn't access [PackageManager] directly, instead they should use the repository. 33 */ 34 interface PackageRepository { getPackageInfonull35 suspend fun getPackageInfo( 36 packageName: String, 37 user: UserHandle, 38 flags: Int = PackageManager.GET_PERMISSIONS 39 ): PackageInfoModel? 40 41 companion object { 42 @Volatile private var instance: PackageRepository? = null 43 44 fun getInstance(app: Application): PackageRepository = 45 instance ?: synchronized(this) { PackageRepositoryImpl(app).also { instance = it } } 46 } 47 } 48 49 class PackageRepositoryImpl( 50 private val app: Application, 51 private val dispatcher: CoroutineDispatcher = Dispatchers.Default, 52 ) : PackageRepository { getPackageInfonull53 override suspend fun getPackageInfo( 54 packageName: String, 55 user: UserHandle, 56 flags: Int 57 ): PackageInfoModel? = 58 withContext(dispatcher) { 59 try { 60 val packageInfo = 61 Utils.getUserContext(app, user) 62 .packageManager 63 .getPackageInfo(packageName, PackageManager.GET_PERMISSIONS) 64 PackageInfoModel(packageInfo) 65 } catch (e: PackageManager.NameNotFoundException) { 66 Log.w(LOG_TAG, "package $packageName not found for user ${user.identifier}") 67 null 68 } 69 } 70 71 companion object { 72 private const val LOG_TAG = "PackageRepository" 73 } 74 } 75