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