blob: efbc4ea79869f0d6f9c51f45f03c32c1000b697b [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;
38import android.os.Build;
39import android.os.Bundle;
40import android.os.Handler;
41import android.os.Looper;
42import android.os.Message;
Philip P. Moltmann376f9fa2019-10-30 15:25:24 -070043import android.os.Process;
Jordan Liu26e820c2019-10-22 14:42:07 -070044import android.os.SystemProperties;
Jordan Liuc872fad2019-10-11 11:42:03 -070045import android.os.UserHandle;
46import android.provider.Settings;
47import android.provider.Telephony;
48import android.provider.Telephony.CellBroadcasts;
49import android.telephony.SmsCbMessage;
50import android.telephony.SubscriptionManager;
Jack Yu2003c522019-10-31 09:47:20 -070051import android.telephony.cdma.CdmaSmsCbProgramData;
Jack Yua1309272019-10-24 00:19:49 -070052import android.text.TextUtils;
Jordan Liuc872fad2019-10-11 11:42:03 -070053import android.text.format.DateUtils;
54import android.util.LocalLog;
55import android.util.Log;
56
Jack Yua1309272019-10-24 00:19:49 -070057import com.android.internal.annotations.VisibleForTesting;
Jordan Liuc872fad2019-10-11 11:42:03 -070058import com.android.internal.telephony.CbGeoUtils.Geometry;
59import com.android.internal.telephony.CbGeoUtils.LatLng;
60import com.android.internal.telephony.metrics.TelephonyMetrics;
61
62import java.io.FileDescriptor;
63import java.io.PrintWriter;
Jack Yua1309272019-10-24 00:19:49 -070064import java.text.DateFormat;
Jordan Liuc872fad2019-10-11 11:42:03 -070065import java.util.ArrayList;
66import java.util.Arrays;
Jack Yua1309272019-10-24 00:19:49 -070067import java.util.HashMap;
Jordan Liuc872fad2019-10-11 11:42:03 -070068import java.util.List;
Jack Yua1309272019-10-24 00:19:49 -070069import java.util.Map;
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);
189 if (Build.IS_DEBUGGABLE) {
190 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 }
277 }, message.getMaximumWaitingTime());
278 } 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.
367 log("Service category check. Not a dup. " + messageToCheck);
368 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()
375 && mServiceCategoryCrossRATMap.get(message.getServiceCategory())
376 != messageToCheck.getServiceCategory()
377 && mServiceCategoryCrossRATMap.get(messageToCheck.getServiceCategory())
378 != message.getServiceCategory()) {
Jack Yua1309272019-10-24 00:19:49 -0700379 // Not a dup. Check next one.
380 log("ETWS primary check. Not a dup. " + messageToCheck);
381 continue;
382 }
383
384 // Compare message body if needed.
385 if (!compareMessageBody || TextUtils.equals(
386 message.getMessageBody(), messageToCheck.getMessageBody())) {
387 log("Duplicate message detected. " + message);
388 return true;
389 }
390 }
391 }
392
393 log("Not a duplicate message. " + message);
394 return false;
395 }
396
397 /**
Jordan Liuc872fad2019-10-11 11:42:03 -0700398 * Perform a geo-fencing check for {@code message}. Broadcast the {@code message} if the
399 * {@code location} is inside the {@code broadcastArea}.
400 * @param message the message need to geo-fencing check
401 * @param uri the message's uri
402 * @param broadcastArea the broadcast area of the message
403 * @param location current location
404 */
405 protected void performGeoFencing(SmsCbMessage message, Uri uri, List<Geometry> broadcastArea,
406 LatLng location, int slotIndex) {
407
408 if (DBG) {
409 logd("Perform geo-fencing check for message identifier = "
410 + message.getServiceCategory()
411 + " serialNumber = " + message.getSerialNumber());
412 }
413
414 for (Geometry geo : broadcastArea) {
415 if (geo.contains(location)) {
416 broadcastMessage(message, uri, slotIndex);
417 return;
418 }
419 }
420
421 if (DBG) {
422 logd("Device location is outside the broadcast area "
423 + CbGeoUtils.encodeGeometriesToString(broadcastArea));
424 }
425 }
426
427 /**
428 * Request a single location update.
429 * @param callback a callback will be called when the location is available.
430 * @param maximumWaitTimeSec the maximum wait time of this request. If location is not updated
431 * within the maximum wait time, {@code callback#onLocationUpadte(null)} will be called.
432 */
433 protected void requestLocationUpdate(LocationUpdateCallback callback, int maximumWaitTimeSec) {
434 mLocationRequester.requestLocationUpdate(callback, maximumWaitTimeSec);
435 }
436
437 /**
Jordan Liuc872fad2019-10-11 11:42:03 -0700438 * Broadcast the {@code message} to the applications.
439 * @param message a message need to broadcast
440 * @param messageUri message's uri
441 */
442 protected void broadcastMessage(@NonNull SmsCbMessage message, @Nullable Uri messageUri,
443 int slotIndex) {
444 String receiverPermission;
445 int appOp;
446 String msg;
447 Intent intent;
448 if (message.isEmergencyMessage()) {
449 msg = "Dispatching emergency SMS CB, SmsCbMessage is: " + message;
450 log(msg);
451 mLocalLog.log(msg);
452 intent = new Intent(Telephony.Sms.Intents.SMS_EMERGENCY_CB_RECEIVED_ACTION);
453 //Emergency alerts need to be delivered with high priority
454 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
455 receiverPermission = Manifest.permission.RECEIVE_EMERGENCY_BROADCAST;
456 appOp = AppOpsManager.OP_RECEIVE_EMERGECY_SMS;
457
458 intent.putExtra(EXTRA_MESSAGE, message);
459 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, slotIndex);
460
461 if (Build.IS_DEBUGGABLE) {
462 // Send additional broadcast intent to the specified package. This is only for sl4a
463 // automation tests.
464 final String additionalPackage = Settings.Secure.getString(
465 mContext.getContentResolver(), CMAS_ADDITIONAL_BROADCAST_PKG);
466 if (additionalPackage != null) {
467 Intent additionalIntent = new Intent(intent);
468 additionalIntent.setPackage(additionalPackage);
469 mContext.sendOrderedBroadcastAsUser(additionalIntent, UserHandle.ALL,
470 receiverPermission, appOp, null, getHandler(), Activity.RESULT_OK,
471 null, null);
472 }
473 }
474
475 String[] pkgs = mContext.getResources().getStringArray(
476 com.android.internal.R.array.config_defaultCellBroadcastReceiverPkgs);
477 mReceiverCount.addAndGet(pkgs.length);
478 for (String pkg : pkgs) {
479 // Explicitly send the intent to all the configured cell broadcast receivers.
480 intent.setPackage(pkg);
481 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, receiverPermission,
482 appOp, mReceiver, getHandler(), Activity.RESULT_OK, null, null);
483 }
484 } else {
485 msg = "Dispatching SMS CB, SmsCbMessage is: " + message;
486 log(msg);
487 mLocalLog.log(msg);
488 intent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION);
489 // Send implicit intent since there are various 3rd party carrier apps listen to
490 // this intent.
491 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
492 receiverPermission = Manifest.permission.RECEIVE_SMS;
493 appOp = AppOpsManager.OP_RECEIVE_SMS;
494
495 intent.putExtra(EXTRA_MESSAGE, message);
496 SubscriptionManager.putPhoneIdAndSubIdExtra(intent, slotIndex);
497
498 mReceiverCount.incrementAndGet();
499 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, receiverPermission, appOp,
500 mReceiver, getHandler(), Activity.RESULT_OK, null, null);
501 }
502
503 if (messageUri != null) {
504 ContentValues cv = new ContentValues();
505 cv.put(CellBroadcasts.MESSAGE_BROADCASTED, 1);
Chen Xu93fdfeb2019-10-21 22:56:37 -0700506 mContext.getContentResolver().update(CellBroadcasts.CONTENT_URI, cv,
Jordan Liuc872fad2019-10-11 11:42:03 -0700507 CellBroadcasts._ID + "=?", new String[] {messageUri.getLastPathSegment()});
508 }
509 }
510
Jack Yua1309272019-10-24 00:19:49 -0700511 /**
512 * Get the device resource based on SIM
513 *
514 * @param subId Subscription index
515 *
516 * @return The resource
517 */
518 public @NonNull Resources getResources(int subId) {
519 if (subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID
520 || !SubscriptionManager.isValidSubscriptionId(subId)) {
521 return mContext.getResources();
522 }
523
524 if (mResourcesCache.containsKey(subId)) {
525 return mResourcesCache.get(subId);
526 }
527
528 Resources res = SubscriptionManager.getResourcesForSubId(mContext, subId);
529 mResourcesCache.put(subId, res);
530
531 return res;
532 }
533
Jordan Liuc872fad2019-10-11 11:42:03 -0700534 @Override
535 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
536 pw.println("CellBroadcastHandler:");
537 mLocalLog.dump(fd, pw, args);
538 pw.flush();
539 }
540
541 /** The callback interface of a location request. */
542 public interface LocationUpdateCallback {
543 /**
544 * Call when the location update is available.
545 * @param location a location in (latitude, longitude) format, or {@code null} if the
546 * location service is not available.
547 */
548 void onLocationUpdate(@Nullable LatLng location);
549 }
550
551 private static final class LocationRequester {
552 private static final String TAG = LocationRequester.class.getSimpleName();
553
554 /**
555 * Use as the default maximum wait time if the cell broadcast doesn't specify the value.
556 * Most of the location request should be responded within 20 seconds.
557 */
558 private static final int DEFAULT_MAXIMUM_WAIT_TIME_SEC = 20;
559
560 /**
561 * Trigger this event when the {@link LocationManager} is not responded within the given
562 * time.
563 */
564 private static final int EVENT_LOCATION_REQUEST_TIMEOUT = 1;
565
566 /** Request a single location update. */
567 private static final int EVENT_REQUEST_LOCATION_UPDATE = 2;
568
569 /**
570 * Request location update from network or gps location provider. Network provider will be
571 * used if available, otherwise use the gps provider.
572 */
573 private static final List<String> LOCATION_PROVIDERS = Arrays.asList(
574 LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER);
575
576 private final LocationManager mLocationManager;
577 private final Looper mLooper;
578 private final List<LocationUpdateCallback> mCallbacks;
579 private final Context mContext;
580 private Handler mLocationHandler;
581
582 LocationRequester(Context context, LocationManager locationManager, Looper looper) {
583 mLocationManager = locationManager;
584 mLooper = looper;
585 mCallbacks = new ArrayList<>();
586 mContext = context;
587 mLocationHandler = new LocationHandler(looper);
588 }
589
590 /**
591 * Request a single location update. If the location is not available, a callback with
592 * {@code null} location will be called immediately.
593 *
594 * @param callback a callback to the response when the location is available
595 * @param maximumWaitTimeSec the maximum wait time of this request. If location is not
596 * updated within the maximum wait time, {@code callback#onLocationUpadte(null)} will be
597 * called.
598 */
599 void requestLocationUpdate(@NonNull LocationUpdateCallback callback,
600 int maximumWaitTimeSec) {
601 mLocationHandler.obtainMessage(EVENT_REQUEST_LOCATION_UPDATE, maximumWaitTimeSec,
602 0 /* arg2 */, callback).sendToTarget();
603 }
604
605 private void onLocationUpdate(@Nullable LatLng location) {
606 for (LocationUpdateCallback callback : mCallbacks) {
607 callback.onLocationUpdate(location);
608 }
609 mCallbacks.clear();
610 }
611
612 private void requestLocationUpdateInternal(@NonNull LocationUpdateCallback callback,
613 int maximumWaitTimeSec) {
614 if (DBG) Log.d(TAG, "requestLocationUpdate");
615 if (!isLocationServiceAvailable()) {
616 if (DBG) {
617 Log.d(TAG, "Can't request location update because of no location permission");
618 }
619 callback.onLocationUpdate(null);
620 return;
621 }
622
623 if (!mLocationHandler.hasMessages(EVENT_LOCATION_REQUEST_TIMEOUT)) {
624 if (maximumWaitTimeSec == SmsCbMessage.MAXIMUM_WAIT_TIME_NOT_SET) {
625 maximumWaitTimeSec = DEFAULT_MAXIMUM_WAIT_TIME_SEC;
626 }
627 mLocationHandler.sendMessageDelayed(
628 mLocationHandler.obtainMessage(EVENT_LOCATION_REQUEST_TIMEOUT),
629 maximumWaitTimeSec * DateUtils.SECOND_IN_MILLIS);
630 }
631
632 mCallbacks.add(callback);
633
634 for (String provider : LOCATION_PROVIDERS) {
635 if (mLocationManager.isProviderEnabled(provider)) {
636 mLocationManager.requestSingleUpdate(provider, mLocationListener, mLooper);
637 break;
638 }
639 }
640 }
641
642 private boolean isLocationServiceAvailable() {
643 if (!hasPermission(Manifest.permission.ACCESS_FINE_LOCATION)
644 && !hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) return false;
645 for (String provider : LOCATION_PROVIDERS) {
646 if (mLocationManager.isProviderEnabled(provider)) return true;
647 }
648 return false;
649 }
650
651 private boolean hasPermission(String permission) {
Philip P. Moltmann376f9fa2019-10-30 15:25:24 -0700652 return mContext.checkPermission(permission, Process.myPid(), Process.myUid())
653 == PackageManager.PERMISSION_GRANTED;
Jordan Liuc872fad2019-10-11 11:42:03 -0700654 }
655
656 private final LocationListener mLocationListener = new LocationListener() {
657 @Override
658 public void onLocationChanged(Location location) {
659 mLocationHandler.removeMessages(EVENT_LOCATION_REQUEST_TIMEOUT);
660 onLocationUpdate(new LatLng(location.getLatitude(), location.getLongitude()));
661 }
662
663 @Override
664 public void onStatusChanged(String provider, int status, Bundle extras) {}
665
666 @Override
667 public void onProviderEnabled(String provider) {}
668
669 @Override
670 public void onProviderDisabled(String provider) {}
671 };
672
673 private final class LocationHandler extends Handler {
674 LocationHandler(Looper looper) {
675 super(looper);
676 }
677
678 @Override
679 public void handleMessage(Message msg) {
680 switch (msg.what) {
681 case EVENT_LOCATION_REQUEST_TIMEOUT:
682 if (DBG) Log.d(TAG, "location request timeout");
683 onLocationUpdate(null);
684 break;
685 case EVENT_REQUEST_LOCATION_UPDATE:
686 requestLocationUpdateInternal((LocationUpdateCallback) msg.obj, msg.arg1);
687 break;
688 default:
689 Log.e(TAG, "Unsupported message type " + msg.what);
690 }
691 }
692 }
693 }
694}