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