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.intentresolver.data
18 
19 import android.content.BroadcastReceiver
20 import android.content.Context
21 import android.content.Intent
22 import android.content.IntentFilter
23 import android.os.Handler
24 import android.os.UserHandle
25 import android.util.Log
26 import com.android.intentresolver.inject.Broadcast
27 import dagger.hilt.android.qualifiers.ApplicationContext
28 import javax.inject.Inject
29 import kotlinx.coroutines.channels.awaitClose
30 import kotlinx.coroutines.channels.onFailure
31 import kotlinx.coroutines.flow.Flow
32 import kotlinx.coroutines.flow.callbackFlow
33 
34 private const val TAG = "BroadcastSubscriber"
35 
36 class BroadcastSubscriber
37 @Inject
38 constructor(
39     @ApplicationContext private val context: Context,
40     @Broadcast private val handler: Handler
41 ) {
42     /**
43      * Returns a [callbackFlow] that, when collected, registers a broadcast receiver and emits a new
44      * value whenever broadcast matching _filter_ is received. The result value will be computed
45      * using [transform] and emitted if non-null.
46      */
47     fun <T> createFlow(
48         filter: IntentFilter,
49         user: UserHandle,
50         transform: (Intent) -> T?,
51     ): Flow<T> = callbackFlow {
52         val receiver =
53             object : BroadcastReceiver() {
54                 override fun onReceive(context: Context, intent: Intent) {
55                     transform(intent)?.also { result ->
56                         trySend(result).onFailure { Log.e(TAG, "Failed to send $result", it) }
57                     }
58                         ?: Log.w(TAG, "Ignored broadcast $intent")
59                 }
60             }
61 
62         @Suppress("MissingPermission")
63         context.registerReceiverAsUser(
64             receiver,
65             user,
66             IntentFilter(filter),
67             null,
68             handler,
69             Context.RECEIVER_NOT_EXPORTED
70         )
71         awaitClose { context.unregisterReceiver(receiver) }
72     }
73 }
74