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