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