1 /*
2  * Copyright (C) 2008 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 android.telephony;
18 
19 import android.Manifest;
20 import android.annotation.NonNull;
21 import android.annotation.RequiresPermission;
22 import android.annotation.SystemApi;
23 import android.annotation.TestApi;
24 import android.compat.annotation.ChangeId;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.os.Binder;
27 import android.os.Build;
28 import android.os.Handler;
29 import android.os.HandlerExecutor;
30 import android.os.Looper;
31 import android.telephony.Annotation.CallState;
32 import android.telephony.Annotation.RadioPowerState;
33 import android.telephony.Annotation.SimActivationState;
34 import android.telephony.Annotation.SrvccState;
35 import android.telephony.emergency.EmergencyNumber;
36 import android.telephony.ims.ImsReasonInfo;
37 
38 import com.android.internal.annotations.VisibleForTesting;
39 import com.android.internal.telephony.IPhoneStateListener;
40 
41 import dalvik.system.VMRuntime;
42 
43 import java.lang.ref.WeakReference;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.concurrent.Executor;
47 
48 /**
49  * A listener class for monitoring changes in specific telephony states
50  * on the device, including service state, signal strength, message
51  * waiting indicator (voicemail), and others.
52  * <p>
53  * Override the methods for the state that you wish to receive updates for, and
54  * pass your PhoneStateListener object, along with bitwise-or of the LISTEN_
55  * flags to {@link TelephonyManager#listen TelephonyManager.listen()}. Methods are
56  * called when the state changes, as well as once on initial registration.
57  * <p>
58  * Note that access to some telephony information is
59  * permission-protected. Your application won't receive updates for protected
60  * information unless it has the appropriate permissions declared in
61  * its manifest file. Where permissions apply, they are noted in the
62  * appropriate LISTEN_ flags.
63  */
64 public class PhoneStateListener {
65     private static final String LOG_TAG = "PhoneStateListener";
66     private static final boolean DBG = false; // STOPSHIP if true
67 
68     /**
69      * Experiment flag to set the per-pid registration limit for PhoneStateListeners
70      *
71      * Limit on registrations of {@link PhoneStateListener}s on a per-pid
72      * basis. When this limit is exceeded, any calls to {@link TelephonyManager#listen} will fail
73      * with an {@link IllegalStateException}.
74      *
75      * {@link android.os.Process#PHONE_UID}, {@link android.os.Process#SYSTEM_UID}, and the uid that
76      * TelephonyRegistry runs under are exempt from this limit.
77      *
78      * If the value of the flag is less than 1, enforcement of the limit will be disabled.
79      * @hide
80      */
81     public static final String FLAG_PER_PID_REGISTRATION_LIMIT =
82             "phone_state_listener_per_pid_registration_limit";
83 
84     /**
85      * Default value for the per-pid registation limit.
86      * See {@link #FLAG_PER_PID_REGISTRATION_LIMIT}.
87      * @hide
88      */
89     public static final int DEFAULT_PER_PID_REGISTRATION_LIMIT = 50;
90 
91     /**
92      * This change enables a limit on the number of {@link PhoneStateListener} objects any process
93      * may register via {@link TelephonyManager#listen}. The default limit is 50, which may change
94      * via remote device config updates.
95      *
96      * This limit is enforced via an {@link IllegalStateException} thrown from
97      * {@link TelephonyManager#listen} when the offending process attempts to register one too many
98      * listeners.
99      *
100      * @hide
101      */
102     @ChangeId
103     public static final long PHONE_STATE_LISTENER_LIMIT_CHANGE_ID = 150880553L;
104 
105     /**
106      * Stop listening for updates.
107      *
108      * The PhoneStateListener is not tied to any subscription and unregistered for any update.
109      */
110     public static final int LISTEN_NONE = 0;
111 
112     /**
113      *  Listen for changes to the network service state (cellular).
114      *
115      *  @see #onServiceStateChanged
116      *  @see ServiceState
117      */
118     public static final int LISTEN_SERVICE_STATE                            = 0x00000001;
119 
120     /**
121      * Listen for changes to the network signal strength (cellular).
122      * {@more}
123      *
124      * @see #onSignalStrengthChanged
125      *
126      * @deprecated by {@link #LISTEN_SIGNAL_STRENGTHS}
127      */
128     @Deprecated
129     public static final int LISTEN_SIGNAL_STRENGTH                          = 0x00000002;
130 
131     /**
132      * Listen for changes to the message-waiting indicator.
133      * {@more}
134      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE
135      * READ_PHONE_STATE} or that the calling app has carrier privileges (see
136      * {@link TelephonyManager#hasCarrierPrivileges}).
137      * <p>
138      * Example: The status bar uses this to determine when to display the
139      * voicemail icon.
140      *
141      * @see #onMessageWaitingIndicatorChanged
142      */
143     public static final int LISTEN_MESSAGE_WAITING_INDICATOR                = 0x00000004;
144 
145     /**
146      * Listen for changes to the call-forwarding indicator.
147      * {@more}
148      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE
149      * READ_PHONE_STATE} or that the calling app has carrier privileges (see
150      * {@link TelephonyManager#hasCarrierPrivileges}).
151      *
152      * @see #onCallForwardingIndicatorChanged
153      */
154     public static final int LISTEN_CALL_FORWARDING_INDICATOR                = 0x00000008;
155 
156     /**
157      * Listen for changes to the device's cell location. Note that
158      * this will result in frequent callbacks to the listener.
159      * {@more}
160      * Requires Permission: {@link android.Manifest.permission#ACCESS_FINE_LOCATION
161      * ACCESS_FINE_LOCATION}
162      * <p>
163      * If you need regular location updates but want more control over
164      * the update interval or location precision, you can set up a listener
165      * through the {@link android.location.LocationManager location manager}
166      * instead.
167      *
168      * @see #onCellLocationChanged
169      */
170     public static final int LISTEN_CELL_LOCATION                            = 0x00000010;
171 
172     /**
173      * Listen for changes to the device call state.
174      * {@more}
175      *
176      * @see #onCallStateChanged
177      */
178     public static final int LISTEN_CALL_STATE                               = 0x00000020;
179 
180     /**
181      * Listen for changes to the data connection state (cellular).
182      *
183      * @see #onDataConnectionStateChanged
184      */
185     public static final int LISTEN_DATA_CONNECTION_STATE                    = 0x00000040;
186 
187     /**
188      * Listen for changes to the direction of data traffic on the data
189      * connection (cellular).
190      * {@more}
191      * Example: The status bar uses this to display the appropriate
192      * data-traffic icon.
193      *
194      * @see #onDataActivity
195      */
196     public static final int LISTEN_DATA_ACTIVITY                            = 0x00000080;
197 
198     /**
199      * Listen for changes to the network signal strengths (cellular).
200      * <p>
201      * Example: The status bar uses this to control the signal-strength
202      * icon.
203      *
204      * @see #onSignalStrengthsChanged
205      */
206     public static final int LISTEN_SIGNAL_STRENGTHS                         = 0x00000100;
207 
208     /**
209      * Listen for changes of the network signal strengths (cellular) always reported from modem,
210      * even in some situations such as the screen of the device is off.
211      *
212      * @see #onSignalStrengthsChanged
213      *
214      * @hide
215      */
216     @RequiresPermission(android.Manifest.permission.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH)
217     public static final int LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH          = 0x00000200;
218 
219     /**
220      * Listen for changes to observed cell info.
221      *
222      * @see #onCellInfoChanged
223      */
224     public static final int LISTEN_CELL_INFO = 0x00000400;
225 
226     /**
227      * Listen for {@link android.telephony.Annotation.PreciseCallStates} of ringing,
228      * background and foreground calls.
229      *
230      * <p>Requires permission {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE}
231      * or the calling app has carrier privileges
232      * (see {@link TelephonyManager#hasCarrierPrivileges}).
233      *
234      * @hide
235      */
236     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
237     @SystemApi
238     public static final int LISTEN_PRECISE_CALL_STATE                       = 0x00000800;
239 
240     /**
241      * Listen for {@link PreciseDataConnectionState} on the data connection (cellular).
242      *
243      * <p>Requires permission {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE}
244      * or the calling app has carrier privileges
245      * (see {@link TelephonyManager#hasCarrierPrivileges}).
246      *
247      * @see #onPreciseDataConnectionStateChanged
248      */
249     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
250     public static final int LISTEN_PRECISE_DATA_CONNECTION_STATE            = 0x00001000;
251 
252     /**
253      * Listen for real time info for all data connections (cellular)).
254      * {@more}
255      * Requires Permission: {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE
256      * READ_PRECISE_PHONE_STATE}
257      * @see #onDataConnectionRealTimeInfoChanged(DataConnectionRealTimeInfo)
258      *
259      * @deprecated Use {@link TelephonyManager#getModemActivityInfo()}
260      * @hide
261      */
262     @Deprecated
263     public static final int LISTEN_DATA_CONNECTION_REAL_TIME_INFO           = 0x00002000;
264 
265     /**
266      * Listen for changes to the SRVCC state of the active call.
267      *
268      * <p>Requires permission {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
269      *
270      * @see #onServiceStateChanged(ServiceState)
271      * @hide
272      */
273     @SystemApi
274     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
275     public static final int LISTEN_SRVCC_STATE_CHANGED                     = 0x00004000;
276 
277     /**
278      * Listen for OEM hook raw event
279      *
280      * @see #onOemHookRawEvent
281      * @hide
282      * @deprecated OEM needs a vendor-extension hal and their apps should use that instead
283      */
284     @Deprecated
285     public static final int LISTEN_OEM_HOOK_RAW_EVENT                       = 0x00008000;
286 
287     /**
288      * Listen for carrier network changes indicated by a carrier app.
289      *
290      * @see #onCarrierNetworkRequest
291      * @see TelephonyManager#notifyCarrierNetworkChange(boolean)
292      * @hide
293      */
294     public static final int LISTEN_CARRIER_NETWORK_CHANGE                   = 0x00010000;
295 
296     /**
297      * Listen for changes to the sim voice activation state
298      *
299      * <p>Requires permission {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
300      *
301      * @see TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATING
302      * @see TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATED
303      * @see TelephonyManager#SIM_ACTIVATION_STATE_DEACTIVATED
304      * @see TelephonyManager#SIM_ACTIVATION_STATE_RESTRICTED
305      * @see TelephonyManager#SIM_ACTIVATION_STATE_UNKNOWN
306      * {@more}
307      * Example: TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATED indicates voice service has been
308      * fully activated
309      *
310      * @see #onVoiceActivationStateChanged
311      * @hide
312      */
313     @SystemApi
314     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
315     public static final int LISTEN_VOICE_ACTIVATION_STATE                   = 0x00020000;
316 
317     /**
318      * Listen for changes to the sim data activation state
319      * @see TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATING
320      * @see TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATED
321      * @see TelephonyManager#SIM_ACTIVATION_STATE_DEACTIVATED
322      * @see TelephonyManager#SIM_ACTIVATION_STATE_RESTRICTED
323      * @see TelephonyManager#SIM_ACTIVATION_STATE_UNKNOWN
324      * {@more}
325      * Example: TelephonyManager#SIM_ACTIVATION_STATE_ACTIVATED indicates data service has been
326      * fully activated
327      *
328      * @see #onDataActivationStateChanged
329      * @hide
330      */
331     public static final int LISTEN_DATA_ACTIVATION_STATE                   = 0x00040000;
332 
333     /**
334      *  Listen for changes to the user mobile data state
335      *
336      *  @see #onUserMobileDataStateChanged
337      */
338     public static final int LISTEN_USER_MOBILE_DATA_STATE                  = 0x00080000;
339 
340     /**
341      *  Listen for display info changed event.
342      *
343      *  @see #onDisplayInfoChanged
344      */
345     public static final int LISTEN_DISPLAY_INFO_CHANGED = 0x00100000;
346 
347     /**
348      *  Listen for changes to the phone capability.
349      *
350      *  @see #onPhoneCapabilityChanged
351      *  @hide
352      */
353     public static final int LISTEN_PHONE_CAPABILITY_CHANGE                 = 0x00200000;
354 
355     /**
356      *  Listen for changes to active data subId. Active data subscription is
357      *  the current subscription used to setup Cellular Internet data. For example,
358      *  it could be the current active opportunistic subscription in use, or the
359      *  subscription user selected as default data subscription in DSDS mode.
360      *
361      *  @see #onActiveDataSubscriptionIdChanged
362      */
363     public static final int LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE = 0x00400000;
364 
365     /**
366      *  Listen for changes to the radio power state.
367      *
368      * <p>Requires permission {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE}
369      *
370      *  @see #onRadioPowerStateChanged
371      *  @hide
372      */
373     @SystemApi
374     @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
375     public static final int LISTEN_RADIO_POWER_STATE_CHANGED               = 0x00800000;
376 
377     /**
378      * Listen for changes to emergency number list based on all active subscriptions.
379      *
380      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
381      * app has carrier privileges (see {@link TelephonyManager#hasCarrierPrivileges}).
382      */
383     public static final int LISTEN_EMERGENCY_NUMBER_LIST                   = 0x01000000;
384 
385     /**
386      * Listen for call disconnect causes which contains {@link DisconnectCause} and
387      * {@link PreciseDisconnectCause}.
388      *
389      * <p>Requires permission {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE}
390      * or the calling app has carrier privileges
391      * (see {@link TelephonyManager#hasCarrierPrivileges}).
392      *
393      */
394     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
395     public static final int LISTEN_CALL_DISCONNECT_CAUSES                  = 0x02000000;
396 
397     /**
398      * Listen for changes to the call attributes of a currently active call.
399      *
400      * <p>Requires permission {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE}
401      * or the calling app has carrier privileges
402      * (see {@link TelephonyManager#hasCarrierPrivileges}).
403      *
404      * @see #onCallAttributesChanged
405      * @hide
406      */
407     @SystemApi
408     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
409     public static final int LISTEN_CALL_ATTRIBUTES_CHANGED                 = 0x04000000;
410 
411     /**
412      * Listen for IMS call disconnect causes which contains
413      * {@link android.telephony.ims.ImsReasonInfo}
414      *
415      * <p>Requires permission {@link android.Manifest.permission#READ_PRECISE_PHONE_STATE}
416      * or the calling app has carrier privileges
417      * (see {@link TelephonyManager#hasCarrierPrivileges}).
418      *
419      * @see #onImsCallDisconnectCauseChanged(ImsReasonInfo)
420      */
421     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
422     public static final int LISTEN_IMS_CALL_DISCONNECT_CAUSES              = 0x08000000;
423 
424     /**
425      * Listen for the emergency number placed from an outgoing call.
426      *
427      * <p>Requires permission {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
428      *
429      * @see #onOutgoingEmergencyCall
430      * @hide
431      */
432     @SystemApi
433     @TestApi
434     @RequiresPermission(Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
435     public static final int LISTEN_OUTGOING_EMERGENCY_CALL                  = 0x10000000;
436 
437     /**
438      * Listen for the emergency number placed from an outgoing SMS.
439      *
440      * <p>Requires permission {@link android.Manifest.permission#READ_ACTIVE_EMERGENCY_SESSION}
441      *
442      * @see #onOutgoingEmergencySms
443      * @hide
444      */
445     @SystemApi
446     @TestApi
447     @RequiresPermission(Manifest.permission.READ_ACTIVE_EMERGENCY_SESSION)
448     public static final int LISTEN_OUTGOING_EMERGENCY_SMS                   = 0x20000000;
449 
450     /**
451      * Listen for Registration Failures.
452      *
453      * Listen for indications that a registration procedure has failed in either the CS or PS
454      * domain. This indication does not necessarily indicate a change of service state, which should
455      * be tracked via {@link #LISTEN_SERVICE_STATE}.
456      *
457      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
458      * app has carrier privileges (see {@link TelephonyManager#hasCarrierPrivileges}).
459      *
460      * @see #onRegistrationFailed
461      */
462     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
463     public static final int LISTEN_REGISTRATION_FAILURE = 0x40000000;
464 
465     /**
466      * Listen for Barring Information for the current registered / camped cell.
467      *
468      * <p>Requires permission {@link android.Manifest.permission#READ_PHONE_STATE} or the calling
469      * app has carrier privileges (see {@link TelephonyManager#hasCarrierPrivileges}).
470      *
471      * @see #onBarringInfoChanged
472      */
473     @RequiresPermission(Manifest.permission.READ_PHONE_STATE)
474     public static final int LISTEN_BARRING_INFO = 0x80000000;
475 
476     /*
477      * Subscription used to listen to the phone state changes
478      * @hide
479      */
480     /** @hide */
481     @UnsupportedAppUsage
482     protected Integer mSubId;
483 
484     /**
485      * @hide
486      */
487     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
488     @UnsupportedAppUsage
489     public final IPhoneStateListener callback;
490 
491     /**
492      * Create a PhoneStateListener for the Phone with the default subscription.
493      * This class requires Looper.myLooper() not return null.
494      */
PhoneStateListener()495     public PhoneStateListener() {
496         this(null, Looper.myLooper());
497     }
498 
499     /**
500      * Create a PhoneStateListener for the Phone with the default subscription
501      * using a particular non-null Looper.
502      * @hide
503      */
504     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
PhoneStateListener(Looper looper)505     public PhoneStateListener(Looper looper) {
506         this(null, looper);
507     }
508 
509     /**
510      * Create a PhoneStateListener for the Phone using the specified subscription.
511      * This class requires Looper.myLooper() not return null. To supply your
512      * own non-null Looper use PhoneStateListener(int subId, Looper looper) below.
513      * @hide
514      */
515     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
PhoneStateListener(Integer subId)516     public PhoneStateListener(Integer subId) {
517         this(subId, Looper.myLooper());
518         if (subId != null && VMRuntime.getRuntime().getTargetSdkVersion()
519                 >= Build.VERSION_CODES.Q) {
520             throw new IllegalArgumentException("PhoneStateListener with subId: "
521                     + subId + " is not supported, use default constructor");
522         }
523     }
524     /**
525      * Create a PhoneStateListener for the Phone using the specified subscription
526      * and non-null Looper.
527      * @hide
528      */
529     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
PhoneStateListener(Integer subId, Looper looper)530     public PhoneStateListener(Integer subId, Looper looper) {
531         this(subId, new HandlerExecutor(new Handler(looper)));
532         if (subId != null && VMRuntime.getRuntime().getTargetSdkVersion()
533                 >= Build.VERSION_CODES.Q) {
534             throw new IllegalArgumentException("PhoneStateListener with subId: "
535                     + subId + " is not supported, use default constructor");
536         }
537     }
538 
539     /**
540      * Create a PhoneStateListener for the Phone using the specified Executor
541      *
542      * <p>Create a PhoneStateListener with a specified Executor for handling necessary callbacks.
543      * The Executor must not be null.
544      *
545      * @param executor a non-null Executor that will execute callbacks for the PhoneStateListener.
546      */
PhoneStateListener(@onNull Executor executor)547     public PhoneStateListener(@NonNull Executor executor) {
548         this(null, executor);
549     }
550 
PhoneStateListener(Integer subId, Executor e)551     private PhoneStateListener(Integer subId, Executor e) {
552         if (e == null) {
553             throw new IllegalArgumentException("PhoneStateListener Executor must be non-null");
554         }
555         mSubId = subId;
556         callback = new IPhoneStateListenerStub(this, e);
557     }
558 
559     /**
560      * Callback invoked when device service state changes on the registered subscription.
561      * Note, the registration subId comes from {@link TelephonyManager} object which registers
562      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
563      * If this TelephonyManager object was created with
564      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
565      * subId. Otherwise, this callback applies to
566      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
567      *
568      * @see ServiceState#STATE_EMERGENCY_ONLY
569      * @see ServiceState#STATE_IN_SERVICE
570      * @see ServiceState#STATE_OUT_OF_SERVICE
571      * @see ServiceState#STATE_POWER_OFF
572      */
onServiceStateChanged(ServiceState serviceState)573     public void onServiceStateChanged(ServiceState serviceState) {
574         // default implementation empty
575     }
576 
577     /**
578      * Callback invoked when network signal strength changes on the registered subscription.
579      * Note, the registration subId comes from {@link TelephonyManager} object which registers
580      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
581      * If this TelephonyManager object was created with
582      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
583      * subId. Otherwise, this callback applies to
584      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
585      *
586      * @see ServiceState#STATE_EMERGENCY_ONLY
587      * @see ServiceState#STATE_IN_SERVICE
588      * @see ServiceState#STATE_OUT_OF_SERVICE
589      * @see ServiceState#STATE_POWER_OFF
590      * @deprecated Use {@link #onSignalStrengthsChanged(SignalStrength)}
591      */
592     @Deprecated
onSignalStrengthChanged(int asu)593     public void onSignalStrengthChanged(int asu) {
594         // default implementation empty
595     }
596 
597     /**
598      * Callback invoked when the message-waiting indicator changes on the registered subscription.
599      * Note, the registration subId comes from {@link TelephonyManager} object which registers
600      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
601      * If this TelephonyManager object was created with
602      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
603      * subId. Otherwise, this callback applies to
604      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
605      */
onMessageWaitingIndicatorChanged(boolean mwi)606     public void onMessageWaitingIndicatorChanged(boolean mwi) {
607         // default implementation empty
608     }
609 
610     /**
611      * Callback invoked when the call-forwarding indicator changes on the registered subscription.
612      * Note, the registration subId comes from {@link TelephonyManager} object which registers
613      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
614      * If this TelephonyManager object was created with
615      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
616      * subId. Otherwise, this callback applies to
617      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
618      */
onCallForwardingIndicatorChanged(boolean cfi)619     public void onCallForwardingIndicatorChanged(boolean cfi) {
620         // default implementation empty
621     }
622 
623     /**
624      * Callback invoked when device cell location changes on the registered subscription.
625      * Note, the registration subId comes from {@link TelephonyManager} object which registers
626      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
627      * If this TelephonyManager object was created with
628      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
629      * subId. Otherwise, this callback applies to
630      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
631      */
onCellLocationChanged(CellLocation location)632     public void onCellLocationChanged(CellLocation location) {
633         // default implementation empty
634     }
635 
636     /**
637      * Callback invoked when device call state changes.
638      * <p>
639      * Reports the state of Telephony (mobile) calls on the device for the registered subscription.
640      * <p>
641      * Note: the registration subId comes from {@link TelephonyManager} object which registers
642      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
643      * If this TelephonyManager object was created with
644      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
645      * subId. Otherwise, this callback applies to
646      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
647      * <p>
648      * Note: The state returned here may differ from that returned by
649      * {@link TelephonyManager#getCallState()}. Receivers of this callback should be aware that
650      * calling {@link TelephonyManager#getCallState()} from within this callback may return a
651      * different state than the callback reports.
652      *
653      * @param state call state
654      * @param phoneNumber call phone number. If application does not have
655      * {@link android.Manifest.permission#READ_CALL_LOG READ_CALL_LOG} permission or carrier
656      * privileges (see {@link TelephonyManager#hasCarrierPrivileges}), an empty string will be
657      * passed as an argument.
658      */
onCallStateChanged(@allState int state, String phoneNumber)659     public void onCallStateChanged(@CallState int state, String phoneNumber) {
660         // default implementation empty
661     }
662 
663     /**
664      * Callback invoked when connection state changes on the registered subscription.
665      * Note, the registration subId comes from {@link TelephonyManager} object which registers
666      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
667      * If this TelephonyManager object was created with
668      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
669      * subId. Otherwise, this callback applies to
670      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
671      *
672      * @see TelephonyManager#DATA_DISCONNECTED
673      * @see TelephonyManager#DATA_CONNECTING
674      * @see TelephonyManager#DATA_CONNECTED
675      * @see TelephonyManager#DATA_SUSPENDED
676      */
onDataConnectionStateChanged(int state)677     public void onDataConnectionStateChanged(int state) {
678         // default implementation empty
679     }
680 
681     /**
682      * same as above, but with the network type.  Both called.
683      */
onDataConnectionStateChanged(int state, int networkType)684     public void onDataConnectionStateChanged(int state, int networkType) {
685     }
686 
687     /**
688      * Callback invoked when data activity state changes on the registered subscription.
689      * Note, the registration subId comes from {@link TelephonyManager} object which registers
690      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
691      * If this TelephonyManager object was created with
692      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
693      * subId. Otherwise, this callback applies to
694      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
695      *
696      * @see TelephonyManager#DATA_ACTIVITY_NONE
697      * @see TelephonyManager#DATA_ACTIVITY_IN
698      * @see TelephonyManager#DATA_ACTIVITY_OUT
699      * @see TelephonyManager#DATA_ACTIVITY_INOUT
700      * @see TelephonyManager#DATA_ACTIVITY_DORMANT
701      */
onDataActivity(int direction)702     public void onDataActivity(int direction) {
703         // default implementation empty
704     }
705 
706     /**
707      * Callback invoked when network signal strengths changes on the registered subscription.
708      * Note, the registration subId comes from {@link TelephonyManager} object which registers
709      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
710      * If this TelephonyManager object was created with
711      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
712      * subId. Otherwise, this callback applies to
713      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
714      */
onSignalStrengthsChanged(SignalStrength signalStrength)715     public void onSignalStrengthsChanged(SignalStrength signalStrength) {
716         // default implementation empty
717     }
718 
719     /**
720      * Callback invoked when a observed cell info has changed or new cells have been added
721      * or removed on the registered subscription.
722      * Note, the registration subId s from {@link TelephonyManager} object which registers
723      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
724      * If this TelephonyManager object was created with
725      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
726      * subId. Otherwise, this callback applies to
727      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
728      *
729      * @param cellInfo is the list of currently visible cells.
730      */
onCellInfoChanged(List<CellInfo> cellInfo)731     public void onCellInfoChanged(List<CellInfo> cellInfo) {
732     }
733 
734     /**
735      * Callback invoked when precise device call state changes on the registered subscription.
736      * Note, the registration subId comes from {@link TelephonyManager} object which registers
737      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
738      * If this TelephonyManager object was created with
739      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
740      * subId. Otherwise, this callback applies to
741      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
742      * @param callState {@link PreciseCallState}
743      * @hide
744      */
745     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
746     @SystemApi
onPreciseCallStateChanged(@onNull PreciseCallState callState)747     public void onPreciseCallStateChanged(@NonNull PreciseCallState callState) {
748         // default implementation empty
749     }
750 
751     /**
752      * Callback invoked when call disconnect cause changes on the registered subscription.
753      * Note, the registration subId comes from {@link TelephonyManager} object which registers
754      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
755      * If this TelephonyManager object was created with
756      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
757      * subId. Otherwise, this callback applies to
758      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
759      *
760      * @param disconnectCause {@link DisconnectCause}.
761      * @param preciseDisconnectCause {@link PreciseDisconnectCause}.
762      *
763      */
764     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
onCallDisconnectCauseChanged(@nnotation.DisconnectCauses int disconnectCause, int preciseDisconnectCause)765     public void onCallDisconnectCauseChanged(@Annotation.DisconnectCauses int disconnectCause,
766             int preciseDisconnectCause) {
767         // default implementation empty
768     }
769 
770     /**
771      * Callback invoked when Ims call disconnect cause changes on the registered subscription.
772      * Note, the registration subId comes from {@link TelephonyManager} object which registers
773      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
774      * If this TelephonyManager object was created with
775      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
776      * subId. Otherwise, this callback applies to
777      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
778      *
779      * @param imsReasonInfo {@link ImsReasonInfo} contains details on why IMS call failed.
780      *
781      */
782     @RequiresPermission((android.Manifest.permission.READ_PRECISE_PHONE_STATE))
onImsCallDisconnectCauseChanged(@onNull ImsReasonInfo imsReasonInfo)783     public void onImsCallDisconnectCauseChanged(@NonNull ImsReasonInfo imsReasonInfo) {
784         // default implementation empty
785     }
786 
787     /**
788      * Callback providing update about the default/internet data connection on the registered
789      * subscription.
790      *
791      * Note, the registration subId comes from {@link TelephonyManager} object which registers
792      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
793      * If this TelephonyManager object was created with
794      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
795      * subId. Otherwise, this callback applies to
796      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
797      *
798      * <p>Requires permission {@link android.Manifest.permission#MODIFY_PHONE_STATE}
799      * or the calling app has carrier privileges
800      * (see {@link TelephonyManager#hasCarrierPrivileges}).
801      *
802      * @param dataConnectionState {@link PreciseDataConnectionState}
803      */
804     @RequiresPermission((android.Manifest.permission.MODIFY_PHONE_STATE))
onPreciseDataConnectionStateChanged( @onNull PreciseDataConnectionState dataConnectionState)805     public void onPreciseDataConnectionStateChanged(
806             @NonNull PreciseDataConnectionState dataConnectionState) {
807         // default implementation empty
808     }
809 
810     /**
811      * Callback invoked when data connection real time info changes on the registered subscription.
812      * Note, the registration subId comes from {@link TelephonyManager} object which registers
813      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
814      * If this TelephonyManager object was created with
815      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
816      * subId. Otherwise, this callback applies to
817      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
818      *
819      * @hide
820      */
821     @UnsupportedAppUsage
onDataConnectionRealTimeInfoChanged( DataConnectionRealTimeInfo dcRtInfo)822     public void onDataConnectionRealTimeInfoChanged(
823             DataConnectionRealTimeInfo dcRtInfo) {
824         // default implementation empty
825     }
826 
827     /**
828      * Callback invoked when there has been a change in the Single Radio Voice Call Continuity
829      * (SRVCC) state for the currently active call on the registered subscription.
830      *
831      * Note, the registration subId comes from {@link TelephonyManager} object which registers
832      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
833      * If this TelephonyManager object was created with
834      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
835      * subId. Otherwise, this callback applies to
836      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
837      *
838      * @hide
839      */
840     @SystemApi
onSrvccStateChanged(@rvccState int srvccState)841     public void onSrvccStateChanged(@SrvccState int srvccState) {
842 
843     }
844 
845     /**
846      * Callback invoked when the SIM voice activation state has changed on the registered
847      * subscription.
848      * Note, the registration subId comes from {@link TelephonyManager} object which registers
849      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
850      * If this TelephonyManager object was created with
851      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
852      * subId. Otherwise, this callback applies to
853      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
854      *
855      * @param state is the current SIM voice activation state
856      * @hide
857      */
858     @SystemApi
onVoiceActivationStateChanged(@imActivationState int state)859     public void onVoiceActivationStateChanged(@SimActivationState int state) {
860     }
861 
862     /**
863      * Callback invoked when the SIM data activation state has changed on the registered
864      * subscription.
865      * Note, the registration subId comes from {@link TelephonyManager} object which registers
866      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
867      * If this TelephonyManager object was created with
868      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
869      * subId. Otherwise, this callback applies to
870      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
871      *
872      * @param state is the current SIM data activation state
873      * @hide
874      */
onDataActivationStateChanged(@imActivationState int state)875     public void onDataActivationStateChanged(@SimActivationState int state) {
876     }
877 
878     /**
879      * Callback invoked when the user mobile data state has changed on the registered subscription.
880      * Note, the registration subId comes from {@link TelephonyManager} object which registers
881      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
882      * If this TelephonyManager object was created with
883      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
884      * subId. Otherwise, this callback applies to
885      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
886      *
887      * @param enabled indicates whether the current user mobile data state is enabled or disabled.
888      */
onUserMobileDataStateChanged(boolean enabled)889     public void onUserMobileDataStateChanged(boolean enabled) {
890         // default implementation empty
891     }
892 
893     /**
894      * Callback invoked when the display info has changed on the registered subscription.
895      * <p> The {@link TelephonyDisplayInfo} contains status information shown to the user based on
896      * carrier policy.
897      *
898      * Requires Permission: {@link android.Manifest.permission#READ_PHONE_STATE} or that the calling
899      * app has carrier privileges (see {@link TelephonyManager#hasCarrierPrivileges}).
900      *
901      * @param telephonyDisplayInfo The display information.
902      */
903     @RequiresPermission((android.Manifest.permission.READ_PHONE_STATE))
onDisplayInfoChanged(@onNull TelephonyDisplayInfo telephonyDisplayInfo)904     public void onDisplayInfoChanged(@NonNull TelephonyDisplayInfo telephonyDisplayInfo) {
905         // default implementation empty
906     }
907 
908     /**
909      * Callback invoked when the current emergency number list has changed on the registered
910      * subscription.
911      * Note, the registration subId comes from {@link TelephonyManager} object which registers
912      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
913      * If this TelephonyManager object was created with
914      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
915      * subId. Otherwise, this callback applies to
916      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
917      *
918      * @param emergencyNumberList Map including the key as the active subscription ID
919      *                           (Note: if there is no active subscription, the key is
920      *                           {@link SubscriptionManager#getDefaultSubscriptionId})
921      *                           and the value as the list of {@link EmergencyNumber};
922      *                           null if this information is not available.
923      * @hide
924      */
onEmergencyNumberListChanged( @onNull Map<Integer, List<EmergencyNumber>> emergencyNumberList)925     public void onEmergencyNumberListChanged(
926             @NonNull Map<Integer, List<EmergencyNumber>> emergencyNumberList) {
927         // default implementation empty
928     }
929 
930     /**
931      * Callback invoked when an outgoing call is placed to an emergency number.
932      *
933      * @param placedEmergencyNumber the emergency number {@link EmergencyNumber} the call is placed
934      *                              to.
935      * @hide
936      */
937     @SystemApi
938     @TestApi
onOutgoingEmergencyCall(@onNull EmergencyNumber placedEmergencyNumber)939     public void onOutgoingEmergencyCall(@NonNull EmergencyNumber placedEmergencyNumber) {
940         // default implementation empty
941     }
942 
943     /**
944      * Callback invoked when an outgoing SMS is placed to an emergency number.
945      *
946      * @param sentEmergencyNumber the emergency number {@link EmergencyNumber} the SMS is sent to.
947      * @hide
948      */
949     @SystemApi
950     @TestApi
onOutgoingEmergencySms(@onNull EmergencyNumber sentEmergencyNumber)951     public void onOutgoingEmergencySms(@NonNull EmergencyNumber sentEmergencyNumber) {
952         // default implementation empty
953     }
954 
955     /**
956      * Callback invoked when OEM hook raw event is received on the registered subscription.
957      * Note, the registration subId comes from {@link TelephonyManager} object which registers
958      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
959      * If this TelephonyManager object was created with
960      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
961      * subId. Otherwise, this callback applies to
962      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
963      *
964      * Requires the READ_PRIVILEGED_PHONE_STATE permission.
965      * @param rawData is the byte array of the OEM hook raw data.
966      * @hide
967      */
968     @UnsupportedAppUsage
onOemHookRawEvent(byte[] rawData)969     public void onOemHookRawEvent(byte[] rawData) {
970         // default implementation empty
971     }
972 
973     /**
974      * Callback invoked when phone capability changes.
975      * Note, this callback triggers regardless of registered subscription.
976      *
977      * @param capability the new phone capability
978      * @hide
979      */
onPhoneCapabilityChanged(PhoneCapability capability)980     public void onPhoneCapabilityChanged(PhoneCapability capability) {
981         // default implementation empty
982     }
983 
984     /**
985      * Callback invoked when active data subId changes.
986      * Note, this callback triggers regardless of registered subscription.
987      *
988      * Requires the READ_PHONE_STATE permission.
989      * @param subId current subscription used to setup Cellular Internet data.
990      *              For example, it could be the current active opportunistic subscription in use,
991      *              or the subscription user selected as default data subscription in DSDS mode.
992      */
onActiveDataSubscriptionIdChanged(int subId)993     public void onActiveDataSubscriptionIdChanged(int subId) {
994         // default implementation empty
995     }
996 
997     /**
998      * Callback invoked when the call attributes changes on the registered subscription.
999      * Note, the registration subId comes from {@link TelephonyManager} object which registers
1000      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
1001      * If this TelephonyManager object was created with
1002      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
1003      * subId. Otherwise, this callback applies to
1004      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
1005      *
1006      * Requires the READ_PRECISE_PHONE_STATE permission.
1007      * @param callAttributes the call attributes
1008      * @hide
1009      */
1010     @SystemApi
onCallAttributesChanged(@onNull CallAttributes callAttributes)1011     public void onCallAttributesChanged(@NonNull CallAttributes callAttributes) {
1012         // default implementation empty
1013     }
1014 
1015     /**
1016      * Callback invoked when modem radio power state changes on the registered subscription.
1017      * Note, the registration subId comes from {@link TelephonyManager} object which registers
1018      * PhoneStateListener by {@link TelephonyManager#listen(PhoneStateListener, int)}.
1019      * If this TelephonyManager object was created with
1020      * {@link TelephonyManager#createForSubscriptionId(int)}, then the callback applies to the
1021      * subId. Otherwise, this callback applies to
1022      * {@link SubscriptionManager#getDefaultSubscriptionId()}.
1023      *
1024      * @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE}
1025      * @param state the modem radio power state
1026      * @hide
1027      */
1028     @SystemApi
onRadioPowerStateChanged(@adioPowerState int state)1029     public void onRadioPowerStateChanged(@RadioPowerState int state) {
1030         // default implementation empty
1031     }
1032 
1033     /**
1034      * Callback invoked when telephony has received notice from a carrier
1035      * app that a network action that could result in connectivity loss
1036      * has been requested by an app using
1037      * {@link android.telephony.TelephonyManager#notifyCarrierNetworkChange(boolean)}
1038      *
1039      * Note, this callback is pinned to the registered subscription and will be invoked when
1040      * the notifying carrier app has carrier privilege rule on the registered
1041      * subscription. {@link android.telephony.TelephonyManager#hasCarrierPrivileges}
1042      *
1043      * @param active Whether the carrier network change is or shortly
1044      *               will be active. This value is true to indicate
1045      *               showing alternative UI and false to stop.
1046      *
1047      * @hide
1048      */
onCarrierNetworkChange(boolean active)1049     public void onCarrierNetworkChange(boolean active) {
1050         // default implementation empty
1051     }
1052 
1053     /**
1054      * Report that Registration or a Location/Routing/Tracking Area update has failed.
1055      *
1056      * <p>Indicate whenever a registration procedure, including a location, routing, or tracking
1057      * area update fails. This includes procedures that do not necessarily result in a change of
1058      * the modem's registration status. If the modem's registration status changes, that is
1059      * reflected in the onNetworkStateChanged() and subsequent get{Voice/Data}RegistrationState().
1060      *
1061      * <p>Because registration failures are ephemeral, this callback is not sticky.
1062      * Registrants will not receive the most recent past value when registering.
1063      *
1064      * @param cellIdentity the CellIdentity, which must include the globally unique identifier
1065      *        for the cell (for example, all components of the CGI or ECGI).
1066      * @param chosenPlmn a 5 or 6 digit alphanumeric PLMN (MCC|MNC) among those broadcast by the
1067      *         cell that was chosen for the failed registration attempt.
1068      * @param domain DOMAIN_CS, DOMAIN_PS or both in case of a combined procedure.
1069      * @param causeCode the primary failure cause code of the procedure.
1070      *        For GSM/UMTS (MM), values are in TS 24.008 Sec 10.5.95
1071      *        For GSM/UMTS (GMM), values are in TS 24.008 Sec 10.5.147
1072      *        For LTE (EMM), cause codes are TS 24.301 Sec 9.9.3.9
1073      *        For NR (5GMM), cause codes are TS 24.501 Sec 9.11.3.2
1074      *        Integer.MAX_VALUE if this value is unused.
1075      * @param additionalCauseCode the cause code of any secondary/combined procedure if appropriate.
1076      *        For UMTS, if a combined attach succeeds for PS only, then the GMM cause code shall be
1077      *        included as an additionalCauseCode. For LTE (ESM), cause codes are in
1078      *        TS 24.301 9.9.4.4. Integer.MAX_VALUE if this value is unused.
1079      */
onRegistrationFailed(@onNull CellIdentity cellIdentity, @NonNull String chosenPlmn, @NetworkRegistrationInfo.Domain int domain, int causeCode, int additionalCauseCode)1080     public void onRegistrationFailed(@NonNull CellIdentity cellIdentity, @NonNull String chosenPlmn,
1081             @NetworkRegistrationInfo.Domain int domain, int causeCode, int additionalCauseCode) {
1082         // default implementation empty
1083     }
1084 
1085     /**
1086      * Report updated barring information for the current camped/registered cell.
1087      *
1088      * <p>Barring info is provided for all services applicable to the current camped/registered
1089      * cell, for the registered PLMN and current access class/access category.
1090      *
1091      * @param barringInfo for all services on the current cell.
1092      *
1093      * @see android.telephony.BarringInfo
1094      */
onBarringInfoChanged(@onNull BarringInfo barringInfo)1095     public void onBarringInfoChanged(@NonNull BarringInfo barringInfo) {
1096         // default implementation empty
1097     }
1098 
1099     /**
1100      * The callback methods need to be called on the handler thread where
1101      * this object was created.  If the binder did that for us it'd be nice.
1102      *
1103      * Using a static class and weak reference here to avoid memory leak caused by the
1104      * IPhoneStateListener.Stub callback retaining references to the outside PhoneStateListeners:
1105      * even caller has been destroyed and "un-registered" the PhoneStateListener, it is still not
1106      * eligible for GC given the references coming from:
1107      * Native Stack --> PhoneStateListener --> Context (Activity).
1108      * memory of caller's context will be collected after GC from service side get triggered
1109      */
1110     private static class IPhoneStateListenerStub extends IPhoneStateListener.Stub {
1111         private WeakReference<PhoneStateListener> mPhoneStateListenerWeakRef;
1112         private Executor mExecutor;
1113 
IPhoneStateListenerStub(PhoneStateListener phoneStateListener, Executor executor)1114         IPhoneStateListenerStub(PhoneStateListener phoneStateListener, Executor executor) {
1115             mPhoneStateListenerWeakRef = new WeakReference<PhoneStateListener>(phoneStateListener);
1116             mExecutor = executor;
1117         }
1118 
onServiceStateChanged(ServiceState serviceState)1119         public void onServiceStateChanged(ServiceState serviceState) {
1120             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1121             if (psl == null) return;
1122 
1123             Binder.withCleanCallingIdentity(
1124                     () -> mExecutor.execute(() -> psl.onServiceStateChanged(serviceState)));
1125         }
1126 
onSignalStrengthChanged(int asu)1127         public void onSignalStrengthChanged(int asu) {
1128             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1129             if (psl == null) return;
1130 
1131             Binder.withCleanCallingIdentity(
1132                     () -> mExecutor.execute(() -> psl.onSignalStrengthChanged(asu)));
1133         }
1134 
onMessageWaitingIndicatorChanged(boolean mwi)1135         public void onMessageWaitingIndicatorChanged(boolean mwi) {
1136             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1137             if (psl == null) return;
1138 
1139             Binder.withCleanCallingIdentity(
1140                     () -> mExecutor.execute(() -> psl.onMessageWaitingIndicatorChanged(mwi)));
1141         }
1142 
onCallForwardingIndicatorChanged(boolean cfi)1143         public void onCallForwardingIndicatorChanged(boolean cfi) {
1144             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1145             if (psl == null) return;
1146 
1147             Binder.withCleanCallingIdentity(
1148                     () -> mExecutor.execute(() -> psl.onCallForwardingIndicatorChanged(cfi)));
1149         }
1150 
onCellLocationChanged(CellIdentity cellIdentity)1151         public void onCellLocationChanged(CellIdentity cellIdentity) {
1152             // There is no system/public API to create an CellIdentity in system server,
1153             // so the server pass a null to indicate an empty initial location.
1154             CellLocation location =
1155                     cellIdentity == null ? CellLocation.getEmpty() : cellIdentity.asCellLocation();
1156             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1157             if (psl == null) return;
1158 
1159             Binder.withCleanCallingIdentity(
1160                     () -> mExecutor.execute(() -> psl.onCellLocationChanged(location)));
1161         }
1162 
onCallStateChanged(int state, String incomingNumber)1163         public void onCallStateChanged(int state, String incomingNumber) {
1164             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1165             if (psl == null) return;
1166 
1167             Binder.withCleanCallingIdentity(
1168                     () -> mExecutor.execute(() -> psl.onCallStateChanged(state, incomingNumber)));
1169         }
1170 
onDataConnectionStateChanged(int state, int networkType)1171         public void onDataConnectionStateChanged(int state, int networkType) {
1172             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1173             if (psl == null) return;
1174 
1175             if (state == TelephonyManager.DATA_DISCONNECTING
1176                     && VMRuntime.getRuntime().getTargetSdkVersion() < Build.VERSION_CODES.R) {
1177                 Binder.withCleanCallingIdentity(() -> mExecutor.execute(
1178                         () -> {
1179                             psl.onDataConnectionStateChanged(
1180                                     TelephonyManager.DATA_CONNECTED, networkType);
1181                             psl.onDataConnectionStateChanged(TelephonyManager.DATA_CONNECTED);
1182                         }));
1183             } else {
1184                 Binder.withCleanCallingIdentity(() -> mExecutor.execute(
1185                         () -> {
1186                             psl.onDataConnectionStateChanged(state, networkType);
1187                             psl.onDataConnectionStateChanged(state);
1188                         }));
1189             }
1190         }
1191 
onDataActivity(int direction)1192         public void onDataActivity(int direction) {
1193             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1194             if (psl == null) return;
1195 
1196             Binder.withCleanCallingIdentity(
1197                     () -> mExecutor.execute(() -> psl.onDataActivity(direction)));
1198         }
1199 
onSignalStrengthsChanged(SignalStrength signalStrength)1200         public void onSignalStrengthsChanged(SignalStrength signalStrength) {
1201             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1202             if (psl == null) return;
1203 
1204             Binder.withCleanCallingIdentity(
1205                     () -> mExecutor.execute(() -> psl.onSignalStrengthsChanged(signalStrength)));
1206         }
1207 
onCellInfoChanged(List<CellInfo> cellInfo)1208         public void onCellInfoChanged(List<CellInfo> cellInfo) {
1209             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1210             if (psl == null) return;
1211 
1212             Binder.withCleanCallingIdentity(
1213                     () -> mExecutor.execute(() -> psl.onCellInfoChanged(cellInfo)));
1214         }
1215 
onPreciseCallStateChanged(PreciseCallState callState)1216         public void onPreciseCallStateChanged(PreciseCallState callState) {
1217             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1218             if (psl == null) return;
1219 
1220             Binder.withCleanCallingIdentity(
1221                     () -> mExecutor.execute(() -> psl.onPreciseCallStateChanged(callState)));
1222         }
1223 
onCallDisconnectCauseChanged(int disconnectCause, int preciseDisconnectCause)1224         public void onCallDisconnectCauseChanged(int disconnectCause, int preciseDisconnectCause) {
1225             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1226             if (psl == null) return;
1227 
1228             Binder.withCleanCallingIdentity(
1229                     () -> mExecutor.execute(() -> psl.onCallDisconnectCauseChanged(
1230                             disconnectCause, preciseDisconnectCause)));
1231         }
1232 
onPreciseDataConnectionStateChanged( PreciseDataConnectionState dataConnectionState)1233         public void onPreciseDataConnectionStateChanged(
1234                 PreciseDataConnectionState dataConnectionState) {
1235             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1236             if (psl == null) return;
1237 
1238             Binder.withCleanCallingIdentity(
1239                     () -> mExecutor.execute(
1240                             () -> psl.onPreciseDataConnectionStateChanged(dataConnectionState)));
1241         }
1242 
onDataConnectionRealTimeInfoChanged(DataConnectionRealTimeInfo dcRtInfo)1243         public void onDataConnectionRealTimeInfoChanged(DataConnectionRealTimeInfo dcRtInfo) {
1244             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1245             if (psl == null) return;
1246 
1247             Binder.withCleanCallingIdentity(
1248                     () -> mExecutor.execute(
1249                             () -> psl.onDataConnectionRealTimeInfoChanged(dcRtInfo)));
1250         }
1251 
onSrvccStateChanged(int state)1252         public void onSrvccStateChanged(int state) {
1253             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1254             if (psl == null) return;
1255 
1256             Binder.withCleanCallingIdentity(
1257                     () -> mExecutor.execute(() -> psl.onSrvccStateChanged(state)));
1258         }
1259 
onVoiceActivationStateChanged(int activationState)1260         public void onVoiceActivationStateChanged(int activationState) {
1261             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1262             if (psl == null) return;
1263 
1264             Binder.withCleanCallingIdentity(
1265                     () -> mExecutor.execute(
1266                             () -> psl.onVoiceActivationStateChanged(activationState)));
1267         }
1268 
onDataActivationStateChanged(int activationState)1269         public void onDataActivationStateChanged(int activationState) {
1270             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1271             if (psl == null) return;
1272 
1273             Binder.withCleanCallingIdentity(
1274                     () -> mExecutor.execute(
1275                             () -> psl.onDataActivationStateChanged(activationState)));
1276         }
1277 
onUserMobileDataStateChanged(boolean enabled)1278         public void onUserMobileDataStateChanged(boolean enabled) {
1279             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1280             if (psl == null) return;
1281 
1282             Binder.withCleanCallingIdentity(
1283                     () -> mExecutor.execute(
1284                             () -> psl.onUserMobileDataStateChanged(enabled)));
1285         }
1286 
onDisplayInfoChanged(TelephonyDisplayInfo telephonyDisplayInfo)1287         public void onDisplayInfoChanged(TelephonyDisplayInfo telephonyDisplayInfo) {
1288             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1289             if (psl == null) return;
1290 
1291             Binder.withCleanCallingIdentity(
1292                     () -> mExecutor.execute(
1293                             () -> psl.onDisplayInfoChanged(telephonyDisplayInfo)));
1294         }
1295 
onOemHookRawEvent(byte[] rawData)1296         public void onOemHookRawEvent(byte[] rawData) {
1297             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1298             if (psl == null) return;
1299 
1300             Binder.withCleanCallingIdentity(
1301                     () -> mExecutor.execute(() -> psl.onOemHookRawEvent(rawData)));
1302         }
1303 
onCarrierNetworkChange(boolean active)1304         public void onCarrierNetworkChange(boolean active) {
1305             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1306             if (psl == null) return;
1307 
1308             Binder.withCleanCallingIdentity(
1309                     () -> mExecutor.execute(() -> psl.onCarrierNetworkChange(active)));
1310         }
1311 
onEmergencyNumberListChanged(Map emergencyNumberList)1312         public void onEmergencyNumberListChanged(Map emergencyNumberList) {
1313             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1314             if (psl == null) return;
1315 
1316             Binder.withCleanCallingIdentity(
1317                     () -> mExecutor.execute(
1318                             () -> psl.onEmergencyNumberListChanged(emergencyNumberList)));
1319         }
1320 
onOutgoingEmergencyCall(@onNull EmergencyNumber placedEmergencyNumber)1321         public void onOutgoingEmergencyCall(@NonNull EmergencyNumber placedEmergencyNumber) {
1322             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1323             if (psl == null) return;
1324 
1325             Binder.withCleanCallingIdentity(
1326                     () -> mExecutor.execute(
1327                             () -> psl.onOutgoingEmergencyCall(placedEmergencyNumber)));
1328         }
1329 
onOutgoingEmergencySms(@onNull EmergencyNumber sentEmergencyNumber)1330         public void onOutgoingEmergencySms(@NonNull EmergencyNumber sentEmergencyNumber) {
1331             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1332             if (psl == null) return;
1333 
1334             Binder.withCleanCallingIdentity(
1335                     () -> mExecutor.execute(
1336                             () -> psl.onOutgoingEmergencySms(sentEmergencyNumber)));
1337         }
1338 
onPhoneCapabilityChanged(PhoneCapability capability)1339         public void onPhoneCapabilityChanged(PhoneCapability capability) {
1340             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1341             if (psl == null) return;
1342 
1343             Binder.withCleanCallingIdentity(
1344                     () -> mExecutor.execute(() -> psl.onPhoneCapabilityChanged(capability)));
1345         }
1346 
onRadioPowerStateChanged(@adioPowerState int state)1347         public void onRadioPowerStateChanged(@RadioPowerState int state) {
1348             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1349             if (psl == null) return;
1350 
1351             Binder.withCleanCallingIdentity(
1352                     () -> mExecutor.execute(() -> psl.onRadioPowerStateChanged(state)));
1353         }
1354 
onCallAttributesChanged(CallAttributes callAttributes)1355         public void onCallAttributesChanged(CallAttributes callAttributes) {
1356             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1357             if (psl == null) return;
1358 
1359             Binder.withCleanCallingIdentity(
1360                     () -> mExecutor.execute(() -> psl.onCallAttributesChanged(callAttributes)));
1361         }
1362 
onActiveDataSubIdChanged(int subId)1363         public void onActiveDataSubIdChanged(int subId) {
1364             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1365             if (psl == null) return;
1366 
1367             Binder.withCleanCallingIdentity(
1368                     () -> mExecutor.execute(() -> psl.onActiveDataSubscriptionIdChanged(subId)));
1369         }
1370 
onImsCallDisconnectCauseChanged(ImsReasonInfo disconnectCause)1371         public void onImsCallDisconnectCauseChanged(ImsReasonInfo disconnectCause) {
1372             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1373             if (psl == null) return;
1374 
1375             Binder.withCleanCallingIdentity(
1376                     () -> mExecutor.execute(
1377                             () -> psl.onImsCallDisconnectCauseChanged(disconnectCause)));
1378 
1379         }
1380 
onRegistrationFailed(@onNull CellIdentity cellIdentity, @NonNull String chosenPlmn, @NetworkRegistrationInfo.Domain int domain, int causeCode, int additionalCauseCode)1381         public void onRegistrationFailed(@NonNull CellIdentity cellIdentity,
1382                 @NonNull String chosenPlmn, @NetworkRegistrationInfo.Domain int domain,
1383                 int causeCode, int additionalCauseCode) {
1384             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1385             if (psl == null) return;
1386 
1387             Binder.withCleanCallingIdentity(
1388                     () -> mExecutor.execute(() -> psl.onRegistrationFailed(
1389                             cellIdentity, chosenPlmn, domain, causeCode, additionalCauseCode)));
1390             // default implementation empty
1391         }
1392 
onBarringInfoChanged(BarringInfo barringInfo)1393         public void onBarringInfoChanged(BarringInfo barringInfo) {
1394             PhoneStateListener psl = mPhoneStateListenerWeakRef.get();
1395             if (psl == null) return;
1396 
1397             Binder.withCleanCallingIdentity(
1398                     () -> mExecutor.execute(() -> psl.onBarringInfoChanged(barringInfo)));
1399         }
1400     }
1401 
1402 
log(String s)1403     private void log(String s) {
1404         Rlog.d(LOG_TAG, s);
1405     }
1406 }
1407