blob: a5d1c8ae7686eca79740af28eee15fc25446112c [file] [log] [blame]
Jordan Liuc872fad2019-10-11 11:42:03 -07001/*
2 * Copyright (C) 2013 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.cellbroadcastservice;
18
Jordan Liuc872fad2019-10-11 11:42:03 -070019import static android.provider.Settings.Secure.CMAS_ADDITIONAL_BROADCAST_PKG;
20
21import android.Manifest;
22import android.annotation.NonNull;
23import android.annotation.Nullable;
24import android.app.Activity;
25import android.app.AppOpsManager;
Jack Yua1309272019-10-24 00:19:49 -070026import android.content.BroadcastReceiver;
Jordan Liuc872fad2019-10-11 11:42:03 -070027import android.content.ContentValues;
28import android.content.Context;
29import android.content.Intent;
Jack Yua1309272019-10-24 00:19:49 -070030import android.content.IntentFilter;
Philip P. Moltmann376f9fa2019-10-30 15:25:24 -070031import android.content.pm.PackageManager;
Jack Yua1309272019-10-24 00:19:49 -070032import android.content.res.Resources;
33import android.database.Cursor;
Jordan Liuc872fad2019-10-11 11:42:03 -070034import android.location.Location;
35import android.location.LocationListener;
36import android.location.LocationManager;
37import android.net.Uri;
Jordan Liuc872fad2019-10-11 11:42:03 -070038import android.os.Bundle;
39import android.os.Handler;
40import android.os.Looper;
41import android.os.Message;
Philip P. Moltmann376f9fa2019-10-30 15:25:24 -070042import android.os.Process;
Jordan Liu26e820c2019-10-22 14:42:07 -070043import android.os.SystemProperties;
Jordan Liuc872fad2019-10-11 11:42:03 -070044import android.os.UserHandle;
45import android.provider.Settings;
46import android.provider.Telephony;
47import android.provider.Telephony.CellBroadcasts;
Jordan Liu4a2ff262019-10-21 12:30:56 -070048import android.telephony.CbGeoUtils.Geometry;
49import android.telephony.CbGeoUtils.LatLng;
Jordan Liuc872fad2019-10-11 11:42:03 -070050import android.telephony.SmsCbMessage;
51import android.telephony.SubscriptionManager;
Jack Yu2003c522019-10-31 09:47:20 -070052import android.telephony.cdma.CdmaSmsCbProgramData;
Jack Yua1309272019-10-24 00:19:49 -070053import android.text.TextUtils;
Jordan Liuc872fad2019-10-11 11:42:03 -070054import android.text.format.DateUtils;
55import android.util.LocalLog;
56import android.util.Log;
57
Jack Yua1309272019-10-24 00:19:49 -070058import com.android.internal.annotations.VisibleForTesting;
Jordan Liuc872fad2019-10-11 11:42:03 -070059import com.android.internal.telephony.metrics.TelephonyMetrics;
60
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
Jack Yua1309272019-10-24 00:19:49 -070063import java.text.DateFormat;
Jordan Liuc872fad2019-10-11 11:42:03 -070064import java.util.ArrayList;
65import java.util.Arrays;
Jack Yua1309272019-10-24 00:19:49 -070066import java.util.HashMap;
Jordan Liuc872fad2019-10-11 11:42:03 -070067import java.util.List;
Jack Yua1309272019-10-24 00:19:49 -070068import java.util.Map;
Jack Yu6f9a26e2019-11-07 23:10:02 -080069import java.util.Objects;
Jack Yu2003c522019-10-31 09:47:20 -070070import java.util.stream.Collectors;
71import java.util.stream.Stream;
Jordan Liuc872fad2019-10-11 11:42:03 -070072
73/**
74 * Dispatch new Cell Broadcasts to receivers. Acquires a private wakelock until the broadcast
75 * completes and our result receiver is called.
76 */
77public class CellBroadcastHandler extends WakeLockStateMachine {
78 private static final String EXTRA_MESSAGE = "message";
79
Jack Yudc607602019-10-31 13:24:43 -070080 /**
81 * To disable cell broadcast duplicate detection for debugging purposes
82 * <code>adb shell am broadcast -a com.android.cellbroadcastservice.action.DUPLICATE_DETECTION
83 * --ez enable false</code>
84 *
85 * To enable cell broadcast duplicate detection for debugging purposes
86 * <code>adb shell am broadcast -a com.android.cellbroadcastservice.action.DUPLICATE_DETECTION
87 * --ez enable true</code>
88 */
89 private static final String ACTION_DUPLICATE_DETECTION =
90 "com.android.cellbroadcastservice.action.DUPLICATE_DETECTION";
91
92 /**
93 * The extra for cell broadcast duplicate detection enable/disable
94 */
95 private static final String EXTRA_ENABLE = "enable";
96
Jordan Liuc872fad2019-10-11 11:42:03 -070097 private final LocalLog mLocalLog = new LocalLog(100);
98
Jordan Liu26e820c2019-10-22 14:42:07 -070099 private static final boolean IS_DEBUGGABLE = SystemProperties.getInt("ro.debuggable", 0) == 1;
100
Jordan Liuc872fad2019-10-11 11:42:03 -0700101 /** Uses to request the location update. */
102 public final LocationRequester mLocationRequester;
103
Jack Yua1309272019-10-24 00:19:49 -0700104 /** Timestamp of last airplane mode on */
105 private long mLastAirplaneModeTime = 0;
106
Jack Yu2003c522019-10-31 09:47:20 -0700107 /** Resource cache */
Jack Yua1309272019-10-24 00:19:49 -0700108 private final Map<Integer, Resources> mResourcesCache = new HashMap<>();
109
Jack Yudc607602019-10-31 13:24:43 -0700110 /** Whether performing duplicate detection or not. Note this is for debugging purposes only. */
111 private boolean mEnableDuplicateDetection = true;
112
Jack Yu2003c522019-10-31 09:47:20 -0700113 /**
114 * Service category equivalent map. The key is the GSM service category, the value is the CDMA
115 * service category.
116 */
117 private final Map<Integer, Integer> mServiceCategoryCrossRATMap;
118
Jordan Liuc872fad2019-10-11 11:42:03 -0700119 private CellBroadcastHandler(Context context) {
120 this("CellBroadcastHandler", context);
121 }
122
123 protected CellBroadcastHandler(String debugTag, Context context) {
124 super(debugTag, context);
125 mLocationRequester = new LocationRequester(
126 context,
127 (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE),
128 getHandler().getLooper());
Jack Yua1309272019-10-24 00:19:49 -0700129
Jack Yu2003c522019-10-31 09:47:20 -0700130 // Adding GSM / CDMA service category mapping.
131 mServiceCategoryCrossRATMap = Stream.of(new Integer[][] {
132 // Presidential alert
133 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_PRESIDENTIAL_LEVEL,
134 CdmaSmsCbProgramData.CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT},
135 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_PRESIDENTIAL_LEVEL_LANGUAGE,
136 CdmaSmsCbProgramData.CATEGORY_CMAS_PRESIDENTIAL_LEVEL_ALERT},
137
138 // Extreme alert
139 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_OBSERVED,
140 CdmaSmsCbProgramData.CATEGORY_CMAS_EXTREME_THREAT},
141 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_OBSERVED_LANGUAGE,
142 CdmaSmsCbProgramData.CATEGORY_CMAS_EXTREME_THREAT},
143 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_LIKELY,
144 CdmaSmsCbProgramData.CATEGORY_CMAS_EXTREME_THREAT},
145 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_IMMEDIATE_LIKELY_LANGUAGE,
146 CdmaSmsCbProgramData.CATEGORY_CMAS_EXTREME_THREAT},
147
148 // Severe alert
149 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_OBSERVED,
150 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
151 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_OBSERVED_LANGUAGE,
152 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
153 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_LIKELY,
154 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
155 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_EXTREME_EXPECTED_LIKELY_LANGUAGE,
156 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
157 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_OBSERVED,
158 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
159 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_OBSERVED_LANGUAGE,
160 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
161 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_LIKELY,
162 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
163 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_IMMEDIATE_LIKELY_LANGUAGE,
164 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
165 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_OBSERVED,
166 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
167 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_OBSERVED_LANGUAGE,
168 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
169 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_LIKELY,
170 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
171 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_SEVERE_EXPECTED_LIKELY_LANGUAGE,
172 CdmaSmsCbProgramData.CATEGORY_CMAS_SEVERE_THREAT},
173
174 // Amber alert
175 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_CHILD_ABDUCTION_EMERGENCY,
176 CdmaSmsCbProgramData.CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY},
177 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_CHILD_ABDUCTION_EMERGENCY_LANGUAGE,
178 CdmaSmsCbProgramData.CATEGORY_CMAS_CHILD_ABDUCTION_EMERGENCY},
179
180 // Monthly test alert
181 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_REQUIRED_MONTHLY_TEST,
182 CdmaSmsCbProgramData.CATEGORY_CMAS_TEST_MESSAGE},
183 { SmsCbConstants.MESSAGE_ID_CMAS_ALERT_REQUIRED_MONTHLY_TEST_LANGUAGE,
184 CdmaSmsCbProgramData.CATEGORY_CMAS_TEST_MESSAGE},
185 }).collect(Collectors.toMap(data -> data[0], data -> data[1]));
186
Jack Yudc607602019-10-31 13:24:43 -0700187 IntentFilter intentFilter = new IntentFilter();
188 intentFilter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
Jordan Liu4a2ff262019-10-21 12:30:56 -0700189 if (IS_DEBUGGABLE) {
Jack Yudc607602019-10-31 13:24:43 -0700190 intentFilter.addAction(ACTION_DUPLICATE_DETECTION);
191 }
Jack Yua1309272019-10-24 00:19:49 -0700192 mContext.registerReceiver(
193 new BroadcastReceiver() {
194 @Override
195 public void onReceive(Context context, Intent intent) {
Jack Yudc607602019-10-31 13:24:43 -0700196 switch (intent.getAction()) {
197 case Intent.ACTION_AIRPLANE_MODE_CHANGED:
198 boolean airplaneModeOn = intent.getBooleanExtra("state", false);
199 if (airplaneModeOn) {
200 mLastAirplaneModeTime = System.currentTimeMillis();
201 log("Airplane mode on. Reset duplicate detection.");
202 }
203 break;
204 case ACTION_DUPLICATE_DETECTION:
205 mEnableDuplicateDetection = intent.getBooleanExtra(EXTRA_ENABLE,
206 true);
207 break;
Jack Yua1309272019-10-24 00:19:49 -0700208 }
Jack Yudc607602019-10-31 13:24:43 -0700209
Jack Yua1309272019-10-24 00:19:49 -0700210 }
Jack Yudc607602019-10-31 13:24:43 -0700211 }, intentFilter);
Jordan Liuc872fad2019-10-11 11:42:03 -0700212 }
213
214 /**
215 * Create a new CellBroadcastHandler.
216 * @param context the context to use for dispatching Intents
217 * @return the new handler
218 */
219 public static CellBroadcastHandler makeCellBroadcastHandler(Context context) {
220 CellBroadcastHandler handler = new CellBroadcastHandler(context);
221 handler.start();
222 return handler;
223 }
224
225 /**
226 * Handle Cell Broadcast messages from {@code CdmaInboundSmsHandler}.
227 * 3GPP-format Cell Broadcast messages sent from radio are handled in the subclass.
228 *
229 * @param message the message to process
230 * @return true if need to wait for geo-fencing or an ordered broadcast was sent.
231 */
232 @Override
233 protected boolean handleSmsMessage(Message message) {
234 if (message.obj instanceof SmsCbMessage) {
Jack Yua1309272019-10-24 00:19:49 -0700235 if (!isDuplicate((SmsCbMessage) message.obj)) {
236 handleBroadcastSms((SmsCbMessage) message.obj);
237 return true;
238 }
239 return false;
Jordan Liuc872fad2019-10-11 11:42:03 -0700240 } else {
241 loge("handleMessage got object of type: " + message.obj.getClass().getName());
242 return false;
243 }
244 }
245
246 /**
247 * Dispatch a Cell Broadcast message to listeners.
248 * @param message the Cell Broadcast to broadcast
249 */
250 protected void handleBroadcastSms(SmsCbMessage message) {
251 int slotIndex = message.getSlotIndex();
252 // Log Cellbroadcast msg received event
253 TelephonyMetrics metrics = TelephonyMetrics.getInstance();
254 metrics.writeNewCBSms(slotIndex, message.getMessageFormat(),
255 message.getMessagePriority(), message.isCmasMessage(), message.isEtwsMessage(),
256 message.getServiceCategory(), message.getSerialNumber(),
257 System.currentTimeMillis());
258
259 // TODO: Database inserting can be time consuming, therefore this should be changed to
260 // asynchronous.
261 ContentValues cv = message.getContentValues();
Chen Xu93fdfeb2019-10-21 22:56:37 -0700262 Uri uri = mContext.getContentResolver().insert(CellBroadcasts.CONTENT_URI, cv);
Jordan Liuc872fad2019-10-11 11:42:03 -0700263
264 if (message.needGeoFencingCheck()) {
265 if (DBG) {
266 log("Request location update for geo-fencing. serialNumber = "
267 + message.getSerialNumber());
268 }
269
270 requestLocationUpdate(location -> {
271 if (location == null) {
272 // Broadcast the message directly if the location is not available.
273 broadcastMessage(message, uri, slotIndex);
274 } else {
275 performGeoFencing(message, uri, message.getGeometries(), location, slotIndex);
276 }
Jordan Liu4a2ff262019-10-21 12:30:56 -0700277 }, message.getMaximumWaitingDuration());
Jordan Liuc872fad2019-10-11 11:42:03 -0700278 } else {
279 if (DBG) {
280 log("Broadcast the message directly because no geo-fencing required, "
281 + "serialNumber = " + message.getSerialNumber()
282 + " needGeoFencing = " + message.needGeoFencingCheck());
283 }
284 broadcastMessage(message, uri, slotIndex);
285 }
286 }
287
288 /**
Jack Yua1309272019-10-24 00:19:49 -0700289 * Check if the message is a duplicate
290 *
291 * @param message Cell broadcast message
292 * @return {@code true} if this message is a duplicate
293 */
294 @VisibleForTesting
295 public boolean isDuplicate(SmsCbMessage message) {
Jack Yudc607602019-10-31 13:24:43 -0700296 if (!mEnableDuplicateDetection) {
297 log("Duplicate detection was disabled for debugging purposes.");
298 return false;
299 }
300
Jack Yua1309272019-10-24 00:19:49 -0700301 // Find the cell broadcast message identify by the message identifier and serial number
302 // and is not broadcasted.
303 String where = CellBroadcasts.RECEIVED_TIME + ">?";
304
305 int slotIndex = message.getSlotIndex();
306 SubscriptionManager subMgr = (SubscriptionManager) mContext.getSystemService(
307 Context.TELEPHONY_SUBSCRIPTION_SERVICE);
308 int[] subIds = subMgr.getSubscriptionIds(slotIndex);
309 Resources res;
310 if (subIds != null) {
311 res = getResources(subIds[0]);
312 } else {
313 res = getResources(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
314 }
315
316 // Only consider cell broadcast messages received within certain period.
317 // By default it's 24 hours.
318 long expirationDuration = res.getInteger(R.integer.message_expiration_time);
319 long dupCheckTime = System.currentTimeMillis() - expirationDuration;
320
321 // Some carriers require reset duplication detection after airplane mode.
322 if (res.getBoolean(R.bool.reset_duplicate_detection_on_airplane_mode)) {
323 dupCheckTime = Long.max(dupCheckTime, mLastAirplaneModeTime);
324 }
325
326 List<SmsCbMessage> cbMessages = new ArrayList<>();
327
328 try (Cursor cursor = mContext.getContentResolver().query(CellBroadcasts.CONTENT_URI,
329 // TODO: QUERY_COLUMNS_FWK is a hidden API, since we are going to move
330 // CellBroadcastProvider to this module we can define those COLUMNS in side
331 // CellBroadcastProvider and reference from there.
332 CellBroadcasts.QUERY_COLUMNS_FWK,
333 where,
334 new String[] {Long.toString(dupCheckTime)},
335 null)) {
336 if (cursor != null) {
337 while (cursor.moveToNext()) {
338 cbMessages.add(SmsCbMessage.createFromCursor(cursor));
339 }
340 }
341 }
342
343 boolean compareMessageBody = res.getBoolean(R.bool.duplicate_compare_body);
344
345 log("Found " + cbMessages.size() + " messages since "
346 + DateFormat.getDateTimeInstance().format(dupCheckTime));
347 for (SmsCbMessage messageToCheck : cbMessages) {
348 // If messages are from different slots, then we only compare the message body.
349 if (message.getSlotIndex() != messageToCheck.getSlotIndex()) {
350 if (TextUtils.equals(message.getMessageBody(), messageToCheck.getMessageBody())) {
351 log("Duplicate message detected from different slot. " + message);
352 return true;
353 }
354 } else {
355 // Check serial number if message is from the same carrier.
356 if (message.getSerialNumber() != messageToCheck.getSerialNumber()) {
357 // Not a dup. Check next one.
358 log("Serial number check. Not a dup. " + messageToCheck);
359 continue;
360 }
361
Jack Yu2003c522019-10-31 09:47:20 -0700362 // ETWS primary / secondary should be treated differently.
363 if (message.isEtwsMessage() && messageToCheck.isEtwsMessage()
364 && message.getEtwsWarningInfo().isPrimary()
365 != messageToCheck.getEtwsWarningInfo().isPrimary()) {
Jack Yua1309272019-10-24 00:19:49 -0700366 // Not a dup. Check next one.
Jack Yu6f9a26e2019-11-07 23:10:02 -0800367 log("ETWS primary check. Not a dup. " + messageToCheck);
Jack Yua1309272019-10-24 00:19:49 -0700368 continue;
369 }
370
Jack Yu2003c522019-10-31 09:47:20 -0700371 // Check if the message category is different. Some carriers send cell broadcast
372 // messages on different techs (i.e. GSM / CDMA), so we need to compare service
373 // category cross techs.
374 if (message.getServiceCategory() != messageToCheck.getServiceCategory()
Jack Yu6f9a26e2019-11-07 23:10:02 -0800375 && !Objects.equals(mServiceCategoryCrossRATMap.get(
376 message.getServiceCategory()), messageToCheck.getServiceCategory())
377 && !Objects.equals(mServiceCategoryCrossRATMap.get(
378 messageToCheck.getServiceCategory()),
379 message.getServiceCategory())) {
Jack Yua1309272019-10-24 00:19:49 -0700380 // Not a dup. Check next one.
Jack Yu6f9a26e2019-11-07 23:10:02 -0800381 log("Service category check. Not a dup. " + messageToCheck);
Jack Yua1309272019-10-24 00:19:49 -0700382 continue;
383 }
384
385 // Compare message body if needed.
386 if (!compareMessageBody || TextUtils.equals(
387 message.getMessageBody(), messageToCheck.getMessageBody())) {
388 log("Duplicate message detected. " + message);
389 return true;
390 }
391 }
392 }
393
394 log("Not a duplicate message. " + message);
395 return false;
396 }
397
398 /**
Jordan Liuc872fad2019-10-11 11:42:03 -0700399 * Perform a geo-fencing check for {@code message}. Broadcast the {@code message} if the
400 * {@code location} is inside the {@code broadcastArea}.
401 * @param message the message need to geo-fencing check
402 * @param uri the message's uri
403 * @param broadcastArea the broadcast area of the message
404 * @param location current location
405 */
406 protected void performGeoFencing(SmsCbMessage message, Uri uri, List<Geometry> broadcastArea,
407 LatLng location, int slotIndex) {
408
409 if (DBG) {
410 logd("Perform geo-fencing check for message identifier = "
411 + message.getServiceCategory()
412 + " serialNumber = " + message.getSerialNumber());
413 }
414
415 for (Geometry geo : broadcastArea) {
416 if (geo.contains(location)) {
417 broadcastMessage(message, uri, slotIndex);
418 return;
419 }
420 }
421
422 if (DBG) {
423 logd("Device location is outside the broadcast area "
424 + CbGeoUtils.encodeGeometriesToString(broadcastArea));
425 }
Jack Yu2f37c432019-11-04 21:28:24 -0800426
427 sendMessage(EVENT_BROADCAST_NOT_REQUIRED);
Jordan Liuc872fad2019-10-11 11:42:03 -0700428 }
429
430 /**
431 * Request a single location update.
432 * @param callback a callback will be called when the location is available.
433 * @param maximumWaitTimeSec the maximum wait time of this request. If location is not updated
434 * within the maximum wait time, {@code callback#onLocationUpadte(null)} will be called.
435 */
436 protected void requestLocationUpdate(LocationUpdateCallback callback, int maximumWaitTimeSec) {
437 mLocationRequester.requestLocationUpdate(callback, maximumWaitTimeSec);
438 }
439
440 /**
Jordan Liu4a2ff262019-10-21 12:30:56 -0700441 * Get the subscription ID for a phone ID, or INVALID_SUBSCRIPTION_ID if the phone does not
442 * have an active sub
443 * @param phoneId the phoneId to use
444 * @return the associated sub id
445 */
446 protected int getSubIdForPhone(int phoneId) {
447 SubscriptionManager subMan =
448 (SubscriptionManager) mContext.getSystemService(
449 Context.TELEPHONY_SUBSCRIPTION_SERVICE);
450 int[] subIds = subMan.getSubscriptionIds(phoneId);
451 if (subIds != null) {
452 return subIds[0];
453 } else {
454 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
455 }
456 }
457
458 /**
Jordan Liuc872fad2019-10-11 11:42:03 -0700459 * Broadcast the {@code message} to the applications.
460 * @param message a message need to broadcast
461 * @param messageUri message's uri
462 */
463 protected void broadcastMessage(@NonNull SmsCbMessage message, @Nullable Uri messageUri,
464 int slotIndex) {
465 String receiverPermission;
466 int appOp;
467 String msg;
468 Intent intent;
469 if (message.isEmergencyMessage()) {
470 msg = "Dispatching emergency SMS CB, SmsCbMessage is: " + message;
471 log(msg);
472 mLocalLog.log(msg);
Chen Xueca1f0a2019-11-06 20:53:24 -0800473 intent = new Intent(Telephony.Sms.Intents.ACTION_SMS_EMERGENCY_CB_RECEIVED);
Jordan Liuc872fad2019-10-11 11:42:03 -0700474 //Emergency alerts need to be delivered with high priority
475 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
476 receiverPermission = Manifest.permission.RECEIVE_EMERGENCY_BROADCAST;
477 appOp = AppOpsManager.OP_RECEIVE_EMERGECY_SMS;
478
479 intent.putExtra(EXTRA_MESSAGE, message);
Jordan Liu4a2ff262019-10-21 12:30:56 -0700480 int subId = getSubIdForPhone(slotIndex);
481 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
482 intent.putExtra("subscription", subId);
483 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
484 }
485 intent.putExtra("phone", slotIndex);
486 intent.putExtra(SubscriptionManager.EXTRA_SLOT_INDEX, slotIndex);
Jordan Liuc872fad2019-10-11 11:42:03 -0700487
Jordan Liu4a2ff262019-10-21 12:30:56 -0700488 if (IS_DEBUGGABLE) {
Jordan Liuc872fad2019-10-11 11:42:03 -0700489 // Send additional broadcast intent to the specified package. This is only for sl4a
490 // automation tests.
491 final String additionalPackage = Settings.Secure.getString(
492 mContext.getContentResolver(), CMAS_ADDITIONAL_BROADCAST_PKG);
493 if (additionalPackage != null) {
494 Intent additionalIntent = new Intent(intent);
495 additionalIntent.setPackage(additionalPackage);
496 mContext.sendOrderedBroadcastAsUser(additionalIntent, UserHandle.ALL,
497 receiverPermission, appOp, null, getHandler(), Activity.RESULT_OK,
498 null, null);
499 }
500 }
501
502 String[] pkgs = mContext.getResources().getStringArray(
503 com.android.internal.R.array.config_defaultCellBroadcastReceiverPkgs);
504 mReceiverCount.addAndGet(pkgs.length);
505 for (String pkg : pkgs) {
506 // Explicitly send the intent to all the configured cell broadcast receivers.
507 intent.setPackage(pkg);
508 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, receiverPermission,
Jordan Liu4a2ff262019-10-21 12:30:56 -0700509 appOp, null, mReceiver, getHandler(), Activity.RESULT_OK, null, null);
Jordan Liuc872fad2019-10-11 11:42:03 -0700510 }
511 } else {
512 msg = "Dispatching SMS CB, SmsCbMessage is: " + message;
513 log(msg);
514 mLocalLog.log(msg);
515 intent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION);
516 // Send implicit intent since there are various 3rd party carrier apps listen to
517 // this intent.
518 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
519 receiverPermission = Manifest.permission.RECEIVE_SMS;
520 appOp = AppOpsManager.OP_RECEIVE_SMS;
521
522 intent.putExtra(EXTRA_MESSAGE, message);
523 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, slotIndex);
524
525 mReceiverCount.incrementAndGet();
Jordan Liu4a2ff262019-10-21 12:30:56 -0700526 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, receiverPermission,
527 appOp, null, mReceiver, getHandler(), Activity.RESULT_OK, null, null);
Jordan Liuc872fad2019-10-11 11:42:03 -0700528 }
529
530 if (messageUri != null) {
531 ContentValues cv = new ContentValues();
532 cv.put(CellBroadcasts.MESSAGE_BROADCASTED, 1);
Chen Xu93fdfeb2019-10-21 22:56:37 -0700533 mContext.getContentResolver().update(CellBroadcasts.CONTENT_URI, cv,
Jordan Liuc872fad2019-10-11 11:42:03 -0700534 CellBroadcasts._ID + "=?", new String[] {messageUri.getLastPathSegment()});
535 }
536 }
537
Jack Yua1309272019-10-24 00:19:49 -0700538 /**
539 * Get the device resource based on SIM
540 *
541 * @param subId Subscription index
542 *
543 * @return The resource
544 */
545 public @NonNull Resources getResources(int subId) {
546 if (subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID
547 || !SubscriptionManager.isValidSubscriptionId(subId)) {
548 return mContext.getResources();
549 }
550
551 if (mResourcesCache.containsKey(subId)) {
552 return mResourcesCache.get(subId);
553 }
554
555 Resources res = SubscriptionManager.getResourcesForSubId(mContext, subId);
556 mResourcesCache.put(subId, res);
557
558 return res;
559 }
560
Jordan Liuc872fad2019-10-11 11:42:03 -0700561 @Override
562 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
563 pw.println("CellBroadcastHandler:");
564 mLocalLog.dump(fd, pw, args);
565 pw.flush();
566 }
567
568 /** The callback interface of a location request. */
569 public interface LocationUpdateCallback {
570 /**
571 * Call when the location update is available.
572 * @param location a location in (latitude, longitude) format, or {@code null} if the
573 * location service is not available.
574 */
575 void onLocationUpdate(@Nullable LatLng location);
576 }
577
578 private static final class LocationRequester {
579 private static final String TAG = LocationRequester.class.getSimpleName();
580
581 /**
582 * Use as the default maximum wait time if the cell broadcast doesn't specify the value.
583 * Most of the location request should be responded within 20 seconds.
584 */
585 private static final int DEFAULT_MAXIMUM_WAIT_TIME_SEC = 20;
586
587 /**
588 * Trigger this event when the {@link LocationManager} is not responded within the given
589 * time.
590 */
591 private static final int EVENT_LOCATION_REQUEST_TIMEOUT = 1;
592
593 /** Request a single location update. */
594 private static final int EVENT_REQUEST_LOCATION_UPDATE = 2;
595
596 /**
597 * Request location update from network or gps location provider. Network provider will be
598 * used if available, otherwise use the gps provider.
599 */
600 private static final List<String> LOCATION_PROVIDERS = Arrays.asList(
601 LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER);
602
603 private final LocationManager mLocationManager;
604 private final Looper mLooper;
605 private final List<LocationUpdateCallback> mCallbacks;
606 private final Context mContext;
607 private Handler mLocationHandler;
608
609 LocationRequester(Context context, LocationManager locationManager, Looper looper) {
610 mLocationManager = locationManager;
611 mLooper = looper;
612 mCallbacks = new ArrayList<>();
613 mContext = context;
614 mLocationHandler = new LocationHandler(looper);
615 }
616
617 /**
618 * Request a single location update. If the location is not available, a callback with
619 * {@code null} location will be called immediately.
620 *
621 * @param callback a callback to the response when the location is available
622 * @param maximumWaitTimeSec the maximum wait time of this request. If location is not
623 * updated within the maximum wait time, {@code callback#onLocationUpadte(null)} will be
624 * called.
625 */
626 void requestLocationUpdate(@NonNull LocationUpdateCallback callback,
627 int maximumWaitTimeSec) {
628 mLocationHandler.obtainMessage(EVENT_REQUEST_LOCATION_UPDATE, maximumWaitTimeSec,
629 0 /* arg2 */, callback).sendToTarget();
630 }
631
632 private void onLocationUpdate(@Nullable LatLng location) {
633 for (LocationUpdateCallback callback : mCallbacks) {
634 callback.onLocationUpdate(location);
635 }
636 mCallbacks.clear();
637 }
638
639 private void requestLocationUpdateInternal(@NonNull LocationUpdateCallback callback,
640 int maximumWaitTimeSec) {
641 if (DBG) Log.d(TAG, "requestLocationUpdate");
642 if (!isLocationServiceAvailable()) {
643 if (DBG) {
644 Log.d(TAG, "Can't request location update because of no location permission");
645 }
646 callback.onLocationUpdate(null);
647 return;
648 }
649
650 if (!mLocationHandler.hasMessages(EVENT_LOCATION_REQUEST_TIMEOUT)) {
651 if (maximumWaitTimeSec == SmsCbMessage.MAXIMUM_WAIT_TIME_NOT_SET) {
652 maximumWaitTimeSec = DEFAULT_MAXIMUM_WAIT_TIME_SEC;
653 }
654 mLocationHandler.sendMessageDelayed(
655 mLocationHandler.obtainMessage(EVENT_LOCATION_REQUEST_TIMEOUT),
656 maximumWaitTimeSec * DateUtils.SECOND_IN_MILLIS);
657 }
658
659 mCallbacks.add(callback);
660
661 for (String provider : LOCATION_PROVIDERS) {
662 if (mLocationManager.isProviderEnabled(provider)) {
663 mLocationManager.requestSingleUpdate(provider, mLocationListener, mLooper);
664 break;
665 }
666 }
667 }
668
669 private boolean isLocationServiceAvailable() {
670 if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)
671 && !hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) return false;
672 for (String provider : LOCATION_PROVIDERS) {
673 if (mLocationManager.isProviderEnabled(provider)) return true;
674 }
675 return false;
676 }
677
678 private boolean hasPermission(String permission) {
Philip P. Moltmann376f9fa2019-10-30 15:25:24 -0700679 return mContext.checkPermission(permission, Process.myPid(), Process.myUid())
680 == PackageManager.PERMISSION_GRANTED;
Jordan Liuc872fad2019-10-11 11:42:03 -0700681 }
682
683 private final LocationListener mLocationListener = new LocationListener() {
684 @Override
685 public void onLocationChanged(Location location) {
686 mLocationHandler.removeMessages(EVENT_LOCATION_REQUEST_TIMEOUT);
687 onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
688 }
689
690 @Override
691 public void onStatusChanged(String provider, int status, Bundle extras) {}
692
693 @Override
694 public void onProviderEnabled(String provider) {}
695
696 @Override
697 public void onProviderDisabled(String provider) {}
698 };
699
700 private final class LocationHandler extends Handler {
701 LocationHandler(Looper looper) {
702 super(looper);
703 }
704
705 @Override
706 public void handleMessage(Message msg) {
707 switch (msg.what) {
708 case EVENT_LOCATION_REQUEST_TIMEOUT:
709 if (DBG) Log.d(TAG, "location request timeout");
710 onLocationUpdate(null);
711 break;
712 case EVENT_REQUEST_LOCATION_UPDATE:
713 requestLocationUpdateInternal((LocationUpdateCallback) msg.obj, msg.arg1);
714 break;
715 default:
716 Log.e(TAG, "Unsupported message type " + msg.what);
717 }
718 }
719 }
720 }
721}