blob: 865ad75ca8cdc43458de4d5e10652534d3ccd88d [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() {
Chiao Cheng7f7c6522013-07-16 18:39:35 -0700765 //InCallScreen.class.getName();
766 return "blah";
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700767 }
768
769 /**
770 * Starts the InCallScreen Activity.
771 */
772 /* package */ void displayCallScreen() {
773 if (VDBG) Log.d(LOG_TAG, "displayCallScreen()...");
774
775 // On non-voice-capable devices we shouldn't ever be trying to
776 // bring up the InCallScreen in the first place.
777 if (!sVoiceCapable) {
778 Log.w(LOG_TAG, "displayCallScreen() not allowed: non-voice-capable device",
779 new Throwable("stack dump")); // Include a stack trace since this warning
780 // indicates a bug in our caller
781 return;
782 }
783
784 try {
Chiao Cheng7f7c6522013-07-16 18:39:35 -0700785 //startActivity(createInCallIntent());
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700786 } catch (ActivityNotFoundException e) {
787 // It's possible that the in-call UI might not exist (like on
788 // non-voice-capable devices), so don't crash if someone
789 // accidentally tries to bring it up...
790 Log.w(LOG_TAG, "displayCallScreen: transition to InCallScreen failed: " + e);
791 }
792 Profiler.callScreenRequested();
793 }
794
795 boolean isSimPinEnabled() {
796 return mIsSimPinEnabled;
797 }
798
799 boolean authenticateAgainstCachedSimPin(String pin) {
800 return (mCachedSimPin != null && mCachedSimPin.equals(pin));
801 }
802
803 void setCachedSimPin(String pin) {
804 mCachedSimPin = pin;
805 }
806
807 void setInCallScreenInstance(InCallScreen inCallScreen) {
808 mInCallScreen = inCallScreen;
809 }
810
811 /**
812 * @return true if the in-call UI is running as the foreground
813 * activity. (In other words, from the perspective of the
814 * InCallScreen activity, return true between onResume() and
815 * onPause().)
816 *
817 * Note this method will return false if the screen is currently off,
818 * even if the InCallScreen *was* in the foreground just before the
819 * screen turned off. (This is because the foreground activity is
820 * always "paused" while the screen is off.)
821 */
822 boolean isShowingCallScreen() {
823 if (mInCallScreen == null) return false;
824 return mInCallScreen.isForegroundActivity();
825 }
826
827 /**
828 * @return true if the in-call UI is running as the foreground activity, or,
829 * it went to background due to screen being turned off. This might be useful
830 * to determine if the in-call screen went to background because of other
831 * activities, or its proximity sensor state or manual power-button press.
832 *
833 * Here are some examples.
834 *
835 * - If you want to know if the activity is in foreground or screen is turned off
836 * from the in-call UI (i.e. though it is not "foreground" anymore it will become
837 * so after screen being turned on), check
838 * {@link #isShowingCallScreenForProximity()} is true or not.
839 * {@link #updateProximitySensorMode(com.android.internal.telephony.PhoneConstants.State)} is
840 * doing this.
841 *
842 * - If you want to know if the activity is not in foreground just because screen
843 * is turned off (not due to other activity's interference), check
844 * {@link #isShowingCallScreen()} is false *and* {@link #isShowingCallScreenForProximity()}
845 * is true. InCallScreen#onDisconnect() is doing this check.
846 *
847 * @see #isShowingCallScreen()
848 *
849 * TODO: come up with better naming..
850 */
851 boolean isShowingCallScreenForProximity() {
852 if (mInCallScreen == null) return false;
853 return mInCallScreen.isForegroundActivityForProximity();
854 }
855
856 /**
857 * Dismisses the in-call UI.
858 *
859 * This also ensures that you won't be able to get back to the in-call
860 * UI via the BACK button (since this call removes the InCallScreen
861 * from the activity history.)
862 * For OTA Call, it call InCallScreen api to handle OTA Call End scenario
863 * to display OTA Call End screen.
864 */
865 /* package */ void dismissCallScreen() {
866 if (mInCallScreen != null) {
867 if ((TelephonyCapabilities.supportsOtasp(phone)) &&
868 (mInCallScreen.isOtaCallInActiveState()
869 || mInCallScreen.isOtaCallInEndState()
870 || ((cdmaOtaScreenState != null)
871 && (cdmaOtaScreenState.otaScreenState
872 != CdmaOtaScreenState.OtaScreenState.OTA_STATUS_UNDEFINED)))) {
873 // TODO: During OTA Call, display should not become dark to
874 // allow user to see OTA UI update. Phone app needs to hold
875 // a SCREEN_DIM_WAKE_LOCK wake lock during the entire OTA call.
876 wakeUpScreen();
877 // If InCallScreen is not in foreground we resume it to show the OTA call end screen
878 // Fire off the InCallScreen intent
879 displayCallScreen();
880
881 mInCallScreen.handleOtaCallEnd();
882 return;
883 } else {
884 mInCallScreen.finish();
885 }
886 }
887 }
888
889 /**
890 * Handles OTASP-related events from the telephony layer.
891 *
892 * While an OTASP call is active, the CallNotifier forwards
893 * OTASP-related telephony events to this method.
894 */
895 void handleOtaspEvent(Message msg) {
896 if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")...");
897
898 if (otaUtils == null) {
899 // We shouldn't be getting OTASP events without ever
900 // having started the OTASP call in the first place!
901 Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! "
902 + "message = " + msg);
903 return;
904 }
905
906 otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
907 }
908
909 /**
910 * Similarly, handle the disconnect event of an OTASP call
911 * by forwarding it to the OtaUtils instance.
912 */
913 /* package */ void handleOtaspDisconnect() {
914 if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()...");
915
916 if (otaUtils == null) {
917 // We shouldn't be getting OTASP events without ever
918 // having started the OTASP call in the first place!
919 Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!");
920 return;
921 }
922
923 otaUtils.onOtaspDisconnect();
924 }
925
926 /**
927 * Sets the activity responsible for un-PUK-blocking the device
928 * so that we may close it when we receive a positive result.
929 * mPUKEntryActivity is also used to indicate to the device that
930 * we are trying to un-PUK-lock the phone. In other words, iff
931 * it is NOT null, then we are trying to unlock and waiting for
932 * the SIM to move to READY state.
933 *
934 * @param activity is the activity to close when PUK has
935 * finished unlocking. Can be set to null to indicate the unlock
936 * or SIM READYing process is over.
937 */
938 void setPukEntryActivity(Activity activity) {
939 mPUKEntryActivity = activity;
940 }
941
942 Activity getPUKEntryActivity() {
943 return mPUKEntryActivity;
944 }
945
946 /**
947 * Sets the dialog responsible for notifying the user of un-PUK-
948 * blocking - SIM READYing progress, so that we may dismiss it
949 * when we receive a positive result.
950 *
951 * @param dialog indicates the progress dialog informing the user
952 * of the state of the device. Dismissed upon completion of
953 * READYing process
954 */
955 void setPukEntryProgressDialog(ProgressDialog dialog) {
956 mPUKEntryProgressDialog = dialog;
957 }
958
959 ProgressDialog getPUKEntryProgressDialog() {
960 return mPUKEntryProgressDialog;
961 }
962
963 /**
964 * Controls whether or not the screen is allowed to sleep.
965 *
966 * Once sleep is allowed (WakeState is SLEEP), it will rely on the
967 * settings for the poke lock to determine when to timeout and let
968 * the device sleep {@link PhoneGlobals#setScreenTimeout}.
969 *
970 * @param ws tells the device to how to wake.
971 */
972 /* package */ void requestWakeState(WakeState ws) {
973 if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
974 synchronized (this) {
975 if (mWakeState != ws) {
976 switch (ws) {
977 case PARTIAL:
978 // acquire the processor wake lock, and release the FULL
979 // lock if it is being held.
980 mPartialWakeLock.acquire();
981 if (mWakeLock.isHeld()) {
982 mWakeLock.release();
983 }
984 break;
985 case FULL:
986 // acquire the full wake lock, and release the PARTIAL
987 // lock if it is being held.
988 mWakeLock.acquire();
989 if (mPartialWakeLock.isHeld()) {
990 mPartialWakeLock.release();
991 }
992 break;
993 case SLEEP:
994 default:
995 // release both the PARTIAL and FULL locks.
996 if (mWakeLock.isHeld()) {
997 mWakeLock.release();
998 }
999 if (mPartialWakeLock.isHeld()) {
1000 mPartialWakeLock.release();
1001 }
1002 break;
1003 }
1004 mWakeState = ws;
1005 }
1006 }
1007 }
1008
1009 /**
1010 * If we are not currently keeping the screen on, then poke the power
1011 * manager to wake up the screen for the user activity timeout duration.
1012 */
1013 /* package */ void wakeUpScreen() {
1014 synchronized (this) {
1015 if (mWakeState == WakeState.SLEEP) {
1016 if (DBG) Log.d(LOG_TAG, "pulse screen lock");
1017 mPowerManager.wakeUp(SystemClock.uptimeMillis());
1018 }
1019 }
1020 }
1021
1022 /**
1023 * Sets the wake state and screen timeout based on the current state
1024 * of the phone, and the current state of the in-call UI.
1025 *
1026 * This method is a "UI Policy" wrapper around
1027 * {@link PhoneGlobals#requestWakeState} and {@link PhoneGlobals#setScreenTimeout}.
1028 *
1029 * It's safe to call this method regardless of the state of the Phone
1030 * (e.g. whether or not it's idle), and regardless of the state of the
1031 * Phone UI (e.g. whether or not the InCallScreen is active.)
1032 */
1033 /* package */ void updateWakeState() {
1034 PhoneConstants.State state = mCM.getState();
1035
1036 // True if the in-call UI is the foreground activity.
1037 // (Note this will be false if the screen is currently off,
1038 // since in that case *no* activity is in the foreground.)
1039 boolean isShowingCallScreen = isShowingCallScreen();
1040
1041 // True if the InCallScreen's DTMF dialer is currently opened.
1042 // (Note this does NOT imply whether or not the InCallScreen
1043 // itself is visible.)
1044 boolean isDialerOpened = (mInCallScreen != null) && mInCallScreen.isDialerOpened();
1045
1046 // True if the speakerphone is in use. (If so, we *always* use
1047 // the default timeout. Since the user is obviously not holding
1048 // the phone up to his/her face, we don't need to worry about
1049 // false touches, and thus don't need to turn the screen off so
1050 // aggressively.)
1051 // Note that we need to make a fresh call to this method any
1052 // time the speaker state changes. (That happens in
1053 // PhoneUtils.turnOnSpeaker().)
1054 boolean isSpeakerInUse = (state == PhoneConstants.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
1055
1056 // TODO (bug 1440854): The screen timeout *might* also need to
1057 // depend on the bluetooth state, but this isn't as clear-cut as
1058 // the speaker state (since while using BT it's common for the
1059 // user to put the phone straight into a pocket, in which case the
1060 // timeout should probably still be short.)
1061
1062 if (DBG) Log.d(LOG_TAG, "updateWakeState: callscreen " + isShowingCallScreen
1063 + ", dialer " + isDialerOpened
1064 + ", speaker " + isSpeakerInUse + "...");
1065
1066 //
1067 // Decide whether to force the screen on or not.
1068 //
1069 // Force the screen to be on if the phone is ringing or dialing,
1070 // or if we're displaying the "Call ended" UI for a connection in
1071 // the "disconnected" state.
1072 // However, if the phone is disconnected while the user is in the
1073 // middle of selecting a quick response message, we should not force
1074 // the screen to be on.
1075 //
1076 boolean isRinging = (state == PhoneConstants.State.RINGING);
1077 boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING);
1078 boolean showingQuickResponseDialog = (mInCallScreen != null) &&
1079 mInCallScreen.isQuickResponseDialogShowing();
1080 boolean showingDisconnectedConnection =
1081 PhoneUtils.hasDisconnectedConnections(phone) && isShowingCallScreen;
1082 boolean keepScreenOn = isRinging || isDialing ||
1083 (showingDisconnectedConnection && !showingQuickResponseDialog);
1084 if (DBG) Log.d(LOG_TAG, "updateWakeState: keepScreenOn = " + keepScreenOn
1085 + " (isRinging " + isRinging
1086 + ", isDialing " + isDialing
1087 + ", showingQuickResponse " + showingQuickResponseDialog
1088 + ", showingDisc " + showingDisconnectedConnection + ")");
1089 // keepScreenOn == true means we'll hold a full wake lock:
1090 requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
1091 }
1092
1093 /**
1094 * Manually pokes the PowerManager's userActivity method. Since we
1095 * set the {@link WindowManager.LayoutParams#INPUT_FEATURE_DISABLE_USER_ACTIVITY}
1096 * flag while the InCallScreen is active when there is no proximity sensor,
1097 * we need to do this for touch events that really do count as user activity
1098 * (like pressing any onscreen UI elements.)
1099 */
1100 /* package */ void pokeUserActivity() {
1101 if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
1102 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
1103 }
1104
1105 /**
1106 * Set when a new outgoing call is beginning, so we can update
1107 * the proximity sensor state.
1108 * Cleared when the InCallScreen is no longer in the foreground,
1109 * in case the call fails without changing the telephony state.
1110 */
1111 /* package */ void setBeginningCall(boolean beginning) {
1112 // Note that we are beginning a new call, for proximity sensor support
1113 mBeginningCall = beginning;
1114 // Update the Proximity sensor based on mBeginningCall state
1115 updateProximitySensorMode(mCM.getState());
1116 }
1117
1118 /**
1119 * Updates the wake lock used to control proximity sensor behavior,
1120 * based on the current state of the phone. This method is called
1121 * from the CallNotifier on any phone state change.
1122 *
1123 * On devices that have a proximity sensor, to avoid false touches
1124 * during a call, we hold a PROXIMITY_SCREEN_OFF_WAKE_LOCK wake lock
1125 * whenever the phone is off hook. (When held, that wake lock causes
1126 * the screen to turn off automatically when the sensor detects an
1127 * object close to the screen.)
1128 *
1129 * This method is a no-op for devices that don't have a proximity
1130 * sensor.
1131 *
1132 * Note this method doesn't care if the InCallScreen is the foreground
1133 * activity or not. That's because we want the proximity sensor to be
1134 * enabled any time the phone is in use, to avoid false cheek events
1135 * for whatever app you happen to be running.
1136 *
1137 * Proximity wake lock will *not* be held if any one of the
1138 * conditions is true while on a call:
1139 * 1) If the audio is routed via Bluetooth
1140 * 2) If a wired headset is connected
1141 * 3) if the speaker is ON
1142 * 4) If the slider is open(i.e. the hardkeyboard is *not* hidden)
1143 *
1144 * @param state current state of the phone (see {@link Phone#State})
1145 */
1146 /* package */ void updateProximitySensorMode(PhoneConstants.State state) {
1147 if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: state = " + state);
1148
1149 if (proximitySensorModeEnabled()) {
1150 synchronized (mProximityWakeLock) {
1151 // turn proximity sensor off and turn screen on immediately if
1152 // we are using a headset, the keyboard is open, or the device
1153 // is being held in a horizontal position.
1154 boolean screenOnImmediately = (isHeadsetPlugged()
1155 || PhoneUtils.isSpeakerOn(this)
1156 || isBluetoothHeadsetAudioOn()
1157 || mIsHardKeyboardOpen);
1158
1159 // We do not keep the screen off when the user is outside in-call screen and we are
1160 // horizontal, but we do not force it on when we become horizontal until the
1161 // proximity sensor goes negative.
1162 boolean horizontal =
1163 (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL);
1164 screenOnImmediately |= !isShowingCallScreenForProximity() && horizontal;
1165
1166 // We do not keep the screen off when dialpad is visible, we are horizontal, and
1167 // the in-call screen is being shown.
1168 // At that moment we're pretty sure users want to use it, instead of letting the
1169 // proximity sensor turn off the screen by their hands.
1170 boolean dialpadVisible = false;
1171 if (mInCallScreen != null) {
1172 dialpadVisible =
1173 mInCallScreen.getUpdatedInCallControlState().dialpadEnabled
1174 && mInCallScreen.getUpdatedInCallControlState().dialpadVisible
1175 && isShowingCallScreen();
1176 }
1177 screenOnImmediately |= dialpadVisible && horizontal;
1178
1179 if (((state == PhoneConstants.State.OFFHOOK) || mBeginningCall) && !screenOnImmediately) {
1180 // Phone is in use! Arrange for the screen to turn off
1181 // automatically when the sensor detects a close object.
1182 if (!mProximityWakeLock.isHeld()) {
1183 if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: acquiring...");
1184 mProximityWakeLock.acquire();
1185 } else {
1186 if (VDBG) Log.d(LOG_TAG, "updateProximitySensorMode: lock already held.");
1187 }
1188 } else {
1189 // Phone is either idle, or ringing. We don't want any
1190 // special proximity sensor behavior in either case.
1191 if (mProximityWakeLock.isHeld()) {
1192 if (DBG) Log.d(LOG_TAG, "updateProximitySensorMode: releasing...");
1193 // Wait until user has moved the phone away from his head if we are
1194 // releasing due to the phone call ending.
1195 // Qtherwise, turn screen on immediately
1196 int flags =
1197 (screenOnImmediately ? 0 : PowerManager.WAIT_FOR_PROXIMITY_NEGATIVE);
1198 mProximityWakeLock.release(flags);
1199 } else {
1200 if (VDBG) {
1201 Log.d(LOG_TAG, "updateProximitySensorMode: lock already released.");
1202 }
1203 }
1204 }
1205 }
1206 }
1207 }
1208
1209 @Override
1210 public void orientationChanged(int orientation) {
1211 mOrientation = orientation;
1212 updateProximitySensorMode(mCM.getState());
1213 }
1214
1215 /**
1216 * Notifies the phone app when the phone state changes.
1217 *
1218 * This method will updates various states inside Phone app (e.g. proximity sensor mode,
1219 * accelerometer listener state, update-lock state, etc.)
1220 */
1221 /* package */ void updatePhoneState(PhoneConstants.State state) {
1222 if (state != mLastPhoneState) {
1223 mLastPhoneState = state;
1224 updateProximitySensorMode(state);
1225
1226 // Try to acquire or release UpdateLock.
1227 //
1228 // Watch out: we don't release the lock here when the screen is still in foreground.
1229 // At that time InCallScreen will release it on onPause().
1230 if (state != PhoneConstants.State.IDLE) {
1231 // UpdateLock is a recursive lock, while we may get "acquire" request twice and
1232 // "release" request once for a single call (RINGING + OFFHOOK and IDLE).
1233 // We need to manually ensure the lock is just acquired once for each (and this
1234 // will prevent other possible buggy situations too).
1235 if (!mUpdateLock.isHeld()) {
1236 mUpdateLock.acquire();
1237 }
1238 } else {
1239 if (!isShowingCallScreen()) {
1240 if (!mUpdateLock.isHeld()) {
1241 mUpdateLock.release();
1242 }
1243 } else {
1244 // For this case InCallScreen will take care of the release() call.
1245 }
1246 }
1247
1248 if (mAccelerometerListener != null) {
1249 // use accelerometer to augment proximity sensor when in call
1250 mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN;
1251 mAccelerometerListener.enable(state == PhoneConstants.State.OFFHOOK);
1252 }
1253 // clear our beginning call flag
1254 mBeginningCall = false;
1255 // While we are in call, the in-call screen should dismiss the keyguard.
1256 // This allows the user to press Home to go directly home without going through
1257 // an insecure lock screen.
1258 // But we do not want to do this if there is no active call so we do not
1259 // bypass the keyguard if the call is not answered or declined.
1260 if (mInCallScreen != null) {
1261 mInCallScreen.updateKeyguardPolicy(state == PhoneConstants.State.OFFHOOK);
1262 }
1263 }
1264 }
1265
1266 /* package */ PhoneConstants.State getPhoneState() {
1267 return mLastPhoneState;
1268 }
1269
1270 /**
1271 * Returns UpdateLock object.
1272 */
1273 /* package */ UpdateLock getUpdateLock() {
1274 return mUpdateLock;
1275 }
1276
1277 /**
1278 * @return true if this device supports the "proximity sensor
1279 * auto-lock" feature while in-call (see updateProximitySensorMode()).
1280 */
1281 /* package */ boolean proximitySensorModeEnabled() {
1282 return (mProximityWakeLock != null);
1283 }
1284
1285 KeyguardManager getKeyguardManager() {
1286 return mKeyguardManager;
1287 }
1288
1289 private void onMMIComplete(AsyncResult r) {
1290 if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
1291 MmiCode mmiCode = (MmiCode) r.result;
1292 PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null);
1293 }
1294
1295 private void initForNewRadioTechnology() {
1296 if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
1297
1298 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1299 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
1300 cdmaPhoneCallState = new CdmaPhoneCallState();
1301 cdmaPhoneCallState.CdmaPhoneCallStateInit();
1302 }
1303 if (TelephonyCapabilities.supportsOtasp(phone)) {
1304 //create instances of CDMA OTA data classes
1305 if (cdmaOtaProvisionData == null) {
1306 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
1307 }
1308 if (cdmaOtaConfigData == null) {
1309 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
1310 }
1311 if (cdmaOtaScreenState == null) {
1312 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
1313 }
1314 if (cdmaOtaInCallScreenUiState == null) {
1315 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
1316 }
1317 } else {
1318 //Clean up OTA data in GSM/UMTS. It is valid only for CDMA
1319 clearOtaState();
1320 }
1321
1322 ringer.updateRingerContextAfterRadioTechnologyChange(this.phone);
1323 notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
1324 callStateMonitor.updateAfterRadioTechnologyChange();
1325
1326 if (mBluetoothPhone != null) {
1327 try {
1328 mBluetoothPhone.updateBtHandsfreeAfterRadioTechnologyChange();
1329 } catch (RemoteException e) {
1330 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
1331 }
1332 }
1333 if (mInCallScreen != null) {
1334 mInCallScreen.updateAfterRadioTechnologyChange();
1335 }
1336
1337 // Update registration for ICC status after radio technology change
1338 IccCard sim = phone.getIccCard();
1339 if (sim != null) {
1340 if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
1341
1342 //Register all events new to the new active phone
1343 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
1344 }
1345 }
1346
1347
1348 /**
1349 * @return true if a wired headset is currently plugged in.
1350 *
1351 * @see Intent.ACTION_HEADSET_PLUG (which we listen for in mReceiver.onReceive())
1352 */
1353 boolean isHeadsetPlugged() {
1354 return mIsHeadsetPlugged;
1355 }
1356
1357 /**
1358 * @return true if the onscreen UI should currently be showing the
1359 * special "bluetooth is active" indication in a couple of places (in
1360 * which UI elements turn blue and/or show the bluetooth logo.)
1361 *
1362 * This depends on the BluetoothHeadset state *and* the current
1363 * telephony state; see shouldShowBluetoothIndication().
1364 *
1365 * @see CallCard
1366 * @see NotificationMgr.updateInCallNotification
1367 */
1368 /* package */ boolean showBluetoothIndication() {
1369 return mShowBluetoothIndication;
1370 }
1371
1372 /**
1373 * Recomputes the mShowBluetoothIndication flag based on the current
1374 * bluetooth state and current telephony state.
1375 *
1376 * This needs to be called any time the bluetooth headset state or the
1377 * telephony state changes.
1378 *
1379 * @param forceUiUpdate if true, force the UI elements that care
1380 * about this flag to update themselves.
1381 */
1382 /* package */ void updateBluetoothIndication(boolean forceUiUpdate) {
1383 mShowBluetoothIndication = shouldShowBluetoothIndication(mBluetoothHeadsetState,
1384 mBluetoothHeadsetAudioState,
1385 mCM);
1386 if (forceUiUpdate) {
1387 // Post Handler messages to the various components that might
1388 // need to be refreshed based on the new state.
1389 if (isShowingCallScreen()) mInCallScreen.requestUpdateBluetoothIndication();
1390 if (DBG) Log.d (LOG_TAG, "- updating in-call notification for BT state change...");
1391 mHandler.sendEmptyMessage(EVENT_UPDATE_INCALL_NOTIFICATION);
1392 }
1393
1394 // Update the Proximity sensor based on Bluetooth audio state
1395 updateProximitySensorMode(mCM.getState());
1396 }
1397
1398 /**
1399 * UI policy helper function for the couple of places in the UI that
1400 * have some way of indicating that "bluetooth is in use."
1401 *
1402 * @return true if the onscreen UI should indicate that "bluetooth is in use",
1403 * based on the specified bluetooth headset state, and the
1404 * current state of the phone.
1405 * @see showBluetoothIndication()
1406 */
1407 private static boolean shouldShowBluetoothIndication(int bluetoothState,
1408 int bluetoothAudioState,
1409 CallManager cm) {
1410 // We want the UI to indicate that "bluetooth is in use" in two
1411 // slightly different cases:
1412 //
1413 // (a) The obvious case: if a bluetooth headset is currently in
1414 // use for an ongoing call.
1415 //
1416 // (b) The not-so-obvious case: if an incoming call is ringing,
1417 // and we expect that audio *will* be routed to a bluetooth
1418 // headset once the call is answered.
1419
1420 switch (cm.getState()) {
1421 case OFFHOOK:
1422 // This covers normal active calls, and also the case if
1423 // the foreground call is DIALING or ALERTING. In this
1424 // case, bluetooth is considered "active" if a headset
1425 // is connected *and* audio is being routed to it.
1426 return ((bluetoothState == BluetoothHeadset.STATE_CONNECTED)
1427 && (bluetoothAudioState == BluetoothHeadset.STATE_AUDIO_CONNECTED));
1428
1429 case RINGING:
1430 // If an incoming call is ringing, we're *not* yet routing
1431 // audio to the headset (since there's no in-call audio
1432 // yet!) In this case, if a bluetooth headset is
1433 // connected at all, we assume that it'll become active
1434 // once the user answers the phone.
1435 return (bluetoothState == BluetoothHeadset.STATE_CONNECTED);
1436
1437 default: // Presumably IDLE
1438 return false;
1439 }
1440 }
1441
1442
1443 /**
1444 * Receiver for misc intent broadcasts the Phone app cares about.
1445 */
1446 private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
1447 @Override
1448 public void onReceive(Context context, Intent intent) {
1449 String action = intent.getAction();
1450 if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
1451 boolean enabled = System.getInt(getContentResolver(),
1452 System.AIRPLANE_MODE_ON, 0) == 0;
1453 phone.setRadioPower(enabled);
1454 } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
1455 mBluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
1456 BluetoothHeadset.STATE_DISCONNECTED);
1457 if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION");
1458 if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState);
1459 updateBluetoothIndication(true); // Also update any visible UI if necessary
1460 } else if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
1461 mBluetoothHeadsetAudioState =
1462 intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
1463 BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
1464 if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_AUDIO_STATE_CHANGED_ACTION");
1465 if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetAudioState);
1466 updateBluetoothIndication(true); // Also update any visible UI if necessary
1467 } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
1468 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
1469 if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(PhoneConstants.STATE_KEY));
1470 if (VDBG) Log.d(LOG_TAG, "- reason: "
1471 + intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1472
1473 // The "data disconnected due to roaming" notification is shown
1474 // if (a) you have the "data roaming" feature turned off, and
1475 // (b) you just lost data connectivity because you're roaming.
1476 boolean disconnectedDueToRoaming =
1477 !phone.getDataRoamingEnabled()
1478 && "DISCONNECTED".equals(intent.getStringExtra(PhoneConstants.STATE_KEY))
1479 && Phone.REASON_ROAMING_ON.equals(
1480 intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1481 mHandler.sendEmptyMessage(disconnectedDueToRoaming
1482 ? EVENT_DATA_ROAMING_DISCONNECTED
1483 : EVENT_DATA_ROAMING_OK);
1484 } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
1485 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_HEADSET_PLUG");
1486 if (VDBG) Log.d(LOG_TAG, " state: " + intent.getIntExtra("state", 0));
1487 if (VDBG) Log.d(LOG_TAG, " name: " + intent.getStringExtra("name"));
1488 mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1);
1489 mHandler.sendMessage(mHandler.obtainMessage(EVENT_WIRED_HEADSET_PLUG, 0));
1490 } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
1491 (mPUKEntryActivity != null)) {
1492 // if an attempt to un-PUK-lock the device was made, while we're
1493 // receiving this state change notification, notify the handler.
1494 // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
1495 // been attempted.
1496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
1497 intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)));
1498 } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
1499 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
1500 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
1501 initForNewRadioTechnology();
1502 } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
1503 handleServiceStateChanged(intent);
1504 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1505 if (TelephonyCapabilities.supportsEcm(phone)) {
1506 Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
1507 // Start Emergency Callback Mode service
1508 if (intent.getBooleanExtra("phoneinECMState", false)) {
1509 context.startService(new Intent(context,
1510 EmergencyCallbackModeService.class));
1511 }
1512 } else {
1513 // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED
1514 // on a device that doesn't support ECM in the first place.
1515 Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, "
1516 + "but ECM isn't supported for phone: " + phone.getPhoneName());
1517 }
1518 } else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1519 mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1520 Intent.EXTRA_DOCK_STATE_UNDOCKED);
1521 if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState);
1522 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0));
1523 } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) {
1524 mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE,
1525 Phone.TTY_MODE_OFF);
1526 if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION");
1527 if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode);
1528 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1529 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
1530 int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
1531 AudioManager.RINGER_MODE_NORMAL);
1532 if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
1533 notifier.silenceRinger();
1534 }
1535 }
1536 }
1537 }
1538
1539 /**
1540 * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent.
1541 *
1542 * This functionality isn't lumped in with the other intents in
1543 * PhoneAppBroadcastReceiver because we instantiate this as a totally
1544 * separate BroadcastReceiver instance, since we need to manually
1545 * adjust its IntentFilter's priority (to make sure we get these
1546 * intents *before* the media player.)
1547 */
1548 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
1549 @Override
1550 public void onReceive(Context context, Intent intent) {
1551 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1552 if (VDBG) Log.d(LOG_TAG,
1553 "MediaButtonBroadcastReceiver.onReceive()... event = " + event);
1554 if ((event != null)
1555 && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1556 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK");
1557 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1558 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1559 if (consumed) {
1560 // If a headset is attached and the press is consumed, also update
1561 // any UI items (such as an InCallScreen mute button) that may need to
1562 // be updated if their state changed.
1563 updateInCallScreen(); // Has no effect if the InCallScreen isn't visible
1564 abortBroadcast();
1565 }
1566 } else {
1567 if (mCM.getState() != PhoneConstants.State.IDLE) {
1568 // If the phone is anything other than completely idle,
1569 // then we consume and ignore any media key events,
1570 // Otherwise it is too easy to accidentally start
1571 // playing music while a phone call is in progress.
1572 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed");
1573 abortBroadcast();
1574 }
1575 }
1576 }
1577 }
1578
1579 /**
1580 * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus
1581 * sent from framework's notification mechanism (which is outside Phone context).
1582 * This should be visible from outside, but shouldn't be in "exported" state.
1583 *
1584 * TODO: If possible merge this into PhoneAppBroadcastReceiver.
1585 */
1586 public static class NotificationBroadcastReceiver extends BroadcastReceiver {
1587 @Override
1588 public void onReceive(Context context, Intent intent) {
1589 String action = intent.getAction();
1590 // TODO: use "if (VDBG)" here.
1591 Log.d(LOG_TAG, "Broadcast from Notification: " + action);
1592
1593 if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) {
1594 PhoneUtils.hangup(PhoneGlobals.getInstance().mCM);
1595 } else if (action.equals(ACTION_CALL_BACK_FROM_NOTIFICATION)) {
1596 // Collapse the expanded notification and the notification item itself.
1597 closeSystemDialogs(context);
1598 clearMissedCallNotification(context);
1599
1600 Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData());
1601 callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1602 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1603 context.startActivity(callIntent);
1604 } else if (action.equals(ACTION_SEND_SMS_FROM_NOTIFICATION)) {
1605 // Collapse the expanded notification and the notification item itself.
1606 closeSystemDialogs(context);
1607 clearMissedCallNotification(context);
1608
1609 Intent smsIntent = new Intent(Intent.ACTION_SENDTO, intent.getData());
1610 smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1611 context.startActivity(smsIntent);
1612 } else {
1613 Log.w(LOG_TAG, "Received hang-up request from notification,"
1614 + " but there's no call the system can hang up.");
1615 }
1616 }
1617
1618 private void closeSystemDialogs(Context context) {
1619 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1620 context.sendBroadcastAsUser(intent, UserHandle.ALL);
1621 }
1622
1623 private void clearMissedCallNotification(Context context) {
1624 Intent clearIntent = new Intent(context, ClearMissedCallsService.class);
1625 clearIntent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
1626 context.startService(clearIntent);
1627 }
1628 }
1629
1630 private void handleServiceStateChanged(Intent intent) {
1631 /**
1632 * This used to handle updating EriTextWidgetProvider this routine
1633 * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
1634 * be removed. But leaving just in case it might be needed in the near
1635 * future.
1636 */
1637
1638 // If service just returned, start sending out the queued messages
1639 ServiceState ss = ServiceState.newFromBundle(intent.getExtras());
1640
1641 if (ss != null) {
1642 int state = ss.getState();
1643 notificationMgr.updateNetworkSelection(state);
1644 }
1645 }
1646
1647 public boolean isOtaCallInActiveState() {
1648 boolean otaCallActive = false;
1649 if (mInCallScreen != null) {
1650 otaCallActive = mInCallScreen.isOtaCallInActiveState();
1651 }
1652 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive);
1653 return otaCallActive;
1654 }
1655
1656 public boolean isOtaCallInEndState() {
1657 boolean otaCallEnded = false;
1658 if (mInCallScreen != null) {
1659 otaCallEnded = mInCallScreen.isOtaCallInEndState();
1660 }
1661 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded);
1662 return otaCallEnded;
1663 }
1664
1665 // it is safe to call clearOtaState() even if the InCallScreen isn't active
1666 public void clearOtaState() {
1667 if (DBG) Log.d(LOG_TAG, "- clearOtaState ...");
1668 if ((mInCallScreen != null)
1669 && (otaUtils != null)) {
1670 otaUtils.cleanOtaScreen(true);
1671 if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen");
1672 }
1673 }
1674
1675 // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active
1676 public void dismissOtaDialogs() {
1677 if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ...");
1678 if ((mInCallScreen != null)
1679 && (otaUtils != null)) {
1680 otaUtils.dismissAllOtaDialogs();
1681 if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs");
1682 }
1683 }
1684
1685 // it is safe to call clearInCallScreenMode() even if the InCallScreen isn't active
1686 public void clearInCallScreenMode() {
1687 if (DBG) Log.d(LOG_TAG, "- clearInCallScreenMode ...");
1688 if (mInCallScreen != null) {
1689 mInCallScreen.resetInCallScreenMode();
1690 }
1691 }
1692
1693 /**
1694 * Force the in-call UI to refresh itself, if it's currently visible.
1695 *
1696 * This method can be used any time there's a state change anywhere in
1697 * the phone app that needs to be reflected in the onscreen UI.
1698 *
1699 * Note that it's *not* necessary to manually refresh the in-call UI
1700 * (via this method) for regular telephony state changes like
1701 * DIALING -> ALERTING -> ACTIVE, since the InCallScreen already
1702 * listens for those state changes itself.
1703 *
1704 * This method does *not* force the in-call UI to come up if it's not
1705 * already visible. To do that, use displayCallScreen().
1706 */
1707 /* package */ void updateInCallScreen() {
1708 if (DBG) Log.d(LOG_TAG, "- updateInCallScreen()...");
1709 if (mInCallScreen != null) {
1710 // Post an updateScreen() request. Note that the
1711 // updateScreen() call will end up being a no-op if the
1712 // InCallScreen isn't the foreground activity.
1713 mInCallScreen.requestUpdateScreen();
1714 }
1715 }
1716
1717 private void handleQueryTTYModeResponse(Message msg) {
1718 AsyncResult ar = (AsyncResult) msg.obj;
1719 if (ar.exception != null) {
1720 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state.");
1721 } else {
1722 if (DBG) Log.d(LOG_TAG,
1723 "handleQueryTTYModeResponse: TTY enable state successfully queried.");
1724
1725 int ttymode = ((int[]) ar.result)[0];
1726 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode);
1727
1728 Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION);
1729 ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF);
1730 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1731
1732 String audioTtyMode;
1733 switch (ttymode) {
1734 case Phone.TTY_MODE_FULL:
1735 audioTtyMode = "tty_full";
1736 break;
1737 case Phone.TTY_MODE_VCO:
1738 audioTtyMode = "tty_vco";
1739 break;
1740 case Phone.TTY_MODE_HCO:
1741 audioTtyMode = "tty_hco";
1742 break;
1743 case Phone.TTY_MODE_OFF:
1744 default:
1745 audioTtyMode = "tty_off";
1746 break;
1747 }
1748 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1749 audioManager.setParameters("tty_mode="+audioTtyMode);
1750 }
1751 }
1752
1753 private void handleSetTTYModeResponse(Message msg) {
1754 AsyncResult ar = (AsyncResult) msg.obj;
1755
1756 if (ar.exception != null) {
1757 if (DBG) Log.d (LOG_TAG,
1758 "handleSetTTYModeResponse: Error setting TTY mode, ar.exception"
1759 + ar.exception);
1760 }
1761 phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET));
1762 }
1763
1764 /**
1765 * "Call origin" may be used by Contacts app to specify where the phone call comes from.
1766 * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}.
1767 * Any other value will be ignored, to make sure that malicious apps can't trick the in-call
1768 * UI into launching some random other app after a call ends.
1769 *
1770 * TODO: make this more generic. Note that we should let the "origin" specify its package
1771 * while we are now assuming it is "com.android.contacts"
1772 */
1773 public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
1774 private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.dialer";
1775 private static final String ALLOWED_EXTRA_CALL_ORIGIN =
1776 "com.android.dialer.DialtactsActivity";
1777 /**
1778 * Used to determine if the preserved call origin is fresh enough.
1779 */
1780 private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000;
1781
1782 public void setLatestActiveCallOrigin(String callOrigin) {
1783 inCallUiState.latestActiveCallOrigin = callOrigin;
1784 if (callOrigin != null) {
1785 inCallUiState.latestActiveCallOriginTimeStamp = SystemClock.elapsedRealtime();
1786 } else {
1787 inCallUiState.latestActiveCallOriginTimeStamp = 0;
1788 }
1789 }
1790
1791 /**
1792 * Reset call origin depending on its timestamp.
1793 *
1794 * See if the current call origin preserved by the app is fresh enough or not. If it is,
1795 * previous call origin will be used as is. If not, call origin will be reset.
1796 *
1797 * This will be effective especially for 3rd party apps which want to bypass phone calls with
1798 * their own telephone lines. In that case Phone app may finish the phone call once and make
1799 * another for the external apps, which will drop call origin information in Intent.
1800 * Even in that case we are sure the second phone call should be initiated just after the first
1801 * phone call, so here we restore it from the previous information iff the second call is done
1802 * fairly soon.
1803 */
1804 public void resetLatestActiveCallOrigin() {
1805 final long callOriginTimestamp = inCallUiState.latestActiveCallOriginTimeStamp;
1806 final long currentTimestamp = SystemClock.elapsedRealtime();
1807 if (VDBG) {
1808 Log.d(LOG_TAG, "currentTimeMillis: " + currentTimestamp
1809 + ", saved timestamp for call origin: " + callOriginTimestamp);
1810 }
1811 if (inCallUiState.latestActiveCallOriginTimeStamp > 0
1812 && (currentTimestamp - callOriginTimestamp < CALL_ORIGIN_EXPIRATION_MILLIS)) {
1813 if (VDBG) {
1814 Log.d(LOG_TAG, "Resume previous call origin (" +
1815 inCallUiState.latestActiveCallOrigin + ")");
1816 }
1817 // Do nothing toward call origin itself but update the timestamp just in case.
1818 inCallUiState.latestActiveCallOriginTimeStamp = currentTimestamp;
1819 } else {
1820 if (VDBG) Log.d(LOG_TAG, "Drop previous call origin and set the current one to null");
1821 setLatestActiveCallOrigin(null);
1822 }
1823 }
1824
1825 /**
1826 * @return Intent which will be used when in-call UI is shown and the phone call is hang up.
1827 * By default CallLog screen will be introduced, but the destination may change depending on
1828 * its latest call origin state.
1829 */
1830 public Intent createPhoneEndIntentUsingCallOrigin() {
1831 if (TextUtils.equals(inCallUiState.latestActiveCallOrigin, ALLOWED_EXTRA_CALL_ORIGIN)) {
1832 if (VDBG) Log.d(LOG_TAG, "Valid latestActiveCallOrigin("
1833 + inCallUiState.latestActiveCallOrigin + ") was found. "
1834 + "Go back to the previous screen.");
1835 // Right now we just launch the Activity which launched in-call UI. Note that we're
1836 // assuming the origin is from "com.android.dialer", which may be incorrect in the
1837 // future.
1838 final Intent intent = new Intent();
1839 intent.setClassName(DEFAULT_CALL_ORIGIN_PACKAGE, inCallUiState.latestActiveCallOrigin);
1840 return intent;
1841 } else {
1842 if (VDBG) Log.d(LOG_TAG, "Current latestActiveCallOrigin ("
1843 + inCallUiState.latestActiveCallOrigin + ") is not valid. "
1844 + "Just use CallLog as a default destination.");
1845 return PhoneGlobals.createCallLogIntent();
1846 }
1847 }
1848
1849 /** Service connection */
1850 private final ServiceConnection mBluetoothPhoneConnection = new ServiceConnection() {
1851
1852 /** Handle the task of binding the local object to the service */
1853 public void onServiceConnected(ComponentName className, IBinder service) {
1854 Log.i(LOG_TAG, "Headset phone created, binding local service.");
1855 mBluetoothPhone = IBluetoothHeadsetPhone.Stub.asInterface(service);
1856 }
1857
1858 /** Handle the task of cleaning up the local binding */
1859 public void onServiceDisconnected(ComponentName className) {
1860 Log.i(LOG_TAG, "Headset phone disconnected, cleaning local binding.");
1861 mBluetoothPhone = null;
1862 }
1863 };
1864}