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