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