blob: 9db596b08389ade79bd0b2416c2623b27c29be62 [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;
23import android.bluetooth.BluetoothAdapter;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070024import android.bluetooth.IBluetoothHeadsetPhone;
25import android.content.ActivityNotFoundException;
26import 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;
34import android.content.res.Configuration;
35import android.media.AudioManager;
36import android.net.Uri;
37import android.os.AsyncResult;
38import android.os.Binder;
39import android.os.Handler;
40import android.os.IBinder;
41import android.os.IPowerManager;
42import android.os.Message;
43import android.os.PowerManager;
44import android.os.RemoteException;
45import android.os.ServiceManager;
46import android.os.SystemClock;
47import android.os.SystemProperties;
48import android.os.UpdateLock;
49import android.os.UserHandle;
50import android.preference.PreferenceManager;
51import android.provider.Settings.System;
52import android.telephony.ServiceState;
53import android.text.TextUtils;
54import android.util.Log;
55import android.util.Slog;
56import android.view.KeyEvent;
57
58import com.android.internal.telephony.Call;
59import com.android.internal.telephony.CallManager;
60import com.android.internal.telephony.IccCard;
61import com.android.internal.telephony.IccCardConstants;
62import com.android.internal.telephony.MmiCode;
63import com.android.internal.telephony.Phone;
64import com.android.internal.telephony.PhoneConstants;
65import com.android.internal.telephony.PhoneFactory;
66import com.android.internal.telephony.TelephonyCapabilities;
67import com.android.internal.telephony.TelephonyIntents;
68import com.android.internal.telephony.cdma.TtyIntent;
69import com.android.phone.common.CallLogAsync;
Santos Cordon27a3c1f2013-08-06 07:49:27 -070070import com.android.phone.BluetoothManager.BluetoothIndicatorListener;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070071import com.android.phone.OtaUtils.CdmaOtaScreenState;
72import com.android.server.sip.SipService;
73
74/**
75 * Global state for the telephony subsystem when running in the primary
76 * phone process.
77 */
78public class PhoneGlobals extends ContextWrapper
Santos Cordon27a3c1f2013-08-06 07:49:27 -070079 implements AccelerometerListener.OrientationListener, BluetoothIndicatorListener {
Santos Cordon7d4ddf62013-07-10 11:58:08 -070080 /* package */ static final String LOG_TAG = "PhoneApp";
81
82 /**
83 * Phone app-wide debug level:
84 * 0 - no debug logging
85 * 1 - normal debug logging if ro.debuggable is set (which is true in
86 * "eng" and "userdebug" builds but not "user" builds)
87 * 2 - ultra-verbose debug logging
88 *
89 * Most individual classes in the phone app have a local DBG constant,
90 * typically set to
91 * (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1)
92 * or else
93 * (PhoneApp.DBG_LEVEL >= 2)
94 * depending on the desired verbosity.
95 *
96 * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 *************
97 */
98 /* package */ static final int DBG_LEVEL = 0;
99
100 private static final boolean DBG =
101 (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
102 private static final boolean VDBG = (PhoneGlobals.DBG_LEVEL >= 2);
103
104 // Message codes; see mHandler below.
105 private static final int EVENT_SIM_NETWORK_LOCKED = 3;
106 private static final int EVENT_WIRED_HEADSET_PLUG = 7;
107 private static final int EVENT_SIM_STATE_CHANGED = 8;
108 private static final int EVENT_UPDATE_INCALL_NOTIFICATION = 9;
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_TTY_PREFERRED_MODE_CHANGED = 14;
114 private static final int EVENT_TTY_MODE_GET = 15;
115 private static final int EVENT_TTY_MODE_SET = 16;
116 private static final int EVENT_START_SIP_SERVICE = 17;
117
118 // The MMI codes are also used by the InCallScreen.
119 public static final int MMI_INITIATE = 51;
120 public static final int MMI_COMPLETE = 52;
121 public static final int MMI_CANCEL = 53;
122 // Don't use message codes larger than 99 here; those are reserved for
123 // the individual Activities of the Phone UI.
124
125 /**
126 * Allowable values for the wake lock code.
127 * SLEEP means the device can be put to sleep.
128 * PARTIAL means wake the processor, but we display can be kept off.
129 * FULL means wake both the processor and the display.
130 */
131 public enum WakeState {
132 SLEEP,
133 PARTIAL,
134 FULL
135 }
136
137 /**
138 * Intent Action used for hanging up the current call from Notification bar. This will
139 * choose first ringing call, first active call, or first background call (typically in
140 * HOLDING state).
141 */
142 public static final String ACTION_HANG_UP_ONGOING_CALL =
143 "com.android.phone.ACTION_HANG_UP_ONGOING_CALL";
144
145 /**
146 * Intent Action used for making a phone call from Notification bar.
147 * This is for missed call notifications.
148 */
149 public static final String ACTION_CALL_BACK_FROM_NOTIFICATION =
150 "com.android.phone.ACTION_CALL_BACK_FROM_NOTIFICATION";
151
152 /**
153 * Intent Action used for sending a SMS from notification bar.
154 * This is for missed call notifications.
155 */
156 public static final String ACTION_SEND_SMS_FROM_NOTIFICATION =
157 "com.android.phone.ACTION_SEND_SMS_FROM_NOTIFICATION";
158
159 private static PhoneGlobals sMe;
160
161 // A few important fields we expose to the rest of the package
162 // directly (rather than thru set/get methods) for efficiency.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700163 CallController callController;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700164 CallManager mCM;
Santos Cordon63a84242013-07-23 13:32:52 -0700165 CallNotifier notifier;
166 CallerInfoCache callerInfoCache;
167 InCallUiState inCallUiState;
168 NotificationMgr notificationMgr;
169 Phone phone;
170 PhoneInterfaceManager phoneMgr;
171
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700172 private BluetoothManager bluetoothManager;
Santos Cordon63a84242013-07-23 13:32:52 -0700173 private CallCommandService callCommandService;
174 private CallHandlerServiceProxy callHandlerServiceProxy;
175 private CallModeler callModeler;
176 private CallStateMonitor callStateMonitor;
Santos Cordon2eaff902013-08-05 04:37:55 -0700177 private DTMFTonePlayer dtmfTonePlayer;
Santos Cordon63a84242013-07-23 13:32:52 -0700178 private IBluetoothHeadsetPhone mBluetoothPhone;
179 private Ringer ringer;
180
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700181 static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
182 static boolean sVoiceCapable = true;
183
184 // Internal PhoneApp Call state tracker
185 CdmaPhoneCallState cdmaPhoneCallState;
186
187 // The InCallScreen instance (or null if the InCallScreen hasn't been
188 // created yet.)
189 private InCallScreen mInCallScreen;
190
191 // The currently-active PUK entry activity and progress dialog.
192 // Normally, these are the Emergency Dialer and the subsequent
193 // progress dialog. null if there is are no such objects in
194 // the foreground.
195 private Activity mPUKEntryActivity;
196 private ProgressDialog mPUKEntryProgressDialog;
197
198 private boolean mIsSimPinEnabled;
199 private String mCachedSimPin;
200
201 // True if a wired headset is currently plugged in, based on the state
202 // from the latest Intent.ACTION_HEADSET_PLUG broadcast we received in
203 // mReceiver.onReceive().
204 private boolean mIsHeadsetPlugged;
205
206 // True if the keyboard is currently *not* hidden
207 // Gets updated whenever there is a Configuration change
208 private boolean mIsHardKeyboardOpen;
209
210 // True if we are beginning a call, but the phone state has not changed yet
211 private boolean mBeginningCall;
212
213 // Last phone state seen by updatePhoneState()
214 private PhoneConstants.State mLastPhoneState = PhoneConstants.State.IDLE;
215
216 private WakeState mWakeState = WakeState.SLEEP;
217
218 private PowerManager mPowerManager;
219 private IPowerManager mPowerManagerService;
220 private PowerManager.WakeLock mWakeLock;
221 private PowerManager.WakeLock mPartialWakeLock;
222 private PowerManager.WakeLock mProximityWakeLock;
223 private KeyguardManager mKeyguardManager;
224 private AccelerometerListener mAccelerometerListener;
225 private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN;
226
227 private UpdateLock mUpdateLock;
228
229 // Broadcast receiver for various intent broadcasts (see onCreate())
230 private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver();
231
232 // Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts
233 private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
234
235 /** boolean indicating restoring mute state on InCallScreen.onResume() */
236 private boolean mShouldRestoreMuteOnInCallResume;
237
238 /**
239 * The singleton OtaUtils instance used for OTASP calls.
240 *
241 * The OtaUtils instance is created lazily the first time we need to
242 * make an OTASP call, regardless of whether it's an interactive or
243 * non-interactive OTASP call.
244 */
245 public OtaUtils otaUtils;
246
247 // Following are the CDMA OTA information Objects used during OTA Call.
248 // cdmaOtaProvisionData object store static OTA information that needs
249 // to be maintained even during Slider open/close scenarios.
250 // cdmaOtaConfigData object stores configuration info to control visiblity
251 // of each OTA Screens.
252 // cdmaOtaScreenState object store OTA Screen State information.
253 public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData;
254 public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData;
255 public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState;
256 public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState;
257
258 // TTY feature enabled on this platform
259 private boolean mTtyEnabled;
260 // Current TTY operating mode selected by user
261 private int mPreferredTtyMode = Phone.TTY_MODE_OFF;
262
263 /**
264 * Set the restore mute state flag. Used when we are setting the mute state
265 * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)}
266 */
267 /*package*/void setRestoreMuteOnInCallResume (boolean mode) {
268 mShouldRestoreMuteOnInCallResume = mode;
269 }
270
271 /**
272 * Get the restore mute state flag.
273 * This is used by the InCallScreen {@link InCallScreen#onResume()} to figure
274 * out if we need to restore the mute state for the current active call.
275 */
276 /*package*/boolean getRestoreMuteOnInCallResume () {
277 return mShouldRestoreMuteOnInCallResume;
278 }
279
280 Handler mHandler = new Handler() {
281 @Override
282 public void handleMessage(Message msg) {
283 PhoneConstants.State phoneState;
284 switch (msg.what) {
285 // Starts the SIP service. It's a no-op if SIP API is not supported
286 // on the deivce.
287 // TODO: Having the phone process host the SIP service is only
288 // temporary. Will move it to a persistent communication process
289 // later.
290 case EVENT_START_SIP_SERVICE:
291 SipService.start(getApplicationContext());
292 break;
293
294 // TODO: This event should be handled by the lock screen, just
295 // like the "SIM missing" and "Sim locked" cases (bug 1804111).
296 case EVENT_SIM_NETWORK_LOCKED:
297 if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) {
298 // Some products don't have the concept of a "SIM network lock"
299 Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; "
300 + "not showing 'SIM network unlock' PIN entry screen");
301 } else {
302 // Normal case: show the "SIM network unlock" PIN entry screen.
303 // The user won't be able to do anything else until
304 // they enter a valid SIM network PIN.
305 Log.i(LOG_TAG, "show sim depersonal panel");
306 IccNetworkDepersonalizationPanel ndpPanel =
307 new IccNetworkDepersonalizationPanel(PhoneGlobals.getInstance());
308 ndpPanel.show();
309 }
310 break;
311
312 case EVENT_UPDATE_INCALL_NOTIFICATION:
313 // Tell the NotificationMgr to update the "ongoing
314 // call" icon in the status bar, if necessary.
315 // Currently, this is triggered by a bluetooth headset
316 // state change (since the status bar icon needs to
317 // turn blue when bluetooth is active.)
318 if (DBG) Log.d (LOG_TAG, "- updating in-call notification from handler...");
319 notificationMgr.updateInCallNotification();
320 break;
321
322 case EVENT_DATA_ROAMING_DISCONNECTED:
323 notificationMgr.showDataDisconnectedRoaming();
324 break;
325
326 case EVENT_DATA_ROAMING_OK:
327 notificationMgr.hideDataDisconnectedRoaming();
328 break;
329
330 case MMI_COMPLETE:
331 onMMIComplete((AsyncResult) msg.obj);
332 break;
333
334 case MMI_CANCEL:
335 PhoneUtils.cancelMmiCode(phone);
336 break;
337
338 case EVENT_WIRED_HEADSET_PLUG:
339 // Since the presence of a wired headset or bluetooth affects the
340 // speakerphone, update the "speaker" state. We ONLY want to do
341 // this on the wired headset connect / disconnect events for now
342 // though, so we're only triggering on EVENT_WIRED_HEADSET_PLUG.
343
344 phoneState = mCM.getState();
345 // Do not change speaker state if phone is not off hook
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700346 if (phoneState == PhoneConstants.State.OFFHOOK &&
347 !bluetoothManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700348 if (!isHeadsetPlugged()) {
349 // if the state is "not connected", restore the speaker state.
350 PhoneUtils.restoreSpeakerMode(getApplicationContext());
351 } else {
352 // if the state is "connected", force the speaker off without
353 // storing the state.
354 PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false);
355 }
356 }
357 // Update the Proximity sensor based on headset state
358 updateProximitySensorMode(phoneState);
359
360 // Force TTY state update according to new headset state
361 if (mTtyEnabled) {
362 sendMessage(obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
363 }
364 break;
365
366 case EVENT_SIM_STATE_CHANGED:
367 // Marks the event where the SIM goes into ready state.
368 // Right now, this is only used for the PUK-unlocking
369 // process.
370 if (msg.obj.equals(IccCardConstants.INTENT_VALUE_ICC_READY)) {
371 // when the right event is triggered and there
372 // are UI objects in the foreground, we close
373 // them to display the lock panel.
374 if (mPUKEntryActivity != null) {
375 mPUKEntryActivity.finish();
376 mPUKEntryActivity = null;
377 }
378 if (mPUKEntryProgressDialog != null) {
379 mPUKEntryProgressDialog.dismiss();
380 mPUKEntryProgressDialog = null;
381 }
382 }
383 break;
384
385 case EVENT_UNSOL_CDMA_INFO_RECORD:
386 //TODO: handle message here;
387 break;
388
389 case EVENT_DOCK_STATE_CHANGED:
390 // If the phone is docked/undocked during a call, and no wired or BT headset
391 // is connected: turn on/off the speaker accordingly.
392 boolean inDockMode = false;
393 if (mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
394 inDockMode = true;
395 }
396 if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = "
397 + inDockMode);
398
399 phoneState = mCM.getState();
400 if (phoneState == PhoneConstants.State.OFFHOOK &&
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700401 !isHeadsetPlugged() && !bluetoothManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700402 PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true);
403 updateInCallScreen(); // Has no effect if the InCallScreen isn't visible
404 }
405 break;
406
407 case EVENT_TTY_PREFERRED_MODE_CHANGED:
408 // TTY mode is only applied if a headset is connected
409 int ttyMode;
410 if (isHeadsetPlugged()) {
411 ttyMode = mPreferredTtyMode;
412 } else {
413 ttyMode = Phone.TTY_MODE_OFF;
414 }
415 phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET));
416 break;
417
418 case EVENT_TTY_MODE_GET:
419 handleQueryTTYModeResponse(msg);
420 break;
421
422 case EVENT_TTY_MODE_SET:
423 handleSetTTYModeResponse(msg);
424 break;
425 }
426 }
427 };
428
429 public PhoneGlobals(Context context) {
430 super(context);
431 sMe = this;
432 }
433
434 public void onCreate() {
435 if (VDBG) Log.v(LOG_TAG, "onCreate()...");
436
437 ContentResolver resolver = getContentResolver();
438
439 // Cache the "voice capable" flag.
440 // This flag currently comes from a resource (which is
441 // overrideable on a per-product basis):
442 sVoiceCapable =
443 getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
444 // ...but this might eventually become a PackageManager "system
445 // feature" instead, in which case we'd do something like:
446 // sVoiceCapable =
447 // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS);
448
449 if (phone == null) {
450 // Initialize the telephony framework
451 PhoneFactory.makeDefaultPhones(this);
452
453 // Get the default phone
454 phone = PhoneFactory.getDefaultPhone();
455
456 // Start TelephonyDebugService After the default phone is created.
457 Intent intent = new Intent(this, TelephonyDebugService.class);
458 startService(intent);
459
460 mCM = CallManager.getInstance();
461 mCM.registerPhone(phone);
462
463 // Create the NotificationMgr singleton, which is used to display
464 // status bar icons and control other status bar behavior.
465 notificationMgr = NotificationMgr.init(this);
466
467 phoneMgr = PhoneInterfaceManager.init(this, phone);
468
469 mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE);
470
471 int phoneType = phone.getPhoneType();
472
473 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
474 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
475 cdmaPhoneCallState = new CdmaPhoneCallState();
476 cdmaPhoneCallState.CdmaPhoneCallStateInit();
477 }
478
479 if (BluetoothAdapter.getDefaultAdapter() != null) {
480 // Start BluetoothPhoneService even if device is not voice capable.
481 // The device can still support VOIP.
482 startService(new Intent(this, BluetoothPhoneService.class));
483 bindService(new Intent(this, BluetoothPhoneService.class),
484 mBluetoothPhoneConnection, 0);
485 } else {
486 // Device is not bluetooth capable
487 mBluetoothPhone = null;
488 }
489
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700490 // Bluetooth manager
491 bluetoothManager = new BluetoothManager(this, mCM);
492 bluetoothManager.addBluetoothIndicatorListener(this);
493
494 ringer = Ringer.init(this, bluetoothManager);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700495
496 // before registering for phone state changes
497 mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
498 mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOG_TAG);
499 // lock used to keep the processor awake, when we don't care for the display.
500 mPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
501 | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
502 // Wake lock used to control proximity sensor behavior.
503 if (mPowerManager.isWakeLockLevelSupported(
504 PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
505 mProximityWakeLock = mPowerManager.newWakeLock(
506 PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, LOG_TAG);
507 }
508 if (DBG) Log.d(LOG_TAG, "onCreate: mProximityWakeLock: " + mProximityWakeLock);
509
510 // create mAccelerometerListener only if we are using the proximity sensor
511 if (proximitySensorModeEnabled()) {
512 mAccelerometerListener = new AccelerometerListener(this, this);
513 }
514
515 mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
516
517 // get a handle to the service so that we can use it later when we
518 // want to set the poke lock.
519 mPowerManagerService = IPowerManager.Stub.asInterface(
520 ServiceManager.getService("power"));
521
522 // Get UpdateLock to suppress system-update related events (e.g. dialog show-up)
523 // during phone calls.
524 mUpdateLock = new UpdateLock("phone");
525
526 if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock);
527
528 CallLogger callLogger = new CallLogger(this, new CallLogAsync());
529
530 // Create the CallController singleton, which is the interface
531 // to the telephony layer for user-initiated telephony functionality
532 // (like making outgoing calls.)
533 callController = CallController.init(this, callLogger);
534 // ...and also the InCallUiState instance, used by the CallController to
535 // keep track of some "persistent state" of the in-call UI.
536 inCallUiState = InCallUiState.init(this);
537
538 // Create the CallerInfoCache singleton, which remembers custom ring tone and
539 // send-to-voicemail settings.
540 //
541 // The asynchronous caching will start just after this call.
542 callerInfoCache = CallerInfoCache.init(this);
543
544 // Monitors call activity from the telephony layer
545 callStateMonitor = new CallStateMonitor(mCM);
546
Santos Cordon63a84242013-07-23 13:32:52 -0700547 // Creates call models for use with CallHandlerService.
Santos Cordona3d05142013-07-29 11:25:17 -0700548 callModeler = new CallModeler(callStateMonitor, mCM);
Santos Cordon63a84242013-07-23 13:32:52 -0700549
Santos Cordon2eaff902013-08-05 04:37:55 -0700550 // Plays DTMF Tones
551 dtmfTonePlayer = new DTMFTonePlayer(mCM, callModeler);
552
Santos Cordon249efd02013-08-05 03:33:56 -0700553 // Service used by in-call UI to control calls
Santos Cordon2eaff902013-08-05 04:37:55 -0700554 callCommandService = new CallCommandService(this, mCM, callModeler, dtmfTonePlayer);
Santos Cordon249efd02013-08-05 03:33:56 -0700555
Santos Cordon89647a62013-07-16 13:38:09 -0700556 // Sends call state to the UI
Santos Cordon63a84242013-07-23 13:32:52 -0700557 callHandlerServiceProxy = new CallHandlerServiceProxy(this, callModeler,
Santos Cordoncba1b442013-07-18 12:43:58 -0700558 callCommandService);
Santos Cordon89647a62013-07-16 13:38:09 -0700559
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700560 // Create the CallNotifer singleton, which handles
561 // asynchronous events from the telephony layer (like
562 // launching the incoming-call UI when an incoming call comes
563 // in.)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700564 notifier = CallNotifier.init(this, phone, ringer, callLogger, callStateMonitor,
565 bluetoothManager);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700566
567 // register for ICC status
568 IccCard sim = phone.getIccCard();
569 if (sim != null) {
570 if (VDBG) Log.v(LOG_TAG, "register for ICC status");
571 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
572 }
573
574 // register for MMI/USSD
575 mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
576
577 // register connection tracking to PhoneUtils
578 PhoneUtils.initializeConnectionHandler(mCM);
579
580 // Read platform settings for TTY feature
581 mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled);
582
583 // Register for misc other intent broadcasts.
584 IntentFilter intentFilter =
585 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700586 intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
587 intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
588 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
589 intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
590 intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
591 intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
592 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
593 if (mTtyEnabled) {
594 intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
595 }
596 intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
597 registerReceiver(mReceiver, intentFilter);
598
599 // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts,
600 // since we need to manually adjust its priority (to make sure
601 // we get these intents *before* the media player.)
602 IntentFilter mediaButtonIntentFilter =
603 new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
604 // TODO verify the independent priority doesn't need to be handled thanks to the
605 // private intent handler registration
606 // Make sure we're higher priority than the media player's
607 // MediaButtonIntentReceiver (which currently has the default
608 // priority of zero; see apps/Music/AndroidManifest.xml.)
609 mediaButtonIntentFilter.setPriority(1);
610 //
611 registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
612 // register the component so it gets priority for calls
613 AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
614 am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(),
615 MediaButtonBroadcastReceiver.class.getName()));
616
617 //set the default values for the preferences in the phone.
618 PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
619
620 PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
621
622 // Make sure the audio mode (along with some
623 // audio-mode-related state of our own) is initialized
624 // correctly, given the current state of the phone.
625 PhoneUtils.setAudioMode(mCM);
626 }
627
628 if (TelephonyCapabilities.supportsOtasp(phone)) {
629 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
630 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
631 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
632 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
633 }
634
635 // XXX pre-load the SimProvider so that it's ready
636 resolver.getType(Uri.parse("content://icc/adn"));
637
638 // start with the default value to set the mute state.
639 mShouldRestoreMuteOnInCallResume = false;
640
641 // TODO: Register for Cdma Information Records
642 // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
643
644 // Read TTY settings and store it into BP NV.
645 // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting
646 // to BP at power up (BP does not need to make the TTY setting persistent storage).
647 // This way, there is a single owner (i.e AP) for the TTY setting in the phone.
648 if (mTtyEnabled) {
649 mPreferredTtyMode = android.provider.Settings.Secure.getInt(
650 phone.getContext().getContentResolver(),
651 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
652 Phone.TTY_MODE_OFF);
653 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
654 }
655 // Read HAC settings and configure audio hardware
656 if (getResources().getBoolean(R.bool.hac_enabled)) {
657 int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(),
658 android.provider.Settings.System.HEARING_AID,
659 0);
660 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
661 audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ?
662 CallFeaturesSetting.HAC_VAL_ON :
663 CallFeaturesSetting.HAC_VAL_OFF);
664 }
665 }
666
667 public void onConfigurationChanged(Configuration newConfig) {
668 if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
669 mIsHardKeyboardOpen = true;
670 } else {
671 mIsHardKeyboardOpen = false;
672 }
673
674 // Update the Proximity sensor based on keyboard state
675 updateProximitySensorMode(mCM.getState());
676 }
677
678 /**
679 * Returns the singleton instance of the PhoneApp.
680 */
681 static PhoneGlobals getInstance() {
682 if (sMe == null) {
683 throw new IllegalStateException("No PhoneGlobals here!");
684 }
685 return sMe;
686 }
687
688 /**
689 * Returns the singleton instance of the PhoneApp if running as the
690 * primary user, otherwise null.
691 */
692 static PhoneGlobals getInstanceIfPrimary() {
693 return sMe;
694 }
695
696 /**
697 * Returns the Phone associated with this instance
698 */
699 static Phone getPhone() {
700 return getInstance().phone;
701 }
702
703 Ringer getRinger() {
704 return ringer;
705 }
706
707 IBluetoothHeadsetPhone getBluetoothPhoneService() {
708 return mBluetoothPhone;
709 }
710
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700711 /* package */ BluetoothManager getBluetoothManager() {
712 return bluetoothManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700713 }
714
715 /**
716 * Returns an Intent that can be used to go to the "Call log"
717 * UI (aka CallLogActivity) in the Contacts app.
718 *
719 * Watch out: there's no guarantee that the system has any activity to
720 * handle this intent. (In particular there may be no "Call log" at
721 * all on on non-voice-capable devices.)
722 */
723 /* package */ static Intent createCallLogIntent() {
724 Intent intent = new Intent(Intent.ACTION_VIEW, null);
725 intent.setType("vnd.android.cursor.dir/calls");
726 return intent;
727 }
728
729 /**
730 * Return an Intent that can be used to bring up the in-call screen.
731 *
732 * This intent can only be used from within the Phone app, since the
733 * InCallScreen is not exported from our AndroidManifest.
734 */
735 /* package */ static Intent createInCallIntent() {
736 Intent intent = new Intent(Intent.ACTION_MAIN, null);
737 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
738 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
739 | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
740 intent.setClassName("com.android.phone", getCallScreenClassName());
741 return intent;
742 }
743
744 /**
745 * Variation of createInCallIntent() that also specifies whether the
746 * DTMF dialpad should be initially visible when the InCallScreen
747 * comes up.
748 */
749 /* package */ static Intent createInCallIntent(boolean showDialpad) {
750 Intent intent = createInCallIntent();
751 intent.putExtra(InCallScreen.SHOW_DIALPAD_EXTRA, showDialpad);
752 return intent;
753 }
754
755 /**
756 * Returns PendingIntent for hanging up ongoing phone call. This will typically be used from
757 * Notification context.
758 */
759 /* package */ static PendingIntent createHangUpOngoingCallPendingIntent(Context context) {
760 Intent intent = new Intent(PhoneGlobals.ACTION_HANG_UP_ONGOING_CALL, null,
761 context, NotificationBroadcastReceiver.class);
762 return PendingIntent.getBroadcast(context, 0, intent, 0);
763 }
764
765 /* package */ static PendingIntent getCallBackPendingIntent(Context context, String number) {
766 Intent intent = new Intent(ACTION_CALL_BACK_FROM_NOTIFICATION,
767 Uri.fromParts(Constants.SCHEME_TEL, number, null),
768 context, NotificationBroadcastReceiver.class);
769 return PendingIntent.getBroadcast(context, 0, intent, 0);
770 }
771
772 /* package */ static PendingIntent getSendSmsFromNotificationPendingIntent(
773 Context context, String number) {
774 Intent intent = new Intent(ACTION_SEND_SMS_FROM_NOTIFICATION,
775 Uri.fromParts(Constants.SCHEME_SMSTO, number, null),
776 context, NotificationBroadcastReceiver.class);
777 return PendingIntent.getBroadcast(context, 0, intent, 0);
778 }
779
780 private static String getCallScreenClassName() {
Chiao Cheng7f7c6522013-07-16 18:39:35 -0700781 //InCallScreen.class.getName();
782 return "blah";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700783 }
784
785 /**
786 * Starts the InCallScreen Activity.
787 */
788 /* package */ void displayCallScreen() {
789 if (VDBG) Log.d(LOG_TAG, "displayCallScreen()...");
790
791 // On non-voice-capable devices we shouldn't ever be trying to
792 // bring up the InCallScreen in the first place.
793 if (!sVoiceCapable) {
794 Log.w(LOG_TAG, "displayCallScreen() not allowed: non-voice-capable device",
795 new Throwable("stack dump")); // Include a stack trace since this warning
796 // indicates a bug in our caller
797 return;
798 }
799
800 try {
Chiao Cheng7f7c6522013-07-16 18:39:35 -0700801 //startActivity(createInCallIntent());
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700802 } catch (ActivityNotFoundException e) {
803 // It's possible that the in-call UI might not exist (like on
804 // non-voice-capable devices), so don't crash if someone
805 // accidentally tries to bring it up...
806 Log.w(LOG_TAG, "displayCallScreen: transition to InCallScreen failed: " + e);
807 }
808 Profiler.callScreenRequested();
809 }
810
811 boolean isSimPinEnabled() {
812 return mIsSimPinEnabled;
813 }
814
815 boolean authenticateAgainstCachedSimPin(String pin) {
816 return (mCachedSimPin != null && mCachedSimPin.equals(pin));
817 }
818
819 void setCachedSimPin(String pin) {
820 mCachedSimPin = pin;
821 }
822
823 void setInCallScreenInstance(InCallScreen inCallScreen) {
824 mInCallScreen = inCallScreen;
825 }
826
827 /**
828 * @return true if the in-call UI is running as the foreground
829 * activity. (In other words, from the perspective of the
830 * InCallScreen activity, return true between onResume() and
831 * onPause().)
832 *
833 * Note this method will return false if the screen is currently off,
834 * even if the InCallScreen *was* in the foreground just before the
835 * screen turned off. (This is because the foreground activity is
836 * always "paused" while the screen is off.)
837 */
838 boolean isShowingCallScreen() {
839 if (mInCallScreen == null) return false;
840 return mInCallScreen.isForegroundActivity();
841 }
842
843 /**
844 * @return true if the in-call UI is running as the foreground activity, or,
845 * it went to background due to screen being turned off. This might be useful
846 * to determine if the in-call screen went to background because of other
847 * activities, or its proximity sensor state or manual power-button press.
848 *
849 * Here are some examples.
850 *
851 * - If you want to know if the activity is in foreground or screen is turned off
852 * from the in-call UI (i.e. though it is not "foreground" anymore it will become
853 * so after screen being turned on), check
854 * {@link #isShowingCallScreenForProximity()} is true or not.
855 * {@link #updateProximitySensorMode(com.android.internal.telephony.PhoneConstants.State)} is
856 * doing this.
857 *
858 * - If you want to know if the activity is not in foreground just because screen
859 * is turned off (not due to other activity's interference), check
860 * {@link #isShowingCallScreen()} is false *and* {@link #isShowingCallScreenForProximity()}
861 * is true. InCallScreen#onDisconnect() is doing this check.
862 *
863 * @see #isShowingCallScreen()
864 *
865 * TODO: come up with better naming..
866 */
867 boolean isShowingCallScreenForProximity() {
868 if (mInCallScreen == null) return false;
869 return mInCallScreen.isForegroundActivityForProximity();
870 }
871
872 /**
873 * Dismisses the in-call UI.
874 *
875 * This also ensures that you won't be able to get back to the in-call
876 * UI via the BACK button (since this call removes the InCallScreen
877 * from the activity history.)
878 * For OTA Call, it call InCallScreen api to handle OTA Call End scenario
879 * to display OTA Call End screen.
880 */
881 /* package */ void dismissCallScreen() {
882 if (mInCallScreen != null) {
883 if ((TelephonyCapabilities.supportsOtasp(phone)) &&
884 (mInCallScreen.isOtaCallInActiveState()
885 || mInCallScreen.isOtaCallInEndState()
886 || ((cdmaOtaScreenState != null)
887 && (cdmaOtaScreenState.otaScreenState
888 != CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) {
889 // TODO: During OTA Call, display should not become dark to
890 // allow user to see OTA UI update. Phone app needs to hold
891 // a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call.
892 wakeUpScreen();
893 // If InCallScreen is not in foreground we resume it to show the OTA call end screen
894 // Fire off the InCallScreen intent
895 displayCallScreen();
896
897 mInCallScreen.handleOtaCallEnd();
898 return;
899 } else {
900 mInCallScreen.finish();
901 }
902 }
903 }
904
905 /**
906 * Handles OTASP-related events from the telephony layer.
907 *
908 * While an OTASP call is active, the CallNotifier forwards
909 * OTASP-related telephony events to this method.
910 */
911 void handleOtaspEvent(Message msg) {
912 if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")...");
913
914 if (otaUtils == null) {
915 // We shouldn't be getting OTASP events without ever
916 // having started the OTASP call in the first place!
917 Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! "
918 + "message = " + msg);
919 return;
920 }
921
922 otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
923 }
924
925 /**
926 * Similarly, handle the disconnect event of an OTASP call
927 * by forwarding it to the OtaUtils instance.
928 */
929 /* package */ void handleOtaspDisconnect() {
930 if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()...");
931
932 if (otaUtils == null) {
933 // We shouldn't be getting OTASP events without ever
934 // having started the OTASP call in the first place!
935 Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!");
936 return;
937 }
938
939 otaUtils.onOtaspDisconnect();
940 }
941
942 /**
943 * Sets the activity responsible for un-PUK-blocking the device
944 * so that we may close it when we receive a positive result.
945 * mPUKEntryActivity is also used to indicate to the device that
946 * we are trying to un-PUK-lock the phone. In other words, iff
947 * it is NOT null, then we are trying to unlock and waiting for
948 * the SIM to move to READY state.
949 *
950 * @param activity is the activity to close when PUK has
951 * finished unlocking. Can be set to null to indicate the unlock
952 * or SIM READYing process is over.
953 */
954 void setPukEntryActivity(Activity activity) {
955 mPUKEntryActivity = activity;
956 }
957
958 Activity getPUKEntryActivity() {
959 return mPUKEntryActivity;
960 }
961
962 /**
963 * Sets the dialog responsible for notifying the user of un-PUK-
964 * blocking - SIM READYing progress, so that we may dismiss it
965 * when we receive a positive result.
966 *
967 * @param dialog indicates the progress dialog informing the user
968 * of the state of the device. Dismissed upon completion of
969 * READYing process
970 */
971 void setPukEntryProgressDialog(ProgressDialog dialog) {
972 mPUKEntryProgressDialog = dialog;
973 }
974
975 ProgressDialog getPUKEntryProgressDialog() {
976 return mPUKEntryProgressDialog;
977 }
978
979 /**
980 * Controls whether or not the screen is allowed to sleep.
981 *
982 * Once sleep is allowed (WakeState is SLEEP), it will rely on the
983 * settings for the poke lock to determine when to timeout and let
984 * the device sleep {@link PhoneGlobals#setScreenTimeout}.
985 *
986 * @param ws tells the device to how to wake.
987 */
988 /* package */ void requestWakeState(WakeState ws) {
989 if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
990 synchronized (this) {
991 if (mWakeState != ws) {
992 switch (ws) {
993 case PARTIAL:
994 // acquire the processor wake lock, and release the FULL
995 // lock if it is being held.
996 mPartialWakeLock.acquire();
997 if (mWakeLock.isHeld()) {
998 mWakeLock.release();
999 }
1000 break;
1001 case FULL:
1002 // acquire the full wake lock, and release the PARTIAL
1003 // lock if it is being held.
1004 mWakeLock.acquire();
1005 if (mPartialWakeLock.isHeld()) {
1006 mPartialWakeLock.release();
1007 }
1008 break;
1009 case SLEEP:
1010 default:
1011 // release both the PARTIAL and FULL locks.
1012 if (mWakeLock.isHeld()) {
1013 mWakeLock.release();
1014 }
1015 if (mPartialWakeLock.isHeld()) {
1016 mPartialWakeLock.release();
1017 }
1018 break;
1019 }
1020 mWakeState = ws;
1021 }
1022 }
1023 }
1024
1025 /**
1026 * If we are not currently keeping the screen on, then poke the power
1027 * manager to wake up the screen for the user activity timeout duration.
1028 */
1029 /* package */ void wakeUpScreen() {
1030 synchronized (this) {
1031 if (mWakeState == WakeState.SLEEP) {
1032 if (DBG) Log.d(LOG_TAG, "pulse screen lock");
1033 mPowerManager.wakeUp(SystemClock.uptimeMillis());
1034 }
1035 }
1036 }
1037
1038 /**
1039 * Sets the wake state and screen timeout based on the current state
1040 * of the phone, and the current state of the in-call UI.
1041 *
1042 * This method is a "UI Policy" wrapper around
1043 * {@link PhoneGlobals#requestWakeState} and {@link PhoneGlobals#setScreenTimeout}.
1044 *
1045 * It's safe to call this method regardless of the state of the Phone
1046 * (e.g. whether or not it's idle), and regardless of the state of the
1047 * Phone UI (e.g. whether or not the InCallScreen is active.)
1048 */
1049 /* package */ void updateWakeState() {
1050 PhoneConstants.State state = mCM.getState();
1051
1052 // True if the in-call UI is the foreground activity.
1053 // (Note this will be false if the screen is currently off,
1054 // since in that case *no* activity is in the foreground.)
1055 boolean isShowingCallScreen = isShowingCallScreen();
1056
1057 // True if the InCallScreen's DTMF dialer is currently opened.
1058 // (Note this does NOT imply whether or not the InCallScreen
1059 // itself is visible.)
1060 boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened();
1061
1062 // True if the speakerphone is in use. (If so, we *always* use
1063 // the default timeout. Since the user is obviously not holding
1064 // the phone up to his/her face, we don't need to worry about
1065 // false touches, and thus don't need to turn the screen off so
1066 // aggressively.)
1067 // Note that we need to make a fresh call to this method any
1068 // time the speaker state changes. (That happens in
1069 // PhoneUtils.turnOnSpeaker().)
1070 boolean isSpeakerInUse = (state == PhoneConstants.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
1071
1072 // TODO (bug 1440854): The screen timeout *might* also need to
1073 // depend on the bluetooth state, but this isn't as clear-cut as
1074 // the speaker state (since while using BT it's common for the
1075 // user to put the phone straight into a pocket, in which case the
1076 // timeout should probably still be short.)
1077
1078 if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen
1079 + ", dialer " + isDialerOpened
1080 + ", speaker " + isSpeakerInUse + "...");
1081
1082 //
1083 // Decide whether to force the screen on or not.
1084 //
1085 // Force the screen to be on if the phone is ringing or dialing,
1086 // or if we're displaying the "Call ended" UI for a connection in
1087 // the "disconnected" state.
1088 // However, if the phone is disconnected while the user is in the
1089 // middle of selecting a quick response message, we should not force
1090 // the screen to be on.
1091 //
1092 boolean isRinging = (state == PhoneConstants.State.RINGING);
1093 boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING);
1094 boolean showingQuickResponseDialog = (mInCallScreen != null) &&
1095 mInCallScreen.isQuickResponseDialogShowing();
1096 boolean showingDisconnectedConnection =
1097 PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen;
1098 boolean keepScreenOn = isRinging || isDialing ||
1099 (showingDisconnectedConnection && !showingQuickResponseDialog);
1100 if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn
1101 + " (isRinging " + isRinging
1102 + ", isDialing " + isDialing
1103 + ", showingQuickResponse " + showingQuickResponseDialog
1104 + ", showingDisc " + showingDisconnectedConnection + ")");
1105 // keepScreenOn == true means we'll hold a full wake lock:
1106 requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
1107 }
1108
1109 /**
1110 * Manually pokes the PowerManager's userActivity method. Since we
1111 * set the {@link WindowManager.LayoutParams#INPUT_FEATURE_DISABLE_USER_ACTIVITY}
1112 * flag while the InCallScreen is active when there is no proximity sensor,
1113 * we need to do this for touch events that really do count as user activity
1114 * (like pressing any onscreen UI elements.)
1115 */
1116 /* package */ void pokeUserActivity() {
1117 if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
1118 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
1119 }
1120
1121 /**
1122 * Set when a new outgoing call is beginning, so we can update
1123 * the proximity sensor state.
1124 * Cleared when the InCallScreen is no longer in the foreground,
1125 * in case the call fails without changing the telephony state.
1126 */
1127 /* package */ void setBeginningCall(boolean beginning) {
1128 // Note that we are beginning a new call, for proximity sensor support
1129 mBeginningCall = beginning;
1130 // Update the Proximity sensor based on mBeginningCall state
1131 updateProximitySensorMode(mCM.getState());
1132 }
1133
1134 /**
1135 * Updates the wake lock used to control proximity sensor behavior,
1136 * based on the current state of the phone. This method is called
1137 * from the CallNotifier on any phone state change.
1138 *
1139 * On devices that have a proximity sensor, to avoid false touches
1140 * during a call, we hold a PROXIMITY_SCREEN_OFF_WAKE_LOCK wake lock
1141 * whenever the phone is off hook. (When held, that wake lock causes
1142 * the screen to turn off automatically when the sensor detects an
1143 * object close to the screen.)
1144 *
1145 * This method is a no-op for devices that don't have a proximity
1146 * sensor.
1147 *
1148 * Note this method doesn't care if the InCallScreen is the foreground
1149 * activity or not. That's because we want the proximity sensor to be
1150 * enabled any time the phone is in use, to avoid false cheek events
1151 * for whatever app you happen to be running.
1152 *
1153 * Proximity wake lock will *not* be held if any one of the
1154 * conditions is true while on a call:
1155 * 1) If the audio is routed via Bluetooth
1156 * 2) If a wired headset is connected
1157 * 3) if the speaker is ON
1158 * 4) If the slider is open(i.e. the hardkeyboard is *not* hidden)
1159 *
1160 * @param state current state of the phone (see {@link Phone#State})
1161 */
1162 /* package */ void updateProximitySensorMode(PhoneConstants.State state) {
1163 if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state);
1164
1165 if (proximitySensorModeEnabled()) {
1166 synchronized (mProximityWakeLock) {
1167 // turn proximity sensor off and turn screen on immediately if
1168 // we are using a headset, the keyboard is open, or the device
1169 // is being held in a horizontal position.
1170 boolean screenOnImmediately = (isHeadsetPlugged()
1171 || PhoneUtils.isSpeakerOn(this)
Santos Cordon27a3c1f2013-08-06 07:49:27 -07001172 || bluetoothManager.isBluetoothHeadsetAudioOn()
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001173 || mIsHardKeyboardOpen);
1174
1175 // We do not keep the screen off when the user is outside in-call screen and we are
1176 // horizontal, but we do not force it on when we become horizontal until the
1177 // proximity sensor goes negative.
1178 boolean horizontal =
1179 (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL);
1180 screenOnImmediately |= !isShowingCallScreenForProximity() && horizontal;
1181
1182 // We do not keep the screen off when dialpad is visible, we are horizontal, and
1183 // the in-call screen is being shown.
1184 // At that moment we're pretty sure users want to use it, instead of letting the
1185 // proximity sensor turn off the screen by their hands.
1186 boolean dialpadVisible = false;
1187 if (mInCallScreen != null) {
1188 dialpadVisible =
1189 mInCallScreen.getUpdatedInCallControlState().dialpadEnabled
1190 && mInCallScreen.getUpdatedInCallControlState().dialpadVisible
1191 && isShowingCallScreen();
1192 }
1193 screenOnImmediately |= dialpadVisible && horizontal;
1194
1195 if (((state == PhoneConstants.State.OFFHOOK) || mBeginningCall) && !screenOnImmediately) {
1196 // Phone is in use! Arrange for the screen to turn off
1197 // automatically when the sensor detects a close object.
1198 if (!mProximityWakeLock.isHeld()) {
1199 if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring...");
1200 mProximityWakeLock.acquire();
1201 } else {
1202 if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held.");
1203 }
1204 } else {
1205 // Phone is either idle, or ringing. We don't want any
1206 // special proximity sensor behavior in either case.
1207 if (mProximityWakeLock.isHeld()) {
1208 if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing...");
1209 // Wait until user has moved the phone away from his head if we are
1210 // releasing due to the phone call ending.
1211 // Qtherwise, turn screen on immediately
1212 int flags =
1213 (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE);
1214 mProximityWakeLock.release(flags);
1215 } else {
1216 if (VDBG) {
1217 Log.d(LOG_TAG, "updateProximitySensorMode: lock already released.");
1218 }
1219 }
1220 }
1221 }
1222 }
1223 }
1224
1225 @Override
1226 public void orientationChanged(int orientation) {
1227 mOrientation = orientation;
1228 updateProximitySensorMode(mCM.getState());
1229 }
1230
1231 /**
1232 * Notifies the phone app when the phone state changes.
1233 *
1234 * This method will updates various states inside Phone app (e.g. proximity sensor mode,
1235 * accelerometer listener state, update-lock state, etc.)
1236 */
1237 /* package */ void updatePhoneState(PhoneConstants.State state) {
1238 if (state != mLastPhoneState) {
1239 mLastPhoneState = state;
1240 updateProximitySensorMode(state);
1241
1242 // Try to acquire or release UpdateLock.
1243 //
1244 // Watch out: we don't release the lock here when the screen is still in foreground.
1245 // At that time InCallScreen will release it on onPause().
1246 if (state != PhoneConstants.State.IDLE) {
1247 // UpdateLock is a recursive lock, while we may get "acquire" request twice and
1248 // "release" request once for a single call (RINGING + OFFHOOK and IDLE).
1249 // We need to manually ensure the lock is just acquired once for each (and this
1250 // will prevent other possible buggy situations too).
1251 if (!mUpdateLock.isHeld()) {
1252 mUpdateLock.acquire();
1253 }
1254 } else {
1255 if (!isShowingCallScreen()) {
1256 if (!mUpdateLock.isHeld()) {
1257 mUpdateLock.release();
1258 }
1259 } else {
1260 // For this case InCallScreen will take care of the release() call.
1261 }
1262 }
1263
1264 if (mAccelerometerListener != null) {
1265 // use accelerometer to augment proximity sensor when in call
1266 mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN;
1267 mAccelerometerListener.enable(state == PhoneConstants.State.OFFHOOK);
1268 }
1269 // clear our beginning call flag
1270 mBeginningCall = false;
1271 // While we are in call, the in-call screen should dismiss the keyguard.
1272 // This allows the user to press Home to go directly home without going through
1273 // an insecure lock screen.
1274 // But we do not want to do this if there is no active call so we do not
1275 // bypass the keyguard if the call is not answered or declined.
1276 if (mInCallScreen != null) {
1277 mInCallScreen.updateKeyguardPolicy(state == PhoneConstants.State.OFFHOOK);
1278 }
1279 }
1280 }
1281
1282 /* package */ PhoneConstants.State getPhoneState() {
1283 return mLastPhoneState;
1284 }
1285
1286 /**
1287 * Returns UpdateLock object.
1288 */
1289 /* package */ UpdateLock getUpdateLock() {
1290 return mUpdateLock;
1291 }
1292
1293 /**
1294 * @return true if this device supports the "proximity sensor
1295 * auto-lock" feature while in-call (see updateProximitySensorMode()).
1296 */
1297 /* package */ boolean proximitySensorModeEnabled() {
1298 return (mProximityWakeLock != null);
1299 }
1300
1301 KeyguardManager getKeyguardManager() {
1302 return mKeyguardManager;
1303 }
1304
1305 private void onMMIComplete(AsyncResult r) {
1306 if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
1307 MmiCode mmiCode = (MmiCode) r.result;
1308 PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null);
1309 }
1310
1311 private void initForNewRadioTechnology() {
1312 if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
1313
1314 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1315 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
1316 cdmaPhoneCallState = new CdmaPhoneCallState();
1317 cdmaPhoneCallState.CdmaPhoneCallStateInit();
1318 }
1319 if (TelephonyCapabilities.supportsOtasp(phone)) {
1320 //create instances of CDMA OTA data classes
1321 if (cdmaOtaProvisionData == null) {
1322 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
1323 }
1324 if (cdmaOtaConfigData == null) {
1325 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
1326 }
1327 if (cdmaOtaScreenState == null) {
1328 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
1329 }
1330 if (cdmaOtaInCallScreenUiState == null) {
1331 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
1332 }
1333 } else {
1334 //Clean up OTA data in GSM/UMTS. It is valid only for CDMA
1335 clearOtaState();
1336 }
1337
1338 ringer.updateRingerContextAfterRadioTechnologyChange(this.phone);
1339 notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
1340 callStateMonitor.updateAfterRadioTechnologyChange();
1341
1342 if (mBluetoothPhone != null) {
1343 try {
1344 mBluetoothPhone.updateBtHandsfreeAfterRadioTechnologyChange();
1345 } catch (RemoteException e) {
1346 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
1347 }
1348 }
1349 if (mInCallScreen != null) {
1350 mInCallScreen.updateAfterRadioTechnologyChange();
1351 }
1352
1353 // Update registration for ICC status after radio technology change
1354 IccCard sim = phone.getIccCard();
1355 if (sim != null) {
1356 if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
1357
1358 //Register all events new to the new active phone
1359 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
1360 }
1361 }
1362
1363
1364 /**
1365 * @return true if a wired headset is currently plugged in.
1366 *
1367 * @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive())
1368 */
1369 boolean isHeadsetPlugged() {
1370 return mIsHeadsetPlugged;
1371 }
1372
1373 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001374 * This needs to be called any time the bluetooth headset state or the
1375 * telephony state changes.
Santos Cordon27a3c1f2013-08-06 07:49:27 -07001376 * TODO(klp): See about a ProximityManager-type class listening to bluetooth
1377 * state changes instead of having this global method
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001378 */
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001379
Santos Cordon27a3c1f2013-08-06 07:49:27 -07001380 @Override
1381 public void onBluetoothIndicationChange(boolean showAsConnected, BluetoothManager manager) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001382 // Update the Proximity sensor based on Bluetooth audio state
1383 updateProximitySensorMode(mCM.getState());
1384 }
1385
1386 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001387 * Receiver for misc intent broadcasts the Phone app cares about.
1388 */
1389 private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
1390 @Override
1391 public void onReceive(Context context, Intent intent) {
1392 String action = intent.getAction();
1393 if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
1394 boolean enabled = System.getInt(getContentResolver(),
1395 System.AIRPLANE_MODE_ON, 0) == 0;
1396 phone.setRadioPower(enabled);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001397 } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
1398 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
1399 if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(PhoneConstants.STATE_KEY));
1400 if (VDBG) Log.d(LOG_TAG, "- reason: "
1401 + intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1402
1403 // The "data disconnected due to roaming" notification is shown
1404 // if (a) you have the "data roaming" feature turned off, and
1405 // (b) you just lost data connectivity because you're roaming.
1406 boolean disconnectedDueToRoaming =
1407 !phone.getDataRoamingEnabled()
1408 && "DISCONNECTED".equals(intent.getStringExtra(PhoneConstants.STATE_KEY))
1409 && Phone.REASON_ROAMING_ON.equals(
1410 intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1411 mHandler.sendEmptyMessage(disconnectedDueToRoaming
1412 ? EVENT_DATA_ROAMING_DISCONNECTED
1413 : EVENT_DATA_ROAMING_OK);
1414 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
1415 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG");
1416 if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0));
1417 if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name"));
1418 mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1);
1419 mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0));
1420 } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
1421 (mPUKEntryActivity != null)) {
1422 // if an attempt to un-PUK-lock the device was made, while we're
1423 // receiving this state change notification, notify the handler.
1424 // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
1425 // been attempted.
1426 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
1427 intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)));
1428 } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
1429 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
1430 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
1431 initForNewRadioTechnology();
1432 } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
1433 handleServiceStateChanged(intent);
1434 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1435 if (TelephonyCapabilities.supportsEcm(phone)) {
1436 Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
1437 // Start Emergency Callback Mode service
1438 if (intent.getBooleanExtra("phoneinECMState", false)) {
1439 context.startService(new Intent(context,
1440 EmergencyCallbackModeService.class));
1441 }
1442 } else {
1443 // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED
1444 // on a device that doesn't support ECM in the first place.
1445 Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, "
1446 + "but ECM isn't supported for phone: " + phone.getPhoneName());
1447 }
1448 } else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1449 mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1450 Intent.EXTRA_DOCK_STATE_UNDOCKED);
1451 if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState);
1452 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0));
1453 } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) {
1454 mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE,
1455 Phone.TTY_MODE_OFF);
1456 if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION");
1457 if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode);
1458 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1459 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
1460 int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
1461 AudioManager.RINGER_MODE_NORMAL);
1462 if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
1463 notifier.silenceRinger();
1464 }
1465 }
1466 }
1467 }
1468
1469 /**
1470 * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent.
1471 *
1472 * This functionality isn't lumped in with the other intents in
1473 * PhoneAppBroadcastReceiver because we instantiate this as a totally
1474 * separate BroadcastReceiver instance, since we need to manually
1475 * adjust its IntentFilter's priority (to make sure we get these
1476 * intents *before* the media player.)
1477 */
1478 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
1479 @Override
1480 public void onReceive(Context context, Intent intent) {
1481 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1482 if (VDBG) Log.d(LOG_TAG,
1483 "MediaButtonBroadcastReceiver.onReceive()... event = " + event);
1484 if ((event != null)
1485 && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1486 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK");
1487 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1488 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1489 if (consumed) {
1490 // If a headset is attached and the press is consumed, also update
1491 // any UI items (such as an InCallScreen mute button) that may need to
1492 // be updated if their state changed.
1493 updateInCallScreen(); // Has no effect if the InCallScreen isn't visible
1494 abortBroadcast();
1495 }
1496 } else {
1497 if (mCM.getState() != PhoneConstants.State.IDLE) {
1498 // If the phone is anything other than completely idle,
1499 // then we consume and ignore any media key events,
1500 // Otherwise it is too easy to accidentally start
1501 // playing music while a phone call is in progress.
1502 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed");
1503 abortBroadcast();
1504 }
1505 }
1506 }
1507 }
1508
1509 /**
1510 * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus
1511 * sent from framework's notification mechanism (which is outside Phone context).
1512 * This should be visible from outside, but shouldn't be in "exported" state.
1513 *
1514 * TODO: If possible merge this into PhoneAppBroadcastReceiver.
1515 */
1516 public static class NotificationBroadcastReceiver extends BroadcastReceiver {
1517 @Override
1518 public void onReceive(Context context, Intent intent) {
1519 String action = intent.getAction();
1520 // TODO: use "if (VDBG)" here.
1521 Log.d(LOG_TAG, "Broadcast from Notification: " + action);
1522
1523 if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) {
1524 PhoneUtils.hangup(PhoneGlobals.getInstance().mCM);
1525 } else if (action.equals(ACTION_CALL_BACK_FROM_NOTIFICATION)) {
1526 // Collapse the expanded notification and the notification item itself.
1527 closeSystemDialogs(context);
1528 clearMissedCallNotification(context);
1529
1530 Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData());
1531 callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1532 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1533 context.startActivity(callIntent);
1534 } else if (action.equals(ACTION_SEND_SMS_FROM_NOTIFICATION)) {
1535 // Collapse the expanded notification and the notification item itself.
1536 closeSystemDialogs(context);
1537 clearMissedCallNotification(context);
1538
1539 Intent smsIntent = new Intent(Intent.ACTION_SENDTO, intent.getData());
1540 smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1541 context.startActivity(smsIntent);
1542 } else {
1543 Log.w(LOG_TAG, "Received hang-up request from notification,"
1544 + " but there's no call the system can hang up.");
1545 }
1546 }
1547
1548 private void closeSystemDialogs(Context context) {
1549 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1550 context.sendBroadcastAsUser(intent, UserHandle.ALL);
1551 }
1552
1553 private void clearMissedCallNotification(Context context) {
1554 Intent clearIntent = new Intent(context, ClearMissedCallsService.class);
1555 clearIntent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
1556 context.startService(clearIntent);
1557 }
1558 }
1559
1560 private void handleServiceStateChanged(Intent intent) {
1561 /**
1562 * This used to handle updating EriTextWidgetProvider this routine
1563 * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
1564 * be removed. But leaving just in case it might be needed in the near
1565 * future.
1566 */
1567
1568 // If service just returned, start sending out the queued messages
1569 ServiceState ss = ServiceState.newFromBundle(intent.getExtras());
1570
1571 if (ss != null) {
1572 int state = ss.getState();
1573 notificationMgr.updateNetworkSelection(state);
1574 }
1575 }
1576
1577 public boolean isOtaCallInActiveState() {
1578 boolean otaCallActive = false;
1579 if (mInCallScreen != null) {
1580 otaCallActive = mInCallScreen.isOtaCallInActiveState();
1581 }
1582 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive);
1583 return otaCallActive;
1584 }
1585
1586 public boolean isOtaCallInEndState() {
1587 boolean otaCallEnded = false;
1588 if (mInCallScreen != null) {
1589 otaCallEnded = mInCallScreen.isOtaCallInEndState();
1590 }
1591 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded);
1592 return otaCallEnded;
1593 }
1594
1595 // it is safe to call clearOtaState() even if the InCallScreen isn't active
1596 public void clearOtaState() {
1597 if (DBG) Log.d(LOG_TAG, "- clearOtaState ...");
1598 if ((mInCallScreen != null)
1599 && (otaUtils != null)) {
1600 otaUtils.cleanOtaScreen(true);
1601 if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen");
1602 }
1603 }
1604
1605 // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active
1606 public void dismissOtaDialogs() {
1607 if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ...");
1608 if ((mInCallScreen != null)
1609 && (otaUtils != null)) {
1610 otaUtils.dismissAllOtaDialogs();
1611 if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs");
1612 }
1613 }
1614
1615 // it is safe to call clearInCallScreenMode() even if the InCallScreen isn't active
1616 public void clearInCallScreenMode() {
1617 if (DBG) Log.d(LOG_TAG, "- clearInCallScreenMode ...");
1618 if (mInCallScreen != null) {
1619 mInCallScreen.resetInCallScreenMode();
1620 }
1621 }
1622
1623 /**
1624 * Force the in-call UI to refresh itself, if it's currently visible.
1625 *
1626 * This method can be used any time there's a state change anywhere in
1627 * the phone app that needs to be reflected in the onscreen UI.
1628 *
1629 * Note that it's *not* necessary to manually refresh the in-call UI
1630 * (via this method) for regular telephony state changes like
1631 * DIALING -> ALERTING -> ACTIVE, since the InCallScreen already
1632 * listens for those state changes itself.
1633 *
1634 * This method does *not* force the in-call UI to come up if it's not
1635 * already visible. To do that, use displayCallScreen().
1636 */
1637 /* package */ void updateInCallScreen() {
1638 if (DBG) Log.d(LOG_TAG, "- updateInCallScreen()...");
1639 if (mInCallScreen != null) {
1640 // Post an updateScreen() request. Note that the
1641 // updateScreen() call will end up being a no-op if the
1642 // InCallScreen isn't the foreground activity.
1643 mInCallScreen.requestUpdateScreen();
1644 }
1645 }
1646
1647 private void handleQueryTTYModeResponse(Message msg) {
1648 AsyncResult ar = (AsyncResult) msg.obj;
1649 if (ar.exception != null) {
1650 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state.");
1651 } else {
1652 if (DBG) Log.d(LOG_TAG,
1653 "handleQueryTTYModeResponse: TTY enable state successfully queried.");
1654
1655 int ttymode = ((int[]) ar.result)[0];
1656 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode);
1657
1658 Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION);
1659 ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF);
1660 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1661
1662 String audioTtyMode;
1663 switch (ttymode) {
1664 case Phone.TTY_MODE_FULL:
1665 audioTtyMode = "tty_full";
1666 break;
1667 case Phone.TTY_MODE_VCO:
1668 audioTtyMode = "tty_vco";
1669 break;
1670 case Phone.TTY_MODE_HCO:
1671 audioTtyMode = "tty_hco";
1672 break;
1673 case Phone.TTY_MODE_OFF:
1674 default:
1675 audioTtyMode = "tty_off";
1676 break;
1677 }
1678 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1679 audioManager.setParameters("tty_mode="+audioTtyMode);
1680 }
1681 }
1682
1683 private void handleSetTTYModeResponse(Message msg) {
1684 AsyncResult ar = (AsyncResult) msg.obj;
1685
1686 if (ar.exception != null) {
1687 if (DBG) Log.d (LOG_TAG,
1688 "handleSetTTYModeResponse: Error setting TTY mode, ar.exception"
1689 + ar.exception);
1690 }
1691 phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET));
1692 }
1693
1694 /**
1695 * "Call origin" may be used by Contacts app to specify where the phone call comes from.
1696 * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}.
1697 * Any other value will be ignored, to make sure that malicious apps can't trick the in-call
1698 * UI into launching some random other app after a call ends.
1699 *
1700 * TODO: make this more generic. Note that we should let the "origin" specify its package
1701 * while we are now assuming it is "com.android.contacts"
1702 */
1703 public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
1704 private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.dialer";
1705 private static final String ALLOWED_EXTRA_CALL_ORIGIN =
1706 "com.android.dialer.DialtactsActivity";
1707 /**
1708 * Used to determine if the preserved call origin is fresh enough.
1709 */
1710 private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000;
1711
1712 public void setLatestActiveCallOrigin(String callOrigin) {
1713 inCallUiState.latestActiveCallOrigin = callOrigin;
1714 if (callOrigin != null) {
1715 inCallUiState.latestActiveCallOriginTimeStamp = SystemClock.elapsedRealtime();
1716 } else {
1717 inCallUiState.latestActiveCallOriginTimeStamp = 0;
1718 }
1719 }
1720
1721 /**
1722 * Reset call origin depending on its timestamp.
1723 *
1724 * See if the current call origin preserved by the app is fresh enough or not. If it is,
1725 * previous call origin will be used as is. If not, call origin will be reset.
1726 *
1727 * This will be effective especially for 3rd party apps which want to bypass phone calls with
1728 * their own telephone lines. In that case Phone app may finish the phone call once and make
1729 * another for the external apps, which will drop call origin information in Intent.
1730 * Even in that case we are sure the second phone call should be initiated just after the first
1731 * phone call, so here we restore it from the previous information iff the second call is done
1732 * fairly soon.
1733 */
1734 public void resetLatestActiveCallOrigin() {
1735 final long callOriginTimestamp = inCallUiState.latestActiveCallOriginTimeStamp;
1736 final long currentTimestamp = SystemClock.elapsedRealtime();
1737 if (VDBG) {
1738 Log.d(LOG_TAG, "currentTimeMillis: " + currentTimestamp
1739 + ", saved timestamp for call origin: " + callOriginTimestamp);
1740 }
1741 if (inCallUiState.latestActiveCallOriginTimeStamp > 0
1742 && (currentTimestamp - callOriginTimestamp < CALL_ORIGIN_EXPIRATION_MILLIS)) {
1743 if (VDBG) {
1744 Log.d(LOG_TAG, "Resume previous call origin (" +
1745 inCallUiState.latestActiveCallOrigin + ")");
1746 }
1747 // Do nothing toward call origin itself but update the timestamp just in case.
1748 inCallUiState.latestActiveCallOriginTimeStamp = currentTimestamp;
1749 } else {
1750 if (VDBG) Log.d(LOG_TAG, "Drop previous call origin and set the current one to null");
1751 setLatestActiveCallOrigin(null);
1752 }
1753 }
1754
1755 /**
1756 * @return Intent which will be used when in-call UI is shown and the phone call is hang up.
1757 * By default CallLog screen will be introduced, but the destination may change depending on
1758 * its latest call origin state.
1759 */
1760 public Intent createPhoneEndIntentUsingCallOrigin() {
1761 if (TextUtils.equals(inCallUiState.latestActiveCallOrigin, ALLOWED_EXTRA_CALL_ORIGIN)) {
1762 if (VDBG) Log.d(LOG_TAG, "Valid latestActiveCallOrigin("
1763 + inCallUiState.latestActiveCallOrigin + ") was found. "
1764 + "Go back to the previous screen.");
1765 // Right now we just launch the Activity which launched in-call UI. Note that we're
1766 // assuming the origin is from "com.android.dialer", which may be incorrect in the
1767 // future.
1768 final Intent intent = new Intent();
1769 intent.setClassName(DEFAULT_CALL_ORIGIN_PACKAGE, inCallUiState.latestActiveCallOrigin);
1770 return intent;
1771 } else {
1772 if (VDBG) Log.d(LOG_TAG, "Current latestActiveCallOrigin ("
1773 + inCallUiState.latestActiveCallOrigin + ") is not valid. "
1774 + "Just use CallLog as a default destination.");
1775 return PhoneGlobals.createCallLogIntent();
1776 }
1777 }
1778
1779 /** Service connection */
1780 private final ServiceConnection mBluetoothPhoneConnection = new ServiceConnection() {
1781
1782 /** Handle the task of binding the local object to the service */
1783 public void onServiceConnected(ComponentName className, IBinder service) {
1784 Log.i(LOG_TAG, "Headset phone created, binding local service.");
1785 mBluetoothPhone = IBluetoothHeadsetPhone.Stub.asInterface(service);
1786 }
1787
1788 /** Handle the task of cleaning up the local binding */
1789 public void onServiceDisconnected(ComponentName className) {
1790 Log.i(LOG_TAG, "Headset phone disconnected, cleaning local binding.");
1791 mBluetoothPhone = null;
1792 }
1793 };
1794}