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