1 /* <lambda>null2 * 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.settings.network.telephony 18 19 import android.content.Context 20 import android.telephony.TelephonyCallback 21 import android.telephony.TelephonyManager 22 import android.util.Log 23 import kotlinx.coroutines.Dispatchers 24 import kotlinx.coroutines.ExperimentalCoroutinesApi 25 import kotlinx.coroutines.flow.Flow 26 import kotlinx.coroutines.flow.combine 27 import kotlinx.coroutines.flow.conflate 28 import kotlinx.coroutines.flow.flatMapLatest 29 import kotlinx.coroutines.flow.flowOf 30 import kotlinx.coroutines.flow.flowOn 31 import kotlinx.coroutines.flow.onEach 32 33 @OptIn(ExperimentalCoroutinesApi::class) 34 class CallStateRepository(private val context: Context) { 35 private val subscriptionManager = context.requireSubscriptionManager() 36 37 /** Flow for call state of given [subId]. */ 38 fun callStateFlow(subId: Int): Flow<Int> = context.telephonyCallbackFlow(subId) { 39 object : TelephonyCallback(), TelephonyCallback.CallStateListener { 40 override fun onCallStateChanged(state: Int) { 41 trySend(state) 42 } 43 } 44 } 45 46 /** 47 * Flow for in call state. 48 * 49 * @return true if any active subscription's call state is not idle. 50 */ 51 fun isInCallFlow(): Flow<Boolean> = context.subscriptionsChangedFlow() 52 .flatMapLatest { 53 val subIds = subscriptionManager.activeSubscriptionIdList 54 if (subIds.isEmpty()) { 55 flowOf(false) 56 } else { 57 combine(subIds.map(::callStateFlow)) { states -> 58 states.any { it != TelephonyManager.CALL_STATE_IDLE } 59 } 60 } 61 } 62 .conflate() 63 .flowOn(Dispatchers.Default) 64 .onEach { Log.d(TAG, "isInCallFlow: $it") } 65 66 private companion object { 67 private const val TAG = "CallStateRepository" 68 } 69 } 70