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