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