1 /* <lambda>null2 * Copyright (C) 2020 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.app.usage.UsageStats 21 import android.app.usage.UsageStatsManager 22 import android.app.usage.UsageStatsManager.INTERVAL_MONTHLY 23 import android.os.UserHandle 24 import com.android.permissioncontroller.PermissionControllerApplication 25 import com.android.permissioncontroller.permission.utils.Utils 26 import kotlinx.coroutines.Job 27 28 /** 29 * A livedata which tracks the usage stats for all packages for all users in a given length of time. 30 * 31 * @param app The current application 32 * @param searchTimeMs The length of time, in milliseconds, that this LiveData will track. The time 33 * will start when the liveData is loaded, and extend backwards searchTimeMs milliseconds. 34 * @param interval The interval to measure in. Default is monthly. 35 */ 36 class UsageStatsLiveData private constructor( 37 private val app: Application, 38 private val searchTimeMs: Long, 39 private val interval: Int = INTERVAL_MONTHLY 40 ) : SmartAsyncMediatorLiveData<Map<UserHandle, List<UsageStats>>>() { 41 42 init { 43 addSource(UsersLiveData) { 44 update() 45 } 46 } 47 48 override suspend fun loadDataAndPostValue(job: Job) { 49 if (!UsersLiveData.isInitialized) { 50 return 51 } 52 53 val now = System.currentTimeMillis() 54 val userMap = mutableMapOf<UserHandle, List<UsageStats>>() 55 for (user in UsersLiveData.value!!) { 56 // If the user is not enabled, or if the user is a managed profile, and this is not an 57 // android TV (where parental control accounts are managed profiles), do not get stats. 58 if (Utils.isUserDisabledOrWorkProfile(user)) { 59 continue 60 } 61 val statsManager = Utils.getUserContext(app, user).getSystemService( 62 UsageStatsManager::class.java)!! 63 statsManager.queryUsageStats(interval, now - searchTimeMs, now)?.let { stats -> 64 userMap[user] = stats 65 } 66 } 67 68 postValue(userMap) 69 } 70 71 companion object : DataRepository<Pair<Long, Int>, UsageStatsLiveData>() { 72 override fun newValue(key: Pair<Long, Int>): UsageStatsLiveData { 73 return UsageStatsLiveData(PermissionControllerApplication.get(), key.first, key.second) 74 } 75 76 operator fun get(interval: Long): UsageStatsLiveData { 77 return get(interval to INTERVAL_MONTHLY) 78 } 79 } 80 }