Home | History | Annotate | Download | only in phone
      1 /*
      2  * Copyright (C) 2006 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.phone;
     18 
     19 import android.app.Activity;
     20 import android.app.KeyguardManager;
     21 import android.app.PendingIntent;
     22 import android.app.ProgressDialog;
     23 import android.app.TaskStackBuilder;
     24 import android.bluetooth.BluetoothAdapter;
     25 import android.bluetooth.IBluetoothHeadsetPhone;
     26 import android.content.BroadcastReceiver;
     27 import android.content.ComponentName;
     28 import android.content.ContentResolver;
     29 import android.content.Context;
     30 import android.content.ContextWrapper;
     31 import android.content.Intent;
     32 import android.content.IntentFilter;
     33 import android.content.ServiceConnection;
     34 import android.media.AudioManager;
     35 import android.net.Uri;
     36 import android.os.AsyncResult;
     37 import android.os.Bundle;
     38 import android.os.Handler;
     39 import android.os.IBinder;
     40 import android.os.IPowerManager;
     41 import android.os.Message;
     42 import android.os.PersistableBundle;
     43 import android.os.PowerManager;
     44 import android.os.RemoteException;
     45 import android.os.ServiceManager;
     46 import android.os.SystemClock;
     47 import android.os.SystemProperties;
     48 import android.os.UpdateLock;
     49 import android.os.UserHandle;
     50 import android.preference.PreferenceManager;
     51 import android.provider.Settings.System;
     52 import android.telephony.CarrierConfigManager;
     53 import android.telephony.ServiceState;
     54 import android.telephony.SubscriptionInfo;
     55 import android.telephony.SubscriptionManager;
     56 import android.util.Log;
     57 
     58 import com.android.internal.telephony.Call;
     59 import com.android.internal.telephony.CallManager;
     60 import com.android.internal.telephony.IccCard;
     61 import com.android.internal.telephony.IccCardConstants;
     62 import com.android.internal.telephony.MmiCode;
     63 import com.android.internal.telephony.Phone;
     64 import com.android.internal.telephony.PhoneConstants;
     65 import com.android.internal.telephony.PhoneFactory;
     66 import com.android.internal.telephony.SubscriptionController;
     67 import com.android.internal.telephony.TelephonyCapabilities;
     68 import com.android.internal.telephony.TelephonyIntents;
     69 import com.android.phone.common.CallLogAsync;
     70 import com.android.phone.settings.SettingsConstants;
     71 import com.android.server.sip.SipService;
     72 import com.android.services.telephony.activation.SimActivationManager;
     73 
     74 import java.util.ArrayList;
     75 import java.util.List;
     76 
     77 /**
     78  * Global state for the telephony subsystem when running in the primary
     79  * phone process.
     80  */
     81 public class PhoneGlobals extends ContextWrapper {
     82     public static final String LOG_TAG = "PhoneApp";
     83 
     84     /**
     85      * Phone app-wide debug level:
     86      *   0 - no debug logging
     87      *   1 - normal debug logging if ro.debuggable is set (which is true in
     88      *       "eng" and "userdebug" builds but not "user" builds)
     89      *   2 - ultra-verbose debug logging
     90      *
     91      * Most individual classes in the phone app have a local DBG constant,
     92      * typically set to
     93      *   (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1)
     94      * or else
     95      *   (PhoneApp.DBG_LEVEL >= 2)
     96      * depending on the desired verbosity.
     97      *
     98      * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 *************
     99      */
    100     public static final int DBG_LEVEL = 0;
    101 
    102     private static final boolean DBG =
    103             (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
    104     private static final boolean VDBG = (PhoneGlobals.DBG_LEVEL >= 2);
    105 
    106     // Message codes; see mHandler below.
    107     private static final int EVENT_SIM_NETWORK_LOCKED = 3;
    108     private static final int EVENT_SIM_STATE_CHANGED = 8;
    109     private static final int EVENT_DATA_ROAMING_DISCONNECTED = 10;
    110     private static final int EVENT_DATA_ROAMING_OK = 11;
    111     private static final int EVENT_UNSOL_CDMA_INFO_RECORD = 12;
    112     private static final int EVENT_DOCK_STATE_CHANGED = 13;
    113     private static final int EVENT_START_SIP_SERVICE = 14;
    114 
    115     // The MMI codes are also used by the InCallScreen.
    116     public static final int MMI_INITIATE = 51;
    117     public static final int MMI_COMPLETE = 52;
    118     public static final int MMI_CANCEL = 53;
    119     // Don't use message codes larger than 99 here; those are reserved for
    120     // the individual Activities of the Phone UI.
    121 
    122     /**
    123      * Allowable values for the wake lock code.
    124      *   SLEEP means the device can be put to sleep.
    125      *   PARTIAL means wake the processor, but we display can be kept off.
    126      *   FULL means wake both the processor and the display.
    127      */
    128     public enum WakeState {
    129         SLEEP,
    130         PARTIAL,
    131         FULL
    132     }
    133 
    134     /**
    135      * Intent Action used for hanging up the current call from Notification bar. This will
    136      * choose first ringing call, first active call, or first background call (typically in
    137      * HOLDING state).
    138      */
    139     public static final String ACTION_HANG_UP_ONGOING_CALL =
    140             "com.android.phone.ACTION_HANG_UP_ONGOING_CALL";
    141 
    142     private static PhoneGlobals sMe;
    143 
    144     // A few important fields we expose to the rest of the package
    145     // directly (rather than thru set/get methods) for efficiency.
    146     CallController callController;
    147     CallManager mCM;
    148     CallNotifier notifier;
    149     CallerInfoCache callerInfoCache;
    150     NotificationMgr notificationMgr;
    151     public PhoneInterfaceManager phoneMgr;
    152     public SimActivationManager simActivationManager;
    153     CarrierConfigLoader configLoader;
    154 
    155     private BluetoothManager bluetoothManager;
    156     private CallGatewayManager callGatewayManager;
    157     private CallStateMonitor callStateMonitor;
    158 
    159     static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
    160     static boolean sVoiceCapable = true;
    161 
    162     // TODO: Remove, no longer used.
    163     CdmaPhoneCallState cdmaPhoneCallState;
    164 
    165     // The currently-active PUK entry activity and progress dialog.
    166     // Normally, these are the Emergency Dialer and the subsequent
    167     // progress dialog.  null if there is are no such objects in
    168     // the foreground.
    169     private Activity mPUKEntryActivity;
    170     private ProgressDialog mPUKEntryProgressDialog;
    171 
    172     private boolean mIsSimPinEnabled;
    173     private String mCachedSimPin;
    174 
    175     // True if we are beginning a call, but the phone state has not changed yet
    176     private boolean mBeginningCall;
    177     private boolean mDataDisconnectedDueToRoaming = false;
    178 
    179     // Last phone state seen by updatePhoneState()
    180     private PhoneConstants.State mLastPhoneState = PhoneConstants.State.IDLE;
    181 
    182     private WakeState mWakeState = WakeState.SLEEP;
    183 
    184     private PowerManager mPowerManager;
    185     private IPowerManager mPowerManagerService;
    186     private PowerManager.WakeLock mWakeLock;
    187     private PowerManager.WakeLock mPartialWakeLock;
    188     private KeyguardManager mKeyguardManager;
    189 
    190     private UpdateLock mUpdateLock;
    191 
    192     // Broadcast receiver for various intent broadcasts (see onCreate())
    193     private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver();
    194 
    195     /** boolean indicating restoring mute state on InCallScreen.onResume() */
    196     private boolean mShouldRestoreMuteOnInCallResume;
    197 
    198     /**
    199      * The singleton OtaUtils instance used for OTASP calls.
    200      *
    201      * The OtaUtils instance is created lazily the first time we need to
    202      * make an OTASP call, regardless of whether it's an interactive or
    203      * non-interactive OTASP call.
    204      */
    205     public OtaUtils otaUtils;
    206 
    207     // Following are the CDMA OTA information Objects used during OTA Call.
    208     // cdmaOtaProvisionData object store static OTA information that needs
    209     // to be maintained even during Slider open/close scenarios.
    210     // cdmaOtaConfigData object stores configuration info to control visiblity
    211     // of each OTA Screens.
    212     // cdmaOtaScreenState object store OTA Screen State information.
    213     public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData;
    214     public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData;
    215     public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState;
    216     public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState;
    217 
    218     /**
    219      * Set the restore mute state flag. Used when we are setting the mute state
    220      * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)}
    221      */
    222     /*package*/void setRestoreMuteOnInCallResume (boolean mode) {
    223         mShouldRestoreMuteOnInCallResume = mode;
    224     }
    225 
    226     Handler mHandler = new Handler() {
    227         @Override
    228         public void handleMessage(Message msg) {
    229             PhoneConstants.State phoneState;
    230             switch (msg.what) {
    231                 // Starts the SIP service. It's a no-op if SIP API is not supported
    232                 // on the deivce.
    233                 // TODO: Having the phone process host the SIP service is only
    234                 // temporary. Will move it to a persistent communication process
    235                 // later.
    236                 case EVENT_START_SIP_SERVICE:
    237                     SipService.start(getApplicationContext());
    238                     break;
    239 
    240                 // TODO: This event should be handled by the lock screen, just
    241                 // like the "SIM missing" and "Sim locked" cases (bug 1804111).
    242                 case EVENT_SIM_NETWORK_LOCKED:
    243                     if (getCarrierConfig().getBoolean(
    244                             CarrierConfigManager.KEY_IGNORE_SIM_NETWORK_LOCKED_EVENTS_BOOL)) {
    245                         // Some products don't have the concept of a "SIM network lock"
    246                         Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; "
    247                               + "not showing 'SIM network unlock' PIN entry screen");
    248                     } else {
    249                         // Normal case: show the "SIM network unlock" PIN entry screen.
    250                         // The user won't be able to do anything else until
    251                         // they enter a valid SIM network PIN.
    252                         Log.i(LOG_TAG, "show sim depersonal panel");
    253                         IccNetworkDepersonalizationPanel ndpPanel =
    254                                 new IccNetworkDepersonalizationPanel(PhoneGlobals.getInstance());
    255                         ndpPanel.show();
    256                     }
    257                     break;
    258 
    259                 case EVENT_DATA_ROAMING_DISCONNECTED:
    260                     notificationMgr.showDataDisconnectedRoaming();
    261                     break;
    262 
    263                 case EVENT_DATA_ROAMING_OK:
    264                     notificationMgr.hideDataDisconnectedRoaming();
    265                     break;
    266 
    267                 case MMI_COMPLETE:
    268                     onMMIComplete((AsyncResult) msg.obj);
    269                     break;
    270 
    271                 case MMI_CANCEL:
    272                     PhoneUtils.cancelMmiCode(mCM.getFgPhone());
    273                     break;
    274 
    275                 case EVENT_SIM_STATE_CHANGED:
    276                     // Marks the event where the SIM goes into ready state.
    277                     // Right now, this is only used for the PUK-unlocking
    278                     // process.
    279                     if (msg.obj.equals(IccCardConstants.INTENT_VALUE_ICC_READY)) {
    280                         // when the right event is triggered and there
    281                         // are UI objects in the foreground, we close
    282                         // them to display the lock panel.
    283                         if (mPUKEntryActivity != null) {
    284                             mPUKEntryActivity.finish();
    285                             mPUKEntryActivity = null;
    286                         }
    287                         if (mPUKEntryProgressDialog != null) {
    288                             mPUKEntryProgressDialog.dismiss();
    289                             mPUKEntryProgressDialog = null;
    290                         }
    291                     }
    292                     break;
    293 
    294                 case EVENT_UNSOL_CDMA_INFO_RECORD:
    295                     //TODO: handle message here;
    296                     break;
    297 
    298                 case EVENT_DOCK_STATE_CHANGED:
    299                     // If the phone is docked/undocked during a call, and no wired or BT headset
    300                     // is connected: turn on/off the speaker accordingly.
    301                     boolean inDockMode = false;
    302                     if (mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
    303                         inDockMode = true;
    304                     }
    305                     if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = "
    306                             + inDockMode);
    307 
    308                     phoneState = mCM.getState();
    309                     if (phoneState == PhoneConstants.State.OFFHOOK &&
    310                             !bluetoothManager.isBluetoothHeadsetAudioOn()) {
    311                         PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true);
    312                     }
    313                     break;
    314             }
    315         }
    316     };
    317 
    318     public PhoneGlobals(Context context) {
    319         super(context);
    320         sMe = this;
    321     }
    322 
    323     public void onCreate() {
    324         if (VDBG) Log.v(LOG_TAG, "onCreate()...");
    325 
    326         ContentResolver resolver = getContentResolver();
    327 
    328         // Cache the "voice capable" flag.
    329         // This flag currently comes from a resource (which is
    330         // overrideable on a per-product basis):
    331         sVoiceCapable =
    332                 getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
    333         // ...but this might eventually become a PackageManager "system
    334         // feature" instead, in which case we'd do something like:
    335         // sVoiceCapable =
    336         //   getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS);
    337 
    338         if (mCM == null) {
    339             // Initialize the telephony framework
    340             PhoneFactory.makeDefaultPhones(this);
    341 
    342             // Start TelephonyDebugService After the default phone is created.
    343             Intent intent = new Intent(this, TelephonyDebugService.class);
    344             startService(intent);
    345 
    346             mCM = CallManager.getInstance();
    347             for (Phone phone : PhoneFactory.getPhones()) {
    348                 mCM.registerPhone(phone);
    349             }
    350 
    351             // Create the NotificationMgr singleton, which is used to display
    352             // status bar icons and control other status bar behavior.
    353             notificationMgr = NotificationMgr.init(this);
    354 
    355             mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE);
    356 
    357             // Create an instance of CdmaPhoneCallState and initialize it to IDLE
    358             cdmaPhoneCallState = new CdmaPhoneCallState();
    359             cdmaPhoneCallState.CdmaPhoneCallStateInit();
    360 
    361             // before registering for phone state changes
    362             mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    363             mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOG_TAG);
    364             // lock used to keep the processor awake, when we don't care for the display.
    365             mPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
    366                     | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
    367 
    368             mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    369 
    370             // get a handle to the service so that we can use it later when we
    371             // want to set the poke lock.
    372             mPowerManagerService = IPowerManager.Stub.asInterface(
    373                     ServiceManager.getService("power"));
    374 
    375             // Get UpdateLock to suppress system-update related events (e.g. dialog show-up)
    376             // during phone calls.
    377             mUpdateLock = new UpdateLock("phone");
    378 
    379             if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock);
    380 
    381             CallLogger callLogger = new CallLogger(this, new CallLogAsync());
    382 
    383             callGatewayManager = CallGatewayManager.getInstance();
    384 
    385             // Create the CallController singleton, which is the interface
    386             // to the telephony layer for user-initiated telephony functionality
    387             // (like making outgoing calls.)
    388             callController = CallController.init(this, callLogger, callGatewayManager);
    389 
    390             // Create the CallerInfoCache singleton, which remembers custom ring tone and
    391             // send-to-voicemail settings.
    392             //
    393             // The asynchronous caching will start just after this call.
    394             callerInfoCache = CallerInfoCache.init(this);
    395 
    396             // Monitors call activity from the telephony layer
    397             callStateMonitor = new CallStateMonitor(mCM);
    398 
    399             // Bluetooth manager
    400             bluetoothManager = new BluetoothManager();
    401 
    402             phoneMgr = PhoneInterfaceManager.init(this, PhoneFactory.getDefaultPhone());
    403 
    404             configLoader = CarrierConfigLoader.init(this);
    405 
    406             // Create the CallNotifer singleton, which handles
    407             // asynchronous events from the telephony layer (like
    408             // launching the incoming-call UI when an incoming call comes
    409             // in.)
    410             notifier = CallNotifier.init(this, callLogger, callStateMonitor, bluetoothManager);
    411 
    412             PhoneUtils.registerIccStatus(mHandler, EVENT_SIM_NETWORK_LOCKED);
    413 
    414             // register for MMI/USSD
    415             mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
    416 
    417             // register connection tracking to PhoneUtils
    418             PhoneUtils.initializeConnectionHandler(mCM);
    419 
    420             // Register for misc other intent broadcasts.
    421             IntentFilter intentFilter =
    422                     new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    423             intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
    424             intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
    425             intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
    426             intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
    427             intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
    428             intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
    429             registerReceiver(mReceiver, intentFilter);
    430 
    431             //set the default values for the preferences in the phone.
    432             PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
    433 
    434             PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
    435 
    436             // Make sure the audio mode (along with some
    437             // audio-mode-related state of our own) is initialized
    438             // correctly, given the current state of the phone.
    439             PhoneUtils.setAudioMode(mCM);
    440         }
    441 
    442         cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
    443         cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
    444         cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
    445         cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
    446 
    447         simActivationManager = new SimActivationManager();
    448 
    449         // XXX pre-load the SimProvider so that it's ready
    450         resolver.getType(Uri.parse("content://icc/adn"));
    451 
    452         // start with the default value to set the mute state.
    453         mShouldRestoreMuteOnInCallResume = false;
    454 
    455         // TODO: Register for Cdma Information Records
    456         // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
    457 
    458         // Read HAC settings and configure audio hardware
    459         if (getResources().getBoolean(R.bool.hac_enabled)) {
    460             int hac = android.provider.Settings.System.getInt(
    461                     getContentResolver(),
    462                     android.provider.Settings.System.HEARING_AID,
    463                     0);
    464             AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    465             audioManager.setParameter(SettingsConstants.HAC_KEY,
    466                     hac == SettingsConstants.HAC_ENABLED
    467                             ? SettingsConstants.HAC_VAL_ON : SettingsConstants.HAC_VAL_OFF);
    468         }
    469     }
    470 
    471     /**
    472      * Returns the singleton instance of the PhoneApp.
    473      */
    474     public static PhoneGlobals getInstance() {
    475         if (sMe == null) {
    476             throw new IllegalStateException("No PhoneGlobals here!");
    477         }
    478         return sMe;
    479     }
    480 
    481     /**
    482      * Returns the singleton instance of the PhoneApp if running as the
    483      * primary user, otherwise null.
    484      */
    485     static PhoneGlobals getInstanceIfPrimary() {
    486         return sMe;
    487     }
    488 
    489     /**
    490      * Returns the default phone.
    491      *
    492      * WARNING: This method should be used carefully, now that there may be multiple phones.
    493      */
    494     public static Phone getPhone() {
    495         return PhoneFactory.getDefaultPhone();
    496     }
    497 
    498     public static Phone getPhone(int subId) {
    499         return PhoneFactory.getPhone(SubscriptionManager.getPhoneId(subId));
    500     }
    501 
    502     /* package */ BluetoothManager getBluetoothManager() {
    503         return bluetoothManager;
    504     }
    505 
    506     /* package */ CallManager getCallManager() {
    507         return mCM;
    508     }
    509 
    510     public PersistableBundle getCarrierConfig() {
    511         return getCarrierConfigForSubId(SubscriptionManager.getDefaultSubId());
    512     }
    513 
    514     public PersistableBundle getCarrierConfigForSubId(int subId) {
    515         return configLoader.getConfigForSubId(subId);
    516     }
    517 
    518     /**
    519      * Returns PendingIntent for hanging up ongoing phone call. This will typically be used from
    520      * Notification context.
    521      */
    522     /* package */ static PendingIntent createHangUpOngoingCallPendingIntent(Context context) {
    523         Intent intent = new Intent(PhoneGlobals.ACTION_HANG_UP_ONGOING_CALL, null,
    524                 context, NotificationBroadcastReceiver.class);
    525         return PendingIntent.getBroadcast(context, 0, intent, 0);
    526     }
    527 
    528     boolean isSimPinEnabled() {
    529         return mIsSimPinEnabled;
    530     }
    531 
    532     boolean authenticateAgainstCachedSimPin(String pin) {
    533         return (mCachedSimPin != null && mCachedSimPin.equals(pin));
    534     }
    535 
    536     void setCachedSimPin(String pin) {
    537         mCachedSimPin = pin;
    538     }
    539 
    540     /**
    541      * Handles OTASP-related events from the telephony layer.
    542      *
    543      * While an OTASP call is active, the CallNotifier forwards
    544      * OTASP-related telephony events to this method.
    545      */
    546     void handleOtaspEvent(Message msg) {
    547         if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")...");
    548 
    549         if (otaUtils == null) {
    550             // We shouldn't be getting OTASP events without ever
    551             // having started the OTASP call in the first place!
    552             Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! "
    553                   + "message = " + msg);
    554             return;
    555         }
    556 
    557         otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
    558     }
    559 
    560     /**
    561      * Similarly, handle the disconnect event of an OTASP call
    562      * by forwarding it to the OtaUtils instance.
    563      */
    564     /* package */ void handleOtaspDisconnect() {
    565         if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()...");
    566 
    567         if (otaUtils == null) {
    568             // We shouldn't be getting OTASP events without ever
    569             // having started the OTASP call in the first place!
    570             Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!");
    571             return;
    572         }
    573 
    574         otaUtils.onOtaspDisconnect();
    575     }
    576 
    577     /**
    578      * Sets the activity responsible for un-PUK-blocking the device
    579      * so that we may close it when we receive a positive result.
    580      * mPUKEntryActivity is also used to indicate to the device that
    581      * we are trying to un-PUK-lock the phone. In other words, iff
    582      * it is NOT null, then we are trying to unlock and waiting for
    583      * the SIM to move to READY state.
    584      *
    585      * @param activity is the activity to close when PUK has
    586      * finished unlocking. Can be set to null to indicate the unlock
    587      * or SIM READYing process is over.
    588      */
    589     void setPukEntryActivity(Activity activity) {
    590         mPUKEntryActivity = activity;
    591     }
    592 
    593     Activity getPUKEntryActivity() {
    594         return mPUKEntryActivity;
    595     }
    596 
    597     /**
    598      * Sets the dialog responsible for notifying the user of un-PUK-
    599      * blocking - SIM READYing progress, so that we may dismiss it
    600      * when we receive a positive result.
    601      *
    602      * @param dialog indicates the progress dialog informing the user
    603      * of the state of the device.  Dismissed upon completion of
    604      * READYing process
    605      */
    606     void setPukEntryProgressDialog(ProgressDialog dialog) {
    607         mPUKEntryProgressDialog = dialog;
    608     }
    609 
    610     ProgressDialog getPUKEntryProgressDialog() {
    611         return mPUKEntryProgressDialog;
    612     }
    613 
    614     /**
    615      * Controls whether or not the screen is allowed to sleep.
    616      *
    617      * Once sleep is allowed (WakeState is SLEEP), it will rely on the
    618      * settings for the poke lock to determine when to timeout and let
    619      * the device sleep {@link PhoneGlobals#setScreenTimeout}.
    620      *
    621      * @param ws tells the device to how to wake.
    622      */
    623     /* package */ void requestWakeState(WakeState ws) {
    624         if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
    625         synchronized (this) {
    626             if (mWakeState != ws) {
    627                 switch (ws) {
    628                     case PARTIAL:
    629                         // acquire the processor wake lock, and release the FULL
    630                         // lock if it is being held.
    631                         mPartialWakeLock.acquire();
    632                         if (mWakeLock.isHeld()) {
    633                             mWakeLock.release();
    634                         }
    635                         break;
    636                     case FULL:
    637                         // acquire the full wake lock, and release the PARTIAL
    638                         // lock if it is being held.
    639                         mWakeLock.acquire();
    640                         if (mPartialWakeLock.isHeld()) {
    641                             mPartialWakeLock.release();
    642                         }
    643                         break;
    644                     case SLEEP:
    645                     default:
    646                         // release both the PARTIAL and FULL locks.
    647                         if (mWakeLock.isHeld()) {
    648                             mWakeLock.release();
    649                         }
    650                         if (mPartialWakeLock.isHeld()) {
    651                             mPartialWakeLock.release();
    652                         }
    653                         break;
    654                 }
    655                 mWakeState = ws;
    656             }
    657         }
    658     }
    659 
    660     /**
    661      * If we are not currently keeping the screen on, then poke the power
    662      * manager to wake up the screen for the user activity timeout duration.
    663      */
    664     /* package */ void wakeUpScreen() {
    665         synchronized (this) {
    666             if (mWakeState == WakeState.SLEEP) {
    667                 if (DBG) Log.d(LOG_TAG, "pulse screen lock");
    668                 mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.phone:WAKE");
    669             }
    670         }
    671     }
    672 
    673     /**
    674      * Sets the wake state and screen timeout based on the current state
    675      * of the phone, and the current state of the in-call UI.
    676      *
    677      * This method is a "UI Policy" wrapper around
    678      * {@link PhoneGlobals#requestWakeState} and {@link PhoneGlobals#setScreenTimeout}.
    679      *
    680      * It's safe to call this method regardless of the state of the Phone
    681      * (e.g. whether or not it's idle), and regardless of the state of the
    682      * Phone UI (e.g. whether or not the InCallScreen is active.)
    683      */
    684     /* package */ void updateWakeState() {
    685         PhoneConstants.State state = mCM.getState();
    686 
    687         // True if the speakerphone is in use.  (If so, we *always* use
    688         // the default timeout.  Since the user is obviously not holding
    689         // the phone up to his/her face, we don't need to worry about
    690         // false touches, and thus don't need to turn the screen off so
    691         // aggressively.)
    692         // Note that we need to make a fresh call to this method any
    693         // time the speaker state changes.  (That happens in
    694         // PhoneUtils.turnOnSpeaker().)
    695         boolean isSpeakerInUse = (state == PhoneConstants.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
    696 
    697         // TODO (bug 1440854): The screen timeout *might* also need to
    698         // depend on the bluetooth state, but this isn't as clear-cut as
    699         // the speaker state (since while using BT it's common for the
    700         // user to put the phone straight into a pocket, in which case the
    701         // timeout should probably still be short.)
    702 
    703         // Decide whether to force the screen on or not.
    704         //
    705         // Force the screen to be on if the phone is ringing or dialing,
    706         // or if we're displaying the "Call ended" UI for a connection in
    707         // the "disconnected" state.
    708         // However, if the phone is disconnected while the user is in the
    709         // middle of selecting a quick response message, we should not force
    710         // the screen to be on.
    711         //
    712         boolean isRinging = (state == PhoneConstants.State.RINGING);
    713         boolean isDialing = (mCM.getFgPhone().getForegroundCall().getState() == Call.State.DIALING);
    714         boolean keepScreenOn = isRinging || isDialing;
    715         // keepScreenOn == true means we'll hold a full wake lock:
    716         requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
    717     }
    718 
    719     /**
    720      * Manually pokes the PowerManager's userActivity method.  Since we
    721      * set the {@link WindowManager.LayoutParams#INPUT_FEATURE_DISABLE_USER_ACTIVITY}
    722      * flag while the InCallScreen is active when there is no proximity sensor,
    723      * we need to do this for touch events that really do count as user activity
    724      * (like pressing any onscreen UI elements.)
    725      */
    726     /* package */ void pokeUserActivity() {
    727         if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
    728         mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
    729     }
    730 
    731     /**
    732      * Notifies the phone app when the phone state changes.
    733      *
    734      * This method will updates various states inside Phone app (e.g. update-lock state, etc.)
    735      */
    736     /* package */ void updatePhoneState(PhoneConstants.State state) {
    737         if (state != mLastPhoneState) {
    738             mLastPhoneState = state;
    739 
    740             // Try to acquire or release UpdateLock.
    741             //
    742             // Watch out: we don't release the lock here when the screen is still in foreground.
    743             // At that time InCallScreen will release it on onPause().
    744             if (state != PhoneConstants.State.IDLE) {
    745                 // UpdateLock is a recursive lock, while we may get "acquire" request twice and
    746                 // "release" request once for a single call (RINGING + OFFHOOK and IDLE).
    747                 // We need to manually ensure the lock is just acquired once for each (and this
    748                 // will prevent other possible buggy situations too).
    749                 if (!mUpdateLock.isHeld()) {
    750                     mUpdateLock.acquire();
    751                 }
    752             } else {
    753                 if (mUpdateLock.isHeld()) {
    754                     mUpdateLock.release();
    755                 }
    756             }
    757         }
    758     }
    759 
    760     /* package */ PhoneConstants.State getPhoneState() {
    761         return mLastPhoneState;
    762     }
    763 
    764     KeyguardManager getKeyguardManager() {
    765         return mKeyguardManager;
    766     }
    767 
    768     private void onMMIComplete(AsyncResult r) {
    769         if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
    770         MmiCode mmiCode = (MmiCode) r.result;
    771         PhoneUtils.displayMMIComplete(mmiCode.getPhone(), getInstance(), mmiCode, null, null);
    772     }
    773 
    774     private void initForNewRadioTechnology(int phoneId) {
    775         if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
    776 
    777         final Phone phone = PhoneFactory.getPhone(phoneId);
    778         if (phone == null || !TelephonyCapabilities.supportsOtasp(phone)) {
    779             // Clean up OTA for non-CDMA since it is only valid for CDMA.
    780             clearOtaState();
    781         }
    782 
    783         notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
    784         callStateMonitor.updateAfterRadioTechnologyChange();
    785 
    786         // Update registration for ICC status after radio technology change
    787         IccCard sim = phone == null ? null : phone.getIccCard();
    788         if (sim != null) {
    789             if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
    790 
    791             //Register all events new to the new active phone
    792             sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
    793         }
    794     }
    795 
    796     /**
    797      * Receiver for misc intent broadcasts the Phone app cares about.
    798      */
    799     private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
    800         @Override
    801         public void onReceive(Context context, Intent intent) {
    802             String action = intent.getAction();
    803             if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
    804                 boolean enabled = System.getInt(getContentResolver(),
    805                         System.AIRPLANE_MODE_ON, 0) == 0;
    806                 PhoneUtils.setRadioPower(enabled);
    807             } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
    808                 int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
    809                         SubscriptionManager.INVALID_SUBSCRIPTION_ID);
    810                 int phoneId = SubscriptionManager.getPhoneId(subId);
    811                 String state = intent.getStringExtra(PhoneConstants.STATE_KEY);
    812                 if (VDBG) {
    813                     Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
    814                     Log.d(LOG_TAG, "- state: " + state);
    815                     Log.d(LOG_TAG, "- reason: "
    816                     + intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
    817                     Log.d(LOG_TAG, "- subId: " + subId);
    818                     Log.d(LOG_TAG, "- phoneId: " + phoneId);
    819                 }
    820                 Phone phone = SubscriptionManager.isValidPhoneId(phoneId) ?
    821                         PhoneFactory.getPhone(phoneId) : PhoneFactory.getDefaultPhone();
    822 
    823                 // The "data disconnected due to roaming" notification is shown
    824                 // if (a) you have the "data roaming" feature turned off, and
    825                 // (b) you just lost data connectivity because you're roaming.
    826                 boolean disconnectedDueToRoaming =
    827                         !phone.getDataRoamingEnabled()
    828                         && PhoneConstants.DataState.DISCONNECTED.equals(state)
    829                         && Phone.REASON_ROAMING_ON.equals(
    830                             intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
    831                 if (mDataDisconnectedDueToRoaming != disconnectedDueToRoaming) {
    832                     mDataDisconnectedDueToRoaming = disconnectedDueToRoaming;
    833                     mHandler.sendEmptyMessage(disconnectedDueToRoaming
    834                             ? EVENT_DATA_ROAMING_DISCONNECTED : EVENT_DATA_ROAMING_OK);
    835                 }
    836             } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
    837                     (mPUKEntryActivity != null)) {
    838                 // if an attempt to un-PUK-lock the device was made, while we're
    839                 // receiving this state change notification, notify the handler.
    840                 // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
    841                 // been attempted.
    842                 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
    843                         intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)));
    844             } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
    845                 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
    846                 int phoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY,
    847                         SubscriptionManager.INVALID_PHONE_INDEX);
    848                 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " (" + phoneId
    849                         + ") is active.");
    850                 initForNewRadioTechnology(phoneId);
    851             } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
    852                 handleServiceStateChanged(intent);
    853             } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
    854                 if (TelephonyCapabilities.supportsEcm(mCM.getFgPhone())) {
    855                     Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
    856                     // Start Emergency Callback Mode service
    857                     if (intent.getBooleanExtra("phoneinECMState", false)) {
    858                         context.startService(new Intent(context,
    859                                 EmergencyCallbackModeService.class));
    860                     }
    861                 } else {
    862                     // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED
    863                     // on a device that doesn't support ECM in the first place.
    864                     Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, "
    865                             + "but ECM isn't supported for phone: "
    866                             + mCM.getFgPhone().getPhoneName());
    867                 }
    868             } else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
    869                 mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
    870                         Intent.EXTRA_DOCK_STATE_UNDOCKED);
    871                 if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState);
    872                 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0));
    873             }
    874         }
    875     }
    876 
    877     /**
    878      * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus
    879      * sent from framework's notification mechanism (which is outside Phone context).
    880      * This should be visible from outside, but shouldn't be in "exported" state.
    881      *
    882      * TODO: If possible merge this into PhoneAppBroadcastReceiver.
    883      */
    884     public static class NotificationBroadcastReceiver extends BroadcastReceiver {
    885         @Override
    886         public void onReceive(Context context, Intent intent) {
    887             String action = intent.getAction();
    888             // TODO: use "if (VDBG)" here.
    889             Log.d(LOG_TAG, "Broadcast from Notification: " + action);
    890 
    891             if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) {
    892                 PhoneUtils.hangup(PhoneGlobals.getInstance().mCM);
    893             } else {
    894                 Log.w(LOG_TAG, "Received hang-up request from notification,"
    895                         + " but there's no call the system can hang up.");
    896             }
    897         }
    898     }
    899 
    900     private void handleServiceStateChanged(Intent intent) {
    901         /**
    902          * This used to handle updating EriTextWidgetProvider this routine
    903          * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
    904          * be removed. But leaving just in case it might be needed in the near
    905          * future.
    906          */
    907 
    908         // If service just returned, start sending out the queued messages
    909         Bundle extras = intent.getExtras();
    910         if (extras != null) {
    911             ServiceState ss = ServiceState.newFromBundle(extras);
    912             if (ss != null) {
    913                 int state = ss.getState();
    914                 notificationMgr.updateNetworkSelection(state);
    915             }
    916         }
    917     }
    918 
    919     public boolean isOtaCallInActiveState() {
    920         boolean otaCallActive = false;
    921         if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive);
    922         return otaCallActive;
    923     }
    924 
    925     public boolean isOtaCallInEndState() {
    926         boolean otaCallEnded = false;
    927         if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded);
    928         return otaCallEnded;
    929     }
    930 
    931     // it is safe to call clearOtaState() even if the InCallScreen isn't active
    932     public void clearOtaState() {
    933         if (DBG) Log.d(LOG_TAG, "- clearOtaState ...");
    934         if (otaUtils != null) {
    935             otaUtils.cleanOtaScreen(true);
    936             if (DBG) Log.d(LOG_TAG, "  - clearOtaState clears OTA screen");
    937         }
    938     }
    939 
    940     // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active
    941     public void dismissOtaDialogs() {
    942         if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ...");
    943         if (otaUtils != null) {
    944             otaUtils.dismissAllOtaDialogs();
    945             if (DBG) Log.d(LOG_TAG, "  - dismissOtaDialogs clears OTA dialogs");
    946         }
    947     }
    948 
    949     /**
    950      * Triggers a refresh of the message waiting (voicemail) indicator.
    951      *
    952      * @param subId the subscription id we should refresh the notification for.
    953      */
    954     public void refreshMwiIndicator(int subId) {
    955         notificationMgr.refreshMwi(subId);
    956     }
    957 
    958     /**
    959      * Dismisses the message waiting (voicemail) indicator.
    960      *
    961      * @param subId the subscription id we should dismiss the notification for.
    962      */
    963     public void clearMwiIndicator(int subId) {
    964         notificationMgr.updateMwi(subId, false);
    965     }
    966 
    967     /**
    968      * "Call origin" may be used by Contacts app to specify where the phone call comes from.
    969      * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}.
    970      * Any other value will be ignored, to make sure that malicious apps can't trick the in-call
    971      * UI into launching some random other app after a call ends.
    972      *
    973      * TODO: make this more generic. Note that we should let the "origin" specify its package
    974      * while we are now assuming it is "com.android.contacts"
    975      */
    976     public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
    977     private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.dialer";
    978     private static final String ALLOWED_EXTRA_CALL_ORIGIN =
    979             "com.android.dialer.DialtactsActivity";
    980     /**
    981      * Used to determine if the preserved call origin is fresh enough.
    982      */
    983     private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000;
    984 }
    985