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