blob: 319a6e09d4d18b4b5f662166a23d91aad08db6dc [file] [log] [blame]
Fabian Kozynski42f86a02019-07-09 12:39:03 -04001/*
2 * Copyright (C) 2019 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
17package com.android.systemui.broadcast
18
19import android.content.BroadcastReceiver
20import android.content.Context
21import android.content.IntentFilter
22import android.os.Handler
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -050023import android.os.HandlerExecutor
Fabian Kozynski42f86a02019-07-09 12:39:03 -040024import android.os.Looper
25import android.os.Message
26import android.os.UserHandle
Fabian Kozynskicfe80452019-10-17 14:29:03 +000027import android.text.TextUtils
Fabian Kozynski42f86a02019-07-09 12:39:03 -040028import android.util.SparseArray
29import com.android.internal.annotations.VisibleForTesting
Fabian Kozynski42f86a02019-07-09 12:39:03 -040030import com.android.systemui.Dumpable
Dave Mankoff00e8a2f2019-12-18 16:59:49 -050031import com.android.systemui.dagger.qualifiers.Background
32import com.android.systemui.dagger.qualifiers.Main
Ned Burnsc7cfa692020-02-12 21:38:50 -050033import com.android.systemui.dump.DumpManager
Fabian Kozynski42f86a02019-07-09 12:39:03 -040034import java.io.FileDescriptor
35import java.io.PrintWriter
Evan Lairdb7f2c692020-04-14 16:55:49 -040036import java.lang.IllegalStateException
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -050037import java.util.concurrent.Executor
Fabian Kozynski42f86a02019-07-09 12:39:03 -040038import javax.inject.Inject
Fabian Kozynski42f86a02019-07-09 12:39:03 -040039import javax.inject.Singleton
40
41data class ReceiverData(
42 val receiver: BroadcastReceiver,
43 val filter: IntentFilter,
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -050044 val executor: Executor,
Fabian Kozynski42f86a02019-07-09 12:39:03 -040045 val user: UserHandle
46)
47
48private const val MSG_ADD_RECEIVER = 0
49private const val MSG_REMOVE_RECEIVER = 1
50private const val MSG_REMOVE_RECEIVER_FOR_USER = 2
51private const val TAG = "BroadcastDispatcher"
Fabian Kozynski2c9b3b42019-12-06 16:39:50 -050052private const val DEBUG = true
Fabian Kozynski42f86a02019-07-09 12:39:03 -040053
54/**
55 * SystemUI master Broadcast Dispatcher.
56 *
57 * This class allows [BroadcastReceiver] to register and centralizes registrations to [Context]
58 * from SystemUI. That way the number of calls to [BroadcastReceiver.onReceive] can be reduced for
59 * a given broadcast.
60 *
61 * Use only for IntentFilters with actions and optionally categories. It does not support,
Fabian Kozynskicb6968c2019-11-26 13:09:11 -050062 * permissions, schemes, data types, data authorities or priority different than 0.
Fabian Kozynskicfe80452019-10-17 14:29:03 +000063 * Cannot be used for getting sticky broadcasts.
Fabian Kozynski42f86a02019-07-09 12:39:03 -040064 */
65@Singleton
66open class BroadcastDispatcher @Inject constructor (
67 private val context: Context,
Dave Mankoff00e8a2f2019-12-18 16:59:49 -050068 @Main private val mainHandler: Handler,
Ned Burnsc7cfa692020-02-12 21:38:50 -050069 @Background private val bgLooper: Looper,
70 dumpManager: DumpManager
Fabian Kozynski42f86a02019-07-09 12:39:03 -040071) : Dumpable {
72
73 // Only modify in BG thread
74 private val receiversByUser = SparseArray<UserBroadcastDispatcher>(20)
75
Ned Burnsc7cfa692020-02-12 21:38:50 -050076 init {
77 // TODO: Don't do this in the constructor
78 dumpManager.registerDumpable(javaClass.name, this)
79 }
80
Fabian Kozynski42f86a02019-07-09 12:39:03 -040081 /**
82 * Register a receiver for broadcast with the dispatcher
83 *
84 * @param receiver A receiver to dispatch the [Intent]
85 * @param filter A filter to determine what broadcasts should be dispatched to this receiver.
Fabian Kozynskicfe80452019-10-17 14:29:03 +000086 * It will only take into account actions and categories for filtering. It must
87 * have at least one action.
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -050088 * @param handler A handler to dispatch [BroadcastReceiver.onReceive].
89 * @param user A user handle to determine which broadcast should be dispatched to this receiver.
90 * By default, it is the current user.
91 * @throws IllegalArgumentException if the filter has other constraints that are not actions or
92 * categories or the filter has no actions.
93 */
94 @Deprecated(message = "Replacing Handler for Executor in SystemUI",
95 replaceWith = ReplaceWith("registerReceiver(receiver, filter, executor, user)"))
96 @JvmOverloads
Fabian Kozynski81168162020-03-18 14:22:26 -040097 open fun registerReceiverWithHandler(
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -050098 receiver: BroadcastReceiver,
99 filter: IntentFilter,
100 handler: Handler,
101 user: UserHandle = context.user
102 ) {
103 registerReceiver(receiver, filter, HandlerExecutor(handler), user)
104 }
105
106 /**
107 * Register a receiver for broadcast with the dispatcher
108 *
109 * @param receiver A receiver to dispatch the [Intent]
110 * @param filter A filter to determine what broadcasts should be dispatched to this receiver.
111 * It will only take into account actions and categories for filtering. It must
112 * have at least one action.
113 * @param executor An executor to dispatch [BroadcastReceiver.onReceive]. Pass null to use an
114 * executor in the main thread (default).
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400115 * @param user A user handle to determine which broadcast should be dispatched to this receiver.
116 * By default, it is the current user.
Fabian Kozynskicfe80452019-10-17 14:29:03 +0000117 * @throws IllegalArgumentException if the filter has other constraints that are not actions or
118 * categories or the filter has no actions.
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400119 */
120 @JvmOverloads
Fabian Kozynski81168162020-03-18 14:22:26 -0400121 open fun registerReceiver(
Ned Burnsc7cfa692020-02-12 21:38:50 -0500122 receiver: BroadcastReceiver,
123 filter: IntentFilter,
124 executor: Executor? = context.mainExecutor,
125 user: UserHandle = context.user
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400126 ) {
Fabian Kozynskicfe80452019-10-17 14:29:03 +0000127 checkFilter(filter)
Fabian Kozynskiff5e91f2019-09-24 15:38:08 -0400128 this.handler
129 .obtainMessage(MSG_ADD_RECEIVER,
Fabian Kozynski5e92c6f2020-01-03 13:56:17 -0500130 ReceiverData(receiver, filter, executor ?: context.mainExecutor, user))
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400131 .sendToTarget()
132 }
133
Fabian Kozynskicfe80452019-10-17 14:29:03 +0000134 private fun checkFilter(filter: IntentFilter) {
135 val sb = StringBuilder()
136 if (filter.countActions() == 0) sb.append("Filter must contain at least one action. ")
137 if (filter.countDataAuthorities() != 0) sb.append("Filter cannot contain DataAuthorities. ")
138 if (filter.countDataPaths() != 0) sb.append("Filter cannot contain DataPaths. ")
139 if (filter.countDataSchemes() != 0) sb.append("Filter cannot contain DataSchemes. ")
140 if (filter.countDataTypes() != 0) sb.append("Filter cannot contain DataTypes. ")
Fabian Kozynskicb6968c2019-11-26 13:09:11 -0500141 if (filter.priority != 0) sb.append("Filter cannot modify priority. ")
Fabian Kozynskicfe80452019-10-17 14:29:03 +0000142 if (!TextUtils.isEmpty(sb)) throw IllegalArgumentException(sb.toString())
143 }
144
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400145 /**
146 * Unregister receiver for all users.
147 * <br>
148 * This will remove every registration of [receiver], not those done just with [UserHandle.ALL].
149 *
150 * @param receiver The receiver to unregister. It will be unregistered for all users.
151 */
Fabian Kozynski81168162020-03-18 14:22:26 -0400152 open fun unregisterReceiver(receiver: BroadcastReceiver) {
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400153 handler.obtainMessage(MSG_REMOVE_RECEIVER, receiver).sendToTarget()
154 }
155
156 /**
157 * Unregister receiver for a particular user.
158 *
159 * @param receiver The receiver to unregister. It will be unregistered for all users.
160 * @param user The user associated to the registered [receiver]. It can be [UserHandle.ALL].
161 */
Fabian Kozynski81168162020-03-18 14:22:26 -0400162 open fun unregisterReceiverForUser(receiver: BroadcastReceiver, user: UserHandle) {
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400163 handler.obtainMessage(MSG_REMOVE_RECEIVER_FOR_USER, user.identifier, 0, receiver)
164 .sendToTarget()
165 }
166
167 @VisibleForTesting
168 protected open fun createUBRForUser(userId: Int) =
Fabian Kozynskiaaf4c5e2020-03-27 13:29:15 -0400169 UserBroadcastDispatcher(context, userId, bgLooper)
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400170
Lucas Dupin64171fe2019-10-30 14:28:29 -0700171 override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) {
172 pw.println("Broadcast dispatcher:")
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400173 for (index in 0 until receiversByUser.size()) {
Lucas Dupin64171fe2019-10-30 14:28:29 -0700174 pw.println(" User ${receiversByUser.keyAt(index)}")
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400175 receiversByUser.valueAt(index).dump(fd, pw, args)
176 }
177 }
178
179 private val handler = object : Handler(bgLooper) {
180 override fun handleMessage(msg: Message) {
181 when (msg.what) {
182 MSG_ADD_RECEIVER -> {
183 val data = msg.obj as ReceiverData
Fabian Kozynski2c9b3b42019-12-06 16:39:50 -0500184 // If the receiver asked to be registered under the current user, we register
185 // under the actual current user.
186 val userId = if (data.user.identifier == UserHandle.USER_CURRENT) {
187 context.userId
188 } else {
189 data.user.identifier
190 }
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400191 if (userId < UserHandle.USER_ALL) {
Evan Lairdb7f2c692020-04-14 16:55:49 -0400192 throw IllegalStateException(
193 "Attempting to register receiver for invalid user {$userId}")
Fabian Kozynski42f86a02019-07-09 12:39:03 -0400194 }
195 val uBR = receiversByUser.get(userId, createUBRForUser(userId))
196 receiversByUser.put(userId, uBR)
197 uBR.registerReceiver(data)
198 }
199
200 MSG_REMOVE_RECEIVER -> {
201 for (it in 0 until receiversByUser.size()) {
202 receiversByUser.valueAt(it).unregisterReceiver(msg.obj as BroadcastReceiver)
203 }
204 }
205
206 MSG_REMOVE_RECEIVER_FOR_USER -> {
207 receiversByUser.get(msg.arg1)?.unregisterReceiver(msg.obj as BroadcastReceiver)
208 }
209
210 else -> super.handleMessage(msg)
211 }
212 }
213 }
214}