Home | History | Annotate | Download | only in server
      1 /*
      2  * Copyright (C) 2007 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.server;
     18 
     19 import android.app.ActivityManager;
     20 import android.app.AppOpsManager;
     21 import android.content.BroadcastReceiver;
     22 import android.content.Context;
     23 import android.content.Intent;
     24 import android.content.IntentFilter;
     25 import android.content.pm.PackageManager;
     26 import android.net.LinkProperties;
     27 import android.net.NetworkCapabilities;
     28 import android.os.Binder;
     29 import android.os.Bundle;
     30 import android.os.Handler;
     31 import android.os.IBinder;
     32 import android.os.Message;
     33 import android.os.RemoteException;
     34 import android.os.UserHandle;
     35 import android.telephony.CellInfo;
     36 import android.telephony.CellLocation;
     37 import android.telephony.DisconnectCause;
     38 import android.telephony.LocationAccessPolicy;
     39 import android.telephony.PhoneStateListener;
     40 import android.telephony.PhysicalChannelConfig;
     41 import android.telephony.PreciseCallState;
     42 import android.telephony.PreciseDataConnectionState;
     43 import android.telephony.PreciseDisconnectCause;
     44 import android.telephony.Rlog;
     45 import android.telephony.ServiceState;
     46 import android.telephony.SignalStrength;
     47 import android.telephony.SubscriptionManager;
     48 import android.telephony.TelephonyManager;
     49 import android.telephony.VoLteServiceState;
     50 import android.text.TextUtils;
     51 import android.util.LocalLog;
     52 
     53 import com.android.internal.app.IBatteryStats;
     54 import com.android.internal.telephony.IOnSubscriptionsChangedListener;
     55 import com.android.internal.telephony.IPhoneStateListener;
     56 import com.android.internal.telephony.ITelephonyRegistry;
     57 import com.android.internal.telephony.PhoneConstantConversions;
     58 import com.android.internal.telephony.PhoneConstants;
     59 import com.android.internal.telephony.TelephonyIntents;
     60 import com.android.internal.telephony.TelephonyPermissions;
     61 import com.android.internal.util.DumpUtils;
     62 import com.android.internal.util.IndentingPrintWriter;
     63 import com.android.server.am.BatteryStatsService;
     64 
     65 import java.io.FileDescriptor;
     66 import java.io.PrintWriter;
     67 import java.util.ArrayList;
     68 import java.util.List;
     69 import java.util.NoSuchElementException;
     70 
     71 /**
     72  * Since phone process can be restarted, this class provides a centralized place
     73  * that applications can register and be called back from.
     74  *
     75  * Change-Id: I450c968bda93767554b5188ee63e10c9f43c5aa4 fixes bugs 16148026
     76  * and 15973975 by saving the phoneId of the registrant and then using the
     77  * phoneId when deciding to to make a callback. This is necessary because
     78  * a subId changes from to a dummy value when a SIM is removed and thus won't
     79  * compare properly. Because SubscriptionManager.getPhoneId(int subId) handles
     80  * the dummy value conversion we properly do the callbacks.
     81  *
     82  * Eventually we may want to remove the notion of dummy value but for now this
     83  * looks like the best approach.
     84  */
     85 class TelephonyRegistry extends ITelephonyRegistry.Stub {
     86     private static final String TAG = "TelephonyRegistry";
     87     private static final boolean DBG = false; // STOPSHIP if true
     88     private static final boolean DBG_LOC = false; // STOPSHIP if true
     89     private static final boolean VDBG = false; // STOPSHIP if true
     90 
     91     private static class Record {
     92         Context context;
     93 
     94         String callingPackage;
     95 
     96         IBinder binder;
     97 
     98         TelephonyRegistryDeathRecipient deathRecipient;
     99 
    100         IPhoneStateListener callback;
    101         IOnSubscriptionsChangedListener onSubscriptionsChangedListenerCallback;
    102 
    103         int callerUid;
    104         int callerPid;
    105 
    106         int events;
    107 
    108         int subId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
    109 
    110         int phoneId = SubscriptionManager.INVALID_PHONE_INDEX;
    111 
    112         boolean matchPhoneStateListenerEvent(int events) {
    113             return (callback != null) && ((events & this.events) != 0);
    114         }
    115 
    116         boolean matchOnSubscriptionsChangedListener() {
    117             return (onSubscriptionsChangedListenerCallback != null);
    118         }
    119 
    120         boolean canReadCallLog() {
    121             try {
    122                 return TelephonyPermissions.checkReadCallLog(
    123                         context, subId, callerPid, callerUid, callingPackage);
    124             } catch (SecurityException e) {
    125                 return false;
    126             }
    127         }
    128 
    129         @Override
    130         public String toString() {
    131             return "{callingPackage=" + callingPackage + " binder=" + binder
    132                     + " callback=" + callback
    133                     + " onSubscriptionsChangedListenererCallback="
    134                                             + onSubscriptionsChangedListenerCallback
    135                     + " callerUid=" + callerUid + " subId=" + subId + " phoneId=" + phoneId
    136                     + " events=" + Integer.toHexString(events) + "}";
    137         }
    138     }
    139 
    140     private final Context mContext;
    141 
    142     // access should be inside synchronized (mRecords) for these two fields
    143     private final ArrayList<IBinder> mRemoveList = new ArrayList<IBinder>();
    144     private final ArrayList<Record> mRecords = new ArrayList<Record>();
    145 
    146     private final IBatteryStats mBatteryStats;
    147 
    148     private final AppOpsManager mAppOps;
    149 
    150     private boolean hasNotifySubscriptionInfoChangedOccurred = false;
    151 
    152     private int mNumPhones;
    153 
    154     private int[] mCallState;
    155 
    156     private String[] mCallIncomingNumber;
    157 
    158     private ServiceState[] mServiceState;
    159 
    160     private int[] mVoiceActivationState;
    161 
    162     private int[] mDataActivationState;
    163 
    164     private boolean[] mUserMobileDataState;
    165 
    166     private SignalStrength[] mSignalStrength;
    167 
    168     private boolean[] mMessageWaiting;
    169 
    170     private boolean[] mCallForwarding;
    171 
    172     private int[] mDataActivity;
    173 
    174     // Connection state of default APN type data (i.e. internet) of phones
    175     private int[] mDataConnectionState;
    176 
    177     private Bundle[] mCellLocation;
    178 
    179     private int[] mDataConnectionNetworkType;
    180 
    181     private int mOtaspMode = TelephonyManager.OTASP_UNKNOWN;
    182 
    183     private ArrayList<List<CellInfo>> mCellInfo = null;
    184 
    185     private ArrayList<List<PhysicalChannelConfig>> mPhysicalChannelConfigs;
    186 
    187     private VoLteServiceState mVoLteServiceState = new VoLteServiceState();
    188 
    189     private int mDefaultSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
    190 
    191     private int mDefaultPhoneId = SubscriptionManager.INVALID_PHONE_INDEX;
    192 
    193     private int mRingingCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
    194 
    195     private int mForegroundCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
    196 
    197     private int mBackgroundCallState = PreciseCallState.PRECISE_CALL_STATE_IDLE;
    198 
    199     private PreciseCallState mPreciseCallState = new PreciseCallState();
    200 
    201     private boolean mCarrierNetworkChangeState = false;
    202 
    203     private final LocalLog mLocalLog = new LocalLog(100);
    204 
    205     private PreciseDataConnectionState mPreciseDataConnectionState =
    206                 new PreciseDataConnectionState();
    207 
    208     static final int ENFORCE_COARSE_LOCATION_PERMISSION_MASK =
    209             PhoneStateListener.LISTEN_CELL_LOCATION
    210                     | PhoneStateListener.LISTEN_CELL_INFO;
    211 
    212     static final int ENFORCE_PHONE_STATE_PERMISSION_MASK =
    213                 PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR |
    214                 PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR |
    215                 PhoneStateListener.LISTEN_VOLTE_STATE;
    216 
    217     static final int PRECISE_PHONE_STATE_PERMISSION_MASK =
    218                 PhoneStateListener.LISTEN_PRECISE_CALL_STATE |
    219                 PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE;
    220 
    221     private static final int MSG_USER_SWITCHED = 1;
    222     private static final int MSG_UPDATE_DEFAULT_SUB = 2;
    223 
    224     private final Handler mHandler = new Handler() {
    225         @Override
    226         public void handleMessage(Message msg) {
    227             switch (msg.what) {
    228                 case MSG_USER_SWITCHED: {
    229                     if (VDBG) log("MSG_USER_SWITCHED userId=" + msg.arg1);
    230                     int numPhones = TelephonyManager.getDefault().getPhoneCount();
    231                     for (int sub = 0; sub < numPhones; sub++) {
    232                         TelephonyRegistry.this.notifyCellLocationForSubscriber(sub,
    233                                 mCellLocation[sub]);
    234                     }
    235                     break;
    236                 }
    237                 case MSG_UPDATE_DEFAULT_SUB: {
    238                     int newDefaultPhoneId = msg.arg1;
    239                     int newDefaultSubId = (Integer)(msg.obj);
    240                     if (VDBG) {
    241                         log("MSG_UPDATE_DEFAULT_SUB:current mDefaultSubId=" + mDefaultSubId
    242                             + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
    243                             + newDefaultSubId + " newDefaultPhoneId=" + newDefaultPhoneId);
    244                     }
    245 
    246                     //Due to possible risk condition,(notify call back using the new
    247                     //defaultSubId comes before new defaultSubId update) we need to recall all
    248                     //possible missed notify callback
    249                     synchronized (mRecords) {
    250                         for (Record r : mRecords) {
    251                             if(r.subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) {
    252                                 checkPossibleMissNotify(r, newDefaultPhoneId);
    253                             }
    254                         }
    255                         handleRemoveListLocked();
    256                     }
    257                     mDefaultSubId = newDefaultSubId;
    258                     mDefaultPhoneId = newDefaultPhoneId;
    259                 }
    260             }
    261         }
    262     };
    263 
    264     private class TelephonyRegistryDeathRecipient implements IBinder.DeathRecipient {
    265 
    266         private final IBinder binder;
    267 
    268         TelephonyRegistryDeathRecipient(IBinder binder) {
    269             this.binder = binder;
    270         }
    271 
    272         @Override
    273         public void binderDied() {
    274             if (DBG) log("binderDied " + binder);
    275             remove(binder);
    276         }
    277     }
    278 
    279     private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    280         @Override
    281         public void onReceive(Context context, Intent intent) {
    282             String action = intent.getAction();
    283             if (VDBG) log("mBroadcastReceiver: action=" + action);
    284             if (Intent.ACTION_USER_SWITCHED.equals(action)) {
    285                 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0);
    286                 if (DBG) log("onReceive: userHandle=" + userHandle);
    287                 mHandler.sendMessage(mHandler.obtainMessage(MSG_USER_SWITCHED, userHandle, 0));
    288             } else if (action.equals(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED)) {
    289                 Integer newDefaultSubIdObj = new Integer(intent.getIntExtra(
    290                         PhoneConstants.SUBSCRIPTION_KEY,
    291                         SubscriptionManager.getDefaultSubscriptionId()));
    292                 int newDefaultPhoneId = intent.getIntExtra(PhoneConstants.SLOT_KEY,
    293                     SubscriptionManager.getPhoneId(mDefaultSubId));
    294                 if (DBG) {
    295                     log("onReceive:current mDefaultSubId=" + mDefaultSubId
    296                         + " current mDefaultPhoneId=" + mDefaultPhoneId + " newDefaultSubId= "
    297                         + newDefaultSubIdObj + " newDefaultPhoneId=" + newDefaultPhoneId);
    298                 }
    299 
    300                 if(validatePhoneId(newDefaultPhoneId) && (!newDefaultSubIdObj.equals(mDefaultSubId)
    301                         || (newDefaultPhoneId != mDefaultPhoneId))) {
    302                     mHandler.sendMessage(mHandler.obtainMessage(MSG_UPDATE_DEFAULT_SUB,
    303                             newDefaultPhoneId, 0, newDefaultSubIdObj));
    304                 }
    305             }
    306         }
    307     };
    308 
    309     // we keep a copy of all of the state so we can send it out when folks
    310     // register for it
    311     //
    312     // In these calls we call with the lock held. This is safe becasuse remote
    313     // calls go through a oneway interface and local calls going through a
    314     // handler before they get to app code.
    315 
    316     TelephonyRegistry(Context context) {
    317         CellLocation  location = CellLocation.getEmpty();
    318 
    319         mContext = context;
    320         mBatteryStats = BatteryStatsService.getService();
    321 
    322         int numPhones = TelephonyManager.getDefault().getPhoneCount();
    323         if (DBG) log("TelephonyRegistry: ctor numPhones=" + numPhones);
    324         mNumPhones = numPhones;
    325         mCallState = new int[numPhones];
    326         mDataActivity = new int[numPhones];
    327         mDataConnectionState = new int[numPhones];
    328         mDataConnectionNetworkType = new int[numPhones];
    329         mCallIncomingNumber = new String[numPhones];
    330         mServiceState = new ServiceState[numPhones];
    331         mVoiceActivationState = new int[numPhones];
    332         mDataActivationState = new int[numPhones];
    333         mUserMobileDataState = new boolean[numPhones];
    334         mSignalStrength = new SignalStrength[numPhones];
    335         mMessageWaiting = new boolean[numPhones];
    336         mCallForwarding = new boolean[numPhones];
    337         mCellLocation = new Bundle[numPhones];
    338         mCellInfo = new ArrayList<List<CellInfo>>();
    339         mPhysicalChannelConfigs = new ArrayList<List<PhysicalChannelConfig>>();
    340         for (int i = 0; i < numPhones; i++) {
    341             mCallState[i] =  TelephonyManager.CALL_STATE_IDLE;
    342             mDataActivity[i] = TelephonyManager.DATA_ACTIVITY_NONE;
    343             mDataConnectionState[i] = TelephonyManager.DATA_UNKNOWN;
    344             mVoiceActivationState[i] = TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
    345             mDataActivationState[i] = TelephonyManager.SIM_ACTIVATION_STATE_UNKNOWN;
    346             mCallIncomingNumber[i] =  "";
    347             mServiceState[i] =  new ServiceState();
    348             mSignalStrength[i] =  new SignalStrength();
    349             mUserMobileDataState[i] = false;
    350             mMessageWaiting[i] =  false;
    351             mCallForwarding[i] =  false;
    352             mCellLocation[i] = new Bundle();
    353             mCellInfo.add(i, null);
    354             mPhysicalChannelConfigs.add(i, new ArrayList<PhysicalChannelConfig>());
    355         }
    356 
    357         // Note that location can be null for non-phone builds like
    358         // like the generic one.
    359         if (location != null) {
    360             for (int i = 0; i < numPhones; i++) {
    361                 location.fillInNotifierBundle(mCellLocation[i]);
    362             }
    363         }
    364 
    365         mAppOps = mContext.getSystemService(AppOpsManager.class);
    366     }
    367 
    368     public void systemRunning() {
    369         // Watch for interesting updates
    370         final IntentFilter filter = new IntentFilter();
    371         filter.addAction(Intent.ACTION_USER_SWITCHED);
    372         filter.addAction(Intent.ACTION_USER_REMOVED);
    373         filter.addAction(TelephonyIntents.ACTION_DEFAULT_SUBSCRIPTION_CHANGED);
    374         log("systemRunning register for intents");
    375         mContext.registerReceiver(mBroadcastReceiver, filter);
    376     }
    377 
    378     @Override
    379     public void addOnSubscriptionsChangedListener(String callingPackage,
    380             IOnSubscriptionsChangedListener callback) {
    381         int callerUserId = UserHandle.getCallingUserId();
    382         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
    383         if (VDBG) {
    384             log("listen oscl: E pkg=" + callingPackage + " myUserId=" + UserHandle.myUserId()
    385                 + " callerUserId="  + callerUserId + " callback=" + callback
    386                 + " callback.asBinder=" + callback.asBinder());
    387         }
    388 
    389         synchronized (mRecords) {
    390             // register
    391             IBinder b = callback.asBinder();
    392             Record r = add(b);
    393 
    394             if (r == null) {
    395                 return;
    396             }
    397 
    398             r.context = mContext;
    399             r.onSubscriptionsChangedListenerCallback = callback;
    400             r.callingPackage = callingPackage;
    401             r.callerUid = Binder.getCallingUid();
    402             r.callerPid = Binder.getCallingPid();
    403             r.events = 0;
    404             if (DBG) {
    405                 log("listen oscl:  Register r=" + r);
    406             }
    407             // Always notify when registration occurs if there has been a notification.
    408             if (hasNotifySubscriptionInfoChangedOccurred) {
    409                 try {
    410                     if (VDBG) log("listen oscl: send to r=" + r);
    411                     r.onSubscriptionsChangedListenerCallback.onSubscriptionsChanged();
    412                     if (VDBG) log("listen oscl: sent to r=" + r);
    413                 } catch (RemoteException e) {
    414                     if (VDBG) log("listen oscl: remote exception sending to r=" + r + " e=" + e);
    415                     remove(r.binder);
    416                 }
    417             } else {
    418                 log("listen oscl: hasNotifySubscriptionInfoChangedOccurred==false no callback");
    419             }
    420         }
    421     }
    422 
    423     @Override
    424     public void removeOnSubscriptionsChangedListener(String pkgForDebug,
    425             IOnSubscriptionsChangedListener callback) {
    426         if (DBG) log("listen oscl: Unregister");
    427         remove(callback.asBinder());
    428     }
    429 
    430     @Override
    431     public void notifySubscriptionInfoChanged() {
    432         if (VDBG) log("notifySubscriptionInfoChanged:");
    433         synchronized (mRecords) {
    434             if (!hasNotifySubscriptionInfoChangedOccurred) {
    435                 log("notifySubscriptionInfoChanged: first invocation mRecords.size="
    436                         + mRecords.size());
    437             }
    438             hasNotifySubscriptionInfoChangedOccurred = true;
    439             mRemoveList.clear();
    440             for (Record r : mRecords) {
    441                 if (r.matchOnSubscriptionsChangedListener()) {
    442                     try {
    443                         if (VDBG) log("notifySubscriptionInfoChanged: call osc to r=" + r);
    444                         r.onSubscriptionsChangedListenerCallback.onSubscriptionsChanged();
    445                         if (VDBG) log("notifySubscriptionInfoChanged: done osc to r=" + r);
    446                     } catch (RemoteException ex) {
    447                         if (VDBG) log("notifySubscriptionInfoChanged: RemoteException r=" + r);
    448                         mRemoveList.add(r.binder);
    449                     }
    450                 }
    451             }
    452             handleRemoveListLocked();
    453         }
    454     }
    455 
    456     @Override
    457     public void listen(String pkgForDebug, IPhoneStateListener callback, int events,
    458             boolean notifyNow) {
    459         listenForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, pkgForDebug, callback,
    460                 events, notifyNow);
    461     }
    462 
    463     @Override
    464     public void listenForSubscriber(int subId, String pkgForDebug, IPhoneStateListener callback,
    465             int events, boolean notifyNow) {
    466         listen(pkgForDebug, callback, events, notifyNow, subId);
    467     }
    468 
    469     private void listen(String callingPackage, IPhoneStateListener callback, int events,
    470             boolean notifyNow, int subId) {
    471         int callerUserId = UserHandle.getCallingUserId();
    472         mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
    473         if (VDBG) {
    474             log("listen: E pkg=" + callingPackage + " events=0x" + Integer.toHexString(events)
    475                 + " notifyNow=" + notifyNow + " subId=" + subId + " myUserId="
    476                 + UserHandle.myUserId() + " callerUserId=" + callerUserId);
    477         }
    478 
    479         if (events != PhoneStateListener.LISTEN_NONE) {
    480             // Checks permission and throws SecurityException for disallowed operations. For pre-M
    481             // apps whose runtime permission has been revoked, we return immediately to skip sending
    482             // events to the app without crashing it.
    483             if (!checkListenerPermission(events, subId, callingPackage, "listen")) {
    484                 return;
    485             }
    486 
    487             int phoneId = SubscriptionManager.getPhoneId(subId);
    488             synchronized (mRecords) {
    489                 // register
    490                 IBinder b = callback.asBinder();
    491                 Record r = add(b);
    492 
    493                 if (r == null) {
    494                     return;
    495                 }
    496 
    497                 r.context = mContext;
    498                 r.callback = callback;
    499                 r.callingPackage = callingPackage;
    500                 r.callerUid = Binder.getCallingUid();
    501                 r.callerPid = Binder.getCallingPid();
    502                 // Legacy applications pass SubscriptionManager.DEFAULT_SUB_ID,
    503                 // force all illegal subId to SubscriptionManager.DEFAULT_SUB_ID
    504                 if (!SubscriptionManager.isValidSubscriptionId(subId)) {
    505                     r.subId = SubscriptionManager.DEFAULT_SUBSCRIPTION_ID;
    506                  } else {//APP specify subID
    507                     r.subId = subId;
    508                 }
    509                 r.phoneId = phoneId;
    510                 r.events = events;
    511                 if (DBG) {
    512                     log("listen:  Register r=" + r + " r.subId=" + r.subId + " phoneId=" + phoneId);
    513                 }
    514                 if (notifyNow && validatePhoneId(phoneId)) {
    515                     if ((events & PhoneStateListener.LISTEN_SERVICE_STATE) != 0) {
    516                         try {
    517                             if (VDBG) log("listen: call onSSC state=" + mServiceState[phoneId]);
    518                             r.callback.onServiceStateChanged(
    519                                     new ServiceState(mServiceState[phoneId]));
    520                         } catch (RemoteException ex) {
    521                             remove(r.binder);
    522                         }
    523                     }
    524                     if ((events & PhoneStateListener.LISTEN_SIGNAL_STRENGTH) != 0) {
    525                         try {
    526                             int gsmSignalStrength = mSignalStrength[phoneId]
    527                                     .getGsmSignalStrength();
    528                             r.callback.onSignalStrengthChanged((gsmSignalStrength == 99 ? -1
    529                                     : gsmSignalStrength));
    530                         } catch (RemoteException ex) {
    531                             remove(r.binder);
    532                         }
    533                     }
    534                     if ((events & PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR) != 0) {
    535                         try {
    536                             r.callback.onMessageWaitingIndicatorChanged(
    537                                     mMessageWaiting[phoneId]);
    538                         } catch (RemoteException ex) {
    539                             remove(r.binder);
    540                         }
    541                     }
    542                     if ((events & PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR) != 0) {
    543                         try {
    544                             r.callback.onCallForwardingIndicatorChanged(
    545                                     mCallForwarding[phoneId]);
    546                         } catch (RemoteException ex) {
    547                             remove(r.binder);
    548                         }
    549                     }
    550                     if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_LOCATION)) {
    551                         try {
    552                             if (DBG_LOC) log("listen: mCellLocation = "
    553                                     + mCellLocation[phoneId]);
    554                             if (checkLocationAccess(r)) {
    555                                 r.callback.onCellLocationChanged(
    556                                         new Bundle(mCellLocation[phoneId]));
    557                             }
    558                         } catch (RemoteException ex) {
    559                             remove(r.binder);
    560                         }
    561                     }
    562                     if ((events & PhoneStateListener.LISTEN_CALL_STATE) != 0) {
    563                         try {
    564                             r.callback.onCallStateChanged(mCallState[phoneId],
    565                                      getCallIncomingNumber(r, phoneId));
    566                         } catch (RemoteException ex) {
    567                             remove(r.binder);
    568                         }
    569                     }
    570                     if ((events & PhoneStateListener.LISTEN_DATA_CONNECTION_STATE) != 0) {
    571                         try {
    572                             r.callback.onDataConnectionStateChanged(mDataConnectionState[phoneId],
    573                                 mDataConnectionNetworkType[phoneId]);
    574                         } catch (RemoteException ex) {
    575                             remove(r.binder);
    576                         }
    577                     }
    578                     if ((events & PhoneStateListener.LISTEN_DATA_ACTIVITY) != 0) {
    579                         try {
    580                             r.callback.onDataActivity(mDataActivity[phoneId]);
    581                         } catch (RemoteException ex) {
    582                             remove(r.binder);
    583                         }
    584                     }
    585                     if ((events & PhoneStateListener.LISTEN_SIGNAL_STRENGTHS) != 0) {
    586                         try {
    587                             r.callback.onSignalStrengthsChanged(mSignalStrength[phoneId]);
    588                         } catch (RemoteException ex) {
    589                             remove(r.binder);
    590                         }
    591                     }
    592                     if ((events & PhoneStateListener.LISTEN_OTASP_CHANGED) != 0) {
    593                         try {
    594                             r.callback.onOtaspChanged(mOtaspMode);
    595                         } catch (RemoteException ex) {
    596                             remove(r.binder);
    597                         }
    598                     }
    599                     if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_INFO)) {
    600                         try {
    601                             if (DBG_LOC) log("listen: mCellInfo[" + phoneId + "] = "
    602                                     + mCellInfo.get(phoneId));
    603                             if (checkLocationAccess(r)) {
    604                                 r.callback.onCellInfoChanged(mCellInfo.get(phoneId));
    605                             }
    606                         } catch (RemoteException ex) {
    607                             remove(r.binder);
    608                         }
    609                     }
    610                     if ((events & PhoneStateListener.LISTEN_PRECISE_CALL_STATE) != 0) {
    611                         try {
    612                             r.callback.onPreciseCallStateChanged(mPreciseCallState);
    613                         } catch (RemoteException ex) {
    614                             remove(r.binder);
    615                         }
    616                     }
    617                     if ((events & PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE) != 0) {
    618                         try {
    619                             r.callback.onPreciseDataConnectionStateChanged(
    620                                     mPreciseDataConnectionState);
    621                         } catch (RemoteException ex) {
    622                             remove(r.binder);
    623                         }
    624                     }
    625                     if ((events & PhoneStateListener.LISTEN_CARRIER_NETWORK_CHANGE) != 0) {
    626                         try {
    627                             r.callback.onCarrierNetworkChange(mCarrierNetworkChangeState);
    628                         } catch (RemoteException ex) {
    629                             remove(r.binder);
    630                         }
    631                     }
    632                     if ((events & PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE) !=0) {
    633                         try {
    634                             r.callback.onVoiceActivationStateChanged(mVoiceActivationState[phoneId]);
    635                         } catch (RemoteException ex) {
    636                             remove(r.binder);
    637                         }
    638                     }
    639                     if ((events & PhoneStateListener.LISTEN_DATA_ACTIVATION_STATE) !=0) {
    640                         try {
    641                             r.callback.onDataActivationStateChanged(mDataActivationState[phoneId]);
    642                         } catch (RemoteException ex) {
    643                             remove(r.binder);
    644                         }
    645                     }
    646                     if ((events & PhoneStateListener.LISTEN_USER_MOBILE_DATA_STATE) != 0) {
    647                         try {
    648                             r.callback.onUserMobileDataStateChanged(mUserMobileDataState[phoneId]);
    649                         } catch (RemoteException ex) {
    650                             remove(r.binder);
    651                         }
    652                     }
    653                     if ((events & PhoneStateListener.LISTEN_PHYSICAL_CHANNEL_CONFIGURATION) != 0) {
    654                         try {
    655                             r.callback.onPhysicalChannelConfigurationChanged(
    656                                     mPhysicalChannelConfigs.get(phoneId));
    657                         } catch (RemoteException ex) {
    658                             remove(r.binder);
    659                         }
    660                     }
    661                 }
    662             }
    663         } else {
    664             if(DBG) log("listen: Unregister");
    665             remove(callback.asBinder());
    666         }
    667     }
    668 
    669     private String getCallIncomingNumber(Record record, int phoneId) {
    670         // Only reveal the incoming number if the record has read call log permission.
    671         return record.canReadCallLog() ? mCallIncomingNumber[phoneId] : "";
    672     }
    673 
    674     private Record add(IBinder binder) {
    675         Record r;
    676 
    677         synchronized (mRecords) {
    678             final int N = mRecords.size();
    679             for (int i = 0; i < N; i++) {
    680                 r = mRecords.get(i);
    681                 if (binder == r.binder) {
    682                     // Already existed.
    683                     return r;
    684                 }
    685             }
    686             r = new Record();
    687             r.binder = binder;
    688             r.deathRecipient = new TelephonyRegistryDeathRecipient(binder);
    689 
    690             try {
    691                 binder.linkToDeath(r.deathRecipient, 0);
    692             } catch (RemoteException e) {
    693                 if (VDBG) log("LinkToDeath remote exception sending to r=" + r + " e=" + e);
    694                 // Binder already died. Return null.
    695                 return null;
    696             }
    697 
    698             mRecords.add(r);
    699             if (DBG) log("add new record");
    700         }
    701 
    702         return r;
    703     }
    704 
    705     private void remove(IBinder binder) {
    706         synchronized (mRecords) {
    707             final int recordCount = mRecords.size();
    708             for (int i = 0; i < recordCount; i++) {
    709                 Record r = mRecords.get(i);
    710                 if (r.binder == binder) {
    711                     if (DBG) {
    712                         log("remove: binder=" + binder + " r.callingPackage " + r.callingPackage
    713                                 + " r.callback " + r.callback);
    714                     }
    715 
    716                     if (r.deathRecipient != null) {
    717                         try {
    718                             binder.unlinkToDeath(r.deathRecipient, 0);
    719                         } catch (NoSuchElementException e) {
    720                             if (VDBG) log("UnlinkToDeath NoSuchElementException sending to r="
    721                                     + r + " e=" + e);
    722                         }
    723                     }
    724 
    725                     mRecords.remove(i);
    726                     return;
    727                 }
    728             }
    729         }
    730     }
    731 
    732     public void notifyCallState(int state, String phoneNumber) {
    733         if (!checkNotifyPermission("notifyCallState()")) {
    734             return;
    735         }
    736 
    737         if (VDBG) {
    738             log("notifyCallState: state=" + state + " phoneNumber=" + phoneNumber);
    739         }
    740 
    741         synchronized (mRecords) {
    742             for (Record r : mRecords) {
    743                 if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_CALL_STATE) &&
    744                         (r.subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID)) {
    745                     try {
    746                         // Ensure the listener has read call log permission; if they do not return
    747                         // an empty phone number.
    748                         String phoneNumberOrEmpty = r.canReadCallLog() ? phoneNumber : "";
    749                         r.callback.onCallStateChanged(state, phoneNumberOrEmpty);
    750                     } catch (RemoteException ex) {
    751                         mRemoveList.add(r.binder);
    752                     }
    753                 }
    754             }
    755             handleRemoveListLocked();
    756         }
    757 
    758         // Called only by Telecomm to communicate call state across different phone accounts. So
    759         // there is no need to add a valid subId or slotId.
    760         broadcastCallStateChanged(state, phoneNumber,
    761                 SubscriptionManager.INVALID_PHONE_INDEX,
    762                 SubscriptionManager.INVALID_SUBSCRIPTION_ID);
    763     }
    764 
    765     public void notifyCallStateForPhoneId(int phoneId, int subId, int state,
    766                 String incomingNumber) {
    767         if (!checkNotifyPermission("notifyCallState()")) {
    768             return;
    769         }
    770         if (VDBG) {
    771             log("notifyCallStateForPhoneId: subId=" + subId
    772                 + " state=" + state + " incomingNumber=" + incomingNumber);
    773         }
    774         synchronized (mRecords) {
    775             if (validatePhoneId(phoneId)) {
    776                 mCallState[phoneId] = state;
    777                 mCallIncomingNumber[phoneId] = incomingNumber;
    778                 for (Record r : mRecords) {
    779                     if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_CALL_STATE) &&
    780                             (r.subId == subId) &&
    781                             (r.subId != SubscriptionManager.DEFAULT_SUBSCRIPTION_ID)) {
    782                         try {
    783                             String incomingNumberOrEmpty = getCallIncomingNumber(r, phoneId);
    784                             r.callback.onCallStateChanged(state, incomingNumberOrEmpty);
    785                         } catch (RemoteException ex) {
    786                             mRemoveList.add(r.binder);
    787                         }
    788                     }
    789                 }
    790             }
    791             handleRemoveListLocked();
    792         }
    793         broadcastCallStateChanged(state, incomingNumber, phoneId, subId);
    794     }
    795 
    796     public void notifyServiceStateForPhoneId(int phoneId, int subId, ServiceState state) {
    797         if (!checkNotifyPermission("notifyServiceState()")){
    798             return;
    799         }
    800 
    801         synchronized (mRecords) {
    802             String str = "notifyServiceStateForSubscriber: subId=" + subId + " phoneId=" + phoneId
    803                     + " state=" + state;
    804             if (VDBG) {
    805                 log(str);
    806             }
    807             mLocalLog.log(str);
    808             if (validatePhoneId(phoneId)) {
    809                 mServiceState[phoneId] = state;
    810 
    811                 for (Record r : mRecords) {
    812                     if (VDBG) {
    813                         log("notifyServiceStateForSubscriber: r=" + r + " subId=" + subId
    814                                 + " phoneId=" + phoneId + " state=" + state);
    815                     }
    816                     if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_SERVICE_STATE) &&
    817                             idMatch(r.subId, subId, phoneId)) {
    818                         try {
    819                             if (DBG) {
    820                                 log("notifyServiceStateForSubscriber: callback.onSSC r=" + r
    821                                         + " subId=" + subId + " phoneId=" + phoneId
    822                                         + " state=" + state);
    823                             }
    824                             r.callback.onServiceStateChanged(new ServiceState(state));
    825                         } catch (RemoteException ex) {
    826                             mRemoveList.add(r.binder);
    827                         }
    828                     }
    829                 }
    830             } else {
    831                 log("notifyServiceStateForSubscriber: INVALID phoneId=" + phoneId);
    832             }
    833             handleRemoveListLocked();
    834         }
    835         broadcastServiceStateChanged(state, phoneId, subId);
    836     }
    837 
    838     public void notifySimActivationStateChangedForPhoneId(int phoneId, int subId,
    839             int activationType, int activationState) {
    840         if (!checkNotifyPermission("notifySimActivationState()")){
    841             return;
    842         }
    843         if (VDBG) {
    844             log("notifySimActivationStateForPhoneId: subId=" + subId + " phoneId=" + phoneId
    845                     + "type=" + activationType + " state=" + activationState);
    846         }
    847         synchronized (mRecords) {
    848             if (validatePhoneId(phoneId)) {
    849                 switch (activationType) {
    850                     case PhoneConstants.SIM_ACTIVATION_TYPE_VOICE:
    851                         mVoiceActivationState[phoneId] = activationState;
    852                         break;
    853                     case PhoneConstants.SIM_ACTIVATION_TYPE_DATA:
    854                         mDataActivationState[phoneId] = activationState;
    855                         break;
    856                     default:
    857                         return;
    858                 }
    859                 for (Record r : mRecords) {
    860                     if (VDBG) {
    861                         log("notifySimActivationStateForPhoneId: r=" + r + " subId=" + subId
    862                                 + " phoneId=" + phoneId + "type=" + activationType
    863                                 + " state=" + activationState);
    864                     }
    865                     try {
    866                         if ((activationType == PhoneConstants.SIM_ACTIVATION_TYPE_VOICE) &&
    867                                 r.matchPhoneStateListenerEvent(
    868                                         PhoneStateListener.LISTEN_VOICE_ACTIVATION_STATE) &&
    869                                 idMatch(r.subId, subId, phoneId)) {
    870                             if (DBG) {
    871                                 log("notifyVoiceActivationStateForPhoneId: callback.onVASC r=" + r
    872                                         + " subId=" + subId + " phoneId=" + phoneId
    873                                         + " state=" + activationState);
    874                             }
    875                             r.callback.onVoiceActivationStateChanged(activationState);
    876                         }
    877                         if ((activationType == PhoneConstants.SIM_ACTIVATION_TYPE_DATA) &&
    878                                 r.matchPhoneStateListenerEvent(
    879                                         PhoneStateListener.LISTEN_DATA_ACTIVATION_STATE) &&
    880                                 idMatch(r.subId, subId, phoneId)) {
    881                             if (DBG) {
    882                                 log("notifyDataActivationStateForPhoneId: callback.onDASC r=" + r
    883                                         + " subId=" + subId + " phoneId=" + phoneId
    884                                         + " state=" + activationState);
    885                             }
    886                             r.callback.onDataActivationStateChanged(activationState);
    887                         }
    888                     }  catch (RemoteException ex) {
    889                         mRemoveList.add(r.binder);
    890                     }
    891                 }
    892             } else {
    893                 log("notifySimActivationStateForPhoneId: INVALID phoneId=" + phoneId);
    894             }
    895             handleRemoveListLocked();
    896         }
    897     }
    898 
    899     public void notifySignalStrengthForPhoneId(int phoneId, int subId,
    900                 SignalStrength signalStrength) {
    901         if (!checkNotifyPermission("notifySignalStrength()")) {
    902             return;
    903         }
    904         if (VDBG) {
    905             log("notifySignalStrengthForPhoneId: subId=" + subId
    906                 +" phoneId=" + phoneId + " signalStrength=" + signalStrength);
    907         }
    908 
    909         synchronized (mRecords) {
    910             if (validatePhoneId(phoneId)) {
    911                 if (VDBG) log("notifySignalStrengthForPhoneId: valid phoneId=" + phoneId);
    912                 mSignalStrength[phoneId] = signalStrength;
    913                 for (Record r : mRecords) {
    914                     if (VDBG) {
    915                         log("notifySignalStrengthForPhoneId: r=" + r + " subId=" + subId
    916                                 + " phoneId=" + phoneId + " ss=" + signalStrength);
    917                     }
    918                     if (r.matchPhoneStateListenerEvent(
    919                                 PhoneStateListener.LISTEN_SIGNAL_STRENGTHS) &&
    920                             idMatch(r.subId, subId, phoneId)) {
    921                         try {
    922                             if (DBG) {
    923                                 log("notifySignalStrengthForPhoneId: callback.onSsS r=" + r
    924                                         + " subId=" + subId + " phoneId=" + phoneId
    925                                         + " ss=" + signalStrength);
    926                             }
    927                             r.callback.onSignalStrengthsChanged(new SignalStrength(signalStrength));
    928                         } catch (RemoteException ex) {
    929                             mRemoveList.add(r.binder);
    930                         }
    931                     }
    932                     if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_SIGNAL_STRENGTH) &&
    933                             idMatch(r.subId, subId, phoneId)){
    934                         try {
    935                             int gsmSignalStrength = signalStrength.getGsmSignalStrength();
    936                             int ss = (gsmSignalStrength == 99 ? -1 : gsmSignalStrength);
    937                             if (DBG) {
    938                                 log("notifySignalStrengthForPhoneId: callback.onSS r=" + r
    939                                         + " subId=" + subId + " phoneId=" + phoneId
    940                                         + " gsmSS=" + gsmSignalStrength + " ss=" + ss);
    941                             }
    942                             r.callback.onSignalStrengthChanged(ss);
    943                         } catch (RemoteException ex) {
    944                             mRemoveList.add(r.binder);
    945                         }
    946                     }
    947                 }
    948             } else {
    949                 log("notifySignalStrengthForPhoneId: invalid phoneId=" + phoneId);
    950             }
    951             handleRemoveListLocked();
    952         }
    953         broadcastSignalStrengthChanged(signalStrength, phoneId, subId);
    954     }
    955 
    956     @Override
    957     public void notifyCarrierNetworkChange(boolean active) {
    958         enforceNotifyPermissionOrCarrierPrivilege("notifyCarrierNetworkChange()");
    959 
    960         if (VDBG) {
    961             log("notifyCarrierNetworkChange: active=" + active);
    962         }
    963 
    964         synchronized (mRecords) {
    965             mCarrierNetworkChangeState = active;
    966             for (Record r : mRecords) {
    967                 if (r.matchPhoneStateListenerEvent(
    968                         PhoneStateListener.LISTEN_CARRIER_NETWORK_CHANGE)) {
    969                     try {
    970                         r.callback.onCarrierNetworkChange(active);
    971                     } catch (RemoteException ex) {
    972                         mRemoveList.add(r.binder);
    973                     }
    974                 }
    975             }
    976             handleRemoveListLocked();
    977         }
    978     }
    979 
    980     public void notifyCellInfo(List<CellInfo> cellInfo) {
    981          notifyCellInfoForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, cellInfo);
    982     }
    983 
    984     public void notifyCellInfoForSubscriber(int subId, List<CellInfo> cellInfo) {
    985         if (!checkNotifyPermission("notifyCellInfo()")) {
    986             return;
    987         }
    988         if (VDBG) {
    989             log("notifyCellInfoForSubscriber: subId=" + subId
    990                 + " cellInfo=" + cellInfo);
    991         }
    992         int phoneId = SubscriptionManager.getPhoneId(subId);
    993         synchronized (mRecords) {
    994             if (validatePhoneId(phoneId)) {
    995                 mCellInfo.set(phoneId, cellInfo);
    996                 for (Record r : mRecords) {
    997                     if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_INFO) &&
    998                             idMatch(r.subId, subId, phoneId) &&
    999                             checkLocationAccess(r)) {
   1000                         try {
   1001                             if (DBG_LOC) {
   1002                                 log("notifyCellInfo: mCellInfo=" + cellInfo + " r=" + r);
   1003                             }
   1004                             r.callback.onCellInfoChanged(cellInfo);
   1005                         } catch (RemoteException ex) {
   1006                             mRemoveList.add(r.binder);
   1007                         }
   1008                     }
   1009                 }
   1010             }
   1011             handleRemoveListLocked();
   1012         }
   1013     }
   1014 
   1015     public void notifyPhysicalChannelConfiguration(List<PhysicalChannelConfig> configs) {
   1016         notifyPhysicalChannelConfigurationForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
   1017                 configs);
   1018     }
   1019 
   1020     public void notifyPhysicalChannelConfigurationForSubscriber(int subId,
   1021             List<PhysicalChannelConfig> configs) {
   1022         if (!checkNotifyPermission("notifyPhysicalChannelConfiguration()")) {
   1023             return;
   1024         }
   1025 
   1026         if (VDBG) {
   1027             log("notifyPhysicalChannelConfiguration: subId=" + subId + " configs=" + configs);
   1028         }
   1029 
   1030         synchronized (mRecords) {
   1031             int phoneId = SubscriptionManager.getPhoneId(subId);
   1032             if (validatePhoneId(phoneId)) {
   1033                 mPhysicalChannelConfigs.set(phoneId, configs);
   1034                 for (Record r : mRecords) {
   1035                     if (r.matchPhoneStateListenerEvent(
   1036                             PhoneStateListener.LISTEN_PHYSICAL_CHANNEL_CONFIGURATION)
   1037                             && idMatch(r.subId, subId, phoneId)) {
   1038                         try {
   1039                             if (DBG_LOC) {
   1040                                 log("notifyPhysicalChannelConfiguration: mPhysicalChannelConfigs="
   1041                                         + configs + " r=" + r);
   1042                             }
   1043                             r.callback.onPhysicalChannelConfigurationChanged(configs);
   1044                         } catch (RemoteException ex) {
   1045                             mRemoveList.add(r.binder);
   1046                         }
   1047                     }
   1048                 }
   1049             }
   1050             handleRemoveListLocked();
   1051         }
   1052     }
   1053 
   1054     @Override
   1055     public void notifyMessageWaitingChangedForPhoneId(int phoneId, int subId, boolean mwi) {
   1056         if (!checkNotifyPermission("notifyMessageWaitingChanged()")) {
   1057             return;
   1058         }
   1059         if (VDBG) {
   1060             log("notifyMessageWaitingChangedForSubscriberPhoneID: subId=" + phoneId
   1061                 + " mwi=" + mwi);
   1062         }
   1063         synchronized (mRecords) {
   1064             if (validatePhoneId(phoneId)) {
   1065                 mMessageWaiting[phoneId] = mwi;
   1066                 for (Record r : mRecords) {
   1067                     if (r.matchPhoneStateListenerEvent(
   1068                             PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR) &&
   1069                             idMatch(r.subId, subId, phoneId)) {
   1070                         try {
   1071                             r.callback.onMessageWaitingIndicatorChanged(mwi);
   1072                         } catch (RemoteException ex) {
   1073                             mRemoveList.add(r.binder);
   1074                         }
   1075                     }
   1076                 }
   1077             }
   1078             handleRemoveListLocked();
   1079         }
   1080     }
   1081 
   1082     public void notifyUserMobileDataStateChangedForPhoneId(int phoneId, int subId, boolean state) {
   1083         if (!checkNotifyPermission("notifyUserMobileDataStateChanged()")) {
   1084             return;
   1085         }
   1086         if (VDBG) {
   1087             log("notifyUserMobileDataStateChangedForSubscriberPhoneID: subId=" + phoneId
   1088                     + " state=" + state);
   1089         }
   1090         synchronized (mRecords) {
   1091             if (validatePhoneId(phoneId)) {
   1092                 mMessageWaiting[phoneId] = state;
   1093                 for (Record r : mRecords) {
   1094                     if (r.matchPhoneStateListenerEvent(
   1095                             PhoneStateListener.LISTEN_USER_MOBILE_DATA_STATE) &&
   1096                             idMatch(r.subId, subId, phoneId)) {
   1097                         try {
   1098                             r.callback.onUserMobileDataStateChanged(state);
   1099                         } catch (RemoteException ex) {
   1100                             mRemoveList.add(r.binder);
   1101                         }
   1102                     }
   1103                 }
   1104             }
   1105             handleRemoveListLocked();
   1106         }
   1107     }
   1108 
   1109     public void notifyCallForwardingChanged(boolean cfi) {
   1110         notifyCallForwardingChangedForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, cfi);
   1111     }
   1112 
   1113     public void notifyCallForwardingChangedForSubscriber(int subId, boolean cfi) {
   1114         if (!checkNotifyPermission("notifyCallForwardingChanged()")) {
   1115             return;
   1116         }
   1117         if (VDBG) {
   1118             log("notifyCallForwardingChangedForSubscriber: subId=" + subId
   1119                 + " cfi=" + cfi);
   1120         }
   1121         int phoneId = SubscriptionManager.getPhoneId(subId);
   1122         synchronized (mRecords) {
   1123             if (validatePhoneId(phoneId)) {
   1124                 mCallForwarding[phoneId] = cfi;
   1125                 for (Record r : mRecords) {
   1126                     if (r.matchPhoneStateListenerEvent(
   1127                             PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR) &&
   1128                             idMatch(r.subId, subId, phoneId)) {
   1129                         try {
   1130                             r.callback.onCallForwardingIndicatorChanged(cfi);
   1131                         } catch (RemoteException ex) {
   1132                             mRemoveList.add(r.binder);
   1133                         }
   1134                     }
   1135                 }
   1136             }
   1137             handleRemoveListLocked();
   1138         }
   1139     }
   1140 
   1141     public void notifyDataActivity(int state) {
   1142         notifyDataActivityForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, state);
   1143     }
   1144 
   1145     public void notifyDataActivityForSubscriber(int subId, int state) {
   1146         if (!checkNotifyPermission("notifyDataActivity()" )) {
   1147             return;
   1148         }
   1149         int phoneId = SubscriptionManager.getPhoneId(subId);
   1150         synchronized (mRecords) {
   1151             if (validatePhoneId(phoneId)) {
   1152                 mDataActivity[phoneId] = state;
   1153                 for (Record r : mRecords) {
   1154                     // Notify by correct subId.
   1155                     if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_DATA_ACTIVITY) &&
   1156                             idMatch(r.subId, subId, phoneId)) {
   1157                         try {
   1158                             r.callback.onDataActivity(state);
   1159                         } catch (RemoteException ex) {
   1160                             mRemoveList.add(r.binder);
   1161                         }
   1162                     }
   1163                 }
   1164             }
   1165             handleRemoveListLocked();
   1166         }
   1167     }
   1168 
   1169     public void notifyDataConnection(int state, boolean isDataAllowed,
   1170             String reason, String apn, String apnType, LinkProperties linkProperties,
   1171             NetworkCapabilities networkCapabilities, int networkType, boolean roaming) {
   1172         notifyDataConnectionForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, state,
   1173             isDataAllowed,reason, apn, apnType, linkProperties,
   1174             networkCapabilities, networkType, roaming);
   1175     }
   1176 
   1177     public void notifyDataConnectionForSubscriber(int subId, int state,
   1178             boolean isDataAllowed, String reason, String apn, String apnType,
   1179             LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
   1180             int networkType, boolean roaming) {
   1181         if (!checkNotifyPermission("notifyDataConnection()" )) {
   1182             return;
   1183         }
   1184         if (VDBG) {
   1185             log("notifyDataConnectionForSubscriber: subId=" + subId
   1186                 + " state=" + state + " isDataAllowed=" + isDataAllowed
   1187                 + " reason='" + reason
   1188                 + "' apn='" + apn + "' apnType=" + apnType + " networkType=" + networkType
   1189                 + " mRecords.size()=" + mRecords.size());
   1190         }
   1191         int phoneId = SubscriptionManager.getPhoneId(subId);
   1192         synchronized (mRecords) {
   1193             if (validatePhoneId(phoneId)) {
   1194                 // We only call the callback when the change is for default APN type.
   1195                 if (PhoneConstants.APN_TYPE_DEFAULT.equals(apnType)
   1196                         && (mDataConnectionState[phoneId] != state
   1197                         || mDataConnectionNetworkType[phoneId] != networkType)) {
   1198                     String str = "onDataConnectionStateChanged(" + state
   1199                             + ", " + networkType + ")";
   1200                     log(str);
   1201                     mLocalLog.log(str);
   1202                     for (Record r : mRecords) {
   1203                         if (r.matchPhoneStateListenerEvent(
   1204                                 PhoneStateListener.LISTEN_DATA_CONNECTION_STATE) &&
   1205                                 idMatch(r.subId, subId, phoneId)) {
   1206                             try {
   1207                                 if (DBG) {
   1208                                     log("Notify data connection state changed on sub: " + subId);
   1209                                 }
   1210                                 r.callback.onDataConnectionStateChanged(state, networkType);
   1211                             } catch (RemoteException ex) {
   1212                                 mRemoveList.add(r.binder);
   1213                             }
   1214                         }
   1215                     }
   1216                     handleRemoveListLocked();
   1217 
   1218                     mDataConnectionState[phoneId] = state;
   1219                     mDataConnectionNetworkType[phoneId] = networkType;
   1220                 }
   1221                 mPreciseDataConnectionState = new PreciseDataConnectionState(state, networkType,
   1222                         apnType, apn, reason, linkProperties, "");
   1223                 for (Record r : mRecords) {
   1224                     if (r.matchPhoneStateListenerEvent(
   1225                             PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
   1226                         try {
   1227                             r.callback.onPreciseDataConnectionStateChanged(
   1228                                     mPreciseDataConnectionState);
   1229                         } catch (RemoteException ex) {
   1230                             mRemoveList.add(r.binder);
   1231                         }
   1232                     }
   1233                 }
   1234             }
   1235             handleRemoveListLocked();
   1236         }
   1237         broadcastDataConnectionStateChanged(state, isDataAllowed, reason, apn,
   1238                 apnType, linkProperties, networkCapabilities, roaming, subId);
   1239         broadcastPreciseDataConnectionStateChanged(state, networkType, apnType, apn, reason,
   1240                 linkProperties, "");
   1241     }
   1242 
   1243     public void notifyDataConnectionFailed(String reason, String apnType) {
   1244          notifyDataConnectionFailedForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
   1245                  reason, apnType);
   1246     }
   1247 
   1248     public void notifyDataConnectionFailedForSubscriber(int subId,
   1249             String reason, String apnType) {
   1250         if (!checkNotifyPermission("notifyDataConnectionFailed()")) {
   1251             return;
   1252         }
   1253         if (VDBG) {
   1254             log("notifyDataConnectionFailedForSubscriber: subId=" + subId
   1255                 + " reason=" + reason + " apnType=" + apnType);
   1256         }
   1257         synchronized (mRecords) {
   1258             mPreciseDataConnectionState = new PreciseDataConnectionState(
   1259                     TelephonyManager.DATA_UNKNOWN,TelephonyManager.NETWORK_TYPE_UNKNOWN,
   1260                     apnType, "", reason, null, "");
   1261             for (Record r : mRecords) {
   1262                 if (r.matchPhoneStateListenerEvent(
   1263                         PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
   1264                     try {
   1265                         r.callback.onPreciseDataConnectionStateChanged(mPreciseDataConnectionState);
   1266                     } catch (RemoteException ex) {
   1267                         mRemoveList.add(r.binder);
   1268                     }
   1269                 }
   1270             }
   1271             handleRemoveListLocked();
   1272         }
   1273         broadcastDataConnectionFailed(reason, apnType, subId);
   1274         broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
   1275                 TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, "", reason, null, "");
   1276     }
   1277 
   1278     public void notifyCellLocation(Bundle cellLocation) {
   1279          notifyCellLocationForSubscriber(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID, cellLocation);
   1280     }
   1281 
   1282     public void notifyCellLocationForSubscriber(int subId, Bundle cellLocation) {
   1283         log("notifyCellLocationForSubscriber: subId=" + subId
   1284                 + " cellLocation=" + cellLocation);
   1285         if (!checkNotifyPermission("notifyCellLocation()")) {
   1286             return;
   1287         }
   1288         if (VDBG) {
   1289             log("notifyCellLocationForSubscriber: subId=" + subId
   1290                 + " cellLocation=" + cellLocation);
   1291         }
   1292         int phoneId = SubscriptionManager.getPhoneId(subId);
   1293         synchronized (mRecords) {
   1294             if (validatePhoneId(phoneId)) {
   1295                 mCellLocation[phoneId] = cellLocation;
   1296                 for (Record r : mRecords) {
   1297                     if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_LOCATION) &&
   1298                             idMatch(r.subId, subId, phoneId) &&
   1299                             checkLocationAccess(r)) {
   1300                         try {
   1301                             if (DBG_LOC) {
   1302                                 log("notifyCellLocation: cellLocation=" + cellLocation
   1303                                         + " r=" + r);
   1304                             }
   1305                             r.callback.onCellLocationChanged(new Bundle(cellLocation));
   1306                         } catch (RemoteException ex) {
   1307                             mRemoveList.add(r.binder);
   1308                         }
   1309                     }
   1310                 }
   1311             }
   1312             handleRemoveListLocked();
   1313         }
   1314     }
   1315 
   1316     public void notifyOtaspChanged(int otaspMode) {
   1317         if (!checkNotifyPermission("notifyOtaspChanged()" )) {
   1318             return;
   1319         }
   1320         synchronized (mRecords) {
   1321             mOtaspMode = otaspMode;
   1322             for (Record r : mRecords) {
   1323                 if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_OTASP_CHANGED)) {
   1324                     try {
   1325                         r.callback.onOtaspChanged(otaspMode);
   1326                     } catch (RemoteException ex) {
   1327                         mRemoveList.add(r.binder);
   1328                     }
   1329                 }
   1330             }
   1331             handleRemoveListLocked();
   1332         }
   1333     }
   1334 
   1335     public void notifyPreciseCallState(int ringingCallState, int foregroundCallState,
   1336             int backgroundCallState) {
   1337         if (!checkNotifyPermission("notifyPreciseCallState()")) {
   1338             return;
   1339         }
   1340         synchronized (mRecords) {
   1341             mRingingCallState = ringingCallState;
   1342             mForegroundCallState = foregroundCallState;
   1343             mBackgroundCallState = backgroundCallState;
   1344             mPreciseCallState = new PreciseCallState(ringingCallState, foregroundCallState,
   1345                     backgroundCallState,
   1346                     DisconnectCause.NOT_VALID,
   1347                     PreciseDisconnectCause.NOT_VALID);
   1348             for (Record r : mRecords) {
   1349                 if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_PRECISE_CALL_STATE)) {
   1350                     try {
   1351                         r.callback.onPreciseCallStateChanged(mPreciseCallState);
   1352                     } catch (RemoteException ex) {
   1353                         mRemoveList.add(r.binder);
   1354                     }
   1355                 }
   1356             }
   1357             handleRemoveListLocked();
   1358         }
   1359         broadcastPreciseCallStateChanged(ringingCallState, foregroundCallState, backgroundCallState,
   1360                 DisconnectCause.NOT_VALID,
   1361                 PreciseDisconnectCause.NOT_VALID);
   1362     }
   1363 
   1364     public void notifyDisconnectCause(int disconnectCause, int preciseDisconnectCause) {
   1365         if (!checkNotifyPermission("notifyDisconnectCause()")) {
   1366             return;
   1367         }
   1368         synchronized (mRecords) {
   1369             mPreciseCallState = new PreciseCallState(mRingingCallState, mForegroundCallState,
   1370                     mBackgroundCallState, disconnectCause, preciseDisconnectCause);
   1371             for (Record r : mRecords) {
   1372                 if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_PRECISE_CALL_STATE)) {
   1373                     try {
   1374                         r.callback.onPreciseCallStateChanged(mPreciseCallState);
   1375                     } catch (RemoteException ex) {
   1376                         mRemoveList.add(r.binder);
   1377                     }
   1378                 }
   1379             }
   1380             handleRemoveListLocked();
   1381         }
   1382         broadcastPreciseCallStateChanged(mRingingCallState, mForegroundCallState,
   1383                 mBackgroundCallState, disconnectCause, preciseDisconnectCause);
   1384     }
   1385 
   1386     public void notifyPreciseDataConnectionFailed(String reason, String apnType,
   1387             String apn, String failCause) {
   1388         if (!checkNotifyPermission("notifyPreciseDataConnectionFailed()")) {
   1389             return;
   1390         }
   1391         synchronized (mRecords) {
   1392             mPreciseDataConnectionState = new PreciseDataConnectionState(
   1393                     TelephonyManager.DATA_UNKNOWN, TelephonyManager.NETWORK_TYPE_UNKNOWN,
   1394                     apnType, apn, reason, null, failCause);
   1395             for (Record r : mRecords) {
   1396                 if (r.matchPhoneStateListenerEvent(
   1397                         PhoneStateListener.LISTEN_PRECISE_DATA_CONNECTION_STATE)) {
   1398                     try {
   1399                         r.callback.onPreciseDataConnectionStateChanged(mPreciseDataConnectionState);
   1400                     } catch (RemoteException ex) {
   1401                         mRemoveList.add(r.binder);
   1402                     }
   1403                 }
   1404             }
   1405             handleRemoveListLocked();
   1406         }
   1407         broadcastPreciseDataConnectionStateChanged(TelephonyManager.DATA_UNKNOWN,
   1408                 TelephonyManager.NETWORK_TYPE_UNKNOWN, apnType, apn, reason, null, failCause);
   1409     }
   1410 
   1411     public void notifyVoLteServiceStateChanged(VoLteServiceState lteState) {
   1412         if (!checkNotifyPermission("notifyVoLteServiceStateChanged()")) {
   1413             return;
   1414         }
   1415         synchronized (mRecords) {
   1416             mVoLteServiceState = lteState;
   1417             for (Record r : mRecords) {
   1418                 if (r.matchPhoneStateListenerEvent(PhoneStateListener.LISTEN_VOLTE_STATE)) {
   1419                     try {
   1420                         r.callback.onVoLteServiceStateChanged(
   1421                                 new VoLteServiceState(mVoLteServiceState));
   1422                     } catch (RemoteException ex) {
   1423                         mRemoveList.add(r.binder);
   1424                     }
   1425                 }
   1426             }
   1427             handleRemoveListLocked();
   1428         }
   1429     }
   1430 
   1431     public void notifyOemHookRawEventForSubscriber(int subId, byte[] rawData) {
   1432         if (!checkNotifyPermission("notifyOemHookRawEventForSubscriber")) {
   1433             return;
   1434         }
   1435 
   1436         synchronized (mRecords) {
   1437             for (Record r : mRecords) {
   1438                 if (VDBG) {
   1439                     log("notifyOemHookRawEventForSubscriber:  r=" + r + " subId=" + subId);
   1440                 }
   1441                 if ((r.matchPhoneStateListenerEvent(
   1442                         PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT)) &&
   1443                         ((r.subId == subId) ||
   1444                         (r.subId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID))) {
   1445                     try {
   1446                         r.callback.onOemHookRawEvent(rawData);
   1447                     } catch (RemoteException ex) {
   1448                         mRemoveList.add(r.binder);
   1449                     }
   1450                 }
   1451             }
   1452             handleRemoveListLocked();
   1453         }
   1454     }
   1455 
   1456     @Override
   1457     public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
   1458         final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
   1459 
   1460         if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
   1461 
   1462         synchronized (mRecords) {
   1463             final int recordCount = mRecords.size();
   1464             pw.println("last known state:");
   1465             pw.increaseIndent();
   1466             for (int i = 0; i < TelephonyManager.getDefault().getPhoneCount(); i++) {
   1467                 pw.println("Phone Id=" + i);
   1468                 pw.increaseIndent();
   1469                 pw.println("mCallState=" + mCallState[i]);
   1470                 pw.println("mCallIncomingNumber=" + mCallIncomingNumber[i]);
   1471                 pw.println("mServiceState=" + mServiceState[i]);
   1472                 pw.println("mVoiceActivationState= " + mVoiceActivationState[i]);
   1473                 pw.println("mDataActivationState= " + mDataActivationState[i]);
   1474                 pw.println("mUserMobileDataState= " + mUserMobileDataState[i]);
   1475                 pw.println("mSignalStrength=" + mSignalStrength[i]);
   1476                 pw.println("mMessageWaiting=" + mMessageWaiting[i]);
   1477                 pw.println("mCallForwarding=" + mCallForwarding[i]);
   1478                 pw.println("mDataActivity=" + mDataActivity[i]);
   1479                 pw.println("mDataConnectionState=" + mDataConnectionState[i]);
   1480                 pw.println("mCellLocation=" + mCellLocation[i]);
   1481                 pw.println("mCellInfo=" + mCellInfo.get(i));
   1482                 pw.decreaseIndent();
   1483             }
   1484             pw.println("mPreciseDataConnectionState=" + mPreciseDataConnectionState);
   1485             pw.println("mPreciseCallState=" + mPreciseCallState);
   1486             pw.println("mCarrierNetworkChangeState=" + mCarrierNetworkChangeState);
   1487             pw.println("mRingingCallState=" + mRingingCallState);
   1488             pw.println("mForegroundCallState=" + mForegroundCallState);
   1489             pw.println("mBackgroundCallState=" + mBackgroundCallState);
   1490             pw.println("mVoLteServiceState=" + mVoLteServiceState);
   1491 
   1492             pw.decreaseIndent();
   1493 
   1494             pw.println("local logs:");
   1495             pw.increaseIndent();
   1496             mLocalLog.dump(fd, pw, args);
   1497             pw.decreaseIndent();
   1498             pw.println("registrations: count=" + recordCount);
   1499             pw.increaseIndent();
   1500             for (Record r : mRecords) {
   1501                 pw.println(r);
   1502             }
   1503             pw.decreaseIndent();
   1504         }
   1505     }
   1506 
   1507     //
   1508     // the legacy intent broadcasting
   1509     //
   1510 
   1511     private void broadcastServiceStateChanged(ServiceState state, int phoneId, int subId) {
   1512         long ident = Binder.clearCallingIdentity();
   1513         try {
   1514             mBatteryStats.notePhoneState(state.getState());
   1515         } catch (RemoteException re) {
   1516             // Can't do much
   1517         } finally {
   1518             Binder.restoreCallingIdentity(ident);
   1519         }
   1520 
   1521         Intent intent = new Intent(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
   1522         intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
   1523         Bundle data = new Bundle();
   1524         state.fillInNotifierBundle(data);
   1525         intent.putExtras(data);
   1526         // Pass the subscription along with the intent.
   1527         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
   1528         intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
   1529         mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   1530     }
   1531 
   1532     private void broadcastSignalStrengthChanged(SignalStrength signalStrength, int phoneId,
   1533             int subId) {
   1534         long ident = Binder.clearCallingIdentity();
   1535         try {
   1536             mBatteryStats.notePhoneSignalStrength(signalStrength);
   1537         } catch (RemoteException e) {
   1538             /* The remote entity disappeared, we can safely ignore the exception. */
   1539         } finally {
   1540             Binder.restoreCallingIdentity(ident);
   1541         }
   1542 
   1543         Intent intent = new Intent(TelephonyIntents.ACTION_SIGNAL_STRENGTH_CHANGED);
   1544         Bundle data = new Bundle();
   1545         signalStrength.fillInNotifierBundle(data);
   1546         intent.putExtras(data);
   1547         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
   1548         intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
   1549         mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   1550     }
   1551 
   1552     /**
   1553      * Broadcasts an intent notifying apps of a phone state change. {@code subId} can be
   1554      * a valid subId, in which case this function fires a subId-specific intent, or it
   1555      * can be {@code SubscriptionManager.INVALID_SUBSCRIPTION_ID}, in which case we send
   1556      * a global state change broadcast ({@code TelephonyManager.ACTION_PHONE_STATE_CHANGED}).
   1557      */
   1558     private void broadcastCallStateChanged(int state, String incomingNumber, int phoneId,
   1559                 int subId) {
   1560         long ident = Binder.clearCallingIdentity();
   1561         try {
   1562             if (state == TelephonyManager.CALL_STATE_IDLE) {
   1563                 mBatteryStats.notePhoneOff();
   1564             } else {
   1565                 mBatteryStats.notePhoneOn();
   1566             }
   1567         } catch (RemoteException e) {
   1568             /* The remote entity disappeared, we can safely ignore the exception. */
   1569         } finally {
   1570             Binder.restoreCallingIdentity(ident);
   1571         }
   1572 
   1573         Intent intent = new Intent(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
   1574         intent.putExtra(PhoneConstants.STATE_KEY,
   1575                 PhoneConstantConversions.convertCallState(state).toString());
   1576 
   1577         // If a valid subId was specified, we should fire off a subId-specific state
   1578         // change intent and include the subId.
   1579         if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
   1580             intent.setAction(PhoneConstants.ACTION_SUBSCRIPTION_PHONE_STATE_CHANGED);
   1581             intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
   1582         }
   1583         // If the phoneId is invalid, the broadcast is for overall call state.
   1584         if (phoneId != SubscriptionManager.INVALID_PHONE_INDEX) {
   1585             intent.putExtra(PhoneConstants.SLOT_KEY, phoneId);
   1586         }
   1587 
   1588         // Wakeup apps for the (SUBSCRIPTION_)PHONE_STATE broadcast.
   1589         intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
   1590 
   1591         Intent intentWithPhoneNumber = new Intent(intent);
   1592         if (!TextUtils.isEmpty(incomingNumber)) {
   1593             intentWithPhoneNumber.putExtra(TelephonyManager.EXTRA_INCOMING_NUMBER, incomingNumber);
   1594         }
   1595         // Send broadcast twice, once for apps that have PRIVILEGED permission and once for those
   1596         // that have the runtime one
   1597         mContext.sendBroadcastAsUser(intentWithPhoneNumber, UserHandle.ALL,
   1598                 android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE);
   1599         mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
   1600                 android.Manifest.permission.READ_PHONE_STATE,
   1601                 AppOpsManager.OP_READ_PHONE_STATE);
   1602         mContext.sendBroadcastAsUserMultiplePermissions(intentWithPhoneNumber, UserHandle.ALL,
   1603                 new String[] { android.Manifest.permission.READ_PHONE_STATE,
   1604                         android.Manifest.permission.READ_CALL_LOG});
   1605     }
   1606 
   1607     private void broadcastDataConnectionStateChanged(int state,
   1608             boolean isDataAllowed,
   1609             String reason, String apn, String apnType, LinkProperties linkProperties,
   1610             NetworkCapabilities networkCapabilities, boolean roaming, int subId) {
   1611         // Note: not reporting to the battery stats service here, because the
   1612         // status bar takes care of that after taking into account all of the
   1613         // required info.
   1614         Intent intent = new Intent(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
   1615         intent.putExtra(PhoneConstants.STATE_KEY,
   1616                 PhoneConstantConversions.convertDataState(state).toString());
   1617         if (!isDataAllowed) {
   1618             intent.putExtra(PhoneConstants.NETWORK_UNAVAILABLE_KEY, true);
   1619         }
   1620         if (reason != null) {
   1621             intent.putExtra(PhoneConstants.STATE_CHANGE_REASON_KEY, reason);
   1622         }
   1623         if (linkProperties != null) {
   1624             intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY, linkProperties);
   1625             String iface = linkProperties.getInterfaceName();
   1626             if (iface != null) {
   1627                 intent.putExtra(PhoneConstants.DATA_IFACE_NAME_KEY, iface);
   1628             }
   1629         }
   1630         if (networkCapabilities != null) {
   1631             intent.putExtra(PhoneConstants.DATA_NETWORK_CAPABILITIES_KEY, networkCapabilities);
   1632         }
   1633         if (roaming) intent.putExtra(PhoneConstants.DATA_NETWORK_ROAMING_KEY, true);
   1634 
   1635         intent.putExtra(PhoneConstants.DATA_APN_KEY, apn);
   1636         intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
   1637         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
   1638         mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   1639     }
   1640 
   1641     private void broadcastDataConnectionFailed(String reason, String apnType,
   1642             int subId) {
   1643         Intent intent = new Intent(TelephonyIntents.ACTION_DATA_CONNECTION_FAILED);
   1644         intent.putExtra(PhoneConstants.FAILURE_REASON_KEY, reason);
   1645         intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
   1646         intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, subId);
   1647         mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
   1648     }
   1649 
   1650     private void broadcastPreciseCallStateChanged(int ringingCallState, int foregroundCallState,
   1651             int backgroundCallState, int disconnectCause, int preciseDisconnectCause) {
   1652         Intent intent = new Intent(TelephonyManager.ACTION_PRECISE_CALL_STATE_CHANGED);
   1653         intent.putExtra(TelephonyManager.EXTRA_RINGING_CALL_STATE, ringingCallState);
   1654         intent.putExtra(TelephonyManager.EXTRA_FOREGROUND_CALL_STATE, foregroundCallState);
   1655         intent.putExtra(TelephonyManager.EXTRA_BACKGROUND_CALL_STATE, backgroundCallState);
   1656         intent.putExtra(TelephonyManager.EXTRA_DISCONNECT_CAUSE, disconnectCause);
   1657         intent.putExtra(TelephonyManager.EXTRA_PRECISE_DISCONNECT_CAUSE, preciseDisconnectCause);
   1658         mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
   1659                 android.Manifest.permission.READ_PRECISE_PHONE_STATE);
   1660     }
   1661 
   1662     private void broadcastPreciseDataConnectionStateChanged(int state, int networkType,
   1663             String apnType, String apn, String reason, LinkProperties linkProperties,
   1664             String failCause) {
   1665         Intent intent = new Intent(TelephonyManager.ACTION_PRECISE_DATA_CONNECTION_STATE_CHANGED);
   1666         intent.putExtra(PhoneConstants.STATE_KEY, state);
   1667         intent.putExtra(PhoneConstants.DATA_NETWORK_TYPE_KEY, networkType);
   1668         if (reason != null) intent.putExtra(PhoneConstants.STATE_CHANGE_REASON_KEY, reason);
   1669         if (apnType != null) intent.putExtra(PhoneConstants.DATA_APN_TYPE_KEY, apnType);
   1670         if (apn != null) intent.putExtra(PhoneConstants.DATA_APN_KEY, apn);
   1671         if (linkProperties != null) {
   1672             intent.putExtra(PhoneConstants.DATA_LINK_PROPERTIES_KEY,linkProperties);
   1673         }
   1674         if (failCause != null) intent.putExtra(PhoneConstants.DATA_FAILURE_CAUSE_KEY, failCause);
   1675 
   1676         mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
   1677                 android.Manifest.permission.READ_PRECISE_PHONE_STATE);
   1678     }
   1679 
   1680     private void enforceNotifyPermissionOrCarrierPrivilege(String method) {
   1681         if (checkNotifyPermission()) {
   1682             return;
   1683         }
   1684 
   1685         TelephonyPermissions.enforceCallingOrSelfCarrierPrivilege(
   1686                 SubscriptionManager.getDefaultSubscriptionId(), method);
   1687     }
   1688 
   1689     private boolean checkNotifyPermission(String method) {
   1690         if (checkNotifyPermission()) {
   1691             return true;
   1692         }
   1693         String msg = "Modify Phone State Permission Denial: " + method + " from pid="
   1694                 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid();
   1695         if (DBG) log(msg);
   1696         return false;
   1697     }
   1698 
   1699     private boolean checkNotifyPermission() {
   1700         return mContext.checkCallingOrSelfPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
   1701                 == PackageManager.PERMISSION_GRANTED;
   1702     }
   1703 
   1704     private boolean checkListenerPermission(
   1705             int events, int subId, String callingPackage, String message) {
   1706         if ((events & ENFORCE_COARSE_LOCATION_PERMISSION_MASK) != 0) {
   1707             mContext.enforceCallingOrSelfPermission(
   1708                     android.Manifest.permission.ACCESS_COARSE_LOCATION, null);
   1709             if (mAppOps.noteOp(AppOpsManager.OP_COARSE_LOCATION, Binder.getCallingUid(),
   1710                     callingPackage) != AppOpsManager.MODE_ALLOWED) {
   1711                 return false;
   1712             }
   1713         }
   1714 
   1715         if ((events & ENFORCE_PHONE_STATE_PERMISSION_MASK) != 0) {
   1716             if (!TelephonyPermissions.checkCallingOrSelfReadPhoneState(
   1717                     mContext, subId, callingPackage, message)) {
   1718                 return false;
   1719             }
   1720         }
   1721 
   1722         if ((events & PRECISE_PHONE_STATE_PERMISSION_MASK) != 0) {
   1723             mContext.enforceCallingOrSelfPermission(
   1724                     android.Manifest.permission.READ_PRECISE_PHONE_STATE, null);
   1725         }
   1726 
   1727         if ((events & PhoneStateListener.LISTEN_OEM_HOOK_RAW_EVENT) != 0) {
   1728             mContext.enforceCallingOrSelfPermission(
   1729                     android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE, null);
   1730         }
   1731 
   1732         return true;
   1733     }
   1734 
   1735     private void handleRemoveListLocked() {
   1736         int size = mRemoveList.size();
   1737         if (VDBG) log("handleRemoveListLocked: mRemoveList.size()=" + size);
   1738         if (size > 0) {
   1739             for (IBinder b: mRemoveList) {
   1740                 remove(b);
   1741             }
   1742             mRemoveList.clear();
   1743         }
   1744     }
   1745 
   1746     private boolean validateEventsAndUserLocked(Record r, int events) {
   1747         int foregroundUser;
   1748         long callingIdentity = Binder.clearCallingIdentity();
   1749         boolean valid = false;
   1750         try {
   1751             foregroundUser = ActivityManager.getCurrentUser();
   1752             valid = UserHandle.getUserId(r.callerUid) == foregroundUser
   1753                     && r.matchPhoneStateListenerEvent(events);
   1754             if (DBG | DBG_LOC) {
   1755                 log("validateEventsAndUserLocked: valid=" + valid
   1756                         + " r.callerUid=" + r.callerUid + " foregroundUser=" + foregroundUser
   1757                         + " r.events=" + r.events + " events=" + events);
   1758             }
   1759         } finally {
   1760             Binder.restoreCallingIdentity(callingIdentity);
   1761         }
   1762         return valid;
   1763     }
   1764 
   1765     private boolean validatePhoneId(int phoneId) {
   1766         boolean valid = (phoneId >= 0) && (phoneId < mNumPhones);
   1767         if (VDBG) log("validatePhoneId: " + valid);
   1768         return valid;
   1769     }
   1770 
   1771     private static void log(String s) {
   1772         Rlog.d(TAG, s);
   1773     }
   1774 
   1775     boolean idMatch(int rSubId, int subId, int phoneId) {
   1776 
   1777         if(subId < 0) {
   1778             // Invalid case, we need compare phoneId with default one.
   1779             return (mDefaultPhoneId == phoneId);
   1780         }
   1781         if(rSubId == SubscriptionManager.DEFAULT_SUBSCRIPTION_ID) {
   1782             return (subId == mDefaultSubId);
   1783         } else {
   1784             return (rSubId == subId);
   1785         }
   1786     }
   1787 
   1788     private boolean checkLocationAccess(Record r) {
   1789         long token = Binder.clearCallingIdentity();
   1790         try {
   1791             return LocationAccessPolicy.canAccessCellLocation(mContext,
   1792                     r.callingPackage, r.callerUid, r.callerPid,
   1793                     /*throwOnDeniedPermission*/ false);
   1794         } finally {
   1795             Binder.restoreCallingIdentity(token);
   1796         }
   1797     }
   1798 
   1799     private void checkPossibleMissNotify(Record r, int phoneId) {
   1800         int events = r.events;
   1801 
   1802         if ((events & PhoneStateListener.LISTEN_SERVICE_STATE) != 0) {
   1803             try {
   1804                 if (VDBG) log("checkPossibleMissNotify: onServiceStateChanged state=" +
   1805                         mServiceState[phoneId]);
   1806                 r.callback.onServiceStateChanged(
   1807                         new ServiceState(mServiceState[phoneId]));
   1808             } catch (RemoteException ex) {
   1809                 mRemoveList.add(r.binder);
   1810             }
   1811         }
   1812 
   1813         if ((events & PhoneStateListener.LISTEN_SIGNAL_STRENGTHS) != 0) {
   1814             try {
   1815                 SignalStrength signalStrength = mSignalStrength[phoneId];
   1816                 if (DBG) {
   1817                     log("checkPossibleMissNotify: onSignalStrengthsChanged SS=" + signalStrength);
   1818                 }
   1819                 r.callback.onSignalStrengthsChanged(new SignalStrength(signalStrength));
   1820             } catch (RemoteException ex) {
   1821                 mRemoveList.add(r.binder);
   1822             }
   1823         }
   1824 
   1825         if ((events & PhoneStateListener.LISTEN_SIGNAL_STRENGTH) != 0) {
   1826             try {
   1827                 int gsmSignalStrength = mSignalStrength[phoneId]
   1828                         .getGsmSignalStrength();
   1829                 if (DBG) {
   1830                     log("checkPossibleMissNotify: onSignalStrengthChanged SS=" +
   1831                             gsmSignalStrength);
   1832                 }
   1833                 r.callback.onSignalStrengthChanged((gsmSignalStrength == 99 ? -1
   1834                         : gsmSignalStrength));
   1835             } catch (RemoteException ex) {
   1836                 mRemoveList.add(r.binder);
   1837             }
   1838         }
   1839 
   1840         if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_INFO)) {
   1841             try {
   1842                 if (DBG_LOC) {
   1843                     log("checkPossibleMissNotify: onCellInfoChanged[" + phoneId + "] = "
   1844                             + mCellInfo.get(phoneId));
   1845                 }
   1846                 if (checkLocationAccess(r)) {
   1847                     r.callback.onCellInfoChanged(mCellInfo.get(phoneId));
   1848                 }
   1849             } catch (RemoteException ex) {
   1850                 mRemoveList.add(r.binder);
   1851             }
   1852         }
   1853 
   1854         if ((events & PhoneStateListener.LISTEN_USER_MOBILE_DATA_STATE) != 0) {
   1855             try {
   1856                 if (VDBG) {
   1857                     log("checkPossibleMissNotify: onUserMobileDataStateChanged phoneId="
   1858                             + phoneId + " umds=" + mUserMobileDataState[phoneId]);
   1859                 }
   1860                 r.callback.onUserMobileDataStateChanged(mUserMobileDataState[phoneId]);
   1861             } catch (RemoteException ex) {
   1862                 mRemoveList.add(r.binder);
   1863             }
   1864         }
   1865 
   1866         if ((events & PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR) != 0) {
   1867             try {
   1868                 if (VDBG) {
   1869                     log("checkPossibleMissNotify: onMessageWaitingIndicatorChanged phoneId="
   1870                             + phoneId + " mwi=" + mMessageWaiting[phoneId]);
   1871                 }
   1872                 r.callback.onMessageWaitingIndicatorChanged(
   1873                         mMessageWaiting[phoneId]);
   1874             } catch (RemoteException ex) {
   1875                 mRemoveList.add(r.binder);
   1876             }
   1877         }
   1878 
   1879         if ((events & PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR) != 0) {
   1880             try {
   1881                 if (VDBG) {
   1882                     log("checkPossibleMissNotify: onCallForwardingIndicatorChanged phoneId="
   1883                         + phoneId + " cfi=" + mCallForwarding[phoneId]);
   1884                 }
   1885                 r.callback.onCallForwardingIndicatorChanged(
   1886                         mCallForwarding[phoneId]);
   1887             } catch (RemoteException ex) {
   1888                 mRemoveList.add(r.binder);
   1889             }
   1890         }
   1891 
   1892         if (validateEventsAndUserLocked(r, PhoneStateListener.LISTEN_CELL_LOCATION)) {
   1893             try {
   1894                 if (DBG_LOC) log("checkPossibleMissNotify: onCellLocationChanged mCellLocation = "
   1895                         + mCellLocation[phoneId]);
   1896                 if (checkLocationAccess(r)) {
   1897                     r.callback.onCellLocationChanged(new Bundle(mCellLocation[phoneId]));
   1898                 }
   1899             } catch (RemoteException ex) {
   1900                 mRemoveList.add(r.binder);
   1901             }
   1902         }
   1903 
   1904         if ((events & PhoneStateListener.LISTEN_DATA_CONNECTION_STATE) != 0) {
   1905             try {
   1906                 if (DBG) {
   1907                     log("checkPossibleMissNotify: onDataConnectionStateChanged(mDataConnectionState"
   1908                             + "=" + mDataConnectionState[phoneId]
   1909                             + ", mDataConnectionNetworkType=" + mDataConnectionNetworkType[phoneId]
   1910                             + ")");
   1911                 }
   1912                 r.callback.onDataConnectionStateChanged(mDataConnectionState[phoneId],
   1913                         mDataConnectionNetworkType[phoneId]);
   1914             } catch (RemoteException ex) {
   1915                 mRemoveList.add(r.binder);
   1916             }
   1917         }
   1918     }
   1919 }
   1920