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.app.usage.NetworkStats 20 import android.content.Context 21 import android.net.NetworkTemplate 22 import android.util.Range 23 import com.android.settings.datausage.lib.AppDataUsageRepository.Companion.withSdkSandboxUids 24 import com.android.settingslib.spa.framework.util.asyncMap 25 26 interface IAppDataUsageDetailsRepository { 27 suspend fun queryDetailsForCycles(): List<NetworkUsageDetailsData> 28 } 29 30 class AppDataUsageDetailsRepository @JvmOverloads constructor( 31 context: Context, 32 private val template: NetworkTemplate, 33 private val cycles: List<Long>?, 34 uids: List<Int>, 35 private val networkCycleDataRepository: INetworkCycleDataRepository = 36 NetworkCycleDataRepository(context, template), 37 private val networkStatsRepository: NetworkStatsRepository = 38 NetworkStatsRepository(context, template), 39 ) : IAppDataUsageDetailsRepository { 40 private val withSdkSandboxUids = withSdkSandboxUids(uids) 41 queryDetailsForCyclesnull42 override suspend fun queryDetailsForCycles(): List<NetworkUsageDetailsData> = 43 getCycles().asyncMap { queryDetails(it) }.filter { it.totalUsage > 0 } 44 getCyclesnull45 private fun getCycles(): List<Range<Long>> = 46 cycles?.zipWithNext { endTime, startTime -> Range(startTime, endTime) } 47 ?: networkCycleDataRepository.getCycles() 48 queryDetailsnull49 private fun queryDetails(range: Range<Long>): NetworkUsageDetailsData { 50 val buckets = networkStatsRepository.queryBuckets(range.lower, range.upper) 51 .filter { it.uid in withSdkSandboxUids } 52 val totalUsage = buckets.sumOf { it.bytes } 53 val foregroundUsage = 54 buckets.filter { it.state == NetworkStats.Bucket.STATE_FOREGROUND }.sumOf { it.bytes } 55 return NetworkUsageDetailsData( 56 range = range, 57 totalUsage = totalUsage, 58 foregroundUsage = foregroundUsage, 59 backgroundUsage = totalUsage - foregroundUsage, 60 ) 61 } 62 } 63