• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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.internal.telephony;
18 
19 import static android.telephony.TelephonyManager.HAL_SERVICE_RADIO;
20 import static android.telephony.ims.ImsService.CAPABILITY_SUPPORTS_SIMULTANEOUS_CALLING;
21 
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.app.BroadcastOptions;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.SharedPreferences;
29 import android.content.pm.PackageManager;
30 import android.content.res.Configuration;
31 import android.hardware.radio.modem.ImeiInfo;
32 import android.net.Uri;
33 import android.os.AsyncResult;
34 import android.os.Build;
35 import android.os.Handler;
36 import android.os.Looper;
37 import android.os.Message;
38 import android.os.PersistableBundle;
39 import android.os.Registrant;
40 import android.os.RegistrantList;
41 import android.os.SystemClock;
42 import android.os.SystemProperties;
43 import android.os.UserHandle;
44 import android.os.UserManager;
45 import android.os.WorkSource;
46 import android.preference.PreferenceManager;
47 import android.sysprop.TelephonyProperties;
48 import android.telecom.VideoProfile;
49 import android.telephony.AccessNetworkConstants;
50 import android.telephony.Annotation.SrvccState;
51 import android.telephony.CarrierConfigManager;
52 import android.telephony.CarrierRestrictionRules;
53 import android.telephony.CellBroadcastIdRange;
54 import android.telephony.CellIdentity;
55 import android.telephony.CellInfo;
56 import android.telephony.ClientRequestStats;
57 import android.telephony.DomainSelectionService;
58 import android.telephony.ImsiEncryptionInfo;
59 import android.telephony.LinkCapacityEstimate;
60 import android.telephony.NetworkRegistrationInfo;
61 import android.telephony.PhoneStateListener;
62 import android.telephony.PhysicalChannelConfig;
63 import android.telephony.PreciseDataConnectionState;
64 import android.telephony.RadioAccessFamily;
65 import android.telephony.RadioAccessSpecifier;
66 import android.telephony.ServiceState;
67 import android.telephony.SignalStrength;
68 import android.telephony.SubscriptionInfo;
69 import android.telephony.SubscriptionManager;
70 import android.telephony.TelephonyDisplayInfo;
71 import android.telephony.TelephonyManager;
72 import android.telephony.TelephonyManager.HalService;
73 import android.telephony.emergency.EmergencyNumber;
74 import android.telephony.ims.RegistrationManager;
75 import android.telephony.ims.feature.MmTelFeature;
76 import android.telephony.ims.stub.ImsRegistrationImplBase;
77 import android.telephony.satellite.NtnSignalStrength;
78 import android.text.TextUtils;
79 import android.util.LocalLog;
80 import android.util.Log;
81 import android.util.Xml;
82 
83 import com.android.ims.ImsCall;
84 import com.android.ims.ImsConfig;
85 import com.android.ims.ImsException;
86 import com.android.ims.ImsManager;
87 import com.android.internal.R;
88 import com.android.internal.annotations.VisibleForTesting;
89 import com.android.internal.telephony.analytics.TelephonyAnalytics;
90 import com.android.internal.telephony.data.AccessNetworksManager;
91 import com.android.internal.telephony.data.DataNetworkController;
92 import com.android.internal.telephony.data.DataSettingsManager;
93 import com.android.internal.telephony.data.LinkBandwidthEstimator;
94 import com.android.internal.telephony.domainselection.DomainSelectionResolver;
95 import com.android.internal.telephony.emergency.EmergencyConstants;
96 import com.android.internal.telephony.emergency.EmergencyNumberTracker;
97 import com.android.internal.telephony.emergency.EmergencyStateTracker;
98 import com.android.internal.telephony.flags.FeatureFlags;
99 import com.android.internal.telephony.imsphone.ImsCallInfo;
100 import com.android.internal.telephony.imsphone.ImsPhone;
101 import com.android.internal.telephony.imsphone.ImsPhoneCall;
102 import com.android.internal.telephony.metrics.SmsStats;
103 import com.android.internal.telephony.metrics.VoiceCallSessionStats;
104 import com.android.internal.telephony.satellite.metrics.ControllerMetricsStats;
105 import com.android.internal.telephony.subscription.SubscriptionInfoInternal;
106 import com.android.internal.telephony.subscription.SubscriptionManagerService;
107 import com.android.internal.telephony.test.SimulatedRadioControl;
108 import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppType;
109 import com.android.internal.telephony.uicc.IccFileHandler;
110 import com.android.internal.telephony.uicc.IccRecords;
111 import com.android.internal.telephony.uicc.IsimRecords;
112 import com.android.internal.telephony.uicc.UiccCard;
113 import com.android.internal.telephony.uicc.UiccCardApplication;
114 import com.android.internal.telephony.uicc.UiccController;
115 import com.android.internal.telephony.uicc.UiccPort;
116 import com.android.internal.telephony.uicc.UsimServiceTable;
117 import com.android.internal.telephony.util.TelephonyUtils;
118 import com.android.internal.util.XmlUtils;
119 import com.android.telephony.Rlog;
120 
121 import org.xmlpull.v1.XmlPullParser;
122 import org.xmlpull.v1.XmlPullParserException;
123 
124 import java.io.File;
125 import java.io.FileDescriptor;
126 import java.io.FileNotFoundException;
127 import java.io.FileReader;
128 import java.io.IOException;
129 import java.io.PrintWriter;
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Collections;
133 import java.util.HashMap;
134 import java.util.HashSet;
135 import java.util.List;
136 import java.util.Locale;
137 import java.util.Map;
138 import java.util.Set;
139 import java.util.concurrent.atomic.AtomicReference;
140 import java.util.function.Consumer;
141 import java.util.stream.Collectors;
142 
143 /**
144  * (<em>Not for SDK use</em>)
145  * A base implementation for the com.android.internal.telephony.Phone interface.
146  *
147  * Note that implementations of Phone.java are expected to be used
148  * from a single application thread. This should be the same thread that
149  * originally called PhoneFactory to obtain the interface.
150  *
151  *  {@hide}
152  *
153  */
154 
155 public abstract class Phone extends Handler implements PhoneInternalInterface {
156 
157     protected final static Object lockForRadioTechnologyChange = new Object();
158 
159     private final String mLogTag;
160     protected final int USSD_MAX_QUEUE = 10;
161 
162     // Key used to read and write the saved network selection numeric value
163     public static final String NETWORK_SELECTION_KEY = "network_selection_key";
164     // Key used to read and write the saved network selection operator name
165     public static final String NETWORK_SELECTION_NAME_KEY = "network_selection_name_key";
166     // Key used to read and write the saved network selection operator short name
167     public static final String NETWORK_SELECTION_SHORT_KEY = "network_selection_short_key";
168 
169 
170     // Key used to read/write "disable data connection on boot" pref (used for testing)
171     public static final String DATA_DISABLED_ON_BOOT_KEY = "disabled_on_boot_key";
172 
173     // Key used to read/write data_roaming_is_user_setting pref
174     public static final String DATA_ROAMING_IS_USER_SETTING_KEY =
175             "data_roaming_is_user_setting_key";
176 
177     // Default value when there has been no last emergency SMS time recorded yet.
178     private static final int EMERGENCY_SMS_NO_TIME_RECORDED = -1;
179     // The max timer value that the platform can be in emergency SMS mode (5 minutes).
180     private static final int EMERGENCY_SMS_TIMER_MAX_MS = 300000;
181 
182     /* Event Constants */
183     protected static final int EVENT_RADIO_AVAILABLE             = 1;
184     /** Supplementary Service Notification received. */
185     protected static final int EVENT_SSN                         = 2;
186     protected static final int EVENT_SIM_RECORDS_LOADED          = 3;
187     private static final int EVENT_MMI_DONE                      = 4;
188     protected static final int EVENT_RADIO_ON                    = 5;
189     protected static final int EVENT_GET_BASEBAND_VERSION_DONE   = 6;
190     protected static final int EVENT_USSD                        = 7;
191     @VisibleForTesting
192     public static final int EVENT_RADIO_OFF_OR_NOT_AVAILABLE  = 8;
193     private static final int EVENT_GET_SIM_STATUS_DONE           = 11;
194     protected static final int EVENT_SET_CALL_FORWARD_DONE       = 12;
195     protected static final int EVENT_GET_CALL_FORWARD_DONE       = 13;
196     protected static final int EVENT_CALL_RING                   = 14;
197     private static final int EVENT_CALL_RING_CONTINUE            = 15;
198 
199     // Used to intercept the carrier selection calls so that
200     // we can save the values.
201     private static final int EVENT_SET_NETWORK_MANUAL_COMPLETE      = 16;
202     private static final int EVENT_SET_NETWORK_AUTOMATIC_COMPLETE   = 17;
203     protected static final int EVENT_SET_CLIR_COMPLETE              = 18;
204     protected static final int EVENT_REGISTERED_TO_NETWORK          = 19;
205     protected static final int EVENT_SET_VM_NUMBER_DONE             = 20;
206     // Events for CDMA support
207     protected static final int EVENT_GET_DEVICE_IDENTITY_DONE       = 21;
208     protected static final int EVENT_RUIM_RECORDS_LOADED            = 22;
209     protected static final int EVENT_NV_READY                       = 23;
210     private static final int EVENT_SET_ENHANCED_VP                  = 24;
211     @VisibleForTesting
212     public static final int EVENT_EMERGENCY_CALLBACK_MODE_ENTER  = 25;
213     protected static final int EVENT_EXIT_EMERGENCY_CALLBACK_RESPONSE = 26;
214     protected static final int EVENT_CDMA_SUBSCRIPTION_SOURCE_CHANGED = 27;
215     // other
216     protected static final int EVENT_SET_NETWORK_AUTOMATIC          = 28;
217     protected static final int EVENT_ICC_RECORD_EVENTS              = 29;
218     @VisibleForTesting
219     protected static final int EVENT_ICC_CHANGED                    = 30;
220     // Single Radio Voice Call Continuity
221     @VisibleForTesting
222     protected static final int EVENT_SRVCC_STATE_CHANGED             = 31;
223     private static final int EVENT_INITIATE_SILENT_REDIAL           = 32;
224     private static final int EVENT_RADIO_NOT_AVAILABLE              = 33;
225     private static final int EVENT_UNSOL_OEM_HOOK_RAW               = 34;
226     protected static final int EVENT_GET_RADIO_CAPABILITY           = 35;
227     protected static final int EVENT_SS                             = 36;
228     private static final int EVENT_CHECK_FOR_NETWORK_AUTOMATIC      = 38;
229     protected static final int EVENT_VOICE_RADIO_TECH_CHANGED       = 39;
230     protected static final int EVENT_REQUEST_VOICE_RADIO_TECH_DONE  = 40;
231     protected static final int EVENT_RIL_CONNECTED                  = 41;
232     protected static final int EVENT_UPDATE_PHONE_OBJECT            = 42;
233     protected static final int EVENT_CARRIER_CONFIG_CHANGED         = 43;
234     // Carrier's CDMA prefer mode setting
235     protected static final int EVENT_SET_ROAMING_PREFERENCE_DONE    = 44;
236     protected static final int EVENT_MODEM_RESET                    = 45;
237     protected static final int EVENT_VRS_OR_RAT_CHANGED             = 46;
238     // Radio state change
239     protected static final int EVENT_RADIO_STATE_CHANGED            = 47;
240     protected static final int EVENT_SET_CARRIER_DATA_ENABLED       = 48;
241     protected static final int EVENT_GET_AVAILABLE_NETWORKS_DONE    = 51;
242 
243     protected static final int EVENT_UICC_APPS_ENABLEMENT_STATUS_CHANGED  = 53;
244     protected static final int EVENT_UICC_APPS_ENABLEMENT_SETTING_CHANGED = 54;
245     protected static final int EVENT_GET_UICC_APPS_ENABLEMENT_DONE        = 55;
246     protected static final int EVENT_REAPPLY_UICC_APPS_ENABLEMENT_DONE    = 56;
247     protected static final int EVENT_REGISTRATION_FAILED = 57;
248     protected static final int EVENT_BARRING_INFO_CHANGED = 58;
249     protected static final int EVENT_LINK_CAPACITY_CHANGED = 59;
250     protected static final int EVENT_RESET_CARRIER_KEY_IMSI_ENCRYPTION = 60;
251     protected static final int EVENT_SET_VONR_ENABLED_DONE = 61;
252     protected static final int EVENT_SUBSCRIPTIONS_CHANGED = 62;
253     protected static final int EVENT_GET_USAGE_SETTING_DONE = 63;
254     protected static final int EVENT_SET_USAGE_SETTING_DONE = 64;
255     protected static final int EVENT_IMS_DEREGISTRATION_TRIGGERED = 65;
256     protected static final int EVENT_SET_NULL_CIPHER_AND_INTEGRITY_DONE = 66;
257     protected static final int EVENT_GET_DEVICE_IMEI_DONE = 67;
258     protected static final int EVENT_TRIGGER_NOTIFY_ANBR = 68;
259     protected static final int EVENT_GET_N1_MODE_ENABLED_DONE = 69;
260     protected static final int EVENT_SET_N1_MODE_ENABLED_DONE = 70;
261     protected static final int EVENT_IMEI_MAPPING_CHANGED = 71;
262     protected static final int EVENT_CELL_IDENTIFIER_DISCLOSURE = 72;
263     protected static final int EVENT_SET_IDENTIFIER_DISCLOSURE_ENABLED_DONE = 73;
264     protected static final int EVENT_SECURITY_ALGORITHM_UPDATE = 74;
265     protected static final int EVENT_SET_SECURITY_ALGORITHMS_UPDATED_ENABLED_DONE = 75;
266     protected static final int EVENT_LAST = EVENT_SET_SECURITY_ALGORITHMS_UPDATED_ENABLED_DONE;
267 
268     // For shared prefs.
269     private static final String GSM_ROAMING_LIST_OVERRIDE_PREFIX = "gsm_roaming_list_";
270     private static final String GSM_NON_ROAMING_LIST_OVERRIDE_PREFIX = "gsm_non_roaming_list_";
271     private static final String CDMA_ROAMING_LIST_OVERRIDE_PREFIX = "cdma_roaming_list_";
272     private static final String CDMA_NON_ROAMING_LIST_OVERRIDE_PREFIX = "cdma_non_roaming_list_";
273 
274     // Key used to read/write current CLIR setting
275     public static final String CLIR_KEY = "clir_sub_key";
276 
277     // Key used for storing voice mail count
278     private static final String VM_COUNT = "vm_count_key";
279     // Key used to read/write the ID for storing the voice mail
280     private static final String VM_ID = "vm_id_key";
281 
282     // Key used for storing call forwarding status
283     public static final String CF_STATUS = "cf_status_key";
284     // Key used to read/write the ID for storing the call forwarding status
285     public static final String CF_ID = "cf_id_key";
286 
287     // Integer used to let the calling application know that the we are ignoring auto mode switch.
288     private static final int ALREADY_IN_AUTO_SELECTION = 1;
289 
290     public static final String PREF_NULL_CIPHER_AND_INTEGRITY_ENABLED =
291             "pref_null_cipher_and_integrity_enabled";
292     private final TelephonyAdminReceiver m2gAdminUpdater;
293 
294     public static final String PREF_IDENTIFIER_DISCLOSURE_NOTIFICATIONS_ENABLED =
295             "pref_identifier_disclosure_notifications_enabled";
296 
297     public static final String PREF_NULL_CIPHER_NOTIFICATIONS_ENABLED =
298             "pref_null_cipher_notifications_enabled";
299 
300     protected final FeatureFlags mFeatureFlags;
301 
302     /**
303      * This method is invoked when the Phone exits Emergency Callback Mode.
304      */
handleExitEmergencyCallbackMode()305     protected void handleExitEmergencyCallbackMode() {
306     }
307 
308     /**
309      * Small container class used to hold information relevant to
310      * the carrier selection process. operatorNumeric can be ""
311      * if we are looking for automatic selection. operatorAlphaLong is the
312      * corresponding operator name.
313      */
314     protected static class NetworkSelectMessage {
315         public Message message;
316         public String operatorNumeric;
317         public String operatorAlphaLong;
318         public String operatorAlphaShort;
319     }
320 
321     public static class SilentRedialParam {
322         public String dialString;
323         public int causeCode;
324         public DialArgs dialArgs;
325 
SilentRedialParam(String dialString, int causeCode, DialArgs dialArgs)326         public SilentRedialParam(String dialString, int causeCode, DialArgs dialArgs) {
327             this.dialString = dialString;
328             this.causeCode = causeCode;
329             this.dialArgs = dialArgs;
330         }
331     }
332 
333     /* Instance Variables */
334     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
335     public CommandsInterface mCi;
336     protected int mVmCount = 0;
337     protected DataNetworkController mDataNetworkController;
338     /* Used for dispatching signals to configured carrier apps */
339     protected CarrierSignalAgent mCarrierSignalAgent;
340     /* Used for dispatching carrier action from carrier apps */
341     protected CarrierActionAgent mCarrierActionAgent;
342     private boolean mDoesRilSendMultipleCallRing;
343     private int mCallRingContinueToken;
344     private int mCallRingDelay;
345     private boolean mIsVoiceCapable = true;
346     private final AppSmsManager mAppSmsManager;
347     private SimActivationTracker mSimActivationTracker;
348     // Keep track of whether or not the phone is in Emergency Callback Mode for Phone and
349     // subclasses
350     protected boolean mIsPhoneInEcmState = false;
351     // Keep track of the case where ECM was cancelled to place another outgoing emergency call.
352     // We will need to restart it after the emergency call ends.
353     protected boolean mEcmCanceledForEmergency = false;
354     private volatile long mTimeLastEmergencySmsSentMs = EMERGENCY_SMS_NO_TIME_RECORDED;
355 
356     // Variable to cache the video capability. When RAT changes, we lose this info and are unable
357     // to recover from the state. We cache it and notify listeners when they register.
358     protected boolean mIsVideoCapable = false;
359     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
360     protected UiccController mUiccController = null;
361     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
362     protected final AtomicReference<IccRecords> mIccRecords = new AtomicReference<IccRecords>();
363     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
364     public SmsStorageMonitor mSmsStorageMonitor;
365     public SmsUsageMonitor mSmsUsageMonitor;
366     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
367     protected AtomicReference<UiccCardApplication> mUiccApplication =
368             new AtomicReference<UiccCardApplication>();
369     private TelephonyTester mTelephonyTester;
370     private String mName;
371     private final String mActionDetached;
372     private final String mActionAttached;
373     protected DeviceStateMonitor mDeviceStateMonitor;
374     protected DisplayInfoController mDisplayInfoController;
375     protected AccessNetworksManager mAccessNetworksManager;
376     // Used for identify the carrier of current subscription
377     protected CarrierResolver mCarrierResolver;
378     protected SignalStrengthController mSignalStrengthController;
379 
380     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
381     protected int mPhoneId;
382 
383     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
384     protected Phone mImsPhone = null;
385 
386     private final AtomicReference<RadioCapability> mRadioCapability =
387             new AtomicReference<RadioCapability>();
388 
389     protected TelephonyComponentFactory mTelephonyComponentFactory;
390 
391     private int mPreferredUsageSetting = SubscriptionManager.USAGE_SETTING_UNKNOWN;
392     private int mUsageSettingFromModem = SubscriptionManager.USAGE_SETTING_UNKNOWN;
393     private boolean mIsUsageSettingSupported = true;
394     private boolean mIsNetworkScanStarted = false;
395 
396     //IMS
397     /**
398      * {@link CallStateException} message text used to indicate that an IMS call has failed because
399      * it needs to be retried using GSM or CDMA (e.g. CS fallback).
400      * TODO: Replace this with a proper exception; {@link CallStateException} doesn't make sense.
401      */
402     public static final String CS_FALLBACK = "cs_fallback";
403 
404     // Used for retry over cs for supplementary services
405     public static final String CS_FALLBACK_SS = "cs_fallback_ss";
406 
407     /**
408      * @deprecated Use {@link android.telephony.ims.ImsManager#EXTRA_WFC_REGISTRATION_FAILURE_TITLE}
409      * instead.
410      */
411     @Deprecated
412     public static final String EXTRA_KEY_ALERT_TITLE =
413             android.telephony.ims.ImsManager.EXTRA_WFC_REGISTRATION_FAILURE_TITLE;
414     /**
415      * @deprecated Use
416      * {@link android.telephony.ims.ImsManager#EXTRA_WFC_REGISTRATION_FAILURE_MESSAGE} instead.
417      */
418     @Deprecated
419     public static final String EXTRA_KEY_ALERT_MESSAGE =
420             android.telephony.ims.ImsManager.EXTRA_WFC_REGISTRATION_FAILURE_MESSAGE;
421     public static final String EXTRA_KEY_ALERT_SHOW = "alertShow";
422     public static final String EXTRA_KEY_NOTIFICATION_MESSAGE = "notificationMessage";
423 
424     protected final RegistrantList mPreciseCallStateRegistrants = new RegistrantList();
425 
426     private final RegistrantList mHandoverRegistrants = new RegistrantList();
427 
428     private final RegistrantList mNewRingingConnectionRegistrants = new RegistrantList();
429 
430     private final RegistrantList mIncomingRingRegistrants = new RegistrantList();
431 
432     protected final RegistrantList mDisconnectRegistrants = new RegistrantList();
433 
434     private final RegistrantList mServiceStateRegistrants = new RegistrantList();
435 
436     protected final RegistrantList mMmiCompleteRegistrants = new RegistrantList();
437 
438     @UnsupportedAppUsage
439     protected final RegistrantList mMmiRegistrants = new RegistrantList();
440 
441     protected final RegistrantList mUnknownConnectionRegistrants = new RegistrantList();
442 
443     protected final RegistrantList mSuppServiceFailedRegistrants = new RegistrantList();
444 
445     protected final RegistrantList mRadioOffOrNotAvailableRegistrants = new RegistrantList();
446 
447     protected final RegistrantList mSimRecordsLoadedRegistrants = new RegistrantList();
448 
449     private final RegistrantList mVideoCapabilityChangedRegistrants = new RegistrantList();
450 
451     protected final RegistrantList mEmergencyCallToggledRegistrants = new RegistrantList();
452 
453     private final RegistrantList mCellInfoRegistrants = new RegistrantList();
454 
455     private final RegistrantList mRedialRegistrants = new RegistrantList();
456 
457     private final RegistrantList mPhysicalChannelConfigRegistrants = new RegistrantList();
458 
459     private final RegistrantList mOtaspRegistrants = new RegistrantList();
460 
461     private final RegistrantList mPreferredNetworkTypeRegistrants = new RegistrantList();
462 
463     protected Registrant mPostDialHandler;
464 
465     protected final LocalLog mLocalLog;
466 
467     private Looper mLooper; /* to insure registrants are in correct thread*/
468 
469     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
470     protected final Context mContext;
471 
472     protected SubscriptionManagerService mSubscriptionManagerService;
473 
474     /**
475      * PhoneNotifier is an abstraction for all system-wide
476      * state change notification. DefaultPhoneNotifier is
477      * used here unless running we're inside a unit test.
478      */
479     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
480     protected PhoneNotifier mNotifier;
481 
482     protected SimulatedRadioControl mSimulatedRadioControl;
483 
484     private Map<Integer, Long> mAllowedNetworkTypesForReasons = new HashMap<>();
485     private static final String ALLOWED_NETWORK_TYPES_TEXT_USER = "user";
486     private static final String ALLOWED_NETWORK_TYPES_TEXT_POWER = "power";
487     private static final String ALLOWED_NETWORK_TYPES_TEXT_CARRIER = "carrier";
488     private static final String ALLOWED_NETWORK_TYPES_TEXT_ENABLE_2G = "enable_2g";
489     private static final String ALLOWED_NETWORK_TYPES_TEXT_TEST = "test";
490     private static final int INVALID_ALLOWED_NETWORK_TYPES = -1;
491     protected boolean mIsCarrierNrSupported = false;
492     protected boolean mIsAllowedNetworkTypesLoadedFromDb = false;
493     private boolean mUnitTestMode;
494 
495     protected VoiceCallSessionStats mVoiceCallSessionStats;
496     protected SmsStats mSmsStats;
497     protected TelephonyAnalytics mTelephonyAnalytics;
498 
499     protected LinkBandwidthEstimator mLinkBandwidthEstimator;
500 
501     public static final int IMEI_TYPE_UNKNOWN = -1;
502     public static final int IMEI_TYPE_PRIMARY = ImeiInfo.ImeiType.PRIMARY;
503     public static final int IMEI_TYPE_SECONDARY = ImeiInfo.ImeiType.SECONDARY;
504 
getIccRecords()505     public IccRecords getIccRecords() {
506         return mIccRecords.get();
507     }
508 
509     /**
510      * Returns a string identifier for this phone interface for parties
511      *  outside the phone app process.
512      *  @return The string name.
513      */
514     @UnsupportedAppUsage
getPhoneName()515     public String getPhoneName() {
516         return mName;
517     }
518 
setPhoneName(String name)519     protected void setPhoneName(String name) {
520         mName = name;
521     }
522 
523     /**
524      * Retrieves Nai for phones. Returns null if Nai is not set.
525      */
526     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getNai()527     public String getNai(){
528          return null;
529     }
530 
531     /**
532      * Return the ActionDetached string. When this action is received by components
533      * they are to simulate detaching from the network.
534      *
535      * @return com.android.internal.telephony.{mName}.action_detached
536      *          {mName} is GSM, CDMA ...
537      */
getActionDetached()538     public String getActionDetached() {
539         return mActionDetached;
540     }
541 
542     /**
543      * Return the ActionAttached string. When this action is received by components
544      * they are to simulate attaching to the network.
545      *
546      * @return com.android.internal.telephony.{mName}.action_detached
547      *          {mName} is GSM, CDMA ...
548      */
getActionAttached()549     public String getActionAttached() {
550         return mActionAttached;
551     }
552 
553     /**
554      * Set a system property, unless we're in unit test mode
555      */
556     // CAF_MSIM TODO this need to be replated with TelephonyManager API ?
557     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getSystemProperty(String property, String defValue)558     public String getSystemProperty(String property, String defValue) {
559         if(getUnitTestMode()) {
560             return null;
561         }
562         return SystemProperties.get(property, defValue);
563     }
564 
565     /**
566      * Constructs a Phone in normal (non-unit test) mode.
567      *
568      * @param name a name for this phone object
569      * @param notifier An instance of DefaultPhoneNotifier,
570      * @param context Context object from hosting application
571      * unless unit testing.
572      * @param ci is CommandsInterface
573      * @param unitTestMode when true, prevents notifications
574      * of state change events
575      * @param featureFlags an instance of the FeatureFlags set
576      */
Phone(String name, PhoneNotifier notifier, Context context, CommandsInterface ci, boolean unitTestMode, FeatureFlags featureFlags)577     protected Phone(String name, PhoneNotifier notifier, Context context, CommandsInterface ci,
578                     boolean unitTestMode, FeatureFlags featureFlags) {
579         this(name, notifier, context, ci, unitTestMode, SubscriptionManager.DEFAULT_PHONE_INDEX,
580                 TelephonyComponentFactory.getInstance(), featureFlags);
581     }
582 
583     /**
584      * Constructs a Phone in normal (non-unit test) mode.
585      *
586      * @param name a name for this phone object
587      * @param notifier An instance of DefaultPhoneNotifier,
588      * @param context Context object from hosting application
589      * unless unit testing.
590      * @param ci is CommandsInterface
591      * @param unitTestMode when true, prevents notifications
592      * of state change events
593      * @param phoneId the phone-id of this phone.
594      * @param telephonyComponentFactory a factory for injecting telephony components
595      * @param featureFlags an instance of the FeatureFlags set
596      */
Phone(String name, PhoneNotifier notifier, Context context, CommandsInterface ci, boolean unitTestMode, int phoneId, TelephonyComponentFactory telephonyComponentFactory, FeatureFlags featureFlags)597     protected Phone(String name, PhoneNotifier notifier, Context context, CommandsInterface ci,
598                     boolean unitTestMode, int phoneId,
599                     TelephonyComponentFactory telephonyComponentFactory,
600                     FeatureFlags featureFlags) {
601         mLogTag = "Phone-" + phoneId;
602         mPhoneId = phoneId;
603         mName = name;
604         mNotifier = notifier;
605         mContext = context;
606         mLooper = Looper.myLooper();
607         mCi = ci;
608         mActionDetached = this.getClass().getPackage().getName() + ".action_detached";
609         mActionAttached = this.getClass().getPackage().getName() + ".action_attached";
610         mAppSmsManager = telephonyComponentFactory.inject(AppSmsManager.class.getName())
611                 .makeAppSmsManager(context);
612         mLocalLog = new LocalLog(64);
613 
614         mFeatureFlags = featureFlags;
615 
616         setUnitTestMode(unitTestMode);
617 
618         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
619         mCi.setOnCallRing(this, EVENT_CALL_RING, null);
620 
621         /* "Voice capable" means that this device supports circuit-switched
622         * (i.e. voice) phone calls over the telephony network, and is allowed
623         * to display the in-call UI while a cellular voice call is active.
624         * This will be false on "data only" devices which can't make voice
625         * calls and don't support any in-call UI.
626         */
627         mIsVoiceCapable = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
628                 .isVoiceCapable();
629 
630         /**
631          *  Some RIL's don't always send RIL_UNSOL_CALL_RING so it needs
632          *  to be generated locally. Ideally all ring tones should be loops
633          * and this wouldn't be necessary. But to minimize changes to upper
634          * layers it is requested that it be generated by lower layers.
635          *
636          * By default old phones won't have the property set but do generate
637          * the RIL_UNSOL_CALL_RING so the default if there is no property is
638          * true.
639          */
640         mDoesRilSendMultipleCallRing = TelephonyProperties.ril_sends_multiple_call_ring()
641                 .orElse(true);
642         Rlog.d(mLogTag, "mDoesRilSendMultipleCallRing=" + mDoesRilSendMultipleCallRing);
643 
644         mCallRingDelay = TelephonyProperties.call_ring_delay().orElse(3000);
645         Rlog.d(mLogTag, "mCallRingDelay=" + mCallRingDelay);
646 
647         // Initialize SMS stats
648         mSmsStats = new SmsStats(this);
649 
650         mSubscriptionManagerService = SubscriptionManagerService.getInstance();
651         m2gAdminUpdater = new TelephonyAdminReceiver(context, this);
652 
653         if (getPhoneType() == PhoneConstants.PHONE_TYPE_IMS) {
654             return;
655         }
656 
657         if (TelephonyUtils.IS_DEBUGGABLE) {
658             mTelephonyTester = new TelephonyTester(this);
659         }
660 
661         // Initialize device storage and outgoing SMS usage monitors for SMSDispatchers.
662         mTelephonyComponentFactory = telephonyComponentFactory;
663         mSmsStorageMonitor = mTelephonyComponentFactory.inject(SmsStorageMonitor.class.getName())
664                 .makeSmsStorageMonitor(this, mFeatureFlags);
665         mSmsUsageMonitor = mTelephonyComponentFactory.inject(SmsUsageMonitor.class.getName())
666                 .makeSmsUsageMonitor(context, mFeatureFlags);
667         mUiccController = UiccController.getInstance();
668         mUiccController.registerForIccChanged(this, EVENT_ICC_CHANGED, null);
669         mSimActivationTracker = mTelephonyComponentFactory
670                 .inject(SimActivationTracker.class.getName())
671                 .makeSimActivationTracker(this);
672         if (getPhoneType() != PhoneConstants.PHONE_TYPE_SIP) {
673             mCi.registerForSrvccStateChanged(this, EVENT_SRVCC_STATE_CHANGED, null);
674         }
675         //Initialize Telephony Analytics
676         mTelephonyAnalytics = new TelephonyAnalytics(this);
677     }
678 
679     /**
680      * Start setup of ImsPhone, which will start trying to connect to the ImsResolver. Will not be
681      * called if this device does not support FEATURE_IMS_TELEPHONY.
682      */
createImsPhone()683     public void createImsPhone() {
684         if (getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
685             return;
686         }
687 
688         synchronized(Phone.lockForRadioTechnologyChange) {
689             if (mImsPhone == null) {
690                 mImsPhone = PhoneFactory.makeImsPhone(mNotifier, this);
691                 CallManager.getInstance().registerPhone(mImsPhone);
692                 mImsPhone.registerForSilentRedial(
693                         this, EVENT_INITIATE_SILENT_REDIAL, null);
694             }
695         }
696     }
697 
698     /**
699      * Checks if device should convert CDMA Caller ID restriction related MMI codes to
700      * equivalent 3GPP MMI Codes that provide same functionality when device is roaming.
701      * This method should only return true on multi-mode devices when carrier requires this
702      * conversion to be done on the device.
703      *
704      * @return true when carrier config
705      * "KEY_CONVERT_CDMA_CALLER_ID_MMI_CODES_WHILE_ROAMING_ON_3GPP_BOOL" is set to true
706      */
supportsConversionOfCdmaCallerIdMmiCodesWhileRoaming()707     public boolean supportsConversionOfCdmaCallerIdMmiCodesWhileRoaming() {
708         CarrierConfigManager configManager = (CarrierConfigManager)
709                 getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
710         PersistableBundle b = configManager.getConfigForSubId(getSubId());
711         if (b != null) {
712             return b.getBoolean(
713                     CarrierConfigManager
714                             .KEY_CONVERT_CDMA_CALLER_ID_MMI_CODES_WHILE_ROAMING_ON_3GPP_BOOL,
715                     false);
716         } else {
717             // Default value set in CarrierConfigManager
718             return false;
719         }
720     }
721 
722     /**
723      * Check if sending CLIR activation("*31#") and deactivation("#31#") code only without dialing
724      * number is prevented.
725      *
726      * @return {@code true} when carrier config
727      * "KEY_PREVENT_CLIR_ACTIVATION_AND_DEACTIVATION_CODE_BOOL" is set to {@code true}
728      */
isClirActivationAndDeactivationPrevented()729     public boolean isClirActivationAndDeactivationPrevented() {
730         CarrierConfigManager configManager = (CarrierConfigManager)
731                 getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
732         PersistableBundle b = configManager.getConfigForSubId(getSubId());
733         if (b == null) {
734             b = CarrierConfigManager.getDefaultConfig();
735         }
736         return b.getBoolean(
737                 CarrierConfigManager.KEY_PREVENT_CLIR_ACTIVATION_AND_DEACTIVATION_CODE_BOOL);
738     }
739 
740     /**
741      * Determines if the carrier prefers to use an in service sim for a normal routed emergency
742      * call.
743      * @return true when carrier config
744      * {@link CarrierConfigManager#KEY_PREFER_IN_SERVICE_SIM_FOR_NORMAL_ROUTED_EMERGENCY_CALLS_BOOL}
745      * is true.
746      */
shouldPreferInServiceSimForNormalRoutedEmergencyCall()747     public boolean shouldPreferInServiceSimForNormalRoutedEmergencyCall() {
748         CarrierConfigManager configManager = (CarrierConfigManager)
749                 getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
750         PersistableBundle b = configManager.getConfigForSubId(getSubId(), CarrierConfigManager
751                 .KEY_PREFER_IN_SERVICE_SIM_FOR_NORMAL_ROUTED_EMERGENCY_CALLS_BOOL);
752         if (b != null) {
753             return b.getBoolean(CarrierConfigManager
754                             .KEY_PREFER_IN_SERVICE_SIM_FOR_NORMAL_ROUTED_EMERGENCY_CALLS_BOOL,
755                     false);
756         } else {
757             // Default value set in CarrierConfigManager
758             return false;
759         }
760     }
761 
762     /**
763      * When overridden the derived class needs to call
764      * super.handleMessage(msg) so this method has a
765      * a chance to process the message.
766      *
767      * @param msg
768      */
769     @Override
handleMessage(Message msg)770     public void handleMessage(Message msg) {
771         AsyncResult ar;
772 
773         // messages to be handled whether or not the phone is being destroyed
774         // should only include messages which are being re-directed and do not use
775         // resources of the phone being destroyed
776         switch (msg.what) {
777             // handle the select network completion callbacks.
778             case EVENT_SET_NETWORK_MANUAL_COMPLETE:
779             case EVENT_SET_NETWORK_AUTOMATIC_COMPLETE:
780                 handleSetSelectNetwork((AsyncResult) msg.obj);
781                 onSetNetworkSelectionModeCompleted();
782                 return;
783         }
784 
785         switch(msg.what) {
786             case EVENT_CALL_RING:
787                 Rlog.d(mLogTag, "Event EVENT_CALL_RING Received state=" + getState());
788                 ar = (AsyncResult)msg.obj;
789                 if (ar.exception == null) {
790                     PhoneConstants.State state = getState();
791                     if ((!mDoesRilSendMultipleCallRing)
792                             && ((state == PhoneConstants.State.RINGING) ||
793                                     (state == PhoneConstants.State.IDLE))) {
794                         mCallRingContinueToken += 1;
795                         sendIncomingCallRingNotification(mCallRingContinueToken);
796                     } else {
797                         notifyIncomingRing();
798                     }
799                 }
800                 break;
801 
802             case EVENT_CALL_RING_CONTINUE:
803                 Rlog.d(mLogTag, "Event EVENT_CALL_RING_CONTINUE Received state=" + getState());
804                 if (getState() == PhoneConstants.State.RINGING) {
805                     sendIncomingCallRingNotification(msg.arg1);
806                 }
807                 break;
808 
809             case EVENT_ICC_CHANGED:
810                 onUpdateIccAvailability();
811                 break;
812 
813             case EVENT_INITIATE_SILENT_REDIAL:
814                 // This is an ImsPhone -> GsmCdmaPhone redial
815                 // See ImsPhone#initiateSilentRedial
816                 Rlog.d(mLogTag, "Event EVENT_INITIATE_SILENT_REDIAL Received");
817                 ar = (AsyncResult) msg.obj;
818                 if ((ar.exception == null) && (ar.result != null)) {
819                     SilentRedialParam result = (SilentRedialParam) ar.result;
820                     String dialString = result.dialString;
821                     int causeCode = result.causeCode;
822                     DialArgs dialArgs = result.dialArgs;
823                     if (TextUtils.isEmpty(dialString)) return;
824                     try {
825                         Connection cn = dialInternal(dialString, dialArgs);
826                         // The ImsPhoneConnection that is owned by the ImsPhone is currently the
827                         // one with a callback registered to TelephonyConnection. Notify the
828                         // redial happened over that Phone so that it can be replaced with the
829                         // new GSM/CDMA Connection.
830                         Rlog.d(mLogTag, "Notify redial connection changed cn: " + cn);
831                         if (mImsPhone != null) {
832                             // Don't care it is null or not.
833                             mImsPhone.notifyRedialConnectionChanged(cn);
834                         }
835                     } catch (CallStateException e) {
836                         Rlog.e(mLogTag, "silent redial failed: " + e);
837                         if (mImsPhone != null) {
838                             mImsPhone.notifyRedialConnectionChanged(null);
839                         }
840                     }
841                 }
842                 break;
843 
844             case EVENT_SRVCC_STATE_CHANGED:
845                 ar = (AsyncResult)msg.obj;
846                 if (ar.exception == null) {
847                     handleSrvccStateChanged((int[]) ar.result);
848                 } else {
849                     Rlog.e(mLogTag, "Srvcc exception: " + ar.exception);
850                 }
851                 break;
852 
853             case EVENT_UNSOL_OEM_HOOK_RAW:
854                 // deprecated, ignore
855                 break;
856 
857             case EVENT_CHECK_FOR_NETWORK_AUTOMATIC: {
858                 onCheckForNetworkSelectionModeAutomatic(msg);
859                 break;
860             }
861 
862             case EVENT_GET_USAGE_SETTING_DONE:
863                 ar = (AsyncResult) msg.obj;
864                 if (ar.exception == null) {
865                     try {
866                         mUsageSettingFromModem = ((int[]) ar.result)[0];
867                     } catch (NullPointerException | ClassCastException e) {
868                         Rlog.e(mLogTag, "Invalid response for usage setting " + ar.result);
869                         break;
870                     }
871 
872                     logd("Received mUsageSettingFromModem=" + mUsageSettingFromModem);
873                     if (mUsageSettingFromModem != mPreferredUsageSetting) {
874                         mCi.setUsageSetting(obtainMessage(EVENT_SET_USAGE_SETTING_DONE),
875                                 mPreferredUsageSetting);
876                     }
877                 } else {
878                     try {
879                         CommandException ce = (CommandException) ar.exception;
880                         if (ce.getCommandError() == CommandException.Error.REQUEST_NOT_SUPPORTED) {
881                             mIsUsageSettingSupported = false;
882                         }
883                         Rlog.w(mLogTag, "Unexpected failure to retrieve usage setting " + ce);
884                     } catch (ClassCastException unused) {
885                         Rlog.e(mLogTag, "Invalid Exception for usage setting " + ar.exception);
886                         break; // technically extraneous, but good hygiene
887                     }
888                 }
889                 break;
890             case EVENT_SET_USAGE_SETTING_DONE:
891                 ar = (AsyncResult) msg.obj;
892                 if (ar.exception != null) {
893                     try {
894                         CommandException ce = (CommandException) ar.exception;
895                         if (ce.getCommandError() == CommandException.Error.REQUEST_NOT_SUPPORTED) {
896                             mIsUsageSettingSupported = false;
897                         }
898                         Rlog.w(mLogTag, "Unexpected failure to set usage setting " + ce);
899                     } catch (ClassCastException unused) {
900                         Rlog.e(mLogTag, "Invalid Exception for usage setting " + ar.exception);
901                         break; // technically extraneous, but good hygiene
902                     }
903                 } else {
904                     mUsageSettingFromModem = msg.arg1;
905                 }
906                 break;
907             default:
908                 throw new RuntimeException("unexpected event not handled, msgId=" + msg.what);
909         }
910     }
911 
getHandoverConnection()912     public ArrayList<Connection> getHandoverConnection() {
913         return null;
914     }
915 
916     /**
917      * Notifies the change of the SRVCC state.
918      * @param state the new SRVCC state.
919      */
notifySrvccState(@rvccState int state)920     public void notifySrvccState(@SrvccState int state) {
921     }
922 
registerForSilentRedial(Handler h, int what, Object obj)923     public void registerForSilentRedial(Handler h, int what, Object obj) {
924     }
925 
unregisterForSilentRedial(Handler h)926     public void unregisterForSilentRedial(Handler h) {
927     }
928 
registerForVolteSilentRedial(Handler h, int what, Object obj)929     public void registerForVolteSilentRedial(Handler h, int what, Object obj) {
930     }
931 
unregisterForVolteSilentRedial(Handler h)932     public void unregisterForVolteSilentRedial(Handler h) {
933     }
934 
handleSrvccStateChanged(int[] ret)935     private void handleSrvccStateChanged(int[] ret) {
936         Rlog.d(mLogTag, "handleSrvccStateChanged");
937 
938         ArrayList<Connection> conn = null;
939         Phone imsPhone = mImsPhone;
940         Call.SrvccState srvccState = Call.SrvccState.NONE;
941         if (ret != null && ret.length != 0) {
942             int state = ret[0];
943             if (imsPhone != null) {
944                 imsPhone.notifySrvccState(state);
945             }
946             switch(state) {
947                 case TelephonyManager.SRVCC_STATE_HANDOVER_STARTED:
948                     srvccState = Call.SrvccState.STARTED;
949                     if (imsPhone != null) {
950                         conn = imsPhone.getHandoverConnection();
951                         migrateFrom(imsPhone);
952                     } else {
953                         Rlog.d(mLogTag, "HANDOVER_STARTED: mImsPhone null");
954                     }
955                     break;
956                 case TelephonyManager.SRVCC_STATE_HANDOVER_COMPLETED:
957                     srvccState = Call.SrvccState.COMPLETED;
958                     break;
959                 case TelephonyManager.SRVCC_STATE_HANDOVER_FAILED:
960                 case TelephonyManager.SRVCC_STATE_HANDOVER_CANCELED:
961                     srvccState = Call.SrvccState.FAILED;
962                     break;
963 
964                 default:
965                     //ignore invalid state
966                     return;
967             }
968 
969             getCallTracker().notifySrvccState(srvccState, conn);
970 
971             notifySrvccStateChanged(state);
972         }
973     }
974 
975     /**
976      * Gets the context for the phone, as set at initialization time.
977      */
978     @UnsupportedAppUsage
getContext()979     public Context getContext() {
980         return mContext;
981     }
982 
983     // Will be called when icc changed
onUpdateIccAvailability()984     protected abstract void onUpdateIccAvailability();
985 
986     /**
987      * Register for getting notifications for change in the Call State {@link Call.State}
988      * This is called PreciseCallState because the call state is more precise than the
989      * {@link PhoneConstants.State} which can be obtained using the {@link PhoneStateListener}
990      *
991      * Resulting events will have an AsyncResult in <code>Message.obj</code>.
992      * AsyncResult.userData will be set to the obj argument here.
993      * The <em>h</em> parameter is held only by a weak reference.
994      */
995     @UnsupportedAppUsage
registerForPreciseCallStateChanged(Handler h, int what, Object obj)996     public void registerForPreciseCallStateChanged(Handler h, int what, Object obj) {
997         checkCorrectThread(h);
998 
999         mPreciseCallStateRegistrants.addUnique(h, what, obj);
1000     }
1001 
1002     /**
1003      * Unregisters for voice call state change notifications.
1004      * Extraneous calls are tolerated silently.
1005      */
1006     @UnsupportedAppUsage
unregisterForPreciseCallStateChanged(Handler h)1007     public void unregisterForPreciseCallStateChanged(Handler h) {
1008         mPreciseCallStateRegistrants.remove(h);
1009     }
1010 
1011     /**
1012      * Notifies when a Handover happens due to SRVCC or Silent Redial
1013      */
registerForHandoverStateChanged(Handler h, int what, Object obj)1014     public void registerForHandoverStateChanged(Handler h, int what, Object obj) {
1015         checkCorrectThread(h);
1016         mHandoverRegistrants.addUnique(h, what, obj);
1017     }
1018 
1019     /**
1020      * Unregisters for handover state notifications
1021      */
unregisterForHandoverStateChanged(Handler h)1022     public void unregisterForHandoverStateChanged(Handler h) {
1023         mHandoverRegistrants.remove(h);
1024     }
1025 
1026     /**
1027      * Subclasses of Phone probably want to replace this with a
1028      * version scoped to their packages
1029      */
notifyHandoverStateChanged(Connection cn)1030     public void notifyHandoverStateChanged(Connection cn) {
1031        AsyncResult ar = new AsyncResult(null, cn, null);
1032        mHandoverRegistrants.notifyRegistrants(ar);
1033     }
1034 
1035     /**
1036      * Notifies when a Handover happens due to Silent Redial
1037      */
registerForRedialConnectionChanged(Handler h, int what, Object obj)1038     public void registerForRedialConnectionChanged(Handler h, int what, Object obj) {
1039         checkCorrectThread(h);
1040         mRedialRegistrants.addUnique(h, what, obj);
1041     }
1042 
1043     /**
1044      * Unregisters for redial connection notifications
1045      */
unregisterForRedialConnectionChanged(Handler h)1046     public void unregisterForRedialConnectionChanged(Handler h) {
1047         mRedialRegistrants.remove(h);
1048     }
1049 
1050     /**
1051      * Subclasses of Phone probably want to replace this with a
1052      * version scoped to their packages
1053      */
notifyRedialConnectionChanged(Connection cn)1054     public void notifyRedialConnectionChanged(Connection cn) {
1055         AsyncResult ar = new AsyncResult(null, cn, null);
1056         mRedialRegistrants.notifyRegistrants(ar);
1057     }
1058 
setIsInEmergencyCall()1059     protected void setIsInEmergencyCall() {
1060     }
1061 
1062     /**
1063      * Notify the phone that an SMS has been sent. This will be used to determine if the SMS was
1064      * sent to an emergency address.
1065      *
1066      * @param destinationAddress the address that the SMS was sent to.
1067      */
notifySmsSent(String destinationAddress)1068     public void notifySmsSent(String destinationAddress) {
1069         TelephonyManager m =
1070                 (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
1071         if (mContext.getPackageManager() != null
1072                 && mContext.getPackageManager()
1073                                 .hasSystemFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)) {
1074             if (m != null && m.isEmergencyNumber(destinationAddress)) {
1075                 mLocalLog.log("Emergency SMS detected, recording time.");
1076                 mTimeLastEmergencySmsSentMs = SystemClock.elapsedRealtime();
1077             }
1078         }
1079     }
1080 
1081     /**
1082      * Determine if the Phone has recently sent an emergency SMS and is still in the interval of
1083      * time defined by a carrier that we may need to do perform special actions, for example
1084      * override user setting for location so the carrier can find the user's location for emergency
1085      * services.
1086      *
1087      * @return true if the device is in emergency SMS mode, false otherwise.
1088      */
isInEmergencySmsMode()1089     public boolean isInEmergencySmsMode() {
1090         long lastSmsTimeMs = mTimeLastEmergencySmsSentMs;
1091         if (lastSmsTimeMs == EMERGENCY_SMS_NO_TIME_RECORDED) {
1092             // an emergency SMS hasn't been sent since the last check.
1093             return false;
1094         }
1095         CarrierConfigManager configManager = (CarrierConfigManager)
1096                 getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
1097         PersistableBundle b = configManager.getConfigForSubId(getSubId());
1098         if (b == null) {
1099             // default for KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT is 0 and CarrierConfig isn't
1100             // available, so return false.
1101             return false;
1102         }
1103         int eSmsTimerMs = b.getInt(CarrierConfigManager.KEY_EMERGENCY_SMS_MODE_TIMER_MS_INT, 0);
1104         if (eSmsTimerMs == 0) {
1105             // We do not support this feature for this carrier.
1106             return false;
1107         }
1108         if (eSmsTimerMs > EMERGENCY_SMS_TIMER_MAX_MS) {
1109             eSmsTimerMs = EMERGENCY_SMS_TIMER_MAX_MS;
1110         }
1111         boolean isInEmergencySmsMode = SystemClock.elapsedRealtime()
1112                 <= (lastSmsTimeMs + eSmsTimerMs);
1113         if (!isInEmergencySmsMode) {
1114             // Shortcut this next time so we do not have to waste time if another emergency SMS
1115             // hasn't been sent since the last query.
1116             mTimeLastEmergencySmsSentMs = EMERGENCY_SMS_NO_TIME_RECORDED;
1117         } else {
1118             mLocalLog.log("isInEmergencySmsMode: queried while eSMS mode is active.");
1119         }
1120         return isInEmergencySmsMode;
1121     }
1122 
migrateFrom(Phone from)1123     protected void migrateFrom(Phone from) {
1124         migrate(mHandoverRegistrants, from.mHandoverRegistrants);
1125         migrate(mPreciseCallStateRegistrants, from.mPreciseCallStateRegistrants);
1126         migrate(mNewRingingConnectionRegistrants, from.mNewRingingConnectionRegistrants);
1127         migrate(mIncomingRingRegistrants, from.mIncomingRingRegistrants);
1128         migrate(mDisconnectRegistrants, from.mDisconnectRegistrants);
1129         migrate(mServiceStateRegistrants, from.mServiceStateRegistrants);
1130         migrate(mMmiCompleteRegistrants, from.mMmiCompleteRegistrants);
1131         migrate(mMmiRegistrants, from.mMmiRegistrants);
1132         migrate(mUnknownConnectionRegistrants, from.mUnknownConnectionRegistrants);
1133         migrate(mSuppServiceFailedRegistrants, from.mSuppServiceFailedRegistrants);
1134         migrate(mCellInfoRegistrants, from.mCellInfoRegistrants);
1135         migrate(mRedialRegistrants, from.mRedialRegistrants);
1136         // The emergency state of IMS phone will be cleared in ImsPhone#notifySrvccState after
1137         // receive SRVCC completed
1138         if (from.isInEmergencyCall()) {
1139             setIsInEmergencyCall();
1140         }
1141         setEcmCanceledForEmergency(from.isEcmCanceledForEmergency());
1142     }
1143 
migrate(RegistrantList to, RegistrantList from)1144     protected void migrate(RegistrantList to, RegistrantList from) {
1145         if (from == null) {
1146             // May be null in some cases, such as testing.
1147             return;
1148         }
1149         from.removeCleared();
1150         for (int i = 0, n = from.size(); i < n; i++) {
1151             Registrant r = (Registrant) from.get(i);
1152             Message msg = r.messageForRegistrant();
1153             // Since CallManager has already registered with both CS and IMS phones,
1154             // the migrate should happen only for those registrants which are not
1155             // registered with CallManager.Hence the below check is needed to add
1156             // only those registrants to the registrant list which are not
1157             // coming from the CallManager.
1158             if (msg != null) {
1159                 if (msg.obj == CallManager.getInstance().getRegistrantIdentifier()) {
1160                     continue;
1161                 } else {
1162                     to.add((Registrant) from.get(i));
1163                 }
1164             } else {
1165                 Rlog.d(mLogTag, "msg is null");
1166             }
1167         }
1168     }
1169 
1170     /**
1171      * Notifies when a previously untracked non-ringing/waiting connection has appeared.
1172      * This is likely due to some other entity (eg, SIM card application) initiating a call.
1173      */
1174     @UnsupportedAppUsage
registerForUnknownConnection(Handler h, int what, Object obj)1175     public void registerForUnknownConnection(Handler h, int what, Object obj) {
1176         checkCorrectThread(h);
1177 
1178         mUnknownConnectionRegistrants.addUnique(h, what, obj);
1179     }
1180 
1181     /**
1182      * Unregisters for unknown connection notifications.
1183      */
1184     @UnsupportedAppUsage
unregisterForUnknownConnection(Handler h)1185     public void unregisterForUnknownConnection(Handler h) {
1186         mUnknownConnectionRegistrants.remove(h);
1187     }
1188 
1189     /**
1190      * Notifies when a new ringing or waiting connection has appeared.<p>
1191      *
1192      *  Messages received from this:
1193      *  Message.obj will be an AsyncResult
1194      *  AsyncResult.userObj = obj
1195      *  AsyncResult.result = a Connection. <p>
1196      *  Please check Connection.isRinging() to make sure the Connection
1197      *  has not dropped since this message was posted.
1198      *  If Connection.isRinging() is true, then
1199      *   Connection.getCall() == Phone.getRingingCall()
1200      */
1201     @UnsupportedAppUsage
registerForNewRingingConnection( Handler h, int what, Object obj)1202     public void registerForNewRingingConnection(
1203             Handler h, int what, Object obj) {
1204         checkCorrectThread(h);
1205 
1206         mNewRingingConnectionRegistrants.addUnique(h, what, obj);
1207     }
1208 
1209     /**
1210      * Unregisters for new ringing connection notification.
1211      * Extraneous calls are tolerated silently
1212      */
1213     @UnsupportedAppUsage
unregisterForNewRingingConnection(Handler h)1214     public void unregisterForNewRingingConnection(Handler h) {
1215         mNewRingingConnectionRegistrants.remove(h);
1216     }
1217 
1218     /**
1219      * Notifies when phone's video capabilities changes <p>
1220      *
1221      *  Messages received from this:
1222      *  Message.obj will be an AsyncResult
1223      *  AsyncResult.userObj = obj
1224      *  AsyncResult.result = true if phone supports video calling <p>
1225      */
registerForVideoCapabilityChanged( Handler h, int what, Object obj)1226     public void registerForVideoCapabilityChanged(
1227             Handler h, int what, Object obj) {
1228         checkCorrectThread(h);
1229 
1230         mVideoCapabilityChangedRegistrants.addUnique(h, what, obj);
1231 
1232         // Notify any registrants of the cached video capability as soon as they register.
1233         notifyForVideoCapabilityChanged(mIsVideoCapable);
1234     }
1235 
1236     /**
1237      * Unregisters for video capability changed notification.
1238      * Extraneous calls are tolerated silently
1239      */
unregisterForVideoCapabilityChanged(Handler h)1240     public void unregisterForVideoCapabilityChanged(Handler h) {
1241         mVideoCapabilityChangedRegistrants.remove(h);
1242     }
1243 
1244     /**
1245      * Register for notifications when a sInCall VoicePrivacy is enabled
1246      *
1247      * @param h Handler that receives the notification message.
1248      * @param what User-defined message code.
1249      * @param obj User object.
1250      */
registerForInCallVoicePrivacyOn(Handler h, int what, Object obj)1251     public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj){
1252         mCi.registerForInCallVoicePrivacyOn(h, what, obj);
1253     }
1254 
1255     /**
1256      * Unegister for notifications when a sInCall VoicePrivacy is enabled
1257      *
1258      * @param h Handler to be removed from the registrant list.
1259      */
unregisterForInCallVoicePrivacyOn(Handler h)1260     public void unregisterForInCallVoicePrivacyOn(Handler h){
1261         mCi.unregisterForInCallVoicePrivacyOn(h);
1262     }
1263 
1264     /**
1265      * Register for notifications when a sInCall VoicePrivacy is disabled
1266      *
1267      * @param h Handler that receives the notification message.
1268      * @param what User-defined message code.
1269      * @param obj User object.
1270      */
registerForInCallVoicePrivacyOff(Handler h, int what, Object obj)1271     public void registerForInCallVoicePrivacyOff(Handler h, int what, Object obj){
1272         mCi.registerForInCallVoicePrivacyOff(h, what, obj);
1273     }
1274 
1275     /**
1276      * Unregister for notifications when a sInCall VoicePrivacy is disabled
1277      *
1278      * @param h Handler to be removed from the registrant list.
1279      */
unregisterForInCallVoicePrivacyOff(Handler h)1280     public void unregisterForInCallVoicePrivacyOff(Handler h){
1281         mCi.unregisterForInCallVoicePrivacyOff(h);
1282     }
1283 
1284     /**
1285      * Notifies when an incoming call rings.<p>
1286      *
1287      *  Messages received from this:
1288      *  Message.obj will be an AsyncResult
1289      *  AsyncResult.userObj = obj
1290      *  AsyncResult.result = a Connection. <p>
1291      */
1292     @UnsupportedAppUsage
registerForIncomingRing( Handler h, int what, Object obj)1293     public void registerForIncomingRing(
1294             Handler h, int what, Object obj) {
1295         checkCorrectThread(h);
1296 
1297         mIncomingRingRegistrants.addUnique(h, what, obj);
1298     }
1299 
1300     /**
1301      * Unregisters for ring notification.
1302      * Extraneous calls are tolerated silently
1303      */
1304     @UnsupportedAppUsage
unregisterForIncomingRing(Handler h)1305     public void unregisterForIncomingRing(Handler h) {
1306         mIncomingRingRegistrants.remove(h);
1307     }
1308 
1309     /**
1310      * Notifies when a voice connection has disconnected, either due to local
1311      * or remote hangup or error.
1312      *
1313      *  Messages received from this will have the following members:<p>
1314      *  <ul><li>Message.obj will be an AsyncResult</li>
1315      *  <li>AsyncResult.userObj = obj</li>
1316      *  <li>AsyncResult.result = a Connection object that is
1317      *  no longer connected.</li></ul>
1318      */
1319     @UnsupportedAppUsage
registerForDisconnect(Handler h, int what, Object obj)1320     public void registerForDisconnect(Handler h, int what, Object obj) {
1321         checkCorrectThread(h);
1322 
1323         mDisconnectRegistrants.addUnique(h, what, obj);
1324     }
1325 
1326     /**
1327      * Unregisters for voice disconnection notification.
1328      * Extraneous calls are tolerated silently
1329      */
1330     @UnsupportedAppUsage
unregisterForDisconnect(Handler h)1331     public void unregisterForDisconnect(Handler h) {
1332         mDisconnectRegistrants.remove(h);
1333     }
1334 
1335     /**
1336      * Register for notifications when a supplementary service attempt fails.
1337      * Message.obj will contain an AsyncResult.
1338      *
1339      * @param h Handler that receives the notification message.
1340      * @param what User-defined message code.
1341      * @param obj User object.
1342      */
registerForSuppServiceFailed(Handler h, int what, Object obj)1343     public void registerForSuppServiceFailed(Handler h, int what, Object obj) {
1344         checkCorrectThread(h);
1345 
1346         mSuppServiceFailedRegistrants.addUnique(h, what, obj);
1347     }
1348 
1349     /**
1350      * Unregister for notifications when a supplementary service attempt fails.
1351      * Extraneous calls are tolerated silently
1352      *
1353      * @param h Handler to be removed from the registrant list.
1354      */
unregisterForSuppServiceFailed(Handler h)1355     public void unregisterForSuppServiceFailed(Handler h) {
1356         mSuppServiceFailedRegistrants.remove(h);
1357     }
1358 
1359     /**
1360      * Register for notifications of initiation of a new MMI code request.
1361      * MMI codes for GSM are discussed in 3GPP TS 22.030.<p>
1362      *
1363      * Example: If Phone.dial is called with "*#31#", then the app will
1364      * be notified here.<p>
1365      *
1366      * The returned <code>Message.obj</code> will contain an AsyncResult.
1367      *
1368      * <code>obj.result</code> will be an "MmiCode" object.
1369      */
1370     @UnsupportedAppUsage
registerForMmiInitiate(Handler h, int what, Object obj)1371     public void registerForMmiInitiate(Handler h, int what, Object obj) {
1372         checkCorrectThread(h);
1373 
1374         mMmiRegistrants.addUnique(h, what, obj);
1375     }
1376 
1377     /**
1378      * Unregisters for new MMI initiate notification.
1379      * Extraneous calls are tolerated silently
1380      */
1381     @UnsupportedAppUsage
unregisterForMmiInitiate(Handler h)1382     public void unregisterForMmiInitiate(Handler h) {
1383         mMmiRegistrants.remove(h);
1384     }
1385 
1386     /**
1387      * Register for notifications that an MMI request has completed
1388      * its network activity and is in its final state. This may mean a state
1389      * of COMPLETE, FAILED, or CANCELLED.
1390      *
1391      * <code>Message.obj</code> will contain an AsyncResult.
1392      * <code>obj.result</code> will be an "MmiCode" object
1393      */
1394     @UnsupportedAppUsage
registerForMmiComplete(Handler h, int what, Object obj)1395     public void registerForMmiComplete(Handler h, int what, Object obj) {
1396         checkCorrectThread(h);
1397 
1398         mMmiCompleteRegistrants.addUnique(h, what, obj);
1399     }
1400 
1401     /**
1402      * Unregisters for MMI complete notification.
1403      * Extraneous calls are tolerated silently
1404      */
1405     @UnsupportedAppUsage
unregisterForMmiComplete(Handler h)1406     public void unregisterForMmiComplete(Handler h) {
1407         checkCorrectThread(h);
1408 
1409         mMmiCompleteRegistrants.remove(h);
1410     }
1411 
1412     /**
1413      * Registration point for Sim records loaded
1414      * @param h handler to notify
1415      * @param what what code of message when delivered
1416      * @param obj placed in Message.obj
1417      */
1418     @UnsupportedAppUsage
registerForSimRecordsLoaded(Handler h, int what, Object obj)1419     public void registerForSimRecordsLoaded(Handler h, int what, Object obj) {
1420     }
1421 
1422     /**
1423      * Unregister for notifications for Sim records loaded
1424      * @param h Handler to be removed from the registrant list.
1425      */
1426     @UnsupportedAppUsage
unregisterForSimRecordsLoaded(Handler h)1427     public void unregisterForSimRecordsLoaded(Handler h) {
1428     }
1429 
1430     /**
1431      * Register for TTY mode change notifications from the network.
1432      * Message.obj will contain an AsyncResult.
1433      * AsyncResult.result will be an Integer containing new mode.
1434      *
1435      * @param h Handler that receives the notification message.
1436      * @param what User-defined message code.
1437      * @param obj User object.
1438      */
registerForTtyModeReceived(Handler h, int what, Object obj)1439     public void registerForTtyModeReceived(Handler h, int what, Object obj) {
1440     }
1441 
1442     /**
1443      * Unregisters for TTY mode change notifications.
1444      * Extraneous calls are tolerated silently
1445      *
1446      * @param h Handler to be removed from the registrant list.
1447      */
unregisterForTtyModeReceived(Handler h)1448     public void unregisterForTtyModeReceived(Handler h) {
1449     }
1450 
1451     /**
1452      * Switches network selection mode to "automatic", re-scanning and
1453      * re-selecting a network if appropriate.
1454      *
1455      * @param response The message to dispatch when the network selection
1456      * is complete.
1457      *
1458      * @see #selectNetworkManually(OperatorInfo, boolean, android.os.Message)
1459      */
1460     @UnsupportedAppUsage
setNetworkSelectionModeAutomatic(Message response)1461     public void setNetworkSelectionModeAutomatic(Message response) {
1462         Rlog.d(mLogTag, "setNetworkSelectionModeAutomatic, querying current mode");
1463         // we don't want to do this unnecessarily - it actually causes
1464         // the radio to repeat network selection and is costly
1465         // first check if we're already in automatic mode
1466         Message msg = obtainMessage(EVENT_CHECK_FOR_NETWORK_AUTOMATIC);
1467         msg.obj = response;
1468         mCi.getNetworkSelectionMode(msg);
1469     }
1470 
onCheckForNetworkSelectionModeAutomatic(Message fromRil)1471     private void onCheckForNetworkSelectionModeAutomatic(Message fromRil) {
1472         AsyncResult ar = (AsyncResult)fromRil.obj;
1473         Message response = (Message)ar.userObj;
1474         boolean doAutomatic = true;
1475         if (ar.exception == null && ar.result != null) {
1476             try {
1477                 int[] modes = (int[])ar.result;
1478                 if (modes[0] == 0) {
1479                     // already confirmed to be in automatic mode - don't resend
1480                     doAutomatic = false;
1481                 }
1482             } catch (Exception e) {
1483                 // send the setting on error
1484             }
1485         }
1486 
1487         // wrap the response message in our own message along with
1488         // an empty string (to indicate automatic selection) for the
1489         // operator's id.
1490         NetworkSelectMessage nsm = new NetworkSelectMessage();
1491         nsm.message = response;
1492         nsm.operatorNumeric = "";
1493         nsm.operatorAlphaLong = "";
1494         nsm.operatorAlphaShort = "";
1495 
1496         if (doAutomatic) {
1497             Rlog.d(mLogTag, "setNetworkSelectionModeAutomatic - set network selection auto");
1498             Message msg = obtainMessage(EVENT_SET_NETWORK_AUTOMATIC_COMPLETE, nsm);
1499             mCi.setNetworkSelectionModeAutomatic(msg);
1500         } else {
1501             Rlog.d(mLogTag, "setNetworkSelectionModeAutomatic - already auto, ignoring");
1502             // let the calling application know that the we are ignoring automatic mode switch.
1503             if (nsm.message != null) {
1504                 nsm.message.arg1 = ALREADY_IN_AUTO_SELECTION;
1505             }
1506 
1507             ar.userObj = nsm;
1508             handleSetSelectNetwork(ar);
1509         }
1510 
1511         updateSavedNetworkOperator(nsm);
1512     }
1513 
1514     /**
1515      * Called when setting network selection mode is complete.
1516      */
onSetNetworkSelectionModeCompleted()1517     protected void onSetNetworkSelectionModeCompleted() {
1518     }
1519 
1520     /**
1521      * Query the radio for the current network selection mode.
1522      *
1523      * Return values:
1524      *     0 - automatic.
1525      *     1 - manual.
1526      */
getNetworkSelectionMode(Message message)1527     public void getNetworkSelectionMode(Message message) {
1528         mCi.getNetworkSelectionMode(message);
1529     }
1530 
getClientRequestStats()1531     public List<ClientRequestStats> getClientRequestStats() {
1532         return mCi.getClientRequestStats();
1533     }
1534 
1535     /**
1536      * Manually selects a network. <code>response</code> is
1537      * dispatched when this is complete.  <code>response.obj</code> will be
1538      * an AsyncResult, and <code>response.obj.exception</code> will be non-null
1539      * on failure.
1540      *
1541      * @see #setNetworkSelectionModeAutomatic(Message)
1542      */
1543     @UnsupportedAppUsage
selectNetworkManually(OperatorInfo network, boolean persistSelection, Message response)1544     public void selectNetworkManually(OperatorInfo network, boolean persistSelection,
1545             Message response) {
1546         // wrap the response message in our own message along with
1547         // the operator's id.
1548         NetworkSelectMessage nsm = new NetworkSelectMessage();
1549         nsm.message = response;
1550         nsm.operatorNumeric = network.getOperatorNumeric();
1551         nsm.operatorAlphaLong = network.getOperatorAlphaLong();
1552         nsm.operatorAlphaShort = network.getOperatorAlphaShort();
1553 
1554         Message msg = obtainMessage(EVENT_SET_NETWORK_MANUAL_COMPLETE, nsm);
1555         mCi.setNetworkSelectionModeManual(network.getOperatorNumeric(), network.getRan(), msg);
1556 
1557         if (persistSelection) {
1558             updateSavedNetworkOperator(nsm);
1559         } else {
1560             clearSavedNetworkSelection();
1561             updateManualNetworkSelection(nsm);
1562         }
1563     }
1564 
1565     /**
1566      * Registration point for emergency call/callback mode start. Message.obj is AsyncResult and
1567      * Message.obj.result will be Integer indicating start of call by value 1 or end of call by
1568      * value 0
1569      * @param h handler to notify
1570      * @param what what code of message when delivered
1571      * @param obj placed in Message.obj.userObj
1572      */
registerForEmergencyCallToggle(Handler h, int what, Object obj)1573     public void registerForEmergencyCallToggle(Handler h, int what, Object obj) {
1574         Registrant r = new Registrant(h, what, obj);
1575         mEmergencyCallToggledRegistrants.add(r);
1576     }
1577 
unregisterForEmergencyCallToggle(Handler h)1578     public void unregisterForEmergencyCallToggle(Handler h) {
1579         mEmergencyCallToggledRegistrants.remove(h);
1580     }
1581 
updateSavedNetworkOperator(NetworkSelectMessage nsm)1582     private void updateSavedNetworkOperator(NetworkSelectMessage nsm) {
1583         int subId = getSubId();
1584         if (SubscriptionManager.isValidSubscriptionId(subId)) {
1585             // open the shared preferences editor, and write the value.
1586             // nsm.operatorNumeric is "" if we're in automatic.selection.
1587             SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
1588             SharedPreferences.Editor editor = sp.edit();
1589             editor.putString(NETWORK_SELECTION_KEY + subId, nsm.operatorNumeric);
1590             editor.putString(NETWORK_SELECTION_NAME_KEY + subId, nsm.operatorAlphaLong);
1591             editor.putString(NETWORK_SELECTION_SHORT_KEY + subId, nsm.operatorAlphaShort);
1592 
1593             // commit and log the result.
1594             if (!editor.commit()) {
1595                 Rlog.e(mLogTag, "failed to commit network selection preference");
1596             }
1597         } else {
1598             Rlog.e(mLogTag, "Cannot update network selection preference due to invalid subId " +
1599                     subId);
1600         }
1601     }
1602 
1603     /**
1604      * Update non-perisited manual network selection.
1605      *
1606      * @param nsm PLMN info of the selected network
1607      */
updateManualNetworkSelection(NetworkSelectMessage nsm)1608     protected void updateManualNetworkSelection(NetworkSelectMessage nsm)  {
1609         Rlog.e(mLogTag, "updateManualNetworkSelection() should be overridden");
1610     }
1611 
1612     /**
1613      * Used to track the settings upon completion of the network change.
1614      */
handleSetSelectNetwork(AsyncResult ar)1615     private void handleSetSelectNetwork(AsyncResult ar) {
1616         // look for our wrapper within the asyncresult, skip the rest if it
1617         // is null.
1618         if (!(ar.userObj instanceof NetworkSelectMessage)) {
1619             Rlog.e(mLogTag, "unexpected result from user object.");
1620             return;
1621         }
1622 
1623         NetworkSelectMessage nsm = (NetworkSelectMessage) ar.userObj;
1624 
1625         // found the object, now we send off the message we had originally
1626         // attached to the request.
1627         if (nsm.message != null) {
1628             AsyncResult.forMessage(nsm.message, ar.result, ar.exception);
1629             nsm.message.sendToTarget();
1630         }
1631     }
1632 
1633     /**
1634      * Method to retrieve the saved operator from the Shared Preferences
1635      */
1636     @NonNull
getSavedNetworkSelection()1637     public OperatorInfo getSavedNetworkSelection() {
1638         // open the shared preferences and search with our key.
1639         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
1640         String numeric = sp.getString(NETWORK_SELECTION_KEY + getSubId(), "");
1641         String name = sp.getString(NETWORK_SELECTION_NAME_KEY + getSubId(), "");
1642         String shrt = sp.getString(NETWORK_SELECTION_SHORT_KEY + getSubId(), "");
1643         return new OperatorInfo(name, shrt, numeric);
1644     }
1645 
1646     /**
1647      * Clears the saved network selection.
1648      */
clearSavedNetworkSelection()1649     private void clearSavedNetworkSelection() {
1650         // open the shared preferences and search with our key.
1651         PreferenceManager.getDefaultSharedPreferences(getContext()).edit().
1652                 remove(NETWORK_SELECTION_KEY + getSubId()).
1653                 remove(NETWORK_SELECTION_NAME_KEY + getSubId()).
1654                 remove(NETWORK_SELECTION_SHORT_KEY + getSubId()).commit();
1655     }
1656 
1657     /**
1658      * Method to restore the previously saved operator id, or reset to
1659      * automatic selection, all depending upon the value in the shared
1660      * preferences.
1661      */
restoreSavedNetworkSelection(Message response)1662     private void restoreSavedNetworkSelection(Message response) {
1663         // retrieve the operator
1664         OperatorInfo networkSelection = getSavedNetworkSelection();
1665 
1666         // set to auto if the id is empty, otherwise select the network.
1667         if (networkSelection == null || TextUtils.isEmpty(networkSelection.getOperatorNumeric())) {
1668             setNetworkSelectionModeAutomatic(response);
1669         } else {
1670             selectNetworkManually(networkSelection, true, response);
1671         }
1672     }
1673 
1674     /**
1675      * Saves CLIR setting so that we can re-apply it as necessary
1676      * (in case the RIL resets it across reboots).
1677      */
saveClirSetting(int commandInterfaceCLIRMode)1678     public void saveClirSetting(int commandInterfaceCLIRMode) {
1679         // Open the shared preferences editor, and write the value.
1680         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
1681         SharedPreferences.Editor editor = sp.edit();
1682         editor.putInt(CLIR_KEY + getSubId(), commandInterfaceCLIRMode);
1683         Rlog.i(mLogTag, "saveClirSetting: " + CLIR_KEY + getSubId() + "="
1684                 + commandInterfaceCLIRMode);
1685 
1686         // Commit and log the result.
1687         if (!editor.commit()) {
1688             Rlog.e(mLogTag, "Failed to commit CLIR preference");
1689         }
1690     }
1691 
1692     /**
1693      * For unit tests; don't send notifications to "Phone"
1694      * mailbox registrants if true.
1695      */
setUnitTestMode(boolean f)1696     private void setUnitTestMode(boolean f) {
1697         mUnitTestMode = f;
1698     }
1699 
1700     /**
1701      * @return true If unit test mode is enabled
1702      */
getUnitTestMode()1703     public boolean getUnitTestMode() {
1704         return mUnitTestMode;
1705     }
1706 
1707     /**
1708      * To be invoked when a voice call Connection disconnects.
1709      *
1710      * Subclasses of Phone probably want to replace this with a
1711      * version scoped to their packages
1712      */
notifyDisconnectP(Connection cn)1713     protected void notifyDisconnectP(Connection cn) {
1714         AsyncResult ar = new AsyncResult(null, cn, null);
1715         mDisconnectRegistrants.notifyRegistrants(ar);
1716     }
1717 
1718     /**
1719      * Register for ServiceState changed.
1720      * Message.obj will contain an AsyncResult.
1721      * AsyncResult.result will be a ServiceState instance
1722      */
1723     @UnsupportedAppUsage
registerForServiceStateChanged( Handler h, int what, Object obj)1724     public void registerForServiceStateChanged(
1725             Handler h, int what, Object obj) {
1726         mServiceStateRegistrants.add(h, what, obj);
1727     }
1728 
1729     /**
1730      * Unregisters for ServiceStateChange notification.
1731      * Extraneous calls are tolerated silently
1732      */
1733     @UnsupportedAppUsage
unregisterForServiceStateChanged(Handler h)1734     public void unregisterForServiceStateChanged(Handler h) {
1735         mServiceStateRegistrants.remove(h);
1736     }
1737 
1738     /**
1739      * Notifies when out-band ringback tone is needed.<p>
1740      *
1741      *  Messages received from this:
1742      *  Message.obj will be an AsyncResult
1743      *  AsyncResult.userObj = obj
1744      *  AsyncResult.result = boolean, true to start play ringback tone
1745      *                       and false to stop. <p>
1746      */
1747     @UnsupportedAppUsage
registerForRingbackTone(Handler h, int what, Object obj)1748     public void registerForRingbackTone(Handler h, int what, Object obj) {
1749         mCi.registerForRingbackTone(h, what, obj);
1750     }
1751 
1752     /**
1753      * Unregisters for ringback tone notification.
1754      */
1755     @UnsupportedAppUsage
unregisterForRingbackTone(Handler h)1756     public void unregisterForRingbackTone(Handler h) {
1757         mCi.unregisterForRingbackTone(h);
1758     }
1759 
1760     /**
1761      * Notifies when out-band on-hold tone is needed.<p>
1762      *
1763      *  Messages received from this:
1764      *  Message.obj will be an AsyncResult
1765      *  AsyncResult.userObj = obj
1766      *  AsyncResult.result = boolean, true to start play on-hold tone
1767      *                       and false to stop. <p>
1768      */
registerForOnHoldTone(Handler h, int what, Object obj)1769     public void registerForOnHoldTone(Handler h, int what, Object obj) {
1770     }
1771 
1772     /**
1773      * Unregisters for on-hold tone notification.
1774      */
unregisterForOnHoldTone(Handler h)1775     public void unregisterForOnHoldTone(Handler h) {
1776     }
1777 
1778     /**
1779      * Registers the handler to reset the uplink mute state to get
1780      * uplink audio.
1781      */
registerForResendIncallMute(Handler h, int what, Object obj)1782     public void registerForResendIncallMute(Handler h, int what, Object obj) {
1783         mCi.registerForResendIncallMute(h, what, obj);
1784     }
1785 
1786     /**
1787      * Unregisters for resend incall mute notifications.
1788      */
unregisterForResendIncallMute(Handler h)1789     public void unregisterForResendIncallMute(Handler h) {
1790         mCi.unregisterForResendIncallMute(h);
1791     }
1792 
1793     /**
1794      * Registers for CellInfo changed.
1795      * Message.obj will contain an AsyncResult.
1796      * AsyncResult.result will be a List<CellInfo> instance
1797      */
registerForCellInfo( Handler h, int what, Object obj)1798     public void registerForCellInfo(
1799             Handler h, int what, Object obj) {
1800         mCellInfoRegistrants.add(h, what, obj);
1801     }
1802 
1803     /**
1804      * Unregisters for CellInfo notification.
1805      * Extraneous calls are tolerated silently
1806      */
unregisterForCellInfo(Handler h)1807     public void unregisterForCellInfo(Handler h) {
1808         mCellInfoRegistrants.remove(h);
1809     }
1810 
1811     /**
1812      * Enables or disables echo suppression.
1813      */
setEchoSuppressionEnabled()1814     public void setEchoSuppressionEnabled() {
1815         // no need for regular phone
1816     }
1817 
1818     /**
1819      * Subclasses of Phone probably want to replace this with a
1820      * version scoped to their packages
1821      */
notifyServiceStateChangedP(ServiceState ss)1822     protected void notifyServiceStateChangedP(ServiceState ss) {
1823         AsyncResult ar = new AsyncResult(null, new ServiceState(ss), null);
1824         mServiceStateRegistrants.notifyRegistrants(ar);
1825 
1826         mNotifier.notifyServiceState(this);
1827     }
1828 
1829     /**
1830      * Version of notifyServiceStateChangedP which allows us to specify the subId. This is used when
1831      * we send out a final ServiceState update when a phone's subId becomes invalid.
1832      */
notifyServiceStateChangedPForSubId(ServiceState ss, int subId)1833     protected void notifyServiceStateChangedPForSubId(ServiceState ss, int subId) {
1834         AsyncResult ar = new AsyncResult(null, ss, null);
1835         mServiceStateRegistrants.notifyRegistrants(ar);
1836 
1837         mNotifier.notifyServiceStateForSubId(this, ss, subId);
1838     }
1839 
1840     /**
1841      * If this is a simulated phone interface, returns a SimulatedRadioControl.
1842      * @return SimulatedRadioControl if this is a simulated interface;
1843      * otherwise, null.
1844      */
getSimulatedRadioControl()1845     public SimulatedRadioControl getSimulatedRadioControl() {
1846         return mSimulatedRadioControl;
1847     }
1848 
1849     /**
1850      * Verifies the current thread is the same as the thread originally
1851      * used in the initialization of this instance. Throws RuntimeException
1852      * if not.
1853      *
1854      * @exception RuntimeException if the current thread is not
1855      * the thread that originally obtained this Phone instance.
1856      */
checkCorrectThread(Handler h)1857     private void checkCorrectThread(Handler h) {
1858         if (h.getLooper() != mLooper) {
1859             throw new RuntimeException(
1860                     "com.android.internal.telephony.Phone must be used from within one thread");
1861         }
1862     }
1863 
1864     /**
1865      * Set the properties by matching the carrier string in
1866      * a string-array resource
1867      */
getLocaleFromCarrierProperties()1868     @Nullable Locale getLocaleFromCarrierProperties() {
1869         String carrier = SystemProperties.get("ro.carrier");
1870 
1871         if (null == carrier || 0 == carrier.length() || "unknown".equals(carrier)) {
1872             return null;
1873         }
1874 
1875         CharSequence[] carrierLocales = mContext.getResources().getTextArray(
1876                 R.array.carrier_properties);
1877 
1878         for (int i = 0; i < carrierLocales.length; i+=3) {
1879             String c = carrierLocales[i].toString();
1880             if (carrier.equals(c)) {
1881                 return Locale.forLanguageTag(carrierLocales[i + 1].toString().replace('_', '-'));
1882             }
1883         }
1884 
1885         return null;
1886     }
1887 
1888     /**
1889      * Get current coarse-grained voice call state.
1890      * Use {@link #registerForPreciseCallStateChanged(Handler, int, Object)
1891      * registerForPreciseCallStateChanged()} for change notification. <p>
1892      * If the phone has an active call and call waiting occurs,
1893      * then the phone state is RINGING not OFFHOOK
1894      * <strong>Note:</strong>
1895      * This registration point provides notification of finer-grained
1896      * changes.<p>
1897      */
1898     @UnsupportedAppUsage
getState()1899     public abstract PhoneConstants.State getState();
1900 
1901     /**
1902      * Retrieves the IccFileHandler of the Phone instance
1903      */
1904     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIccFileHandler()1905     public IccFileHandler getIccFileHandler(){
1906         UiccCardApplication uiccApplication = mUiccApplication.get();
1907         IccFileHandler fh;
1908 
1909         if (uiccApplication == null) {
1910             Rlog.d(mLogTag, "getIccFileHandler: uiccApplication == null, return null");
1911             fh = null;
1912         } else {
1913             fh = uiccApplication.getIccFileHandler();
1914         }
1915 
1916         Rlog.d(mLogTag, "getIccFileHandler: fh=" + fh);
1917         return fh;
1918     }
1919 
1920     /*
1921      * Retrieves the Handler of the Phone instance
1922      */
getHandler()1923     public Handler getHandler() {
1924         return this;
1925     }
1926 
1927     /**
1928      * Update the phone object if the voice radio technology has changed
1929      *
1930      * @param voiceRadioTech The new voice radio technology
1931      */
updatePhoneObject(int voiceRadioTech)1932     public void updatePhoneObject(int voiceRadioTech) {
1933     }
1934 
1935     /**
1936     * Retrieves the ServiceStateTracker of the phone instance.
1937     */
1938     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getServiceStateTracker()1939     public ServiceStateTracker getServiceStateTracker() {
1940         return null;
1941     }
1942 
1943     /**
1944      * Override to merge into {@link #getServiceState} when telecom has registered a SIM call
1945      * manager that supports over-the-top SIM-based calling (e.g. carrier-provided wi-fi calling
1946      * implementation).
1947      *
1948      * @param hasService Whether or not the SIM call manager currently provides over-the-top voice
1949      */
setVoiceServiceStateOverride(boolean hasService)1950     public void setVoiceServiceStateOverride(boolean hasService) {}
1951 
1952     /**
1953      * Check whether the radio is off for thermal reason.
1954      *
1955      * @return {@code true} only if thermal mitigation is one of the reason for which radio is off.
1956      */
isRadioOffForThermalMitigation()1957     public boolean isRadioOffForThermalMitigation() {
1958         ServiceStateTracker sst = getServiceStateTracker();
1959         return sst != null && sst.getRadioPowerOffReasons()
1960                 .contains(TelephonyManager.RADIO_POWER_REASON_THERMAL);
1961     }
1962 
1963     /**
1964      * @return true if this device supports calling, false otherwise.
1965      */
hasCalling()1966     public boolean hasCalling() {
1967         return TelephonyCapabilities.supportsTelephonyCalling(mFeatureFlags, mContext);
1968     }
1969 
1970     /**
1971      * @return true if this device supports messaging, false otherwise.
1972      */
hasMessaging()1973     public boolean hasMessaging() {
1974         return TelephonyCapabilities.supportsTelephonyMessaging(mFeatureFlags, mContext);
1975     }
1976 
1977     /**
1978      * Retrieves the EmergencyNumberTracker of the phone instance.
1979      */
getEmergencyNumberTracker()1980     public EmergencyNumberTracker getEmergencyNumberTracker() {
1981         return null;
1982     }
1983 
1984     /**
1985     * Get call tracker
1986     */
1987     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getCallTracker()1988     public CallTracker getCallTracker() {
1989         return null;
1990     }
1991 
1992     /**
1993      * @return The instance of access networks manager.
1994      */
getAccessNetworksManager()1995     public AccessNetworksManager getAccessNetworksManager() {
1996         return null;
1997     }
1998 
1999     /**
2000      * Retrieves the DeviceStateMonitor of the phone instance.
2001      */
getDeviceStateMonitor()2002     public DeviceStateMonitor getDeviceStateMonitor() {
2003         return null;
2004     }
2005 
2006     /**
2007      * Retrieves the DisplayInfoController of the phone instance.
2008      */
getDisplayInfoController()2009     public DisplayInfoController getDisplayInfoController() {
2010         return null;
2011     }
2012 
2013     /**
2014      * Retrieves the SignalStrengthController of the phone instance.
2015      */
getSignalStrengthController()2016     public SignalStrengthController getSignalStrengthController() {
2017         Log.wtf(mLogTag, "getSignalStrengthController return null.");
2018         return null;
2019     }
2020 
2021     /**
2022      * Update voice activation state
2023      */
setVoiceActivationState(int state)2024     public void setVoiceActivationState(int state) {
2025         mSimActivationTracker.setVoiceActivationState(state);
2026     }
2027     /**
2028      * Update data activation state
2029      */
setDataActivationState(int state)2030     public void setDataActivationState(int state) {
2031         mSimActivationTracker.setDataActivationState(state);
2032     }
2033 
2034     /**
2035      * Returns voice activation state
2036      */
getVoiceActivationState()2037     public int getVoiceActivationState() {
2038         return mSimActivationTracker.getVoiceActivationState();
2039     }
2040     /**
2041      * Returns data activation state
2042      */
getDataActivationState()2043     public int getDataActivationState() {
2044         return mSimActivationTracker.getDataActivationState();
2045     }
2046 
2047     /**
2048      * Update voice mail count related fields and notify listeners
2049      */
updateVoiceMail()2050     public void updateVoiceMail() {
2051         Rlog.e(mLogTag, "updateVoiceMail() should be overridden");
2052     }
2053 
getCurrentUiccAppType()2054     public AppType getCurrentUiccAppType() {
2055         UiccCardApplication currentApp = mUiccApplication.get();
2056         if (currentApp != null) {
2057             return currentApp.getType();
2058         }
2059         return AppType.APPTYPE_UNKNOWN;
2060     }
2061 
2062     /**
2063      * Returns the ICC card interface for this phone, or null
2064      * if not applicable to underlying technology.
2065      */
2066     @UnsupportedAppUsage
getIccCard()2067     public IccCard getIccCard() {
2068         return null;
2069         //throw new Exception("getIccCard Shouldn't be called from Phone");
2070     }
2071 
2072     /**
2073      * Retrieves the serial number of the ICC, if applicable. Returns only the decimal digits before
2074      * the first hex digit in the ICC ID.
2075      */
2076     @UnsupportedAppUsage
getIccSerialNumber()2077     public String getIccSerialNumber() {
2078         IccRecords r = mIccRecords.get();
2079         return (r != null) ? r.getIccId() : null;
2080     }
2081 
2082     /**
2083      * Retrieves the full serial number of the ICC (including hex digits), if applicable.
2084      */
getFullIccSerialNumber()2085     public String getFullIccSerialNumber() {
2086         IccRecords r = mIccRecords.get();
2087         return (r != null) ? r.getFullIccId() : null;
2088     }
2089 
2090     /**
2091      * Returns SIM record load state. Use
2092      * <code>getSimCard().registerForReady()</code> for change notification.
2093      *
2094      * @return true if records from the SIM have been loaded and are
2095      * available (if applicable). If not applicable to the underlying
2096      * technology, returns true as well.
2097      */
getIccRecordsLoaded()2098     public boolean getIccRecordsLoaded() {
2099         IccRecords r = mIccRecords.get();
2100         return (r != null) ? r.getRecordsLoaded() : false;
2101     }
2102 
2103     /** Set the minimum interval for CellInfo requests to the modem */
setCellInfoMinInterval(int interval)2104     public void setCellInfoMinInterval(int interval) {
2105         getServiceStateTracker().setCellInfoMinInterval(interval);
2106     }
2107 
2108     /**
2109      * @return the last known CellInfo
2110      */
getAllCellInfo()2111     public List<CellInfo> getAllCellInfo() {
2112         return getServiceStateTracker().getAllCellInfo();
2113     }
2114 
2115     /**
2116      * @param workSource calling WorkSource
2117      * @param rspMsg the response message containing the cell info
2118      */
requestCellInfoUpdate(WorkSource workSource, Message rspMsg)2119     public void requestCellInfoUpdate(WorkSource workSource, Message rspMsg) {
2120         getServiceStateTracker().requestAllCellInfo(workSource, rspMsg);
2121     }
2122 
2123     /**
2124      * Returns the current CellIdentity if known
2125      */
getCurrentCellIdentity()2126     public CellIdentity getCurrentCellIdentity() {
2127         return getServiceStateTracker().getCellIdentity();
2128     }
2129 
2130     /**
2131      * @param workSource calling WorkSource
2132      * @param rspMsg the response message containing the cell location
2133      */
getCellIdentity(WorkSource workSource, Message rspMsg)2134     public void getCellIdentity(WorkSource workSource, Message rspMsg) {
2135         getServiceStateTracker().requestCellIdentity(workSource, rspMsg);
2136     }
2137 
2138     /**
2139      * Sets the minimum time in milli-seconds between {@link PhoneStateListener#onCellInfoChanged
2140      * PhoneStateListener.onCellInfoChanged} will be invoked.
2141      *
2142      * The default, 0, means invoke onCellInfoChanged when any of the reported
2143      * information changes. Setting the value to INT_MAX(0x7fffffff) means never issue
2144      * A onCellInfoChanged.
2145      *
2146      * @param rateInMillis the rate
2147      * @param workSource calling WorkSource
2148      */
setCellInfoListRate(int rateInMillis, WorkSource workSource)2149     public void setCellInfoListRate(int rateInMillis, WorkSource workSource) {
2150         mCi.setCellInfoListRate(rateInMillis, null, workSource);
2151     }
2152 
2153     /**
2154      * Get voice message waiting indicator status. No change notification
2155      * available on this interface. Use PhoneStateNotifier or similar instead.
2156      *
2157      * @return true if there is a voice message waiting
2158      */
getMessageWaitingIndicator()2159     public boolean getMessageWaitingIndicator() {
2160         return mVmCount != 0;
2161     }
2162 
2163     /**
2164      *  Retrieves manually selected network info.
2165      */
getManualNetworkSelectionPlmn()2166     public String getManualNetworkSelectionPlmn() {
2167         return null;
2168     }
2169 
2170 
getCallForwardingIndicatorFromSharedPref()2171     private int getCallForwardingIndicatorFromSharedPref() {
2172         int status = IccRecords.CALL_FORWARDING_STATUS_DISABLED;
2173         int subId = getSubId();
2174         if (SubscriptionManager.isValidSubscriptionId(subId)) {
2175             SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
2176             status = sp.getInt(CF_STATUS + subId, IccRecords.CALL_FORWARDING_STATUS_UNKNOWN);
2177             Rlog.d(mLogTag, "getCallForwardingIndicatorFromSharedPref: for subId " + subId + "= " +
2178                     status);
2179             // Check for old preference if status is UNKNOWN for current subId. This part of the
2180             // code is needed only when upgrading from M to N.
2181             if (status == IccRecords.CALL_FORWARDING_STATUS_UNKNOWN) {
2182                 String subscriberId = sp.getString(CF_ID, null);
2183                 if (subscriberId != null) {
2184                     String currentSubscriberId = getSubscriberId();
2185 
2186                     if (subscriberId.equals(currentSubscriberId)) {
2187                         // get call forwarding status from preferences
2188                         status = sp.getInt(CF_STATUS, IccRecords.CALL_FORWARDING_STATUS_DISABLED);
2189                         setCallForwardingIndicatorInSharedPref(
2190                                 status == IccRecords.CALL_FORWARDING_STATUS_ENABLED ? true : false);
2191                         Rlog.d(mLogTag, "getCallForwardingIndicatorFromSharedPref: " + status);
2192                     } else {
2193                         Rlog.d(mLogTag, "getCallForwardingIndicatorFromSharedPref: returning " +
2194                                 "DISABLED as status for matching subscriberId not found");
2195                     }
2196 
2197                     // get rid of old preferences.
2198                     SharedPreferences.Editor editor = sp.edit();
2199                     editor.remove(CF_ID);
2200                     editor.remove(CF_STATUS);
2201                     editor.apply();
2202                 }
2203             }
2204         } else {
2205             Rlog.e(mLogTag, "getCallForwardingIndicatorFromSharedPref: invalid subId " + subId);
2206         }
2207         return status;
2208     }
2209 
setCallForwardingIndicatorInSharedPref(boolean enable)2210     private void setCallForwardingIndicatorInSharedPref(boolean enable) {
2211         int status = enable ? IccRecords.CALL_FORWARDING_STATUS_ENABLED :
2212                 IccRecords.CALL_FORWARDING_STATUS_DISABLED;
2213         int subId = getSubId();
2214         Rlog.i(mLogTag, "setCallForwardingIndicatorInSharedPref: Storing status = " + status +
2215                 " in pref " + CF_STATUS + subId);
2216 
2217         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
2218         SharedPreferences.Editor editor = sp.edit();
2219         editor.putInt(CF_STATUS + subId, status);
2220         editor.apply();
2221     }
2222 
setVoiceCallForwardingFlag(int line, boolean enable, String number)2223     public void setVoiceCallForwardingFlag(int line, boolean enable, String number) {
2224         setCallForwardingIndicatorInSharedPref(enable);
2225         IccRecords r = getIccRecords();
2226         if (r != null) {
2227             r.setVoiceCallForwardingFlag(line, enable, number);
2228         }
2229         notifyCallForwardingIndicator();
2230     }
2231 
2232     /**
2233      * Set the voice call forwarding flag for GSM/UMTS and the like SIMs
2234      *
2235      * @param r to enable/disable
2236      * @param line to enable/disable
2237      * @param enable
2238      * @param number to which CFU is enabled
2239      */
setVoiceCallForwardingFlag(IccRecords r, int line, boolean enable, String number)2240     public void setVoiceCallForwardingFlag(IccRecords r, int line, boolean enable,
2241                                               String number) {
2242         setCallForwardingIndicatorInSharedPref(enable);
2243         if (r != null) {
2244             r.setVoiceCallForwardingFlag(line, enable, number);
2245         }
2246         notifyCallForwardingIndicator();
2247     }
2248 
2249     /**
2250      * Get voice call forwarding indicator status. No change notification
2251      * available on this interface. Use PhoneStateNotifier or similar instead.
2252      *
2253      * @return true if there is a voice call forwarding
2254      */
getCallForwardingIndicator()2255     public boolean getCallForwardingIndicator() {
2256         if (getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
2257             Rlog.e(mLogTag, "getCallForwardingIndicator: not possible in CDMA");
2258             return false;
2259         }
2260         IccRecords r = getIccRecords();
2261         int callForwardingIndicator = IccRecords.CALL_FORWARDING_STATUS_UNKNOWN;
2262         if (r != null) {
2263             callForwardingIndicator = r.getVoiceCallForwardingFlag();
2264         }
2265         if (callForwardingIndicator == IccRecords.CALL_FORWARDING_STATUS_UNKNOWN) {
2266             callForwardingIndicator = getCallForwardingIndicatorFromSharedPref();
2267         }
2268         Rlog.v(mLogTag, "getCallForwardingIndicator: iccForwardingFlag=" + (r != null
2269                     ? r.getVoiceCallForwardingFlag() : "null") + ", sharedPrefFlag="
2270                     + getCallForwardingIndicatorFromSharedPref());
2271         return (callForwardingIndicator == IccRecords.CALL_FORWARDING_STATUS_ENABLED);
2272     }
2273 
getCarrierSignalAgent()2274     public CarrierSignalAgent getCarrierSignalAgent() {
2275         return mCarrierSignalAgent;
2276     }
2277 
getCarrierActionAgent()2278     public CarrierActionAgent getCarrierActionAgent() {
2279         return mCarrierActionAgent;
2280     }
2281 
2282     /**
2283      * Query the CDMA roaming preference setting.
2284      *
2285      * @param response is callback message to report one of TelephonyManager#CDMA_ROAMING_MODE_*
2286      */
queryCdmaRoamingPreference(Message response)2287     public void queryCdmaRoamingPreference(Message response) {
2288         if (mFeatureFlags.cleanupCdma()) return;
2289         mCi.queryCdmaRoamingPreference(response);
2290     }
2291 
2292     /**
2293      * Get the CDMA subscription mode setting.
2294      *
2295      * @param response is callback message to report one of TelephonyManager#CDMA_SUBSCRIPTION_*
2296      */
queryCdmaSubscriptionMode(Message response)2297     public void queryCdmaSubscriptionMode(Message response) {
2298         if (mFeatureFlags.cleanupCdma()) return;
2299         mCi.getCdmaSubscriptionSource(response);
2300     }
2301 
2302     /**
2303      * Get current signal strength. No change notification available on this
2304      * interface. Use <code>PhoneStateNotifier</code> or an equivalent.
2305      * An ASU is 0-31 or -1 if unknown (for GSM, dBm = -113 - 2 * asu).
2306      * The following special values are defined:</p>
2307      * <ul><li>0 means "-113 dBm or less".</li>
2308      * <li>31 means "-51 dBm or greater".</li></ul>
2309      *
2310      * @return Current signal strength as SignalStrength
2311      */
getSignalStrength()2312     public @NonNull SignalStrength getSignalStrength() {
2313         SignalStrengthController ssc = getSignalStrengthController();
2314         if (ssc == null) {
2315             return new SignalStrength();
2316         } else {
2317             return ssc.getSignalStrength();
2318         }
2319     }
2320 
2321     /**
2322      * @return true, if the device is in a state where both voice and data
2323      * are supported simultaneously. This can change based on location or network condition.
2324      */
isConcurrentVoiceAndDataAllowed()2325     public boolean isConcurrentVoiceAndDataAllowed() {
2326         ServiceStateTracker sst = getServiceStateTracker();
2327         return sst == null ? false : sst.isConcurrentVoiceAndDataAllowed();
2328     }
2329 
2330     /**
2331      * Requests to set the CDMA roaming preference
2332      * @param cdmaRoamingType one of TelephonyManager#CDMA_ROAMING_MODE_*
2333      * @param response is callback message
2334      */
setCdmaRoamingPreference(int cdmaRoamingType, Message response)2335     public void setCdmaRoamingPreference(int cdmaRoamingType, Message response) {
2336         if (mFeatureFlags.cleanupCdma()) return;
2337         mCi.setCdmaRoamingPreference(cdmaRoamingType, response);
2338     }
2339 
2340     /**
2341      * Requests to set the CDMA subscription mode
2342      * @param cdmaSubscriptionType one of TelephonyManager#CDMA_SUBSCRIPTION_*
2343      * @param response is callback message
2344      */
setCdmaSubscriptionMode(int cdmaSubscriptionType, Message response)2345     public void setCdmaSubscriptionMode(int cdmaSubscriptionType, Message response) {
2346         if (mFeatureFlags.cleanupCdma()) return;
2347         mCi.setCdmaSubscriptionSource(cdmaSubscriptionType, response);
2348     }
2349 
2350     /**
2351      * Get the effective allowed network types on the device.
2352      *
2353      * @return effective network type
2354      */
getEffectiveAllowedNetworkTypes()2355     private @TelephonyManager.NetworkTypeBitMask long getEffectiveAllowedNetworkTypes() {
2356         long allowedNetworkTypes = TelephonyManager.getAllNetworkTypesBitmask();
2357         synchronized (mAllowedNetworkTypesForReasons) {
2358             for (long networkTypes : mAllowedNetworkTypesForReasons.values()) {
2359                 allowedNetworkTypes = allowedNetworkTypes & networkTypes;
2360             }
2361         }
2362         if (!mIsCarrierNrSupported) {
2363             allowedNetworkTypes &= ~TelephonyManager.NETWORK_TYPE_BITMASK_NR;
2364         }
2365         if (m2gAdminUpdater.isCellular2gDisabled()) {
2366             logd("SubId " + getSubId()
2367                     + " disabling 2g in getEffectiveAllowedNetworkTypes according to admin user "
2368                     + "restriction");
2369             allowedNetworkTypes &= ~TelephonyManager.NETWORK_CLASS_BITMASK_2G;
2370         }
2371         logd("SubId" + getSubId() + ",getEffectiveAllowedNetworkTypes: "
2372                 + TelephonyManager.convertNetworkTypeBitmaskToString(allowedNetworkTypes));
2373         return allowedNetworkTypes;
2374     }
2375 
2376     /**
2377      * Notify the latest allowed network types changed.
2378      */
notifyAllowedNetworkTypesChanged( @elephonyManager.AllowedNetworkTypesReason int reason)2379     public void notifyAllowedNetworkTypesChanged(
2380             @TelephonyManager.AllowedNetworkTypesReason int reason) {
2381         logd("SubId" + getSubId() + ",notifyAllowedNetworkTypesChanged: reason: " + reason
2382                 + " value:" + TelephonyManager.convertNetworkTypeBitmaskToString(
2383                 getAllowedNetworkTypes(reason)));
2384         mNotifier.notifyAllowedNetworkTypesChanged(this, reason, getAllowedNetworkTypes(reason));
2385     }
2386 
2387     /**
2388      * Is E-UTRA-NR Dual Connectivity enabled
2389      */
isNrDualConnectivityEnabled(Message message, WorkSource workSource)2390     public void isNrDualConnectivityEnabled(Message message, WorkSource workSource) {
2391         mCi.isNrDualConnectivityEnabled(message, workSource);
2392     }
2393 
2394     /**
2395      * Enable/Disable E-UTRA-NR Dual Connectivity
2396      * @param nrDualConnectivityState expected NR dual connectivity state
2397      * This can be passed following states
2398      * <ol>
2399      * <li>Enable NR dual connectivity {@link TelephonyManager#NR_DUAL_CONNECTIVITY_ENABLE}
2400      * <li>Disable NR dual connectivity {@link TelephonyManager#NR_DUAL_CONNECTIVITY_DISABLE}
2401      * <li>Disable NR dual connectivity and force secondary cell to be released
2402      * {@link TelephonyManager#NR_DUAL_CONNECTIVITY_DISABLE_IMMEDIATE}
2403      * </ol>
2404      */
setNrDualConnectivityState( @elephonyManager.NrDualConnectivityState int nrDualConnectivityState, Message message, WorkSource workSource)2405     public void setNrDualConnectivityState(
2406             @TelephonyManager.NrDualConnectivityState int nrDualConnectivityState,
2407             Message message, WorkSource workSource) {
2408         mCi.setNrDualConnectivityState(nrDualConnectivityState, message, workSource);
2409     }
2410 
2411     /**
2412      * Get the allowed network types for a certain reason.
2413      * @param reason reason to configure allowed network types
2414      * @return the allowed network types.
2415      */
getAllowedNetworkTypes( @elephonyManager.AllowedNetworkTypesReason int reason)2416     public @TelephonyManager.NetworkTypeBitMask long getAllowedNetworkTypes(
2417             @TelephonyManager.AllowedNetworkTypesReason int reason) {
2418         long allowedNetworkTypes;
2419         long defaultAllowedNetworkTypes = RadioAccessFamily.getRafFromNetworkType(
2420                 RILConstants.PREFERRED_NETWORK_MODE);
2421 
2422         if (!TelephonyManager.isValidAllowedNetworkTypesReason(reason)) {
2423             throw new IllegalArgumentException("AllowedNetworkTypes NumberFormat exception");
2424         }
2425 
2426         synchronized (mAllowedNetworkTypesForReasons) {
2427             allowedNetworkTypes = mAllowedNetworkTypesForReasons.getOrDefault(
2428                     reason,
2429                     defaultAllowedNetworkTypes);
2430         }
2431         if (!mIsCarrierNrSupported
2432                 && reason == TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER) {
2433             allowedNetworkTypes = updateAllowedNetworkTypeForCarrierWithCarrierConfig();
2434         }
2435         logd("SubId" + getSubId() + ",get allowed network types "
2436                 + convertAllowedNetworkTypeMapIndexToDbName(reason)
2437                 + ": value = " + TelephonyManager.convertNetworkTypeBitmaskToString(
2438                 allowedNetworkTypes));
2439         return allowedNetworkTypes;
2440     }
2441 
2442     /**
2443      * Loads the allowed network type from subscription database.
2444      */
loadAllowedNetworksFromSubscriptionDatabase()2445     public void loadAllowedNetworksFromSubscriptionDatabase() {
2446         String result = null;
2447         SubscriptionInfoInternal subInfo = mSubscriptionManagerService
2448                 .getSubscriptionInfoInternal(getSubId());
2449         if (subInfo != null) {
2450             result = subInfo.getAllowedNetworkTypesForReasons();
2451         }
2452 
2453         // After fw load network type from DB, do unlock if subId is valid.
2454         mIsAllowedNetworkTypesLoadedFromDb = SubscriptionManager.isValidSubscriptionId(
2455                 getSubId());
2456 
2457         if (TextUtils.isEmpty(result)) {
2458             return;
2459         }
2460 
2461         logd("SubId" + getSubId() + ",load allowed network types : value = " + result);
2462         Map<Integer, Long> oldAllowedNetworkTypes = new HashMap<>(mAllowedNetworkTypesForReasons);
2463         mAllowedNetworkTypesForReasons.clear();
2464         try {
2465             // Format: "REASON=VALUE,REASON2=VALUE2"
2466             for (String pair : result.trim().split(",")) {
2467                 String[] networkTypesValues = (pair.trim().toLowerCase(Locale.ROOT)).split("=");
2468                 if (networkTypesValues.length != 2) {
2469                     Rlog.e(mLogTag, "Invalid ALLOWED_NETWORK_TYPES from DB, value = " + pair);
2470                     continue;
2471                 }
2472                 int key = convertAllowedNetworkTypeDbNameToMapIndex(networkTypesValues[0]);
2473                 long value = Long.parseLong(networkTypesValues[1]);
2474                 if (TelephonyManager.isValidAllowedNetworkTypesReason(key)
2475                         && value != INVALID_ALLOWED_NETWORK_TYPES) {
2476                     synchronized (mAllowedNetworkTypesForReasons) {
2477                         mAllowedNetworkTypesForReasons.put(key, value);
2478                     }
2479                     if (!oldAllowedNetworkTypes.containsKey(key)
2480                             || oldAllowedNetworkTypes.get(key) != value) {
2481                         if (oldAllowedNetworkTypes.containsKey(key)) {
2482                             oldAllowedNetworkTypes.remove(key);
2483                         }
2484                         notifyAllowedNetworkTypesChanged(key);
2485                     }
2486                 }
2487             }
2488         } catch (NumberFormatException e) {
2489             Rlog.e(mLogTag, "allowedNetworkTypes NumberFormat exception" + e);
2490         }
2491 
2492         for (int key : oldAllowedNetworkTypes.keySet()) {
2493             notifyAllowedNetworkTypesChanged(key);
2494         }
2495     }
2496 
convertAllowedNetworkTypeDbNameToMapIndex(String name)2497     private int convertAllowedNetworkTypeDbNameToMapIndex(String name) {
2498         switch (name) {
2499             case ALLOWED_NETWORK_TYPES_TEXT_USER:
2500                 return TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER;
2501             case ALLOWED_NETWORK_TYPES_TEXT_POWER:
2502                 return TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER;
2503             case ALLOWED_NETWORK_TYPES_TEXT_CARRIER:
2504                 return TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER;
2505             case ALLOWED_NETWORK_TYPES_TEXT_ENABLE_2G:
2506                 return TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G;
2507             case ALLOWED_NETWORK_TYPES_TEXT_TEST:
2508                 return TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_TEST;
2509             default:
2510                 return INVALID_ALLOWED_NETWORK_TYPES;
2511         }
2512     }
2513 
2514     /**
2515      * Convert the allowed network types reason to string.
2516      *
2517      * @param reason The allowed network types reason.
2518      *
2519      * @return The converted string.
2520      */
convertAllowedNetworkTypeMapIndexToDbName( @elephonyManager.AllowedNetworkTypesReason int reason)2521     public static String convertAllowedNetworkTypeMapIndexToDbName(
2522             @TelephonyManager.AllowedNetworkTypesReason int reason) {
2523         switch (reason) {
2524             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER:
2525                 return ALLOWED_NETWORK_TYPES_TEXT_USER;
2526             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_POWER:
2527                 return ALLOWED_NETWORK_TYPES_TEXT_POWER;
2528             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER:
2529                 return ALLOWED_NETWORK_TYPES_TEXT_CARRIER;
2530             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G:
2531                 return ALLOWED_NETWORK_TYPES_TEXT_ENABLE_2G;
2532             case TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_TEST:
2533                 return ALLOWED_NETWORK_TYPES_TEXT_TEST;
2534             default:
2535                 throw new IllegalArgumentException(
2536                         "No DB name conversion available for allowed network type reason: " + reason
2537                                 + ". Did you forget to add an ALLOWED_NETWORK_TYPE_TEXT entry for"
2538                                 + " a new reason?");
2539         }
2540     }
2541 
2542     private @TelephonyManager.NetworkTypeBitMask long
updateAllowedNetworkTypeForCarrierWithCarrierConfig()2543             updateAllowedNetworkTypeForCarrierWithCarrierConfig() {
2544         long defaultAllowedNetworkTypes = RadioAccessFamily.getRafFromNetworkType(
2545                 RILConstants.PREFERRED_NETWORK_MODE);
2546         long allowedNetworkTypes;
2547         synchronized (mAllowedNetworkTypesForReasons) {
2548             allowedNetworkTypes = mAllowedNetworkTypesForReasons.getOrDefault(
2549                     TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_CARRIER,
2550                     defaultAllowedNetworkTypes);
2551         }
2552         if (mIsCarrierNrSupported) {
2553             return allowedNetworkTypes;
2554         }
2555         allowedNetworkTypes = allowedNetworkTypes & ~TelephonyManager.NETWORK_TYPE_BITMASK_NR;
2556 
2557         logd("Allowed network types for 'carrier' reason is changed by carrier config = "
2558                 + TelephonyManager.convertNetworkTypeBitmaskToString(allowedNetworkTypes));
2559         return allowedNetworkTypes;
2560     }
2561 
2562     /**
2563      * Requests to set the allowed network types for a specific reason
2564      *
2565      * @param reason reason to configure allowed network type
2566      * @param networkTypes one of the network types
2567      * @param response callback Message
2568      */
setAllowedNetworkTypes(@elephonyManager.AllowedNetworkTypesReason int reason, @TelephonyManager.NetworkTypeBitMask long networkTypes, @Nullable Message response)2569     public void setAllowedNetworkTypes(@TelephonyManager.AllowedNetworkTypesReason int reason,
2570             @TelephonyManager.NetworkTypeBitMask long networkTypes, @Nullable Message response) {
2571         int subId = getSubId();
2572         if (!TelephonyManager.isValidAllowedNetworkTypesReason(reason)) {
2573             loge("setAllowedNetworkTypes: Invalid allowed network type reason: " + reason);
2574             if (response != null) {
2575                 AsyncResult.forMessage(response, null,
2576                         new CommandException(CommandException.Error.INVALID_ARGUMENTS));
2577                 response.sendToTarget();
2578             }
2579             return;
2580         }
2581         if (!SubscriptionManager.isUsableSubscriptionId(subId)
2582                 || !mIsAllowedNetworkTypesLoadedFromDb) {
2583             loge("setAllowedNetworkTypes: no sim or network type is not loaded. SubscriptionId: "
2584                     + subId + ", isNetworkTypeLoaded" + mIsAllowedNetworkTypesLoadedFromDb);
2585             if (response != null) {
2586                 AsyncResult.forMessage(response, null,
2587                         new CommandException(CommandException.Error.MISSING_RESOURCE));
2588                 response.sendToTarget();
2589             }
2590             return;
2591         }
2592         String mapAsString = "";
2593         synchronized (mAllowedNetworkTypesForReasons) {
2594             mAllowedNetworkTypesForReasons.put(reason, networkTypes);
2595             mapAsString = mAllowedNetworkTypesForReasons.keySet().stream()
2596                     .map(key -> convertAllowedNetworkTypeMapIndexToDbName(key) + "="
2597                             + mAllowedNetworkTypesForReasons.get(key))
2598                     .collect(Collectors.joining(","));
2599         }
2600         SubscriptionManager.setSubscriptionProperty(subId,
2601                 SubscriptionManager.ALLOWED_NETWORK_TYPES,
2602                 mapAsString);
2603         logd("setAllowedNetworkTypes: SubId" + subId + ",setAllowedNetworkTypes " + mapAsString);
2604 
2605         updateAllowedNetworkTypes(response);
2606         notifyAllowedNetworkTypesChanged(reason);
2607     }
2608 
updateAllowedNetworkTypes(Message response)2609     protected void updateAllowedNetworkTypes(Message response) {
2610         int modemRaf = getRadioAccessFamily();
2611         if (modemRaf == RadioAccessFamily.RAF_UNKNOWN) {
2612             Rlog.d(mLogTag, "setPreferredNetworkType: Abort, unknown RAF: "
2613                     + modemRaf);
2614             if (response != null) {
2615                 CommandException ex;
2616                 ex = new CommandException(CommandException.Error.GENERIC_FAILURE);
2617                 AsyncResult.forMessage(response, null, ex);
2618                 response.sendToTarget();
2619             }
2620             return;
2621         }
2622 
2623         int filteredRaf = (int) (modemRaf & getEffectiveAllowedNetworkTypes());
2624 
2625         logd("setAllowedNetworkTypes: modemRafBitMask = " + modemRaf
2626                 + " ,modemRaf = " + TelephonyManager.convertNetworkTypeBitmaskToString(modemRaf)
2627                 + " ,filteredRafBitMask = " + filteredRaf
2628                 + " ,filteredRaf = " + TelephonyManager.convertNetworkTypeBitmaskToString(
2629                 filteredRaf));
2630         mCi.setAllowedNetworkTypesBitmap(filteredRaf, response);
2631         mPreferredNetworkTypeRegistrants.notifyRegistrants();
2632     }
2633 
2634     /**
2635      * Query the allowed network types bitmask setting
2636      *
2637      * @param response is callback message to report network types bitmask
2638      */
getAllowedNetworkTypesBitmask(Message response)2639     public void getAllowedNetworkTypesBitmask(Message response) {
2640         mCi.getAllowedNetworkTypesBitmap(response);
2641     }
2642 
2643     /**
2644      * Register for preferred network type changes
2645      *
2646      * @param h Handler that receives the notification message.
2647      * @param what User-defined message code.
2648      * @param obj User object.
2649      */
registerForPreferredNetworkTypeChanged(Handler h, int what, Object obj)2650     public void registerForPreferredNetworkTypeChanged(Handler h, int what, Object obj) {
2651         checkCorrectThread(h);
2652         mPreferredNetworkTypeRegistrants.addUnique(h, what, obj);
2653     }
2654 
2655     /**
2656      * Unregister for preferred network type changes.
2657      *
2658      * @param h Handler that should be unregistered.
2659      */
unregisterForPreferredNetworkTypeChanged(Handler h)2660     public void unregisterForPreferredNetworkTypeChanged(Handler h) {
2661         mPreferredNetworkTypeRegistrants.remove(h);
2662     }
2663 
2664     /**
2665      * Get the cached value of the preferred network type setting
2666      */
getCachedAllowedNetworkTypesBitmask()2667     public int getCachedAllowedNetworkTypesBitmask() {
2668         if (mCi != null && mCi instanceof BaseCommands) {
2669             return ((BaseCommands) mCi).mAllowedNetworkTypesBitmask;
2670         } else {
2671             return RadioAccessFamily.getRafFromNetworkType(RILConstants.PREFERRED_NETWORK_MODE);
2672         }
2673     }
2674 
2675     /**
2676      * Gets the default SMSC address.
2677      *
2678      * @param result Callback message contains the SMSC address.
2679      */
2680     @UnsupportedAppUsage
getSmscAddress(Message result)2681     public void getSmscAddress(Message result) {
2682         mCi.getSmscAddress(result);
2683     }
2684 
2685     /**
2686      * Sets the default SMSC address.
2687      *
2688      * @param address new SMSC address
2689      * @param result Callback message is empty on completion
2690      */
2691     @UnsupportedAppUsage
setSmscAddress(String address, Message result)2692     public void setSmscAddress(String address, Message result) {
2693         mCi.setSmscAddress(address, result);
2694     }
2695 
2696     /**
2697      * setTTYMode
2698      * sets a TTY mode option.
2699      * @param ttyMode is a one of the following:
2700      * - {@link com.android.internal.telephony.Phone#TTY_MODE_OFF}
2701      * - {@link com.android.internal.telephony.Phone#TTY_MODE_FULL}
2702      * - {@link com.android.internal.telephony.Phone#TTY_MODE_HCO}
2703      * - {@link com.android.internal.telephony.Phone#TTY_MODE_VCO}
2704      * @param onComplete a callback message when the action is completed
2705      */
setTTYMode(int ttyMode, Message onComplete)2706     public void setTTYMode(int ttyMode, Message onComplete) {
2707         mCi.setTTYMode(ttyMode, onComplete);
2708     }
2709 
2710     /**
2711      * setUiTTYMode
2712      * sets a TTY mode option.
2713      * @param ttyMode is a one of the following:
2714      * - {@link com.android.internal.telephony.Phone#TTY_MODE_OFF}
2715      * - {@link com.android.internal.telephony.Phone#TTY_MODE_FULL}
2716      * - {@link com.android.internal.telephony.Phone#TTY_MODE_HCO}
2717      * - {@link com.android.internal.telephony.Phone#TTY_MODE_VCO}
2718      * @param onComplete a callback message when the action is completed
2719      */
setUiTTYMode(int uiTtyMode, Message onComplete)2720     public void setUiTTYMode(int uiTtyMode, Message onComplete) {
2721         Rlog.d(mLogTag, "unexpected setUiTTYMode method call");
2722     }
2723 
2724     /**
2725      * queryTTYMode
2726      * query the status of the TTY mode
2727      *
2728      * @param onComplete a callback message when the action is completed.
2729      */
queryTTYMode(Message onComplete)2730     public void queryTTYMode(Message onComplete) {
2731         mCi.queryTTYMode(onComplete);
2732     }
2733 
2734     /**
2735      * Enable or disable enhanced Voice Privacy (VP). If enhanced VP is
2736      * disabled, normal VP is enabled.
2737      *
2738      * @param enable whether true or false to enable or disable.
2739      * @param onComplete a callback message when the action is completed.
2740      */
enableEnhancedVoicePrivacy(boolean enable, Message onComplete)2741     public void enableEnhancedVoicePrivacy(boolean enable, Message onComplete) {
2742     }
2743 
2744     /**
2745      * Get the currently set Voice Privacy (VP) mode.
2746      *
2747      * @param onComplete a callback message when the action is completed.
2748      */
getEnhancedVoicePrivacy(Message onComplete)2749     public void getEnhancedVoicePrivacy(Message onComplete) {
2750     }
2751 
2752     /**
2753      * Assign a specified band for RF configuration.
2754      *
2755      * @param bandMode one of BM_*_BAND
2756      * @param response is callback message
2757      */
setBandMode(int bandMode, Message response)2758     public void setBandMode(int bandMode, Message response) {
2759         mCi.setBandMode(bandMode, response);
2760     }
2761 
2762     /**
2763      * Query the list of band mode supported by RF.
2764      *
2765      * @param response is callback message
2766      *        ((AsyncResult)response.obj).result  is an int[] where int[0] is
2767      *        the size of the array and the rest of each element representing
2768      *        one available BM_*_BAND
2769      */
queryAvailableBandMode(Message response)2770     public void queryAvailableBandMode(Message response) {
2771         mCi.queryAvailableBandMode(response);
2772     }
2773 
2774     /**
2775      * Read one of the NV items defined in {@link RadioNVItems} / {@code ril_nv_items.h}.
2776      * Used for device configuration by some CDMA operators.
2777      *
2778      * @param itemID the ID of the item to read
2779      * @param response callback message with the String response in the obj field
2780      * @param workSource calling WorkSource
2781      */
nvReadItem(int itemID, Message response, WorkSource workSource)2782     public void nvReadItem(int itemID, Message response, WorkSource workSource) {
2783         if (mFeatureFlags.cleanupCdma()) return;
2784         mCi.nvReadItem(itemID, response, workSource);
2785     }
2786 
2787     /**
2788      * Write one of the NV items defined in {@link RadioNVItems} / {@code ril_nv_items.h}.
2789      * Used for device configuration by some CDMA operators.
2790      *
2791      * @param itemID the ID of the item to read
2792      * @param itemValue the value to write, as a String
2793      * @param response Callback message.
2794      * @param workSource calling WorkSource
2795      */
nvWriteItem(int itemID, String itemValue, Message response, WorkSource workSource)2796     public void nvWriteItem(int itemID, String itemValue, Message response,
2797             WorkSource workSource) {
2798         if (mFeatureFlags.cleanupCdma()) return;
2799         mCi.nvWriteItem(itemID, itemValue, response, workSource);
2800     }
2801 
2802     /**
2803      * Update the CDMA Preferred Roaming List (PRL) in the radio NV storage.
2804      * Used for device configuration by some CDMA operators.
2805      *
2806      * @param preferredRoamingList byte array containing the new PRL
2807      * @param response Callback message.
2808      */
nvWriteCdmaPrl(byte[] preferredRoamingList, Message response)2809     public void nvWriteCdmaPrl(byte[] preferredRoamingList, Message response) {
2810         if (mFeatureFlags.cleanupCdma()) return;
2811         mCi.nvWriteCdmaPrl(preferredRoamingList, response);
2812     }
2813 
2814     /**
2815      * Perform the radio modem reboot. The radio will be taken offline. Used for device
2816      * configuration by some CDMA operators.
2817      * TODO: reuse nvResetConfig for now, should move to separate HAL API.
2818      *
2819      * @param response Callback message.
2820      */
rebootModem(Message response)2821     public void rebootModem(Message response) {
2822         mCi.nvResetConfig(1 /* 1: reload NV reset, trigger a modem reboot */, response);
2823     }
2824 
2825     /**
2826      * Perform the modem configuration reset. Used for device configuration by some CDMA operators.
2827      * TODO: reuse nvResetConfig for now, should move to separate HAL API.
2828      *
2829      * @param response Callback message.
2830      */
resetModemConfig(Message response)2831     public void resetModemConfig(Message response) {
2832         if (mFeatureFlags.cleanupCdma()) return;
2833         mCi.nvResetConfig(3 /* factory NV reset */, response);
2834     }
2835 
2836     /**
2837      * Perform modem configuration erase. Used for network reset
2838      *
2839      * @param response Callback message.
2840      */
eraseModemConfig(Message response)2841     public void eraseModemConfig(Message response) {
2842         if (mFeatureFlags.cleanupCdma()) return;
2843         mCi.nvResetConfig(2 /* erase NV */, response);
2844     }
2845 
2846     /**
2847      * Erase data saved in the SharedPreference. Used for network reset
2848      *
2849      */
eraseDataInSharedPreferences()2850     public boolean eraseDataInSharedPreferences() {
2851         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
2852         SharedPreferences.Editor editor = sp.edit();
2853         Rlog.d(mLogTag, "Erase all data saved in SharedPreferences");
2854         editor.clear();
2855         return editor.commit();
2856     }
2857 
setSystemSelectionChannels(List<RadioAccessSpecifier> specifiers, Message response)2858     public void setSystemSelectionChannels(List<RadioAccessSpecifier> specifiers,
2859             Message response) {
2860         mCi.setSystemSelectionChannels(specifiers, response);
2861     }
2862 
2863     /**
2864      * Get which bands the modem's background scan is acting on.
2865      *
2866      * @param response Callback message.
2867      */
getSystemSelectionChannels(Message response)2868     public void getSystemSelectionChannels(Message response) {
2869         mCi.getSystemSelectionChannels(response);
2870     }
2871 
notifyDataActivity()2872     public void notifyDataActivity() {
2873         mNotifier.notifyDataActivity(this);
2874     }
2875 
notifyMessageWaitingIndicator()2876     private void notifyMessageWaitingIndicator() {
2877         // Do not notify voice mail waiting if device doesn't support voice
2878         if (!mIsVoiceCapable)
2879             return;
2880 
2881         // This function is added to send the notification to DefaultPhoneNotifier.
2882         mNotifier.notifyMessageWaitingChanged(this);
2883     }
2884 
2885     /** Send notification with an updated PreciseDataConnectionState to a single data connection */
notifyDataConnection(PreciseDataConnectionState state)2886     public void notifyDataConnection(PreciseDataConnectionState state) {
2887         mNotifier.notifyDataConnection(this, state);
2888     }
2889 
2890     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
notifyOtaspChanged(int otaspMode)2891     public void notifyOtaspChanged(int otaspMode) {
2892         mOtaspRegistrants.notifyRegistrants(new AsyncResult(null, otaspMode, null));
2893     }
2894 
notifyVoiceActivationStateChanged(int state)2895     public void notifyVoiceActivationStateChanged(int state) {
2896         mNotifier.notifyVoiceActivationStateChanged(this, state);
2897     }
2898 
notifyDataActivationStateChanged(int state)2899     public void notifyDataActivationStateChanged(int state) {
2900         mNotifier.notifyDataActivationStateChanged(this, state);
2901     }
2902 
notifyUserMobileDataStateChanged(boolean state)2903     public void notifyUserMobileDataStateChanged(boolean state) {
2904         mNotifier.notifyUserMobileDataStateChanged(this, state);
2905     }
2906 
2907     /** Send notification that display info has changed. */
notifyDisplayInfoChanged(TelephonyDisplayInfo telephonyDisplayInfo)2908     public void notifyDisplayInfoChanged(TelephonyDisplayInfo telephonyDisplayInfo) {
2909         mNotifier.notifyDisplayInfoChanged(this, telephonyDisplayInfo);
2910     }
2911 
notifySignalStrength()2912     public void notifySignalStrength() {
2913         mNotifier.notifySignalStrength(this);
2914     }
2915 
getDataConnectionState(String apnType)2916     public PhoneConstants.DataState getDataConnectionState(String apnType) {
2917         return PhoneConstants.DataState.DISCONNECTED;
2918     }
2919 
2920     /** Default implementation to get the PreciseDataConnectionState */
getPreciseDataConnectionState(String apnType)2921     public @Nullable PreciseDataConnectionState getPreciseDataConnectionState(String apnType) {
2922         return null;
2923     }
2924 
notifyCellInfo(List<CellInfo> cellInfo)2925     public void notifyCellInfo(List<CellInfo> cellInfo) {
2926         AsyncResult ar = new AsyncResult(null, cellInfo, null);
2927         mCellInfoRegistrants.notifyRegistrants(ar);
2928 
2929         mNotifier.notifyCellInfo(this, cellInfo);
2930     }
2931 
2932     /**
2933      * Registration point for PhysicalChannelConfig change.
2934      * @param h handler to notify
2935      * @param what what code of message when delivered
2936      * @param obj placed in Message.obj.userObj
2937      */
registerForPhysicalChannelConfig(Handler h, int what, Object obj)2938     public void registerForPhysicalChannelConfig(Handler h, int what, Object obj) {
2939         checkCorrectThread(h);
2940         Registrant registrant = new Registrant(h, what, obj);
2941         mPhysicalChannelConfigRegistrants.add(registrant);
2942         // notify first
2943         List<PhysicalChannelConfig> physicalChannelConfigs = getPhysicalChannelConfigList();
2944         if (physicalChannelConfigs != null) {
2945             registrant.notifyRegistrant(new AsyncResult(null, physicalChannelConfigs, null));
2946         }
2947     }
2948 
unregisterForPhysicalChannelConfig(Handler h)2949     public void unregisterForPhysicalChannelConfig(Handler h) {
2950         mPhysicalChannelConfigRegistrants.remove(h);
2951     }
2952 
2953     /** Notify {@link PhysicalChannelConfig} changes. */
notifyPhysicalChannelConfig(List<PhysicalChannelConfig> configs)2954     public void notifyPhysicalChannelConfig(List<PhysicalChannelConfig> configs) {
2955         mPhysicalChannelConfigRegistrants.notifyRegistrants(new AsyncResult(null, configs, null));
2956         mNotifier.notifyPhysicalChannelConfig(this, configs);
2957     }
2958 
getPhysicalChannelConfigList()2959     public List<PhysicalChannelConfig> getPhysicalChannelConfigList() {
2960         return null;
2961     }
2962 
2963     /**
2964      * Notify listeners that SRVCC state has changed.
2965      */
notifySrvccStateChanged(int state)2966     public void notifySrvccStateChanged(int state) {
2967         mNotifier.notifySrvccStateChanged(this, state);
2968     }
2969 
2970     /** Notify the {@link EmergencyNumber} changes. */
notifyEmergencyNumberList()2971     public void notifyEmergencyNumberList() {
2972         mNotifier.notifyEmergencyNumberList(this);
2973     }
2974 
2975     /** Notify the outgoing Sms {@link EmergencyNumber} changes. */
notifyOutgoingEmergencySms(EmergencyNumber emergencyNumber)2976     public void notifyOutgoingEmergencySms(EmergencyNumber emergencyNumber) {
2977         mNotifier.notifyOutgoingEmergencySms(this, emergencyNumber);
2978     }
2979 
2980     /** Notify the data enabled changes. */
notifyDataEnabled(boolean enabled, @TelephonyManager.DataEnabledReason int reason)2981     public void notifyDataEnabled(boolean enabled,
2982             @TelephonyManager.DataEnabledReason int reason) {
2983         mNotifier.notifyDataEnabled(this, enabled, reason);
2984     }
2985 
2986     /** Notify link capacity estimate has changed. */
notifyLinkCapacityEstimateChanged( List<LinkCapacityEstimate> linkCapacityEstimateList)2987     public void notifyLinkCapacityEstimateChanged(
2988             List<LinkCapacityEstimate> linkCapacityEstimateList) {
2989         mNotifier.notifyLinkCapacityEstimateChanged(this, linkCapacityEstimateList);
2990     }
2991 
2992     /**
2993      * @return true if a mobile originating emergency call is active
2994      */
isInEmergencyCall()2995     public boolean isInEmergencyCall() {
2996         return false;
2997     }
2998 
2999     // This property is used to handle phone process crashes, and is the same for CDMA and IMS
3000     // phones
getInEcmMode()3001     protected static boolean getInEcmMode() {
3002         if (DomainSelectionResolver.getInstance().isDomainSelectionSupported()) {
3003             return EmergencyStateTracker.getInstance().isInEcm();
3004         }
3005         return TelephonyProperties.in_ecm_mode().orElse(false);
3006     }
3007 
3008     /**
3009      * @return {@code true} if we are in emergency call back mode. This is a period where the phone
3010      * should be using as little power as possible and be ready to receive an incoming call from the
3011      * emergency operator.
3012      */
isInEcm()3013     public boolean isInEcm() {
3014         if (DomainSelectionResolver.getInstance().isDomainSelectionSupported()) {
3015             return EmergencyStateTracker.getInstance().isInEcm();
3016         }
3017         return mIsPhoneInEcmState;
3018     }
3019 
isInImsEcm()3020     public boolean isInImsEcm() {
3021         return false;
3022     }
3023 
isInCdmaEcm()3024     public boolean isInCdmaEcm() {
3025         if (DomainSelectionResolver.getInstance().isDomainSelectionSupported()) {
3026             return EmergencyStateTracker.getInstance().isInCdmaEcm();
3027         }
3028         return getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA && isInEcm()
3029                 && (mImsPhone == null || !mImsPhone.isInImsEcm());
3030     }
3031 
setIsInEcm(boolean isInEcm)3032     public void setIsInEcm(boolean isInEcm) {
3033         if (!getUnitTestMode()) {
3034             TelephonyProperties.in_ecm_mode(isInEcm);
3035         }
3036         mIsPhoneInEcmState = isInEcm;
3037     }
3038 
3039     /**
3040      * @return true if this Phone is in an emergency call that caused emergency callback mode to be
3041      * canceled, false if not.
3042      */
isEcmCanceledForEmergency()3043     public boolean isEcmCanceledForEmergency() {
3044         return mEcmCanceledForEmergency;
3045     }
3046 
3047     /**
3048      * Set whether or not this Phone has an active emergency call that was placed during emergency
3049      * callback mode and caused it to be temporarily canceled.
3050      * @param isCanceled true if an emergency call was placed that caused ECM to be canceled, false
3051      *                   if it is not in this state.
3052      */
setEcmCanceledForEmergency(boolean isCanceled)3053     public void setEcmCanceledForEmergency(boolean isCanceled) {
3054         mEcmCanceledForEmergency = isCanceled;
3055     }
3056 
3057     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getVideoState(Call call)3058     private static int getVideoState(Call call) {
3059         int videoState = VideoProfile.STATE_AUDIO_ONLY;
3060         Connection conn = call.getEarliestConnection();
3061         if (conn != null) {
3062             videoState = conn.getVideoState();
3063         }
3064         return videoState;
3065     }
3066 
3067     /**
3068      * Determines if the specified call currently is or was at some point a video call, or if it is
3069      * a conference call.
3070      * @param call The call.
3071      * @return {@code true} if the call is or was a video call or is a conference call,
3072      *      {@code false} otherwise.
3073      */
isVideoCallOrConference(Call call)3074     private boolean isVideoCallOrConference(Call call) {
3075         if (call.isMultiparty()) {
3076             return true;
3077         }
3078 
3079         boolean isDowngradedVideoCall = false;
3080         if (call instanceof ImsPhoneCall) {
3081             ImsPhoneCall imsPhoneCall = (ImsPhoneCall) call;
3082             ImsCall imsCall = imsPhoneCall.getImsCall();
3083             return imsCall != null && (imsCall.isVideoCall() ||
3084                     imsCall.wasVideoCall());
3085         }
3086         return isDowngradedVideoCall;
3087     }
3088 
3089     /**
3090      * @return {@code true} if an IMS video call or IMS conference is present, false otherwise.
3091      */
isImsVideoCallOrConferencePresent()3092     public boolean isImsVideoCallOrConferencePresent() {
3093         boolean isPresent = false;
3094         if (mImsPhone != null) {
3095             isPresent = isVideoCallOrConference(mImsPhone.getForegroundCall()) ||
3096                     isVideoCallOrConference(mImsPhone.getBackgroundCall()) ||
3097                     isVideoCallOrConference(mImsPhone.getRingingCall());
3098         }
3099         Rlog.d(mLogTag, "isImsVideoCallOrConferencePresent: " + isPresent);
3100         return isPresent;
3101     }
3102 
3103     /**
3104      * Return a numerical identifier for the phone radio interface.
3105      * @return PHONE_TYPE_XXX as defined above.
3106      */
3107     @UnsupportedAppUsage
getPhoneType()3108     public abstract int getPhoneType();
3109 
3110     /**
3111      * Returns unread voicemail count. This count is shown when the  voicemail
3112      * notification is expanded.<p>
3113      */
getVoiceMessageCount()3114     public int getVoiceMessageCount(){
3115         return mVmCount;
3116     }
3117 
3118     /** sets the voice mail count of the phone and notifies listeners. */
setVoiceMessageCount(int countWaiting)3119     public void setVoiceMessageCount(int countWaiting) {
3120         mVmCount = countWaiting;
3121         int subId = getSubId();
3122         if (SubscriptionManager.isValidSubscriptionId(subId)) {
3123 
3124             Rlog.d(mLogTag, "setVoiceMessageCount: Storing Voice Mail Count = " + countWaiting +
3125                     " for mVmCountKey = " + VM_COUNT + subId + " in preferences.");
3126 
3127             SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
3128             SharedPreferences.Editor editor = sp.edit();
3129             editor.putInt(VM_COUNT + subId, countWaiting);
3130             editor.apply();
3131         } else {
3132             Rlog.e(mLogTag, "setVoiceMessageCount in sharedPreference: invalid subId " + subId);
3133         }
3134         // store voice mail count in SIM
3135         IccRecords records = UiccController.getInstance().getIccRecords(
3136                 mPhoneId, UiccController.APP_FAM_3GPP);
3137         if (records != null) {
3138             Rlog.d(mLogTag, "setVoiceMessageCount: updating SIM Records");
3139             records.setVoiceMessageWaiting(1, countWaiting);
3140         } else {
3141             Rlog.d(mLogTag, "setVoiceMessageCount: SIM Records not found");
3142         }
3143         // notify listeners of voice mail
3144         notifyMessageWaitingIndicator();
3145     }
3146 
3147     /** gets the voice mail count from preferences */
getStoredVoiceMessageCount()3148     protected int getStoredVoiceMessageCount() {
3149         int countVoiceMessages = 0;
3150         int subId = getSubId();
3151         if (SubscriptionManager.isValidSubscriptionId(subId)) {
3152             int invalidCount = -2;  //-1 is not really invalid. It is used for unknown number of vm
3153             SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
3154             int countFromSP = sp.getInt(VM_COUNT + subId, invalidCount);
3155             if (countFromSP != invalidCount) {
3156                 countVoiceMessages = countFromSP;
3157                 Rlog.d(mLogTag, "getStoredVoiceMessageCount: from preference for subId " + subId +
3158                         "= " + countVoiceMessages);
3159             } else {
3160                 // Check for old preference if count not found for current subId. This part of the
3161                 // code is needed only when upgrading from M to N.
3162                 String subscriberId = sp.getString(VM_ID, null);
3163                 if (subscriberId != null) {
3164                     String currentSubscriberId = getSubscriberId();
3165 
3166                     if (currentSubscriberId != null && currentSubscriberId.equals(subscriberId)) {
3167                         // get voice mail count from preferences
3168                         countVoiceMessages = sp.getInt(VM_COUNT, 0);
3169                         setVoiceMessageCount(countVoiceMessages);
3170                         Rlog.d(mLogTag, "getStoredVoiceMessageCount: from preference = " +
3171                                 countVoiceMessages);
3172                     } else {
3173                         Rlog.d(mLogTag, "getStoredVoiceMessageCount: returning 0 as count for " +
3174                                 "matching subscriberId not found");
3175 
3176                     }
3177                     // get rid of old preferences.
3178                     SharedPreferences.Editor editor = sp.edit();
3179                     editor.remove(VM_ID);
3180                     editor.remove(VM_COUNT);
3181                     editor.apply();
3182                 }
3183             }
3184         } else {
3185             Rlog.e(mLogTag, "getStoredVoiceMessageCount: invalid subId " + subId);
3186         }
3187         return countVoiceMessages;
3188     }
3189 
3190     /**
3191      * send secret dialer codes to launch arbitrary activities.
3192      * an Intent is started with the android_secret_code://<code> URI.
3193      *
3194      * @param code stripped version of secret code without *#*# prefix and #*#* suffix
3195      */
sendDialerSpecialCode(String code)3196     public void sendDialerSpecialCode(String code) {
3197         if (!TextUtils.isEmpty(code)) {
3198             final BroadcastOptions options = BroadcastOptions.makeBasic();
3199             options.setBackgroundActivityStartsAllowed(true);
3200             Intent intent = new Intent(TelephonyIntents.SECRET_CODE_ACTION,
3201                     Uri.parse("android_secret_code://" + code));
3202             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3203             if (mFeatureFlags.hsumBroadcast()) {
3204                 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, null, options.toBundle());
3205             } else {
3206                 mContext.sendBroadcast(intent, null, options.toBundle());
3207             }
3208 
3209             // {@link TelephonyManager.ACTION_SECRET_CODE} will replace {@link
3210             // TelephonyIntents#SECRET_CODE_ACTION} in the next Android version. Before
3211             // that both of these two actions will be broadcast.
3212             Intent secrectCodeIntent = new Intent(TelephonyManager.ACTION_SECRET_CODE,
3213                     Uri.parse("android_secret_code://" + code));
3214             secrectCodeIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3215             if (mFeatureFlags.hsumBroadcast()) {
3216                 mContext.sendBroadcastAsUser(secrectCodeIntent, UserHandle.ALL, null,
3217                         options.toBundle());
3218             } else {
3219                 mContext.sendBroadcast(secrectCodeIntent, null, options.toBundle());
3220             }
3221         }
3222     }
3223 
3224     /**
3225      * Returns the CDMA ERI icon index to display
3226      */
getCdmaEriIconIndex()3227     public int getCdmaEriIconIndex() {
3228         return -1;
3229     }
3230 
3231     /**
3232      * Returns the CDMA ERI icon mode,
3233      * 0 - ON
3234      * 1 - FLASHING
3235      */
getCdmaEriIconMode()3236     public int getCdmaEriIconMode() {
3237         return -1;
3238     }
3239 
3240     /**
3241      * Returns the CDMA ERI text,
3242      */
getCdmaEriText()3243     public String getCdmaEriText() {
3244         return "GSM nw, no ERI";
3245     }
3246 
3247     /**
3248      * Retrieves the MIN for CDMA phones.
3249      */
getCdmaMin()3250     public String getCdmaMin() {
3251         return null;
3252     }
3253 
3254     /**
3255      * Check if subscription data has been assigned to mMin
3256      *
3257      * return true if MIN info is ready; false otherwise.
3258      */
isMinInfoReady()3259     public boolean isMinInfoReady() {
3260         return false;
3261     }
3262 
3263     /**
3264      *  Retrieves PRL Version for CDMA phones
3265      */
getCdmaPrlVersion()3266     public String getCdmaPrlVersion(){
3267         return null;
3268     }
3269 
3270     /**
3271      * @return {@code true} if data is suspended.
3272      */
isDataSuspended()3273     public boolean isDataSuspended() {
3274         return false;
3275     }
3276 
3277     /**
3278      * send burst DTMF tone, it can send the string as single character or multiple character
3279      * ignore if there is no active call or not valid digits string.
3280      * Valid digit means only includes characters ISO-LATIN characters 0-9, *, #
3281      * The difference between sendDtmf and sendBurstDtmf is sendDtmf only sends one character,
3282      * this api can send single character and multiple character, also, this api has response
3283      * back to caller.
3284      *
3285      * @param dtmfString is string representing the dialing digit(s) in the active call
3286      * @param on the DTMF ON length in milliseconds, or 0 for default
3287      * @param off the DTMF OFF length in milliseconds, or 0 for default
3288      * @param onComplete is the callback message when the action is processed by BP
3289      *
3290      */
sendBurstDtmf(String dtmfString, int on, int off, Message onComplete)3291     public void sendBurstDtmf(String dtmfString, int on, int off, Message onComplete) {
3292     }
3293 
3294     /**
3295      * Sets an event to be fired when the telephony system processes
3296      * a post-dial character on an outgoing call.<p>
3297      *
3298      * Messages of type <code>what</code> will be sent to <code>h</code>.
3299      * The <code>obj</code> field of these Message's will be instances of
3300      * <code>AsyncResult</code>. <code>Message.obj.result</code> will be
3301      * a Connection object.<p>
3302      *
3303      * Message.arg1 will be the post dial character being processed,
3304      * or 0 ('\0') if end of string.<p>
3305      *
3306      * If Connection.getPostDialState() == WAIT,
3307      * the application must call
3308      * {@link com.android.internal.telephony.Connection#proceedAfterWaitChar()
3309      * Connection.proceedAfterWaitChar()} or
3310      * {@link com.android.internal.telephony.Connection#cancelPostDial()
3311      * Connection.cancelPostDial()}
3312      * for the telephony system to continue playing the post-dial
3313      * DTMF sequence.<p>
3314      *
3315      * If Connection.getPostDialState() == WILD,
3316      * the application must call
3317      * {@link com.android.internal.telephony.Connection#proceedAfterWildChar
3318      * Connection.proceedAfterWildChar()}
3319      * or
3320      * {@link com.android.internal.telephony.Connection#cancelPostDial()
3321      * Connection.cancelPostDial()}
3322      * for the telephony system to continue playing the
3323      * post-dial DTMF sequence.<p>
3324      *
3325      * Only one post dial character handler may be set. <p>
3326      * Calling this method with "h" equal to null unsets this handler.<p>
3327      */
3328     @UnsupportedAppUsage
setOnPostDialCharacter(Handler h, int what, Object obj)3329     public void setOnPostDialCharacter(Handler h, int what, Object obj) {
3330         mPostDialHandler = new Registrant(h, what, obj);
3331     }
3332 
getPostDialHandler()3333     public Registrant getPostDialHandler() {
3334         return mPostDialHandler;
3335     }
3336 
3337     /**
3338      * request to exit emergency call back mode
3339      * the caller should use setOnECMModeExitResponse
3340      * to receive the emergency callback mode exit response
3341      */
3342     @UnsupportedAppUsage
exitEmergencyCallbackMode()3343     public void exitEmergencyCallbackMode() {
3344     }
3345 
3346     /**
3347      * Register for notifications when CDMA OTA Provision status change
3348      *
3349      * @param h Handler that receives the notification message.
3350      * @param what User-defined message code.
3351      * @param obj User object.
3352      */
registerForCdmaOtaStatusChange(Handler h, int what, Object obj)3353     public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj) {
3354     }
3355 
3356     /**
3357      * Unregister for notifications when CDMA OTA Provision status change
3358      * @param h Handler to be removed from the registrant list.
3359      */
unregisterForCdmaOtaStatusChange(Handler h)3360     public void unregisterForCdmaOtaStatusChange(Handler h) {
3361     }
3362 
3363     /**
3364      * Registration point for subscription info ready
3365      * @param h handler to notify
3366      * @param what what code of message when delivered
3367      * @param obj placed in Message.obj
3368      */
registerForSubscriptionInfoReady(Handler h, int what, Object obj)3369     public void registerForSubscriptionInfoReady(Handler h, int what, Object obj) {
3370     }
3371 
3372     /**
3373      * Unregister for notifications for subscription info
3374      * @param h Handler to be removed from the registrant list.
3375      */
unregisterForSubscriptionInfoReady(Handler h)3376     public void unregisterForSubscriptionInfoReady(Handler h) {
3377     }
3378 
3379     /**
3380      * Returns true if OTA Service Provisioning needs to be performed.
3381      */
3382     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
needsOtaServiceProvisioning()3383     public boolean needsOtaServiceProvisioning() {
3384         return false;
3385     }
3386 
3387     /**
3388      * this decides if the dial number is OTA(Over the air provision) number or not
3389      * @param dialStr is string representing the dialing digit(s)
3390      * @return  true means the dialStr is OTA number, and false means the dialStr is not OTA number
3391      */
isOtaSpNumber(String dialStr)3392     public  boolean isOtaSpNumber(String dialStr) {
3393         return false;
3394     }
3395 
3396     /**
3397      * Register for notifications when OTA Service Provisioning mode has changed.
3398      *
3399      * <p>The mode is integer. {@link TelephonyManager#OTASP_UNKNOWN}
3400      * means the value is currently unknown and the system should wait until
3401      * {@link TelephonyManager#OTASP_NEEDED} or {@link TelephonyManager#OTASP_NOT_NEEDED} is
3402      * received before making the decision to perform OTASP or not.
3403      *
3404      * @param h Handler that receives the notification message.
3405      * @param what User-defined message code.
3406      * @param obj User object.
3407      */
registerForOtaspChange(Handler h, int what, Object obj)3408     public void registerForOtaspChange(Handler h, int what, Object obj) {
3409         checkCorrectThread(h);
3410         mOtaspRegistrants.addUnique(h, what, obj);
3411         // notify first
3412         new Registrant(h, what, obj).notifyRegistrant(new AsyncResult(null, getOtasp(), null));
3413     }
3414 
3415     /**
3416      * Unegister for notifications when OTA Service Provisioning mode has changed.
3417      * @param h Handler to be removed from the registrant list.
3418      */
unregisterForOtaspChange(Handler h)3419     public void unregisterForOtaspChange(Handler h) {
3420         mOtaspRegistrants.remove(h);
3421     }
3422 
3423     /**
3424      * Returns the current OTA Service Provisioning mode.
3425      *
3426      * @see registerForOtaspChange
3427      */
getOtasp()3428     public int getOtasp() {
3429         return TelephonyManager.OTASP_UNKNOWN;
3430     }
3431 
3432     /**
3433      * Register for notifications when CDMA call waiting comes
3434      *
3435      * @param h Handler that receives the notification message.
3436      * @param what User-defined message code.
3437      * @param obj User object.
3438      */
registerForCallWaiting(Handler h, int what, Object obj)3439     public void registerForCallWaiting(Handler h, int what, Object obj){
3440     }
3441 
3442     /**
3443      * Unegister for notifications when CDMA Call waiting comes
3444      * @param h Handler to be removed from the registrant list.
3445      */
unregisterForCallWaiting(Handler h)3446     public void unregisterForCallWaiting(Handler h){
3447     }
3448 
3449     /**
3450      * Registration point for Ecm timer reset
3451      * @param h handler to notify
3452      * @param what user-defined message code
3453      * @param obj placed in Message.obj
3454      */
3455     @UnsupportedAppUsage
registerForEcmTimerReset(Handler h, int what, Object obj)3456     public void registerForEcmTimerReset(Handler h, int what, Object obj) {
3457     }
3458 
3459     /**
3460      * Unregister for notification for Ecm timer reset
3461      * @param h Handler to be removed from the registrant list.
3462      */
3463     @UnsupportedAppUsage
unregisterForEcmTimerReset(Handler h)3464     public void unregisterForEcmTimerReset(Handler h) {
3465     }
3466 
3467     /**
3468      * Register for signal information notifications from the network.
3469      * Message.obj will contain an AsyncResult.
3470      * AsyncResult.result will be a SuppServiceNotification instance.
3471      *
3472      * @param h Handler that receives the notification message.
3473      * @param what User-defined message code.
3474      * @param obj User object.
3475      */
registerForSignalInfo(Handler h, int what, Object obj)3476     public void registerForSignalInfo(Handler h, int what, Object obj) {
3477         mCi.registerForSignalInfo(h, what, obj);
3478     }
3479 
3480     /**
3481      * Unregisters for signal information notifications.
3482      * Extraneous calls are tolerated silently
3483      *
3484      * @param h Handler to be removed from the registrant list.
3485      */
unregisterForSignalInfo(Handler h)3486     public void unregisterForSignalInfo(Handler h) {
3487         mCi.unregisterForSignalInfo(h);
3488     }
3489 
3490     /**
3491      * Register for display information notifications from the network.
3492      * Message.obj will contain an AsyncResult.
3493      * AsyncResult.result will be a SuppServiceNotification instance.
3494      *
3495      * @param h Handler that receives the notification message.
3496      * @param what User-defined message code.
3497      * @param obj User object.
3498      */
registerForDisplayInfo(Handler h, int what, Object obj)3499     public void registerForDisplayInfo(Handler h, int what, Object obj) {
3500         mCi.registerForDisplayInfo(h, what, obj);
3501     }
3502 
3503     /**
3504      * Unregisters for display information notifications.
3505      * Extraneous calls are tolerated silently
3506      *
3507      * @param h Handler to be removed from the registrant list.
3508      */
unregisterForDisplayInfo(Handler h)3509     public void unregisterForDisplayInfo(Handler h) {
3510          mCi.unregisterForDisplayInfo(h);
3511     }
3512 
3513     /**
3514      * Register for CDMA number information record notification from the network.
3515      * Message.obj will contain an AsyncResult.
3516      * AsyncResult.result will be a CdmaInformationRecords.CdmaNumberInfoRec
3517      * instance.
3518      *
3519      * @param h Handler that receives the notification message.
3520      * @param what User-defined message code.
3521      * @param obj User object.
3522      */
registerForNumberInfo(Handler h, int what, Object obj)3523     public void registerForNumberInfo(Handler h, int what, Object obj) {
3524         if (mFeatureFlags.cleanupCdma()) return;
3525         mCi.registerForNumberInfo(h, what, obj);
3526     }
3527 
3528     /**
3529      * Unregisters for number information record notifications.
3530      * Extraneous calls are tolerated silently
3531      *
3532      * @param h Handler to be removed from the registrant list.
3533      */
unregisterForNumberInfo(Handler h)3534     public void unregisterForNumberInfo(Handler h) {
3535         if (mFeatureFlags.cleanupCdma()) return;
3536         mCi.unregisterForNumberInfo(h);
3537     }
3538 
3539     /**
3540      * Register for CDMA redirected number information record notification
3541      * from the network.
3542      * Message.obj will contain an AsyncResult.
3543      * AsyncResult.result will be a CdmaInformationRecords.CdmaRedirectingNumberInfoRec
3544      * instance.
3545      *
3546      * @param h Handler that receives the notification message.
3547      * @param what User-defined message code.
3548      * @param obj User object.
3549      */
registerForRedirectedNumberInfo(Handler h, int what, Object obj)3550     public void registerForRedirectedNumberInfo(Handler h, int what, Object obj) {
3551         if (mFeatureFlags.cleanupCdma()) return;
3552         mCi.registerForRedirectedNumberInfo(h, what, obj);
3553     }
3554 
3555     /**
3556      * Unregisters for redirected number information record notification.
3557      * Extraneous calls are tolerated silently
3558      *
3559      * @param h Handler to be removed from the registrant list.
3560      */
unregisterForRedirectedNumberInfo(Handler h)3561     public void unregisterForRedirectedNumberInfo(Handler h) {
3562         if (mFeatureFlags.cleanupCdma()) return;
3563         mCi.unregisterForRedirectedNumberInfo(h);
3564     }
3565 
3566     /**
3567      * Register for CDMA line control information record notification
3568      * from the network.
3569      * Message.obj will contain an AsyncResult.
3570      * AsyncResult.result will be a CdmaInformationRecords.CdmaLineControlInfoRec
3571      * instance.
3572      *
3573      * @param h Handler that receives the notification message.
3574      * @param what User-defined message code.
3575      * @param obj User object.
3576      */
registerForLineControlInfo(Handler h, int what, Object obj)3577     public void registerForLineControlInfo(Handler h, int what, Object obj) {
3578         if (mFeatureFlags.cleanupCdma()) return;
3579         mCi.registerForLineControlInfo(h, what, obj);
3580     }
3581 
3582     /**
3583      * Unregisters for line control information notifications.
3584      * Extraneous calls are tolerated silently
3585      *
3586      * @param h Handler to be removed from the registrant list.
3587      */
unregisterForLineControlInfo(Handler h)3588     public void unregisterForLineControlInfo(Handler h) {
3589         if (mFeatureFlags.cleanupCdma()) return;
3590         mCi.unregisterForLineControlInfo(h);
3591     }
3592 
3593     /**
3594      * Register for CDMA T53 CLIR information record notifications
3595      * from the network.
3596      * Message.obj will contain an AsyncResult.
3597      * AsyncResult.result will be a CdmaInformationRecords.CdmaT53ClirInfoRec
3598      * instance.
3599      *
3600      * @param h Handler that receives the notification message.
3601      * @param what User-defined message code.
3602      * @param obj User object.
3603      */
registerFoT53ClirlInfo(Handler h, int what, Object obj)3604     public void registerFoT53ClirlInfo(Handler h, int what, Object obj) {
3605         if (mFeatureFlags.cleanupCdma()) return;
3606         mCi.registerFoT53ClirlInfo(h, what, obj);
3607     }
3608 
3609     /**
3610      * Unregisters for T53 CLIR information record notification
3611      * Extraneous calls are tolerated silently
3612      *
3613      * @param h Handler to be removed from the registrant list.
3614      */
unregisterForT53ClirInfo(Handler h)3615     public void unregisterForT53ClirInfo(Handler h) {
3616         if (mFeatureFlags.cleanupCdma()) return;
3617         mCi.unregisterForT53ClirInfo(h);
3618     }
3619 
3620     /**
3621      * Register for CDMA T53 audio control information record notifications
3622      * from the network.
3623      * Message.obj will contain an AsyncResult.
3624      * AsyncResult.result will be a CdmaInformationRecords.CdmaT53AudioControlInfoRec
3625      * instance.
3626      *
3627      * @param h Handler that receives the notification message.
3628      * @param what User-defined message code.
3629      * @param obj User object.
3630      */
registerForT53AudioControlInfo(Handler h, int what, Object obj)3631     public void registerForT53AudioControlInfo(Handler h, int what, Object obj) {
3632         if (mFeatureFlags.cleanupCdma()) return;
3633         mCi.registerForT53AudioControlInfo(h, what, obj);
3634     }
3635 
3636     /**
3637      * Unregisters for T53 audio control information record notifications.
3638      * Extraneous calls are tolerated silently
3639      *
3640      * @param h Handler to be removed from the registrant list.
3641      */
unregisterForT53AudioControlInfo(Handler h)3642     public void unregisterForT53AudioControlInfo(Handler h) {
3643         if (mFeatureFlags.cleanupCdma()) return;
3644         mCi.unregisterForT53AudioControlInfo(h);
3645     }
3646 
3647     /**
3648      * registers for exit emergency call back mode request response
3649      *
3650      * @param h Handler that receives the notification message.
3651      * @param what User-defined message code.
3652      * @param obj User object.
3653      */
3654     @UnsupportedAppUsage
setOnEcbModeExitResponse(Handler h, int what, Object obj)3655     public void setOnEcbModeExitResponse(Handler h, int what, Object obj){
3656     }
3657 
3658     /**
3659      * Unregisters for exit emergency call back mode request response
3660      *
3661      * @param h Handler to be removed from the registrant list.
3662      */
3663     @UnsupportedAppUsage
unsetOnEcbModeExitResponse(Handler h)3664     public void unsetOnEcbModeExitResponse(Handler h){
3665     }
3666 
3667     /**
3668      * Register for radio off or not available
3669      *
3670      * @param h Handler that receives the notification message.
3671      * @param what User-defined message code.
3672      * @param obj User object.
3673      */
registerForRadioOffOrNotAvailable(Handler h, int what, Object obj)3674     public void registerForRadioOffOrNotAvailable(Handler h, int what, Object obj) {
3675         mRadioOffOrNotAvailableRegistrants.addUnique(h, what, obj);
3676     }
3677 
3678     /**
3679      * Unregisters for radio off or not available
3680      *
3681      * @param h Handler to be removed from the registrant list.
3682      */
unregisterForRadioOffOrNotAvailable(Handler h)3683     public void unregisterForRadioOffOrNotAvailable(Handler h) {
3684         mRadioOffOrNotAvailableRegistrants.remove(h);
3685     }
3686 
3687     /**
3688      *  Location to an updatable file listing carrier provisioning urls.
3689      *  An example:
3690      *
3691      * <?xml version="1.0" encoding="utf-8"?>
3692      *  <provisioningUrls>
3693      *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3694      *  </provisioningUrls>
3695      */
3696     private static final String PROVISIONING_URL_PATH =
3697             "/data/misc/radio/provisioning_urls.xml";
3698     private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3699 
3700     /** XML tag for root element. */
3701     private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3702     /** XML tag for individual url */
3703     private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3704     /** XML attribute for mcc */
3705     private static final String ATTR_MCC = "mcc";
3706     /** XML attribute for mnc */
3707     private static final String ATTR_MNC = "mnc";
3708 
getProvisioningUrlBaseFromFile()3709     private String getProvisioningUrlBaseFromFile() {
3710         XmlPullParser parser;
3711         final Configuration config = mContext.getResources().getConfiguration();
3712 
3713         try (FileReader fileReader = new FileReader(mProvisioningUrlFile)) {
3714             parser = Xml.newPullParser();
3715             parser.setInput(fileReader);
3716             XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3717 
3718             while (true) {
3719                 XmlUtils.nextElement(parser);
3720 
3721                 final String element = parser.getName();
3722                 if (element == null) break;
3723 
3724                 if (element.equals(TAG_PROVISIONING_URL)) {
3725                     String mcc = parser.getAttributeValue(null, ATTR_MCC);
3726                     try {
3727                         if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3728                             String mnc = parser.getAttributeValue(null, ATTR_MNC);
3729                             if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3730                                 parser.next();
3731                                 if (parser.getEventType() == XmlPullParser.TEXT) {
3732                                     return parser.getText();
3733                                 }
3734                             }
3735                         }
3736                     } catch (NumberFormatException e) {
3737                         Rlog.e(mLogTag, "Exception in getProvisioningUrlBaseFromFile: " + e);
3738                     }
3739                 }
3740             }
3741             return null;
3742         } catch (FileNotFoundException e) {
3743             Rlog.e(mLogTag, "Carrier Provisioning Urls file not found");
3744         } catch (XmlPullParserException e) {
3745             Rlog.e(mLogTag, "Xml parser exception reading Carrier Provisioning Urls file: " + e);
3746         } catch (IOException e) {
3747             Rlog.e(mLogTag, "I/O exception reading Carrier Provisioning Urls file: " + e);
3748         }
3749         return null;
3750     }
3751 
3752     /**
3753      * Get the mobile provisioning url.
3754      */
getMobileProvisioningUrl()3755     public String getMobileProvisioningUrl() {
3756         String url = getProvisioningUrlBaseFromFile();
3757         if (TextUtils.isEmpty(url)) {
3758             url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3759             Rlog.d(mLogTag, "getMobileProvisioningUrl: url from resource =" + url);
3760         } else {
3761             Rlog.d(mLogTag, "getMobileProvisioningUrl: url from File =" + url);
3762         }
3763         // Populate the iccid, imei and phone number in the provisioning url.
3764         if (!TextUtils.isEmpty(url)) {
3765             String phoneNumber = getLine1Number();
3766             if (TextUtils.isEmpty(phoneNumber)) {
3767                 phoneNumber = "0000000000";
3768             }
3769             url = String.format(url,
3770                     getIccSerialNumber() /* ICCID */,
3771                     getDeviceId() /* IMEI */,
3772                     phoneNumber /* Phone number */);
3773         }
3774 
3775         return url;
3776     }
3777 
3778     /**
3779      * Check if there are matching tethering (i.e DUN) for the carrier.
3780      * @return true if there is a matching DUN APN.
3781      */
hasMatchedTetherApnSetting()3782     public boolean hasMatchedTetherApnSetting() {
3783         NetworkRegistrationInfo nrs = getServiceState().getNetworkRegistrationInfo(
3784                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
3785         if (nrs != null) {
3786             return getDataNetworkController().getDataProfileManager()
3787                     .isTetheringDataProfileExisting(nrs.getAccessNetworkTechnology());
3788         }
3789         return false;
3790     }
3791 
3792     /**
3793      * Report on whether data connectivity is allowed for internet.
3794      *
3795      * @return {@code true} if internet data is allowed to be established.
3796      */
isDataAllowed()3797     public boolean isDataAllowed() {
3798         return getDataNetworkController().isInternetDataAllowed(false/* ignoreExistingNetworks */);
3799     }
3800 
3801     /**
3802      * Action set from carrier signalling broadcast receivers to enable/disable metered apns.
3803      */
carrierActionSetMeteredApnsEnabled(boolean enabled)3804     public void carrierActionSetMeteredApnsEnabled(boolean enabled) {
3805         mCarrierActionAgent.carrierActionSetMeteredApnsEnabled(enabled);
3806     }
3807 
3808     /**
3809      * Action set from carrier signalling broadcast receivers to enable/disable radio
3810      */
carrierActionSetRadioEnabled(boolean enabled)3811     public void carrierActionSetRadioEnabled(boolean enabled) {
3812         mCarrierActionAgent.carrierActionSetRadioEnabled(enabled);
3813     }
3814 
3815     /**
3816      * Action set from carrier app to start/stop reporting default network condition.
3817      */
carrierActionReportDefaultNetworkStatus(boolean report)3818     public void carrierActionReportDefaultNetworkStatus(boolean report) {
3819         mCarrierActionAgent.carrierActionReportDefaultNetworkStatus(report);
3820     }
3821 
3822     /**
3823      * Action set from carrier signalling broadcast receivers to reset all carrier actions
3824      */
carrierActionResetAll()3825     public void carrierActionResetAll() {
3826         mCarrierActionAgent.carrierActionReset();
3827     }
3828 
3829     /**
3830      * Notify registrants of a new ringing Connection.
3831      * Subclasses of Phone probably want to replace this with a
3832      * version scoped to their packages
3833      */
notifyNewRingingConnectionP(Connection cn)3834     public void notifyNewRingingConnectionP(Connection cn) {
3835         Rlog.i(mLogTag, String.format(
3836                 "notifyNewRingingConnection: phoneId=[%d], connection=[%s], registrants=[%s]",
3837                 getPhoneId(), cn, getNewRingingConnectionRegistrantsAsString()));
3838         if (!mIsVoiceCapable)
3839             return;
3840         AsyncResult ar = new AsyncResult(null, cn, null);
3841         mNewRingingConnectionRegistrants.notifyRegistrants(ar);
3842     }
3843 
3844     /**
3845      * helper for notifyNewRingingConnectionP(Connection) to create a string for a log message.
3846      *
3847      * @return a list of objects in mNewRingingConnectionRegistrants as a String
3848      */
getNewRingingConnectionRegistrantsAsString()3849     private String getNewRingingConnectionRegistrantsAsString() {
3850         List<String> registrants = new ArrayList<>();
3851         for (int i = 0; i < mNewRingingConnectionRegistrants.size(); i++) {
3852             registrants.add(mNewRingingConnectionRegistrants.get(i).toString());
3853         }
3854         return String.join(", ", registrants);
3855     }
3856 
3857     /**
3858      * Notify registrants of a new unknown connection.
3859      */
notifyUnknownConnectionP(Connection cn)3860     public void notifyUnknownConnectionP(Connection cn) {
3861         mUnknownConnectionRegistrants.notifyResult(cn);
3862     }
3863 
3864     /**
3865      * Notify registrants if phone is video capable.
3866      */
notifyForVideoCapabilityChanged(boolean isVideoCallCapable)3867     public void notifyForVideoCapabilityChanged(boolean isVideoCallCapable) {
3868         // Cache the current video capability so that we don't lose the information.
3869         mIsVideoCapable = isVideoCallCapable;
3870 
3871         AsyncResult ar = new AsyncResult(null, isVideoCallCapable, null);
3872         mVideoCapabilityChangedRegistrants.notifyRegistrants(ar);
3873     }
3874 
3875     /**
3876      * Notify registrants of a RING event.
3877      */
notifyIncomingRing()3878     private void notifyIncomingRing() {
3879         if (!mIsVoiceCapable)
3880             return;
3881         AsyncResult ar = new AsyncResult(null, this, null);
3882         mIncomingRingRegistrants.notifyRegistrants(ar);
3883     }
3884 
3885     /**
3886      * Send the incoming call Ring notification if conditions are right.
3887      */
sendIncomingCallRingNotification(int token)3888     private void sendIncomingCallRingNotification(int token) {
3889         if (mIsVoiceCapable && !mDoesRilSendMultipleCallRing &&
3890                 (token == mCallRingContinueToken)) {
3891             Rlog.d(mLogTag, "Sending notifyIncomingRing");
3892             notifyIncomingRing();
3893             sendMessageDelayed(
3894                     obtainMessage(EVENT_CALL_RING_CONTINUE, token, 0), mCallRingDelay);
3895         } else {
3896             Rlog.d(mLogTag, "Ignoring ring notification request,"
3897                     + " mDoesRilSendMultipleCallRing=" + mDoesRilSendMultipleCallRing
3898                     + " token=" + token
3899                     + " mCallRingContinueToken=" + mCallRingContinueToken
3900                     + " mIsVoiceCapable=" + mIsVoiceCapable);
3901         }
3902     }
3903 
3904     /**
3905      * Enable or disable always reporting signal strength changes from radio.
3906      *
3907      * @param isEnable {@code true} for enabling; {@code false} for disabling.
3908      */
setAlwaysReportSignalStrength(boolean isEnable)3909     public void setAlwaysReportSignalStrength(boolean isEnable) {
3910         if (mDeviceStateMonitor != null) {
3911             mDeviceStateMonitor.setAlwaysReportSignalStrength(isEnable);
3912         }
3913     }
3914 
3915     /**
3916      * TODO: Adding a function for each property is not good.
3917      * A fucntion of type getPhoneProp(propType) where propType is an
3918      * enum of GSM+CDMA+LTE props would be a better approach.
3919      *
3920      * Get "Restriction of menu options for manual PLMN selection" bit
3921      * status from EF_CSP data, this belongs to "Value Added Services Group".
3922      * @return true if this bit is set or EF_CSP data is unavailable,
3923      * false otherwise
3924      */
3925     @UnsupportedAppUsage
isCspPlmnEnabled()3926     public boolean isCspPlmnEnabled() {
3927         return false;
3928     }
3929 
3930     /**
3931      * Return an interface to retrieve the ISIM records for IMS, if available.
3932      * @return the interface to retrieve the ISIM records, or null if not supported
3933      */
3934     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getIsimRecords()3935     public IsimRecords getIsimRecords() {
3936         Rlog.e(mLogTag, "getIsimRecords() is only supported on LTE devices");
3937         return null;
3938     }
3939 
3940     /**
3941      * Retrieves the MSISDN from the UICC. For GSM/UMTS phones, this is equivalent to
3942      * {@link #getLine1Number()}. For CDMA phones, {@link #getLine1Number()} returns
3943      * the MDN, so this method is provided to return the MSISDN on CDMA/LTE phones.
3944      */
3945     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMsisdn()3946     public String getMsisdn() {
3947         return null;
3948     }
3949 
3950     /**
3951      * Retrieves the EF_PNN from the UICC For GSM/UMTS phones.
3952      */
getPlmn()3953     public String getPlmn() {
3954         return null;
3955     }
3956 
notifyCallForwardingIndicator()3957     public void notifyCallForwardingIndicator() {
3958     }
3959 
3960     /**
3961      * Sets the SIM voice message waiting indicator records.
3962      * @param line GSM Subscriber Profile Number, one-based. Only '1' is supported
3963      * @param countWaiting The number of messages waiting, if known. Use
3964      *                     -1 to indicate that an unknown number of
3965      *                      messages are waiting
3966      */
setVoiceMessageWaiting(int line, int countWaiting)3967     public void setVoiceMessageWaiting(int line, int countWaiting) {
3968         // This function should be overridden by class GsmCdmaPhone.
3969         Rlog.e(mLogTag, "Error! This function should never be executed, inactive Phone.");
3970     }
3971 
3972     /**
3973      * Gets the USIM service table from the UICC, if present and available.
3974      * @return an interface to the UsimServiceTable record, or null if not available
3975      */
getUsimServiceTable()3976     public UsimServiceTable getUsimServiceTable() {
3977         IccRecords r = mIccRecords.get();
3978         return (r != null) ? r.getUsimServiceTable() : null;
3979     }
3980 
3981     /**
3982      * Gets the Uicc card corresponding to this phone.
3983      * @return the UiccCard object corresponding to the phone ID.
3984      */
3985     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getUiccCard()3986     public UiccCard getUiccCard() {
3987         return mUiccController.getUiccCard(mPhoneId);
3988     }
3989 
3990     /**
3991      * Gets the Uicc port corresponding to this phone.
3992      * @return the UiccPort object corresponding to the phone ID.
3993      */
getUiccPort()3994     public UiccPort getUiccPort() {
3995         return mUiccController.getUiccPort(mPhoneId);
3996     }
3997 
3998     /**
3999      * Set IMS registration state
4000      */
setImsRegistrationState(boolean registered)4001     public void setImsRegistrationState(boolean registered) {
4002     }
4003 
4004     /**
4005      * Return an instance of a IMS phone
4006      */
4007     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getImsPhone()4008     public Phone getImsPhone() {
4009         return mImsPhone;
4010     }
4011 
4012     @VisibleForTesting
setImsPhone(ImsPhone imsPhone)4013     public void setImsPhone(ImsPhone imsPhone) {
4014         mImsPhone = imsPhone;
4015     }
4016 
4017     /**
4018      * Returns Carrier specific information that will be used to encrypt the IMSI and IMPI.
4019      * @param keyType whether the key is being used for WLAN or ePDG.
4020      * @param fallback whether or not to fall back to the encryption key info stored in carrier
4021      *                 config
4022      * @return ImsiEncryptionInfo which includes the Key Type, the Public Key
4023      *        {@link java.security.PublicKey} and the Key Identifier.
4024      *        The keyIdentifier This is used by the server to help it locate the private key to
4025      *        decrypt the permanent identity.
4026      */
getCarrierInfoForImsiEncryption(int keyType, boolean fallback)4027     public ImsiEncryptionInfo getCarrierInfoForImsiEncryption(int keyType, boolean fallback) {
4028         return null;
4029     }
4030 
4031     /**
4032      * Sets the carrier information needed to encrypt the IMSI and IMPI.
4033      * @param imsiEncryptionInfo Carrier specific information that will be used to encrypt the
4034      *        IMSI and IMPI. This includes the Key type, the Public key
4035      *        {@link java.security.PublicKey} and the Key identifier.
4036      */
setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo)4037     public void setCarrierInfoForImsiEncryption(ImsiEncryptionInfo imsiEncryptionInfo) {
4038         return;
4039     }
4040 
4041     /**
4042      * Deletes all the keys for a given Carrier from the device keystore.
4043      * @param carrierId : the carrier ID which needs to be matched in the delete query
4044      */
deleteCarrierInfoForImsiEncryption(int carrierId)4045     public void deleteCarrierInfoForImsiEncryption(int carrierId) {
4046         return;
4047     }
4048 
4049     /**
4050      * Deletes all the keys for a given Carrier from the device keystore.
4051      * @param carrierId : the carrier ID which needs to be matched in the delete query
4052      * @param simOperator : MccMnc which needs to be matched in the delete query.
4053      */
deleteCarrierInfoForImsiEncryption(int carrierId, String simOperator)4054     public void deleteCarrierInfoForImsiEncryption(int carrierId, String simOperator) {
4055 
4056     }
4057 
getCarrierId()4058     public int getCarrierId() {
4059         return TelephonyManager.UNKNOWN_CARRIER_ID;
4060     }
4061 
getCarrierName()4062     public String getCarrierName() {
4063         return null;
4064     }
4065 
getMNOCarrierId()4066     public int getMNOCarrierId() {
4067         return TelephonyManager.UNKNOWN_CARRIER_ID;
4068     }
4069 
getSpecificCarrierId()4070     public int getSpecificCarrierId() {
4071         return TelephonyManager.UNKNOWN_CARRIER_ID;
4072     }
4073 
getSpecificCarrierName()4074     public String getSpecificCarrierName() {
4075         return null;
4076     }
4077 
getCarrierIdListVersion()4078     public int getCarrierIdListVersion() {
4079         return TelephonyManager.UNKNOWN_CARRIER_ID_LIST_VERSION;
4080     }
4081 
getEmergencyNumberDbVersion()4082     public int getEmergencyNumberDbVersion() {
4083         return TelephonyManager.INVALID_EMERGENCY_NUMBER_DB_VERSION;
4084     }
4085 
resolveSubscriptionCarrierId(String simState)4086     public void resolveSubscriptionCarrierId(String simState) {
4087     }
4088 
4089     /**
4090      *  Resets the Carrier Keys in the database. This involves 2 steps:
4091      *  1. Delete the keys from the database.
4092      *  2. Send an intent to download new Certificates.
4093      */
resetCarrierKeysForImsiEncryption()4094     public void resetCarrierKeysForImsiEncryption() {
4095         return;
4096     }
4097 
4098     /**
4099      * Resets the Carrier Keys in the database. This involves 2 steps:
4100      * 1. Delete the keys from the database.
4101      * 2. Send an intent to download new Certificates.
4102      *
4103      * @param forceResetAll : Force delete the downloaded key if any.
4104      */
resetCarrierKeysForImsiEncryption(boolean forceResetAll)4105     public void resetCarrierKeysForImsiEncryption(boolean forceResetAll) {
4106     }
4107 
4108     /**
4109      * Return if UT capability of ImsPhone is enabled or not
4110      */
4111     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
isUtEnabled()4112     public boolean isUtEnabled() {
4113         if (mImsPhone != null) {
4114             return mImsPhone.isUtEnabled();
4115         }
4116         return false;
4117     }
4118 
4119     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
dispose()4120     public void dispose() {
4121     }
4122 
4123     /**
4124      * Dials a number.
4125      *
4126      * @param dialString The number to dial.
4127      * @param dialArgs Parameters to dial with.
4128      * @return The Connection.
4129      * @throws CallStateException
4130      */
dialInternal(String dialString, DialArgs dialArgs)4131     protected Connection dialInternal(String dialString, DialArgs dialArgs)
4132             throws CallStateException {
4133         // dialInternal shall be overriden by GsmCdmaPhone
4134         return null;
4135     }
4136 
4137     /*
4138      * This function is for CSFB SS. GsmCdmaPhone overrides this function.
4139      */
setCallWaiting(boolean enable, int serviceClass, Message onComplete)4140     public void setCallWaiting(boolean enable, int serviceClass, Message onComplete) {
4141     }
4142 
queryCLIP(Message onComplete)4143     public void queryCLIP(Message onComplete) {
4144     }
4145 
4146     /*
4147      * Returns the subscription id.
4148      */
4149     @UnsupportedAppUsage
getSubId()4150     public int getSubId() {
4151         return mSubscriptionManagerService.getSubId(mPhoneId);
4152     }
4153 
4154     /**
4155      * Returns the phone id.
4156      */
4157     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getPhoneId()4158     public int getPhoneId() {
4159         return mPhoneId;
4160     }
4161 
4162     /**
4163      * Override the service provider name and the operator name for the current ICCID.
4164      */
setOperatorBrandOverride(String brand)4165     public boolean setOperatorBrandOverride(String brand) {
4166         return false;
4167     }
4168 
4169     /**
4170      * Sets the network scan started status.
4171      *
4172      * @param started {@code true} if the network scan has started, {@code false} otherwise.
4173      */
setNetworkScanStarted(boolean started)4174     public void setNetworkScanStarted(boolean started) {
4175         mIsNetworkScanStarted = started;
4176     }
4177 
4178     /**
4179      * Gets the network scan started status.
4180      *
4181      * @return {@code true} if the network scan has started, {@code false} otherwise.
4182      */
getNetworkScanStarted()4183     public boolean getNetworkScanStarted() {
4184         return mIsNetworkScanStarted;
4185     }
4186 
4187     /**
4188      * Override the roaming indicator for the current ICCID.
4189      */
setRoamingOverride(List<String> gsmRoamingList, List<String> gsmNonRoamingList, List<String> cdmaRoamingList, List<String> cdmaNonRoamingList)4190     public boolean setRoamingOverride(List<String> gsmRoamingList,
4191             List<String> gsmNonRoamingList, List<String> cdmaRoamingList,
4192             List<String> cdmaNonRoamingList) {
4193         String iccId = getIccSerialNumber();
4194         if (TextUtils.isEmpty(iccId)) {
4195             return false;
4196         }
4197 
4198         setRoamingOverrideHelper(gsmRoamingList, GSM_ROAMING_LIST_OVERRIDE_PREFIX, iccId);
4199         setRoamingOverrideHelper(gsmNonRoamingList, GSM_NON_ROAMING_LIST_OVERRIDE_PREFIX, iccId);
4200         if (!mFeatureFlags.cleanupCdma()) {
4201             setRoamingOverrideHelper(cdmaRoamingList, CDMA_ROAMING_LIST_OVERRIDE_PREFIX, iccId);
4202             setRoamingOverrideHelper(cdmaNonRoamingList, CDMA_NON_ROAMING_LIST_OVERRIDE_PREFIX,
4203                     iccId);
4204         }
4205 
4206         // Refresh.
4207         ServiceStateTracker tracker = getServiceStateTracker();
4208         if (tracker != null) {
4209             tracker.pollState();
4210         }
4211         return true;
4212     }
4213 
setRoamingOverrideHelper(List<String> list, String prefix, String iccId)4214     private void setRoamingOverrideHelper(List<String> list, String prefix, String iccId) {
4215         SharedPreferences.Editor spEditor =
4216                 PreferenceManager.getDefaultSharedPreferences(mContext).edit();
4217         String key = prefix + iccId;
4218         if (list == null || list.isEmpty()) {
4219             spEditor.remove(key).commit();
4220         } else {
4221             spEditor.putStringSet(key, new HashSet<String>(list)).commit();
4222         }
4223     }
4224 
isMccMncMarkedAsRoaming(String mccMnc)4225     public boolean isMccMncMarkedAsRoaming(String mccMnc) {
4226         return getRoamingOverrideHelper(GSM_ROAMING_LIST_OVERRIDE_PREFIX, mccMnc);
4227     }
4228 
isMccMncMarkedAsNonRoaming(String mccMnc)4229     public boolean isMccMncMarkedAsNonRoaming(String mccMnc) {
4230         return getRoamingOverrideHelper(GSM_NON_ROAMING_LIST_OVERRIDE_PREFIX, mccMnc);
4231     }
4232 
isSidMarkedAsRoaming(int SID)4233     public boolean isSidMarkedAsRoaming(int SID) {
4234         return getRoamingOverrideHelper(CDMA_ROAMING_LIST_OVERRIDE_PREFIX,
4235                 Integer.toString(SID));
4236     }
4237 
isSidMarkedAsNonRoaming(int SID)4238     public boolean isSidMarkedAsNonRoaming(int SID) {
4239         return getRoamingOverrideHelper(CDMA_NON_ROAMING_LIST_OVERRIDE_PREFIX,
4240                 Integer.toString(SID));
4241     }
4242 
4243     /**
4244      * Query the IMS Registration Status.
4245      *
4246      * @return true if IMS is Registered
4247      */
isImsRegistered()4248     public boolean isImsRegistered() {
4249         Phone imsPhone = mImsPhone;
4250         boolean isImsRegistered = false;
4251         if (imsPhone != null) {
4252             isImsRegistered = imsPhone.isImsRegistered();
4253         } else {
4254             ServiceStateTracker sst = getServiceStateTracker();
4255             if (sst != null) {
4256                 isImsRegistered = sst.isImsRegistered();
4257             }
4258         }
4259         Rlog.d(mLogTag, "isImsRegistered =" + isImsRegistered);
4260         return isImsRegistered;
4261     }
4262 
4263     /**
4264      * Get Wifi Calling Feature Availability
4265      */
4266     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
isWifiCallingEnabled()4267     public boolean isWifiCallingEnabled() {
4268         Phone imsPhone = mImsPhone;
4269         boolean isWifiCallingEnabled = false;
4270         if (imsPhone != null) {
4271             isWifiCallingEnabled = imsPhone.isWifiCallingEnabled();
4272         }
4273         Rlog.d(mLogTag, "isWifiCallingEnabled =" + isWifiCallingEnabled);
4274         return isWifiCallingEnabled;
4275     }
4276 
4277     /**
4278      * @return true if the IMS capability for the registration technology specified is available,
4279      * false otherwise.
4280      */
isImsCapabilityAvailable(int capability, int regTech)4281     public boolean isImsCapabilityAvailable(int capability, int regTech) throws ImsException {
4282         Phone imsPhone = mImsPhone;
4283         boolean isAvailable = false;
4284         if (imsPhone != null) {
4285             isAvailable = imsPhone.isImsCapabilityAvailable(capability, regTech);
4286         }
4287         Rlog.d(mLogTag, "isImsCapabilityAvailable, capability=" + capability + ", regTech="
4288                 + regTech + ", isAvailable=" + isAvailable);
4289         return isAvailable;
4290     }
4291 
4292     /**
4293      * Get Volte Feature Availability
4294      * @deprecated Use {@link #isVoiceOverCellularImsEnabled} instead.
4295      */
4296     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
4297     @Deprecated
isVolteEnabled()4298     public boolean isVolteEnabled() {
4299         return isVoiceOverCellularImsEnabled();
4300     }
4301 
4302     /**
4303      * @return {@code true} if voice over IMS on cellular is enabled, {@code false} otherwise.
4304      */
isVoiceOverCellularImsEnabled()4305     public boolean isVoiceOverCellularImsEnabled() {
4306         Phone imsPhone = mImsPhone;
4307         boolean isVolteEnabled = false;
4308         if (imsPhone != null) {
4309             isVolteEnabled = imsPhone.isVoiceOverCellularImsEnabled();
4310         }
4311         Rlog.d(mLogTag, "isVoiceOverCellularImsEnabled=" + isVolteEnabled);
4312         return isVolteEnabled;
4313     }
4314 
4315     /**
4316      * @return the IMS MmTel Registration technology for this Phone, defined in
4317      * {@link ImsRegistrationImplBase}.
4318      */
getImsRegistrationTech()4319     public int getImsRegistrationTech() {
4320         Phone imsPhone = mImsPhone;
4321         int regTech = ImsRegistrationImplBase.REGISTRATION_TECH_NONE;
4322         if (imsPhone != null) {
4323             regTech = imsPhone.getImsRegistrationTech();
4324         }
4325         Rlog.d(mLogTag, "getImsRegistrationTechnology =" + regTech);
4326         return regTech;
4327     }
4328 
4329     /**
4330      * Get the IMS MmTel Registration technology for this Phone, defined in
4331      * {@link ImsRegistrationImplBase}.
4332      */
getImsRegistrationTech(Consumer<Integer> callback)4333     public void getImsRegistrationTech(Consumer<Integer> callback) {
4334         Phone imsPhone = mImsPhone;
4335         if (imsPhone != null) {
4336             imsPhone.getImsRegistrationTech(callback);
4337         } else {
4338             callback.accept(ImsRegistrationImplBase.REGISTRATION_TECH_NONE);
4339         }
4340     }
4341 
4342     /**
4343      * Asynchronously get the IMS MmTel Registration state for this Phone.
4344      */
getImsRegistrationState(Consumer<Integer> callback)4345     public void getImsRegistrationState(Consumer<Integer> callback) {
4346         Phone imsPhone = mImsPhone;
4347         if (imsPhone != null) {
4348             imsPhone.getImsRegistrationState(callback);
4349         } else {
4350             callback.accept(RegistrationManager.REGISTRATION_STATE_NOT_REGISTERED);
4351         }
4352     }
4353 
4354 
getRoamingOverrideHelper(String prefix, String key)4355     private boolean getRoamingOverrideHelper(String prefix, String key) {
4356         String iccId = getIccSerialNumber();
4357         if (TextUtils.isEmpty(iccId) || TextUtils.isEmpty(key)) {
4358             return false;
4359         }
4360 
4361         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
4362         Set<String> value = sp.getStringSet(prefix + iccId, null);
4363         if (value == null) {
4364             return false;
4365         }
4366         return value.contains(key);
4367     }
4368 
4369     /**
4370      * @return returns the latest radio state from the modem
4371      */
getRadioPowerState()4372     public int getRadioPowerState() {
4373         return mCi.getRadioState();
4374     }
4375 
4376     /**
4377      * Is Radio Present on the device and is it accessible
4378      */
isRadioAvailable()4379     public boolean isRadioAvailable() {
4380         return mCi.getRadioState() != TelephonyManager.RADIO_POWER_UNAVAILABLE;
4381     }
4382 
4383     /**
4384      * Is Radio turned on
4385      */
isRadioOn()4386     public boolean isRadioOn() {
4387         return mCi.getRadioState() == TelephonyManager.RADIO_POWER_ON;
4388     }
4389 
4390     /**
4391      * shutdown Radio gracefully
4392      */
shutdownRadio()4393     public void shutdownRadio() {
4394         getServiceStateTracker().requestShutdown();
4395     }
4396 
4397     /**
4398      * Return true if the device is shutting down.
4399      */
isShuttingDown()4400     public boolean isShuttingDown() {
4401         return getServiceStateTracker().isDeviceShuttingDown();
4402     }
4403 
4404     /**
4405      *  Set phone radio capability
4406      *
4407      *  @param rc the phone radio capability defined in
4408      *         RadioCapability. It's a input object used to transfer parameter to logic modem
4409      *  @param response Callback message.
4410      */
setRadioCapability(RadioCapability rc, Message response)4411     public void setRadioCapability(RadioCapability rc, Message response) {
4412         mCi.setRadioCapability(rc, response);
4413     }
4414 
4415     /**
4416      *  Get phone radio access family
4417      *
4418      *  @return a bit mask to identify the radio access family.
4419      */
getRadioAccessFamily()4420     public int getRadioAccessFamily() {
4421         final RadioCapability rc = getRadioCapability();
4422         return (rc == null ? RadioAccessFamily.RAF_UNKNOWN : rc.getRadioAccessFamily());
4423     }
4424 
4425     /**
4426      *  Get the associated data modems Id.
4427      *
4428      *  @return a String containing the id of the data modem
4429      */
getModemUuId()4430     public String getModemUuId() {
4431         final RadioCapability rc = getRadioCapability();
4432         return (rc == null ? "" : rc.getLogicalModemUuid());
4433     }
4434 
4435     /**
4436      *  Get phone radio capability
4437      *
4438      *  @return the capability of the radio defined in RadioCapability
4439      */
getRadioCapability()4440     public RadioCapability getRadioCapability() {
4441         return mRadioCapability.get();
4442     }
4443 
4444     /**
4445      *  The RadioCapability has changed. This comes up from the RIL and is called when radios first
4446      *  become available or after a capability switch.  The flow is we use setRadioCapability to
4447      *  request a change with the RIL and get an UNSOL response with the new data which gets set
4448      *  here.
4449      *
4450      *  @param rc the phone radio capability currently in effect for this phone.
4451      *  @param capabilitySwitched whether this method called after a radio capability switch
4452      *      completion or called when radios first become available.
4453      */
radioCapabilityUpdated(RadioCapability rc, boolean capabilitySwitched)4454     public void radioCapabilityUpdated(RadioCapability rc, boolean capabilitySwitched) {
4455         // Called when radios first become available or after a capability switch
4456         // Update the cached value
4457         mRadioCapability.set(rc);
4458 
4459         if (SubscriptionManager.isValidSubscriptionId(getSubId())) {
4460             boolean restoreSelection = !mContext.getResources().getBoolean(
4461                     com.android.internal.R.bool.skip_restoring_network_selection);
4462             sendSubscriptionSettings(restoreSelection);
4463         }
4464 
4465         // When radio capability switch is done, query IMEI value and update it in Phone objects
4466         // to make it in sync with the IMEI value currently used by Logical-Modem.
4467         if (capabilitySwitched) {
4468             mCi.getImei(obtainMessage(EVENT_GET_DEVICE_IMEI_DONE));
4469             mCi.getDeviceIdentity(obtainMessage(EVENT_GET_DEVICE_IDENTITY_DONE));
4470         }
4471     }
4472 
sendSubscriptionSettings(boolean restoreNetworkSelection)4473     public void sendSubscriptionSettings(boolean restoreNetworkSelection) {
4474         // Send settings down
4475         if (mIsAllowedNetworkTypesLoadedFromDb) {
4476             updateAllowedNetworkTypes(null);
4477         }
4478 
4479         if (restoreNetworkSelection) {
4480             restoreSavedNetworkSelection(null);
4481         }
4482 
4483         updateUsageSetting();
4484     }
4485 
getResolvedUsageSetting(int subId)4486     private int getResolvedUsageSetting(int subId) {
4487         SubscriptionInfo subInfo = null;
4488         SubscriptionInfoInternal subInfoInternal = mSubscriptionManagerService
4489                 .getSubscriptionInfoInternal(subId);
4490         if (subInfoInternal != null) {
4491             subInfo = subInfoInternal.toSubscriptionInfo();
4492         }
4493 
4494         if (subInfo == null) {
4495             loge("Failed to get SubscriptionInfo for subId=" + subId);
4496             return SubscriptionManager.USAGE_SETTING_UNKNOWN;
4497         }
4498 
4499         if (subInfo.getUsageSetting() == SubscriptionManager.USAGE_SETTING_UNKNOWN) {
4500             return SubscriptionManager.USAGE_SETTING_UNKNOWN;
4501         }
4502 
4503         if (subInfo.getUsageSetting() != SubscriptionManager.USAGE_SETTING_DEFAULT) {
4504             return subInfo.getUsageSetting();
4505         }
4506 
4507         if (subInfo.isOpportunistic()) {
4508             return SubscriptionManager.USAGE_SETTING_DATA_CENTRIC;
4509         } else {
4510             return mContext.getResources().getInteger(
4511                     com.android.internal.R.integer.config_default_cellular_usage_setting);
4512         }
4513     }
4514 
4515     /**
4516      * Attempt to update the usage setting.
4517      *
4518      * @return whether the usage setting will be updated (used for test)
4519      */
updateUsageSetting()4520     public boolean updateUsageSetting() {
4521         if (!mIsUsageSettingSupported) return false;
4522 
4523         final int subId = getSubId();
4524         if (!SubscriptionManager.isValidSubscriptionId(subId)) return false;
4525 
4526         final int lastPreferredUsageSetting = mPreferredUsageSetting;
4527 
4528         mPreferredUsageSetting = getResolvedUsageSetting(subId);
4529         if (mPreferredUsageSetting == SubscriptionManager.USAGE_SETTING_UNKNOWN) {
4530             loge("Usage Setting is Supported but Preferred Setting Unknown!");
4531             return false;
4532         }
4533 
4534         // We might get a lot of requests to update, so definitely we don't want to hammer
4535         // the modem with multiple duplicate requests for usage setting updates
4536         if (mPreferredUsageSetting == lastPreferredUsageSetting) return false;
4537 
4538         String logStr = "mPreferredUsageSetting=" + mPreferredUsageSetting
4539                 + ", lastPreferredUsageSetting=" + lastPreferredUsageSetting
4540                 + ", mUsageSettingFromModem=" + mUsageSettingFromModem;
4541         logd(logStr);
4542         mLocalLog.log(logStr);
4543 
4544         // If the modem value hasn't been updated, request it.
4545         if (mUsageSettingFromModem == SubscriptionManager.USAGE_SETTING_UNKNOWN) {
4546             mCi.getUsageSetting(obtainMessage(EVENT_GET_USAGE_SETTING_DONE));
4547             // If the modem value is already known, and the value has changed, proceed to update.
4548         } else if (mPreferredUsageSetting != mUsageSettingFromModem) {
4549             mCi.setUsageSetting(obtainMessage(EVENT_SET_USAGE_SETTING_DONE,
4550                         mPreferredUsageSetting, 0 /* unused */),
4551                     mPreferredUsageSetting);
4552         }
4553         return true;
4554     }
4555 
4556 
4557 
4558     /**
4559      * Registers the handler when phone radio  capability is changed.
4560      *
4561      * @param h Handler for notification message.
4562      * @param what User-defined message code.
4563      * @param obj User object.
4564      */
registerForRadioCapabilityChanged(Handler h, int what, Object obj)4565     public void registerForRadioCapabilityChanged(Handler h, int what, Object obj) {
4566         mCi.registerForRadioCapabilityChanged(h, what, obj);
4567     }
4568 
4569     /**
4570      * Unregister for notifications when phone radio type and access technology is changed.
4571      *
4572      * @param h Handler to be removed from the registrant list.
4573      */
unregisterForRadioCapabilityChanged(Handler h)4574     public void unregisterForRadioCapabilityChanged(Handler h) {
4575         mCi.unregisterForRadioCapabilityChanged(this);
4576     }
4577 
4578     /**
4579      * Determines if the connection to IMS services are available yet.
4580      * @return {@code true} if the connection to IMS services are available.
4581      */
isImsAvailable()4582     public boolean isImsAvailable() {
4583         if (mImsPhone == null) {
4584             return false;
4585         }
4586 
4587         return mImsPhone.isImsAvailable();
4588     }
4589 
4590     /**
4591      * Determines if video calling is enabled for the phone.
4592      *
4593      * @return {@code true} if video calling is enabled, {@code false} otherwise.
4594      */
4595     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
isVideoEnabled()4596     public boolean isVideoEnabled() {
4597         Phone imsPhone = mImsPhone;
4598         if (imsPhone != null) {
4599             return imsPhone.isVideoEnabled();
4600         }
4601         return false;
4602     }
4603 
4604     /**
4605      * Returns the modem activity information
4606      */
getModemActivityInfo(Message response, WorkSource workSource)4607     public void getModemActivityInfo(Message response, WorkSource workSource)  {
4608         mCi.getModemActivityInfo(response, workSource);
4609     }
4610 
4611     /**
4612      * Control the data throttling at modem.
4613      *
4614      * @param result Message that will be sent back to the requester
4615      * @param workSource calling Worksource
4616      * @param dataThrottlingAction the DataThrottlingAction that is being requested. Defined in
4617      *      android.telephony.TelephonyManger.
4618      * @param completionWindowMillis milliseconds in which data throttling action has to be
4619      *      achieved.
4620      */
setDataThrottling(Message result, WorkSource workSource, int dataThrottlingAction, long completionWindowMillis)4621     public void setDataThrottling(Message result, WorkSource workSource,
4622             int dataThrottlingAction, long completionWindowMillis) {
4623         mCi.setDataThrottling(result, workSource, dataThrottlingAction, completionWindowMillis);
4624     }
4625 
4626     /**
4627      * Set allowed carriers
4628      */
setAllowedCarriers(CarrierRestrictionRules carrierRestrictionRules, Message response, WorkSource workSource)4629     public void setAllowedCarriers(CarrierRestrictionRules carrierRestrictionRules,
4630             Message response, WorkSource workSource) {
4631         mCi.setAllowedCarriers(carrierRestrictionRules, response, workSource);
4632     }
4633 
4634     /** Sets the SignalStrength reporting criteria. */
setLinkCapacityReportingCriteria(int[] dlThresholds, int[] ulThresholds, int ran)4635     public void setLinkCapacityReportingCriteria(int[] dlThresholds, int[] ulThresholds, int ran) {
4636         // no-op default implementation
4637     }
4638 
4639     /**
4640      * Get allowed carriers
4641      */
getAllowedCarriers(Message response, WorkSource workSource)4642     public void getAllowedCarriers(Message response, WorkSource workSource) {
4643         mCi.getAllowedCarriers(response, workSource);
4644     }
4645 
4646     /**
4647      * Returns the locale based on the carrier properties (such as {@code ro.carrier}) and
4648      * SIM preferences.
4649      */
getLocaleFromSimAndCarrierPrefs()4650     public Locale getLocaleFromSimAndCarrierPrefs() {
4651         final IccRecords records = mIccRecords.get();
4652         if (records != null && records.getSimLanguage() != null) {
4653             return new Locale(records.getSimLanguage());
4654         }
4655 
4656         return getLocaleFromCarrierProperties();
4657     }
4658 
updateCurrentCarrierInProvider()4659     public boolean updateCurrentCarrierInProvider() {
4660         return false;
4661     }
4662 
4663     @UnsupportedAppUsage
getIccSmsInterfaceManager()4664     public IccSmsInterfaceManager getIccSmsInterfaceManager(){
4665         return null;
4666     }
4667 
isMatchGid(String gid)4668     protected boolean isMatchGid(String gid) {
4669         String gid1 = getGroupIdLevel1();
4670         int gidLength = gid.length();
4671         if (!TextUtils.isEmpty(gid1) && (gid1.length() >= gidLength)
4672                 && gid1.substring(0, gidLength).equalsIgnoreCase(gid)) {
4673             return true;
4674         }
4675         return false;
4676     }
4677 
checkWfcWifiOnlyModeBeforeDial(Phone imsPhone, int phoneId, Context context)4678     public static void checkWfcWifiOnlyModeBeforeDial(Phone imsPhone, int phoneId, Context context)
4679             throws CallStateException {
4680         if (imsPhone == null || !imsPhone.isWifiCallingEnabled()) {
4681             ImsManager imsManager = ImsManager.getInstance(context, phoneId);
4682             boolean wfcWiFiOnly = (imsManager.isWfcEnabledByPlatform()
4683                     && imsManager.isWfcEnabledByUser() && (imsManager.getWfcMode()
4684                     == ImsConfig.WfcModeFeatureValueConstants.WIFI_ONLY));
4685             if (wfcWiFiOnly) {
4686                 throw new CallStateException(
4687                         CallStateException.ERROR_OUT_OF_SERVICE,
4688                         "WFC Wi-Fi Only Mode: IMS not registered");
4689             }
4690         }
4691     }
4692 
isImsServiceSimultaneousCallingSupportCapable(Context context)4693     public boolean isImsServiceSimultaneousCallingSupportCapable(Context context) {
4694         if (!mFeatureFlags.simultaneousCallingIndications()) return false;
4695         boolean capable = false;
4696         ImsManager imsManager = ImsManager.getInstance(context, mPhoneId);
4697         if (imsManager != null) {
4698             try {
4699                 capable = imsManager.isCapable(CAPABILITY_SUPPORTS_SIMULTANEOUS_CALLING);
4700             } catch (ImsException e) {
4701                 loge("initializeTerminalBasedCallWaiting : exception " + e);
4702             }
4703         }
4704         return capable;
4705     }
4706 
startRingbackTone()4707     public void startRingbackTone() {
4708     }
4709 
stopRingbackTone()4710     public void stopRingbackTone() {
4711     }
4712 
callEndCleanupHandOverCallIfAny()4713     public void callEndCleanupHandOverCallIfAny() {
4714     }
4715 
4716     /**
4717      * Cancel USSD session.
4718      *
4719      * @param msg The message to dispatch when the USSD session terminated.
4720      */
cancelUSSD(Message msg)4721     public void cancelUSSD(Message msg) {
4722     }
4723 
4724     /**
4725      * Set boolean broadcastEmergencyCallStateChanges
4726      */
setBroadcastEmergencyCallStateChanges(boolean broadcast)4727     public abstract void setBroadcastEmergencyCallStateChanges(boolean broadcast);
4728 
sendEmergencyCallStateChange(boolean callActive)4729     public abstract void sendEmergencyCallStateChange(boolean callActive);
4730 
4731     /**
4732      * This function returns the parent phone of the current phone. It is applicable
4733      * only for IMS phone (function is overridden by ImsPhone). For others the phone
4734      * object itself is returned.
4735      * @return
4736      */
getDefaultPhone()4737     public Phone getDefaultPhone() {
4738         return this;
4739     }
4740 
4741     /**
4742      * SIP URIs aliased to the current subscriber given by the IMS implementation.
4743      * Applicable only on IMS; used in absence of line1number.
4744      * @return array of SIP URIs aliased to the current subscriber
4745      */
getCurrentSubscriberUris()4746     public Uri[] getCurrentSubscriberUris() {
4747         return null;
4748     }
4749 
getAppSmsManager()4750     public AppSmsManager getAppSmsManager() {
4751         return mAppSmsManager;
4752     }
4753 
4754     /**
4755      * Set SIM card power state.
4756      * @param state State of SIM (power down, power up, pass through)
4757      * - {@link android.telephony.TelephonyManager#CARD_POWER_DOWN}
4758      * - {@link android.telephony.TelephonyManager#CARD_POWER_UP}
4759      * - {@link android.telephony.TelephonyManager#CARD_POWER_UP_PASS_THROUGH}
4760      **/
setSimPowerState(int state, Message result, WorkSource workSource)4761     public void setSimPowerState(int state, Message result, WorkSource workSource) {
4762         mCi.setSimCardPower(state, result, workSource);
4763     }
4764 
4765     /**
4766      * Enable or disable Voice over NR (VoNR)
4767      * @param enabled enable or disable VoNR.
4768      **/
setVoNrEnabled(boolean enabled, Message result, WorkSource workSource)4769     public void setVoNrEnabled(boolean enabled, Message result, WorkSource workSource) {
4770         mCi.setVoNrEnabled(enabled, result, workSource);
4771     }
4772 
4773     /**
4774      * Is voice over NR enabled
4775      */
isVoNrEnabled(Message message, WorkSource workSource)4776     public void isVoNrEnabled(Message message, WorkSource workSource) {
4777         mCi.isVoNrEnabled(message, workSource);
4778     }
4779 
setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1, String gid2, String pnn, String spn, String carrierPrivilegeRules, String apn)4780     public void setCarrierTestOverride(String mccmnc, String imsi, String iccid, String gid1,
4781             String gid2, String pnn, String spn, String carrierPrivilegeRules, String apn) {
4782     }
4783 
4784     /**
4785      * Check if the device can only make the emergency call. The device is emergency call only if
4786      * none of the phone is in service, and one of them has the capability to make the emergency
4787      * call.
4788      *
4789      * @return {@code True} if the device is emergency call only, otherwise return {@code False}.
4790      */
isEmergencyCallOnly()4791     public static boolean isEmergencyCallOnly() {
4792         boolean isEmergencyCallOnly = false;
4793         for (Phone phone : PhoneFactory.getPhones()) {
4794             if (phone != null) {
4795                 ServiceStateTracker sst = phone.getServiceStateTracker();
4796                 ServiceState ss = sst.getServiceState();
4797                 // Combined reg state is in service, hence the device is not emergency call only.
4798                 if (sst.getCombinedRegState(ss) == ServiceState.STATE_IN_SERVICE) {
4799                     return false;
4800                 }
4801                 isEmergencyCallOnly |= ss.isEmergencyOnly();
4802             }
4803         }
4804         return isEmergencyCallOnly;
4805     }
4806 
4807     // Return true if either CSIM or RUIM app is present. By default it returns false.
isCdmaSubscriptionAppPresent()4808     public boolean isCdmaSubscriptionAppPresent() {
4809         return false;
4810     }
4811 
4812     /**
4813      * Enable or disable uicc applications.
4814      * @param enable whether to enable or disable uicc applications.
4815      * @param onCompleteMessage callback for async operation. Ignored if blockingCall is true.
4816      */
enableUiccApplications(boolean enable, Message onCompleteMessage)4817     public void enableUiccApplications(boolean enable, Message onCompleteMessage) {}
4818 
4819     /**
4820      * Whether disabling a physical subscription is supported or not.
4821      */
canDisablePhysicalSubscription()4822     public boolean canDisablePhysicalSubscription() {
4823         return false;
4824     }
4825 
4826     /**
4827      * Get the HAL version.
4828      *
4829      * @return the current HalVersion
4830      *
4831      * @deprecated Use {@link #getHalVersion(int service)} instead.
4832      */
4833     @Deprecated
getHalVersion()4834     public HalVersion getHalVersion() {
4835         return getHalVersion(HAL_SERVICE_RADIO);
4836     }
4837 
4838     /**
4839      * Get the HAL version with a specific service.
4840      *
4841      * @param service the service id to query
4842      * @return the current HalVersion for a specific service
4843      *
4844      */
getHalVersion(@alService int service)4845     public HalVersion getHalVersion(@HalService int service) {
4846         if (mCi != null && mCi instanceof RIL) {
4847             return ((RIL) mCi).getHalVersion(service);
4848         }
4849         return RIL.RADIO_HAL_VERSION_UNKNOWN;
4850     }
4851 
4852     /**
4853      * Get the SIM's MCC/MNC
4854      *
4855      * @return MCC/MNC in string format, empty string if not available.
4856      */
4857     @NonNull
getOperatorNumeric()4858     public String getOperatorNumeric() {
4859         return "";
4860     }
4861 
4862     /** Returns the {@link VoiceCallSessionStats} for this phone ID. */
getVoiceCallSessionStats()4863     public VoiceCallSessionStats getVoiceCallSessionStats() {
4864         return mVoiceCallSessionStats;
4865     }
4866 
4867     /** Sets the {@link VoiceCallSessionStats} mock for this phone ID during unit testing. */
4868     @VisibleForTesting
setVoiceCallSessionStats(VoiceCallSessionStats voiceCallSessionStats)4869     public void setVoiceCallSessionStats(VoiceCallSessionStats voiceCallSessionStats) {
4870         mVoiceCallSessionStats = voiceCallSessionStats;
4871     }
4872 
4873     /** Returns the {@link SmsStats} for this phone ID. */
getSmsStats()4874     public SmsStats getSmsStats() {
4875         return mSmsStats;
4876     }
4877 
4878     /** Sets the {@link SmsStats} mock for this phone ID during unit testing. */
4879     @VisibleForTesting
setSmsStats(SmsStats smsStats)4880     public void setSmsStats(SmsStats smsStats) {
4881         mSmsStats = smsStats;
4882     }
4883 
4884     /** Getter for Telephony Analytics */
getTelephonyAnalytics()4885     public TelephonyAnalytics getTelephonyAnalytics() {
4886         return mTelephonyAnalytics;
4887     }
4888 
4889     /** @hide */
getCarrierPrivilegesTracker()4890     public CarrierPrivilegesTracker getCarrierPrivilegesTracker() {
4891         return null;
4892     }
4893 
useSsOverIms(Message onComplete)4894     public boolean useSsOverIms(Message onComplete) {
4895         return false;
4896     }
4897 
4898     /**
4899      * Check if device is idle. Device is idle when it is not in high power consumption mode.
4900      *
4901      * @see DeviceStateMonitor#shouldEnableHighPowerConsumptionIndications()
4902      *
4903      * @return true if device is idle
4904      */
isDeviceIdle()4905     public boolean isDeviceIdle() {
4906         DeviceStateMonitor dsm = getDeviceStateMonitor();
4907         if (dsm == null) {
4908             Rlog.e(mLogTag, "isDeviceIdle: DeviceStateMonitor is null");
4909             return false;
4910         }
4911         return !dsm.shouldEnableHighPowerConsumptionIndications();
4912     }
4913 
4914     /**
4915      * Get notified when device idleness state has changed
4916      *
4917      * @param isIdle true if the new state is idle
4918      */
notifyDeviceIdleStateChanged(boolean isIdle)4919     public void notifyDeviceIdleStateChanged(boolean isIdle) {
4920         SignalStrengthController ssc = getSignalStrengthController();
4921         if (ssc == null) {
4922             Rlog.e(mLogTag, "notifyDeviceIdleStateChanged: SignalStrengthController is null");
4923             return;
4924         }
4925         ssc.onDeviceIdleStateChanged(isIdle);
4926     }
4927 
4928     /**
4929      * Returns a list of the equivalent home PLMNs (EF_EHPLMN) from the USIM app.
4930      *
4931      * @return A list of equivalent home PLMNs. Returns an empty list if EF_EHPLMN is empty or
4932      * does not exist on the SIM card.
4933      */
getEquivalentHomePlmns()4934     public @NonNull List<String> getEquivalentHomePlmns() {
4935         return Collections.emptyList();
4936     }
4937 
4938     /**
4939      *
4940      * @return
4941      */
getDataServicePackages()4942     public @NonNull List<String> getDataServicePackages() {
4943         return Collections.emptyList();
4944     }
4945 
4946     /**
4947      * Return link bandwidth estimator
4948      */
getLinkBandwidthEstimator()4949     public LinkBandwidthEstimator getLinkBandwidthEstimator() {
4950         return mLinkBandwidthEstimator;
4951     }
4952 
4953     /**
4954      * Request to get the current slicing configuration including URSP rules and
4955      * NSSAIs (configured, allowed and rejected).
4956      */
getSlicingConfig(Message response)4957     public void getSlicingConfig(Message response) {
4958         mCi.getSlicingConfig(response);
4959     }
4960 
4961     /**
4962      * Returns the InboundSmsHandler object for this phone
4963      */
getInboundSmsHandler(boolean is3gpp2)4964     public InboundSmsHandler getInboundSmsHandler(boolean is3gpp2) {
4965         return null;
4966     }
4967 
4968     /**
4969      * @return The data network controller
4970      */
getDataNetworkController()4971     public @NonNull DataNetworkController getDataNetworkController() {
4972         return mDataNetworkController;
4973     }
4974 
4975     /**
4976      * @return The sms dispatchers controller
4977      */
4978     @Nullable
getSmsDispatchersController()4979     public SmsDispatchersController getSmsDispatchersController() {
4980         return null;
4981     }
4982 
4983     /**
4984      * @return The data settings manager
4985      */
4986     @NonNull
getDataSettingsManager()4987     public DataSettingsManager getDataSettingsManager() {
4988         return mDataNetworkController.getDataSettingsManager();
4989     }
4990 
4991     /**
4992      * Used in unit tests to set whether the AllowedNetworkTypes is loaded from Db.  Should not
4993      * be used otherwise.
4994      *
4995      * @return {@code true} if the AllowedNetworkTypes is loaded from Db,
4996      * {@code false} otherwise.
4997      */
4998     @VisibleForTesting
isAllowedNetworkTypesLoadedFromDb()4999     public boolean isAllowedNetworkTypesLoadedFromDb() {
5000         return mIsAllowedNetworkTypesLoadedFromDb;
5001     }
5002 
5003     /**
5004      * Returns the user's last setting for terminal-based call waiting
5005      * @param forCsOnly indicates the caller expects the result for CS calls only
5006      */
getTerminalBasedCallWaitingState(boolean forCsOnly)5007     public int getTerminalBasedCallWaitingState(boolean forCsOnly) {
5008         return CallWaitingController.TERMINAL_BASED_NOT_SUPPORTED;
5009     }
5010 
5011     /**
5012      * Notifies the change of the user setting of the terminal-based call waiting service
5013      * to IMS service.
5014      */
setTerminalBasedCallWaitingStatus(int state)5015     public void setTerminalBasedCallWaitingStatus(int state) {
5016     }
5017 
5018     /**
5019      * Notifies that the IMS service connected supports the terminal-based call waiting service
5020      */
setTerminalBasedCallWaitingSupported(boolean supported)5021     public void setTerminalBasedCallWaitingSupported(boolean supported) {
5022     }
5023 
5024     /**
5025      * Notifies the NAS and RRC layers of the radio the type of upcoming IMS traffic.
5026      *
5027      * @param token A nonce to identify the request.
5028      * @param trafficType IMS traffic type like registration, voice, video, SMS, emergency, and etc.
5029      * @param accessNetworkType The type of the radio access network used.
5030      * @param trafficDirection Indicates whether traffic is originated by mobile originated or
5031      *        mobile terminated use case eg. MO/MT call/SMS etc.
5032      * @param response is callback message.
5033      */
startImsTraffic(int token, @MmTelFeature.ImsTrafficType int trafficType, @AccessNetworkConstants.RadioAccessNetworkType int accessNetworkType, @MmTelFeature.ImsTrafficDirection int trafficDirection, Message response)5034     public void startImsTraffic(int token,
5035             @MmTelFeature.ImsTrafficType int trafficType,
5036             @AccessNetworkConstants.RadioAccessNetworkType int accessNetworkType,
5037             @MmTelFeature.ImsTrafficDirection int trafficDirection, Message response) {
5038         mCi.startImsTraffic(token, trafficType, accessNetworkType, trafficDirection, response);
5039     }
5040 
5041     /**
5042      * Notifies IMS traffic has been stopped.
5043      *
5044      * @param token The token assigned by startImsTraffic.
5045      * @param response is callback message.
5046      */
stopImsTraffic(int token, Message response)5047     public void stopImsTraffic(int token, Message response) {
5048         mCi.stopImsTraffic(token, response);
5049     }
5050 
5051     /**
5052      * Register for notifications of connection setup failure
5053      *
5054      * @param h Handler for notification message.
5055      * @param what User-defined message code.
5056      * @param obj User object.
5057      */
registerForConnectionSetupFailure(Handler h, int what, Object obj)5058     public void registerForConnectionSetupFailure(Handler h, int what, Object obj) {
5059         mCi.registerForConnectionSetupFailure(h, what, obj);
5060     }
5061 
5062     /**
5063      * Unregister for notifications of connection setup failure
5064      *
5065      * @param h Handler to be removed from the registrant list.
5066      */
unregisterForConnectionSetupFailure(Handler h)5067     public void unregisterForConnectionSetupFailure(Handler h) {
5068         mCi.unregisterForConnectionSetupFailure(h);
5069     }
5070 
5071     /**
5072      * Triggers the UE initiated EPS fallback procedure.
5073      *
5074      * @param reason specifies the reason for EPS fallback.
5075      * @param response is callback message.
5076      */
triggerEpsFallback(@mTelFeature.EpsFallbackReason int reason, Message response)5077     public void triggerEpsFallback(@MmTelFeature.EpsFallbackReason int reason, Message response) {
5078         mCi.triggerEpsFallback(reason, response);
5079     }
5080 
5081     /**
5082      * Notifies the recommended bit rate for the indicated logical channel and direction.
5083      *
5084      * @param mediaType MediaType is used to identify media stream such as audio or video.
5085      * @param direction Direction of this packet stream (e.g. uplink or downlink).
5086      * @param bitsPerSecond The recommended bit rate for the UE for a specific logical channel and
5087      *        a specific direction by NW.
5088      */
triggerNotifyAnbr(int mediaType, int direction, int bitsPerSecond)5089     public void triggerNotifyAnbr(int mediaType, int direction, int bitsPerSecond) {
5090     }
5091 
5092     /**
5093      * Sets the emergency mode
5094      *
5095      * @param emcMode The radio emergency mode type.
5096      * @param result Callback message.
5097      */
setEmergencyMode(@mergencyConstants.EmergencyMode int emcMode, @Nullable Message result)5098     public void setEmergencyMode(@EmergencyConstants.EmergencyMode int emcMode,
5099             @Nullable Message result) {
5100         mCi.setEmergencyMode(emcMode, result);
5101     }
5102 
5103     /**
5104      * Triggers an emergency network scan.
5105      *
5106      * @param accessNetwork Contains the list of access network types to be prioritized
5107      *        during emergency scan. The 1st entry has the highest priority.
5108      * @param scanType Indicates the type of scans to be performed i.e. limited scan,
5109      *        full service scan or any scan.
5110      * @param result Callback message.
5111      */
triggerEmergencyNetworkScan( @onNull @ccessNetworkConstants.RadioAccessNetworkType int[] accessNetwork, @DomainSelectionService.EmergencyScanType int scanType, @Nullable Message result)5112     public void triggerEmergencyNetworkScan(
5113             @NonNull @AccessNetworkConstants.RadioAccessNetworkType int[] accessNetwork,
5114             @DomainSelectionService.EmergencyScanType int scanType, @Nullable Message result) {
5115         mCi.triggerEmergencyNetworkScan(accessNetwork, scanType, result);
5116     }
5117 
5118     /**
5119      * Cancels ongoing emergency network scan
5120      * @param resetScan Indicates how the next {@link #triggerEmergencyNetworkScan} should work.
5121      *        If {@code true}, then the modem shall start the new scan from the beginning,
5122      *        otherwise the modem shall resume from the last search.
5123      * @param result Callback message.
5124      */
cancelEmergencyNetworkScan(boolean resetScan, @Nullable Message result)5125     public void cancelEmergencyNetworkScan(boolean resetScan, @Nullable Message result) {
5126         mCi.cancelEmergencyNetworkScan(resetScan, result);
5127     }
5128 
5129     /**
5130      * Exits ongoing emergency mode
5131      * @param result Callback message.
5132      */
exitEmergencyMode(@ullable Message result)5133     public void exitEmergencyMode(@Nullable Message result) {
5134         mCi.exitEmergencyMode(result);
5135     }
5136 
5137     /**
5138      * Registers for emergency network scan result.
5139      *
5140      * @param h Handler for notification message.
5141      * @param what User-defined message code.
5142      * @param obj User object.
5143      */
registerForEmergencyNetworkScan(@onNull Handler h, int what, @Nullable Object obj)5144     public void registerForEmergencyNetworkScan(@NonNull Handler h,
5145             int what, @Nullable Object obj) {
5146         mCi.registerForEmergencyNetworkScan(h, what, obj);
5147     }
5148 
5149     /**
5150      * Unregisters for emergency network scan result.
5151      *
5152      * @param h Handler to be removed from the registrant list.
5153      */
unregisterForEmergencyNetworkScan(@onNull Handler h)5154     public void unregisterForEmergencyNetworkScan(@NonNull Handler h) {
5155         mCi.unregisterForEmergencyNetworkScan(h);
5156     }
5157 
5158     /**
5159      * Notifies that IMS deregistration is triggered.
5160      *
5161      * @param reason the reason why the deregistration is triggered.
5162      */
triggerImsDeregistration( @msRegistrationImplBase.ImsDeregistrationReason int reason)5163     public void triggerImsDeregistration(
5164             @ImsRegistrationImplBase.ImsDeregistrationReason int reason) {
5165         if (mImsPhone != null) {
5166             mImsPhone.triggerImsDeregistration(reason);
5167         }
5168     }
5169 
5170     /**
5171      * Registers for the domain selected for emergency calls.
5172      *
5173      * @param h Handler for notification message.
5174      * @param what User-defined message code.
5175      * @param obj User object.
5176      */
registerForEmergencyDomainSelected( @onNull Handler h, int what, @Nullable Object obj)5177     public void registerForEmergencyDomainSelected(
5178             @NonNull Handler h, int what, @Nullable Object obj) {
5179     }
5180 
5181     /**
5182      * Unregisters for the domain selected for emergency calls.
5183      *
5184      * @param h Handler to be removed from the registrant list.
5185      */
unregisterForEmergencyDomainSelected(@onNull Handler h)5186     public void unregisterForEmergencyDomainSelected(@NonNull Handler h) {
5187     }
5188 
5189     /**
5190      * Notifies the domain selected.
5191      *
5192      * @param transportType The preferred transport type.
5193      */
notifyEmergencyDomainSelected( @ccessNetworkConstants.TransportType int transportType)5194     public void notifyEmergencyDomainSelected(
5195             @AccessNetworkConstants.TransportType int transportType) {
5196     }
5197 
5198     /**
5199      * @return Telephony tester instance.
5200      */
getTelephonyTester()5201     public @Nullable TelephonyTester getTelephonyTester() {
5202         return mTelephonyTester;
5203     }
5204 
5205     /**
5206      * @return User handle associated with the phone's subscription id. {@code null} if subscription
5207      * is invalid or not found.
5208      */
5209     @Nullable
getUserHandle()5210     public UserHandle getUserHandle() {
5211         int subId = getSubId();
5212 
5213         UserHandle userHandle = null;
5214         try {
5215             SubscriptionManager subManager = mContext.getSystemService(SubscriptionManager.class);
5216             if (subManager != null) {
5217                 userHandle = subManager.getSubscriptionUserHandle(subId);
5218             }
5219         } catch (IllegalArgumentException ex) {
5220             loge("getUserHandle: ex=" + ex);
5221         }
5222 
5223         return userHandle;
5224     }
5225 
5226     /**
5227      * Checks if the context user is a managed profile.
5228      *
5229      * Note that this applies specifically to <em>managed</em> profiles.
5230      *
5231      * @return whether the context user is a managed profile.
5232      */
isManagedProfile()5233     public boolean isManagedProfile() {
5234         UserHandle userHandle = getUserHandle();
5235         UserManager userManager = mContext.getSystemService(UserManager.class);
5236         if (userHandle == null || userManager == null) return false;
5237         return userManager.isManagedProfile(userHandle.getIdentifier());
5238     }
5239 
5240     /**
5241      * @return global null cipher and integrity enabled preference
5242      */
getNullCipherAndIntegrityEnabledPreference()5243     public boolean getNullCipherAndIntegrityEnabledPreference() {
5244         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
5245         return sp.getBoolean(PREF_NULL_CIPHER_AND_INTEGRITY_ENABLED, true);
5246     }
5247 
5248     /**
5249      * @return whether or not this Phone interacts with a modem that supports the null cipher
5250      * and integrity feature.
5251      */
isNullCipherAndIntegritySupported()5252     public boolean isNullCipherAndIntegritySupported() {
5253         return false;
5254     }
5255 
5256     /**
5257      * Override to implement handling of an update to the enablement of the null cipher and
5258      * integrity preference.
5259      * {@see #PREF_NULL_CIPHER_AND_INTEGRITY_ENABLED}
5260      */
handleNullCipherEnabledChange()5261     public void handleNullCipherEnabledChange() {
5262     }
5263 
5264     /**
5265      * @return whether or not this Phone interacts with a modem that supports the cellular
5266      * identifier disclosure transparency feature.
5267      */
isIdentifierDisclosureTransparencySupported()5268     public boolean isIdentifierDisclosureTransparencySupported() {
5269         return false;
5270     }
5271 
5272     /**
5273      * @return global cellular identifier disclosure transparency enabled preference
5274      */
getIdentifierDisclosureNotificationsPreferenceEnabled()5275     public boolean getIdentifierDisclosureNotificationsPreferenceEnabled() {
5276         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
5277         return sp.getBoolean(PREF_IDENTIFIER_DISCLOSURE_NOTIFICATIONS_ENABLED, false);
5278     }
5279 
5280     /**
5281      * Override to handle an update to the cellular identifier disclosure transparency preference.
5282      */
handleIdentifierDisclosureNotificationPreferenceChange()5283     public void handleIdentifierDisclosureNotificationPreferenceChange() {
5284     }
5285 
5286     /**
5287      * @return whether this Phone interacts with a modem that supports the null cipher
5288      * notification feature.
5289      */
isNullCipherNotificationSupported()5290     public boolean isNullCipherNotificationSupported() {
5291         return false;
5292     }
5293 
5294     /**
5295      * @return whether the global null cipher notifications preference is enabled.
5296      */
getNullCipherNotificationsPreferenceEnabled()5297     public boolean getNullCipherNotificationsPreferenceEnabled() {
5298         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
5299         return sp.getBoolean(PREF_NULL_CIPHER_NOTIFICATIONS_ENABLED, false);
5300     }
5301 
5302     /**
5303      * Override to handle an update to the null cipher notification preference.
5304      */
handleNullCipherNotificationPreferenceChanged()5305     public void handleNullCipherNotificationPreferenceChanged() {
5306     }
5307 
5308     /**
5309      * Refresh the safety sources in response to the identified broadcast.
5310      */
refreshSafetySources(String refreshBroadcastId)5311     public void refreshSafetySources(String refreshBroadcastId) {
5312     }
5313 
5314     /**
5315      * Notifies the IMS call status to the modem.
5316      *
5317      * @param imsCallInfo The list of {@link ImsCallInfo}.
5318      * @param response A callback to receive the response.
5319      */
updateImsCallStatus(@onNull List<ImsCallInfo> imsCallInfo, Message response)5320     public void updateImsCallStatus(@NonNull List<ImsCallInfo> imsCallInfo, Message response) {
5321         mCi.updateImsCallStatus(imsCallInfo, response);
5322     }
5323 
5324     /**
5325      * Enables or disables N1 mode (access to 5G core network) in accordance with
5326      * 3GPP TS 24.501 4.9.
5327      * @param enable {@code true} to enable N1 mode, {@code false} to disable N1 mode.
5328      * @param result Callback message to receive the result.
5329      */
setN1ModeEnabled(boolean enable, Message result)5330     public void setN1ModeEnabled(boolean enable, Message result) {
5331         mCi.setN1ModeEnabled(enable, result);
5332     }
5333 
5334     /**
5335      * Check whether N1 mode (access to 5G core network) is enabled or not.
5336      * @param result Callback message to receive the result.
5337      */
isN1ModeEnabled(Message result)5338     public void isN1ModeEnabled(Message result) {
5339         mCi.isN1ModeEnabled(result);
5340     }
5341 
5342     /**
5343      * Return current cell broadcast ranges.
5344      */
getCellBroadcastIdRanges()5345     public List<CellBroadcastIdRange> getCellBroadcastIdRanges() {
5346         return new ArrayList<>();
5347     }
5348 
5349     /**
5350      * Set reception of cell broadcast messages with the list of the given ranges.
5351      */
setCellBroadcastIdRanges( @onNull List<CellBroadcastIdRange> ranges, Consumer<Integer> callback)5352     public void setCellBroadcastIdRanges(
5353             @NonNull List<CellBroadcastIdRange> ranges, Consumer<Integer> callback) {
5354         callback.accept(TelephonyManager.CELL_BROADCAST_RESULT_UNSUPPORTED);
5355     }
5356 
5357     /**
5358      * Start the emergency callback mode
5359      * @param type for callback mode entry.
5360      * @param durationMillis is the number of milliseconds remaining in the emergency callback
5361      *                        mode.
5362      */
startEmergencyCallbackMode(@elephonyManager.EmergencyCallbackModeType int type, long durationMillis)5363     public void startEmergencyCallbackMode(@TelephonyManager.EmergencyCallbackModeType int type,
5364             long durationMillis) {
5365         if (!mFeatureFlags.emergencyCallbackModeNotification()) return;
5366 
5367         Rlog.d(mLogTag, "startEmergencyCallbackMode:type=" + type);
5368         mNotifier.notifyCallbackModeStarted(this, type, durationMillis);
5369     }
5370 
5371     /**
5372      * Restart the emergency callback mode
5373      * @param type for callback mode entry.
5374      * @param durationMillis is the number of milliseconds remaining in the emergency callback
5375      *                        mode.
5376      */
restartEmergencyCallbackMode(@elephonyManager.EmergencyCallbackModeType int type, long durationMillis)5377     public void restartEmergencyCallbackMode(@TelephonyManager.EmergencyCallbackModeType int type,
5378             long durationMillis) {
5379         if (!mFeatureFlags.emergencyCallbackModeNotification()) return;
5380 
5381         Rlog.d(mLogTag, "restartEmergencyCallbackMode:type=" + type);
5382         mNotifier.notifyCallbackModeRestarted(this, type, durationMillis);
5383     }
5384 
5385     /**
5386      * Stop the emergency callback mode
5387      * @param type for callback mode exit.
5388      * @param reason for stopping callback mode.
5389      */
stopEmergencyCallbackMode(@elephonyManager.EmergencyCallbackModeType int type, @TelephonyManager.EmergencyCallbackModeStopReason int reason)5390     public void stopEmergencyCallbackMode(@TelephonyManager.EmergencyCallbackModeType int type,
5391             @TelephonyManager.EmergencyCallbackModeStopReason int reason) {
5392         if (!mFeatureFlags.emergencyCallbackModeNotification()) return;
5393 
5394         Rlog.d(mLogTag, "stopEmergencyCallbackMode:type=" + type + ", reason=" + reason);
5395         mNotifier.notifyCallbackModeStopped(this, type, reason);
5396     }
5397 
5398     /**
5399      * Notify carrier roaming non-terrestrial network mode changed
5400      * @param active {@code true} If the device is connected to carrier roaming
5401      *                           non-terrestrial network or was connected within the
5402      *                           {CarrierConfigManager#KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT}
5403      *                           duration, {code false} otherwise.
5404      */
notifyCarrierRoamingNtnModeChanged(boolean active)5405     public void notifyCarrierRoamingNtnModeChanged(boolean active) {
5406         logd("notifyCarrierRoamingNtnModeChanged active:" + active);
5407         mNotifier.notifyCarrierRoamingNtnModeChanged(this, active);
5408     }
5409 
5410     /**
5411      * Notify external listeners that the device eligibility to connect to carrier roaming
5412      * non-terrestrial network changed.
5413      *
5414      * @param eligible {@code true} when the device is eligible for satellite
5415      * communication if all the following conditions are met:
5416      * <ul>
5417      * <li>Any subscription on the device supports P2P satellite messaging which is defined by
5418      * {@link CarrierConfigManager#KEY_SATELLITE_ATTACH_SUPPORTED_BOOL} </li>
5419      * <li>{@link CarrierConfigManager#KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT} set to
5420      * {@link CarrierConfigManager#CARRIER_ROAMING_NTN_CONNECT_MANUAL} </li>
5421      * <li>The device is in {@link ServiceState#STATE_OUT_OF_SERVICE}, not connected to Wi-Fi,
5422      * and the hysteresis timer defined by {@link CarrierConfigManager
5423      * #KEY_CARRIER_SUPPORTED_SATELLITE_NOTIFICATION_HYSTERESIS_SEC_INT} is expired. </li>
5424      * </ul>
5425      */
notifyCarrierRoamingNtnEligibleStateChanged(boolean eligible)5426     public void notifyCarrierRoamingNtnEligibleStateChanged(boolean eligible) {
5427         logd("notifyCarrierRoamingNtnEligibleStateChanged eligible:" + eligible);
5428         mNotifier.notifyCarrierRoamingNtnEligibleStateChanged(this, eligible);
5429         ControllerMetricsStats.getInstance().reportP2PSmsEligibilityNotificationsCount(eligible);
5430     }
5431 
5432     /**
5433      * Notify external listeners that carrier roaming non-terrestrial available services changed.
5434      * @param availableServices The list of the supported services.
5435      */
notifyCarrierRoamingNtnAvailableServicesChanged( @etworkRegistrationInfo.ServiceType int[] availableServices)5436     public void notifyCarrierRoamingNtnAvailableServicesChanged(
5437             @NetworkRegistrationInfo.ServiceType int[] availableServices) {
5438         logd("notifyCarrierRoamingNtnAvailableServicesChanged availableServices:"
5439                 + Arrays.toString(availableServices));
5440         mNotifier.notifyCarrierRoamingNtnAvailableServicesChanged(this, availableServices);
5441     }
5442 
5443     /**
5444      * Notify external listeners that carrier roaming non-terrestrial network
5445      * signal strength changed.
5446      * @param ntnSignalStrength non-terrestrial network signal strength.
5447      */
notifyCarrierRoamingNtnSignalStrengthChanged( @onNull NtnSignalStrength ntnSignalStrength)5448     public void notifyCarrierRoamingNtnSignalStrengthChanged(
5449             @NonNull NtnSignalStrength ntnSignalStrength) {
5450         logd("notifyCarrierRoamingNtnSignalStrengthChanged: ntnSignalStrength="
5451                 + ntnSignalStrength.getLevel());
5452         mNotifier.notifyCarrierRoamingNtnSignalStrengthChanged(this, ntnSignalStrength);
5453     }
5454 
5455     /**
5456      * Set the non-terrestrial PLMN with lower priority than terrestrial networks.
5457      *
5458      * @param simSlot Indicates the SIM slot to which this API will be applied. The modem will use
5459      *                this information to determine the relevant carrier.
5460      * @param carrierPlmnList The list of roaming PLMN used for connecting to satellite networks
5461      *                        supported by user subscription.
5462      * @param allSatellitePlmnList Modem should use the allSatellitePlmnList to identify satellite
5463      *                             PLMNs that are not supported by the carrier and make sure not to
5464      *                             attach to them.
5465      * @param result Callback message to receive the result.
5466      */
setSatellitePlmn(int simSlot, @NonNull List<String> carrierPlmnList, @NonNull List<String> allSatellitePlmnList, Message result)5467     public void setSatellitePlmn(int simSlot,
5468             @NonNull List<String> carrierPlmnList, @NonNull List<String> allSatellitePlmnList,
5469             Message result) {
5470         logd("setSatellitePlmn: simSlot=" + simSlot
5471                 + " carrierPlmnList=" + carrierPlmnList.toString()
5472                 + " allSatellitePlmnList=" + allSatellitePlmnList.toString());
5473         mCi.setSatellitePlmn(simSlot, carrierPlmnList, allSatellitePlmnList, result);
5474     }
5475 
5476     /**
5477      * Enable or disable satellite in the cellular modem associated with a carrier.
5478      *
5479      * @param simSlot Indicates the SIM slot to which this API will be applied. The modem will use
5480      *                this information to determine the relevant carrier.
5481      * @param satelliteEnabled {@code true} to enable satellite, {@code false} to disable satellite.
5482      * @param result Callback message to receive the result.
5483      */
setSatelliteEnabledForCarrier(int simSlot, boolean satelliteEnabled, Message result)5484     public void setSatelliteEnabledForCarrier(int simSlot, boolean satelliteEnabled,
5485             Message result) {
5486         logd("setSatelliteEnabledForCarrier: simSlot=" + simSlot
5487                 + " satelliteEnabled=" + satelliteEnabled);
5488         mCi.setSatelliteEnabledForCarrier(simSlot, satelliteEnabled, result);
5489     }
5490 
5491     /**
5492      * Check whether satellite is enabled in the cellular modem associated with a carrier.
5493      *
5494      * @param simSlot Indicates the SIM slot to which this API will be applied.
5495      * @param result Callback message to receive the result.
5496      */
isSatelliteEnabledForCarrier(int simSlot, Message result)5497     public void isSatelliteEnabledForCarrier(int simSlot, Message result) {
5498         mCi.isSatelliteEnabledForCarrier(simSlot, result);
5499     }
5500 
dump(FileDescriptor fd, PrintWriter pw, String[] args)5501     public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5502         pw.println("Phone: subId=" + getSubId());
5503         pw.println(" mPhoneId=" + mPhoneId);
5504         pw.println(" mCi=" + mCi);
5505         pw.println(" mDoesRilSendMultipleCallRing=" + mDoesRilSendMultipleCallRing);
5506         pw.println(" mCallRingContinueToken=" + mCallRingContinueToken);
5507         pw.println(" mCallRingDelay=" + mCallRingDelay);
5508         pw.println(" mIsVoiceCapable=" + mIsVoiceCapable);
5509         pw.println(" mIccRecords=" + mIccRecords.get());
5510         pw.println(" mUiccApplication=" + mUiccApplication.get());
5511         pw.println(" mSmsStorageMonitor=" + mSmsStorageMonitor);
5512         pw.println(" mSmsUsageMonitor=" + mSmsUsageMonitor);
5513         pw.flush();
5514         pw.println(" mLooper=" + mLooper);
5515         pw.println(" mContext=" + mContext);
5516         pw.println(" mNotifier=" + mNotifier);
5517         pw.println(" mSimulatedRadioControl=" + mSimulatedRadioControl);
5518         pw.println(" mUnitTestMode=" + mUnitTestMode);
5519         pw.println(" getUnitTestMode()=" + getUnitTestMode());
5520         pw.println(" getState()=" + getState());
5521         pw.println(" getIccSerialNumber()=" + Rlog.pii(mLogTag, getIccSerialNumber()));
5522         pw.println(" getIccRecordsLoaded()=" + getIccRecordsLoaded());
5523         pw.println(" getMessageWaitingIndicator()=" + getMessageWaitingIndicator());
5524         pw.println(" getCallForwardingIndicator()=" + getCallForwardingIndicator());
5525         pw.println(" isInEmergencyCall()=" + isInEmergencyCall());
5526         pw.flush();
5527         pw.println(" isInEcm()=" + isInEcm());
5528         pw.println(" getPhoneName()=" + getPhoneName());
5529         pw.println(" getPhoneType()=" + getPhoneType());
5530         pw.println(" getVoiceMessageCount()=" + getVoiceMessageCount());
5531         pw.println(" needsOtaServiceProvisioning=" + needsOtaServiceProvisioning());
5532         pw.println(" isInEmergencySmsMode=" + isInEmergencySmsMode());
5533         pw.println(" isEcmCanceledForEmergency=" + isEcmCanceledForEmergency());
5534         pw.println(" service state=" + getServiceState());
5535         pw.flush();
5536         pw.println("++++++++++++++++++++++++++++++++");
5537 
5538         if (mImsPhone != null) {
5539             try {
5540                 mImsPhone.dump(fd, pw, args);
5541             } catch (Exception e) {
5542                 e.printStackTrace();
5543             }
5544 
5545             pw.flush();
5546             pw.println("++++++++++++++++++++++++++++++++");
5547         }
5548 
5549         if (mDataNetworkController != null) {
5550             try {
5551                 mDataNetworkController.dump(fd, pw, args);
5552             } catch (Exception e) {
5553                 e.printStackTrace();
5554             }
5555             pw.flush();
5556             pw.println("++++++++++++++++++++++++++++++++");
5557         }
5558 
5559         if (getServiceStateTracker() != null) {
5560             try {
5561                 getServiceStateTracker().dump(fd, pw, args);
5562             } catch (Exception e) {
5563                 e.printStackTrace();
5564             }
5565 
5566             pw.flush();
5567             pw.println("++++++++++++++++++++++++++++++++");
5568         }
5569 
5570         if (getEmergencyNumberTracker() != null) {
5571             try {
5572                 getEmergencyNumberTracker().dump(fd, pw, args);
5573             } catch (Exception e) {
5574                 e.printStackTrace();
5575             }
5576 
5577             pw.flush();
5578             pw.println("++++++++++++++++++++++++++++++++");
5579         }
5580 
5581         if (getDisplayInfoController() != null) {
5582             try {
5583                 getDisplayInfoController().dump(fd, pw, args);
5584             } catch (Exception e) {
5585                 e.printStackTrace();
5586             }
5587 
5588             pw.flush();
5589             pw.println("++++++++++++++++++++++++++++++++");
5590         }
5591 
5592         if (mCarrierResolver != null) {
5593             try {
5594                 mCarrierResolver.dump(fd, pw, args);
5595             } catch (Exception e) {
5596                 e.printStackTrace();
5597             }
5598 
5599             pw.flush();
5600             pw.println("++++++++++++++++++++++++++++++++");
5601         }
5602 
5603         if (mCarrierActionAgent != null) {
5604             try {
5605                 mCarrierActionAgent.dump(fd, pw, args);
5606             } catch (Exception e) {
5607                 e.printStackTrace();
5608             }
5609 
5610             pw.flush();
5611             pw.println("++++++++++++++++++++++++++++++++");
5612         }
5613 
5614         if (mCarrierSignalAgent != null) {
5615             try {
5616                 mCarrierSignalAgent.dump(fd, pw, args);
5617             } catch (Exception e) {
5618                 e.printStackTrace();
5619             }
5620 
5621             pw.flush();
5622             pw.println("++++++++++++++++++++++++++++++++");
5623         }
5624 
5625         if (getCallTracker() != null) {
5626             try {
5627                 getCallTracker().dump(fd, pw, args);
5628             } catch (Exception e) {
5629                 e.printStackTrace();
5630             }
5631 
5632             pw.flush();
5633             pw.println("++++++++++++++++++++++++++++++++");
5634         }
5635 
5636         if (mSimActivationTracker != null) {
5637             try {
5638                 mSimActivationTracker.dump(fd, pw, args);
5639             } catch (Exception e) {
5640                 e.printStackTrace();
5641             }
5642 
5643             pw.flush();
5644             pw.println("++++++++++++++++++++++++++++++++");
5645         }
5646 
5647         if (mDeviceStateMonitor != null) {
5648             pw.println("DeviceStateMonitor:");
5649             mDeviceStateMonitor.dump(fd, pw, args);
5650             pw.println("++++++++++++++++++++++++++++++++");
5651         }
5652 
5653         if (mSignalStrengthController != null) {
5654             pw.println("SignalStrengthController:");
5655             mSignalStrengthController.dump(fd, pw, args);
5656             pw.println("++++++++++++++++++++++++++++++++");
5657         }
5658 
5659         if (mAccessNetworksManager != null) {
5660             mAccessNetworksManager.dump(fd, pw, args);
5661         }
5662 
5663         if (mCi != null && mCi instanceof RIL) {
5664             try {
5665                 ((RIL)mCi).dump(fd, pw, args);
5666             } catch (Exception e) {
5667                 e.printStackTrace();
5668             }
5669 
5670             pw.flush();
5671             pw.println("++++++++++++++++++++++++++++++++");
5672         }
5673 
5674         if (getCarrierPrivilegesTracker() != null) {
5675             pw.println("CarrierPrivilegesTracker:");
5676             getCarrierPrivilegesTracker().dump(fd, pw, args);
5677             pw.println("++++++++++++++++++++++++++++++++");
5678         }
5679 
5680         if (getLinkBandwidthEstimator() != null) {
5681             pw.println("LinkBandwidthEstimator:");
5682             getLinkBandwidthEstimator().dump(fd, pw, args);
5683             pw.println("++++++++++++++++++++++++++++++++");
5684         }
5685 
5686         pw.println("Phone Local Log: ");
5687         if (mLocalLog != null) {
5688             try {
5689                 mLocalLog.dump(fd, pw, args);
5690             } catch (Exception e) {
5691                 e.printStackTrace();
5692             }
5693             pw.flush();
5694             pw.println("++++++++++++++++++++++++++++++++");
5695         }
5696         if (mTelephonyAnalytics != null) {
5697             try {
5698                 mTelephonyAnalytics.dump(fd, pw, args);
5699             } catch (Exception e) {
5700                 e.printStackTrace();
5701             }
5702         }
5703     }
5704 
logd(String s)5705     private void logd(String s) {
5706         Rlog.d(mLogTag, "[" + mPhoneId + "] " + s);
5707     }
5708 
logi(String s)5709     private void logi(String s) {
5710         Rlog.i(mLogTag, "[" + mPhoneId + "] " + s);
5711     }
5712 
loge(String s)5713     private void loge(String s) {
5714         Rlog.e(mLogTag, "[" + mPhoneId + "] " + s);
5715     }
5716 }
5717