Advertisement
nospamdan

dj

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