blob: cc49c2e53553498a4f7f8a444af2e24abd9292d6 [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;
Yorke Leeca6ec3b2013-08-29 14:21:43 -070023import android.app.TaskStackBuilder;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070024import android.bluetooth.BluetoothAdapter;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070025import android.bluetooth.IBluetoothHeadsetPhone;
26import android.content.ActivityNotFoundException;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.ContextWrapper;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.ServiceConnection;
35import android.content.res.Configuration;
36import android.media.AudioManager;
RoboErik5d6506f2014-05-14 12:38:54 -070037import android.media.session.Session;
38import android.media.session.SessionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070039import android.net.Uri;
40import android.os.AsyncResult;
41import android.os.Binder;
42import android.os.Handler;
43import android.os.IBinder;
44import android.os.IPowerManager;
45import android.os.Message;
46import android.os.PowerManager;
47import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.os.SystemClock;
50import android.os.SystemProperties;
51import android.os.UpdateLock;
52import android.os.UserHandle;
53import android.preference.PreferenceManager;
54import android.provider.Settings.System;
55import android.telephony.ServiceState;
56import android.text.TextUtils;
57import android.util.Log;
58import android.util.Slog;
59import android.view.KeyEvent;
60
61import com.android.internal.telephony.Call;
62import com.android.internal.telephony.CallManager;
63import com.android.internal.telephony.IccCard;
64import com.android.internal.telephony.IccCardConstants;
65import com.android.internal.telephony.MmiCode;
66import com.android.internal.telephony.Phone;
67import com.android.internal.telephony.PhoneConstants;
68import com.android.internal.telephony.PhoneFactory;
69import com.android.internal.telephony.TelephonyCapabilities;
70import com.android.internal.telephony.TelephonyIntents;
71import com.android.internal.telephony.cdma.TtyIntent;
72import com.android.phone.common.CallLogAsync;
73import com.android.phone.OtaUtils.CdmaOtaScreenState;
Santos Cordon593ab382013-08-06 21:58:23 -070074import com.android.phone.WiredHeadsetManager.WiredHeadsetListener;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070075import com.android.server.sip.SipService;
Santos Cordon593ab382013-08-06 21:58:23 -070076import com.android.services.telephony.common.AudioMode;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070077
78/**
79 * Global state for the telephony subsystem when running in the primary
80 * phone process.
81 */
Santos Cordonfc309812013-08-20 18:33:16 -070082public class PhoneGlobals extends ContextWrapper implements WiredHeadsetListener {
Santos Cordon7d4ddf62013-07-10 11:58:08 -070083 /* package */ static final String LOG_TAG = "PhoneApp";
84
85 /**
86 * Phone app-wide debug level:
87 * 0 - no debug logging
88 * 1 - normal debug logging if ro.debuggable is set (which is true in
89 * "eng" and "userdebug" builds but not "user" builds)
90 * 2 - ultra-verbose debug logging
91 *
92 * Most individual classes in the phone app have a local DBG constant,
93 * typically set to
94 * (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1)
95 * or else
96 * (PhoneApp.DBG_LEVEL >= 2)
97 * depending on the desired verbosity.
98 *
99 * ***** DO NOT SUBMIT WITH DBG_LEVEL > 0 *************
100 */
101 /* package */ static final int DBG_LEVEL = 0;
102
103 private static final boolean DBG =
104 (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
105 private static final boolean VDBG = (PhoneGlobals.DBG_LEVEL >= 2);
106
107 // Message codes; see mHandler below.
108 private static final int EVENT_SIM_NETWORK_LOCKED = 3;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700109 private static final int EVENT_SIM_STATE_CHANGED = 8;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700110 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;
Santos Cordon63a84242013-07-23 13:32:52 -0700168 NotificationMgr notificationMgr;
169 Phone phone;
170 PhoneInterfaceManager phoneMgr;
171
Santos Cordon9b7bac72013-08-06 08:04:52 -0700172 private AudioRouter audioRouter;
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700173 private BluetoothManager bluetoothManager;
Santos Cordon63a84242013-07-23 13:32:52 -0700174 private CallCommandService callCommandService;
Santos Cordon69a69192013-08-22 14:25:42 -0700175 private CallGatewayManager callGatewayManager;
Santos Cordon63a84242013-07-23 13:32:52 -0700176 private CallHandlerServiceProxy callHandlerServiceProxy;
177 private CallModeler callModeler;
178 private CallStateMonitor callStateMonitor;
Santos Cordon2eaff902013-08-05 04:37:55 -0700179 private DTMFTonePlayer dtmfTonePlayer;
Santos Cordon63a84242013-07-23 13:32:52 -0700180 private IBluetoothHeadsetPhone mBluetoothPhone;
181 private Ringer ringer;
Santos Cordon593ab382013-08-06 21:58:23 -0700182 private WiredHeadsetManager wiredHeadsetManager;
Santos Cordon63a84242013-07-23 13:32:52 -0700183
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
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700190 // The currently-active PUK entry activity and progress dialog.
191 // Normally, these are the Emergency Dialer and the subsequent
192 // progress dialog. null if there is are no such objects in
193 // the foreground.
194 private Activity mPUKEntryActivity;
195 private ProgressDialog mPUKEntryProgressDialog;
196
197 private boolean mIsSimPinEnabled;
198 private String mCachedSimPin;
199
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700200 // True if we are beginning a call, but the phone state has not changed yet
201 private boolean mBeginningCall;
202
203 // Last phone state seen by updatePhoneState()
204 private PhoneConstants.State mLastPhoneState = PhoneConstants.State.IDLE;
205
206 private WakeState mWakeState = WakeState.SLEEP;
207
208 private PowerManager mPowerManager;
209 private IPowerManager mPowerManagerService;
210 private PowerManager.WakeLock mWakeLock;
211 private PowerManager.WakeLock mPartialWakeLock;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700212 private KeyguardManager mKeyguardManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700213
214 private UpdateLock mUpdateLock;
215
216 // Broadcast receiver for various intent broadcasts (see onCreate())
217 private final BroadcastReceiver mReceiver = new PhoneAppBroadcastReceiver();
218
219 // Broadcast receiver purely for ACTION_MEDIA_BUTTON broadcasts
220 private final BroadcastReceiver mMediaButtonReceiver = new MediaButtonBroadcastReceiver();
RoboErik5d6506f2014-05-14 12:38:54 -0700221 private final SessionCallback mSessionCallback = new SessionCallback();
222
223 private Session mSession;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700224
225 /** boolean indicating restoring mute state on InCallScreen.onResume() */
226 private boolean mShouldRestoreMuteOnInCallResume;
227
228 /**
229 * The singleton OtaUtils instance used for OTASP calls.
230 *
231 * The OtaUtils instance is created lazily the first time we need to
232 * make an OTASP call, regardless of whether it's an interactive or
233 * non-interactive OTASP call.
234 */
235 public OtaUtils otaUtils;
236
237 // Following are the CDMA OTA information Objects used during OTA Call.
238 // cdmaOtaProvisionData object store static OTA information that needs
239 // to be maintained even during Slider open/close scenarios.
240 // cdmaOtaConfigData object stores configuration info to control visiblity
241 // of each OTA Screens.
242 // cdmaOtaScreenState object store OTA Screen State information.
243 public OtaUtils.CdmaOtaProvisionData cdmaOtaProvisionData;
244 public OtaUtils.CdmaOtaConfigData cdmaOtaConfigData;
245 public OtaUtils.CdmaOtaScreenState cdmaOtaScreenState;
246 public OtaUtils.CdmaOtaInCallScreenUiState cdmaOtaInCallScreenUiState;
247
248 // TTY feature enabled on this platform
249 private boolean mTtyEnabled;
250 // Current TTY operating mode selected by user
251 private int mPreferredTtyMode = Phone.TTY_MODE_OFF;
252
253 /**
254 * Set the restore mute state flag. Used when we are setting the mute state
255 * OUTSIDE of user interaction {@link PhoneUtils#startNewCall(Phone)}
256 */
257 /*package*/void setRestoreMuteOnInCallResume (boolean mode) {
258 mShouldRestoreMuteOnInCallResume = mode;
259 }
260
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700261 Handler mHandler = new Handler() {
262 @Override
263 public void handleMessage(Message msg) {
264 PhoneConstants.State phoneState;
265 switch (msg.what) {
266 // Starts the SIP service. It's a no-op if SIP API is not supported
267 // on the deivce.
268 // TODO: Having the phone process host the SIP service is only
269 // temporary. Will move it to a persistent communication process
270 // later.
271 case EVENT_START_SIP_SERVICE:
272 SipService.start(getApplicationContext());
273 break;
274
275 // TODO: This event should be handled by the lock screen, just
276 // like the "SIM missing" and "Sim locked" cases (bug 1804111).
277 case EVENT_SIM_NETWORK_LOCKED:
278 if (getResources().getBoolean(R.bool.ignore_sim_network_locked_events)) {
279 // Some products don't have the concept of a "SIM network lock"
280 Log.i(LOG_TAG, "Ignoring EVENT_SIM_NETWORK_LOCKED event; "
281 + "not showing 'SIM network unlock' PIN entry screen");
282 } else {
283 // Normal case: show the "SIM network unlock" PIN entry screen.
284 // The user won't be able to do anything else until
285 // they enter a valid SIM network PIN.
286 Log.i(LOG_TAG, "show sim depersonal panel");
287 IccNetworkDepersonalizationPanel ndpPanel =
288 new IccNetworkDepersonalizationPanel(PhoneGlobals.getInstance());
289 ndpPanel.show();
290 }
291 break;
292
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700293 case EVENT_DATA_ROAMING_DISCONNECTED:
294 notificationMgr.showDataDisconnectedRoaming();
295 break;
296
297 case EVENT_DATA_ROAMING_OK:
298 notificationMgr.hideDataDisconnectedRoaming();
299 break;
300
301 case MMI_COMPLETE:
302 onMMIComplete((AsyncResult) msg.obj);
303 break;
304
305 case MMI_CANCEL:
306 PhoneUtils.cancelMmiCode(phone);
307 break;
308
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700309 case EVENT_SIM_STATE_CHANGED:
310 // Marks the event where the SIM goes into ready state.
311 // Right now, this is only used for the PUK-unlocking
312 // process.
313 if (msg.obj.equals(IccCardConstants.INTENT_VALUE_ICC_READY)) {
314 // when the right event is triggered and there
315 // are UI objects in the foreground, we close
316 // them to display the lock panel.
317 if (mPUKEntryActivity != null) {
318 mPUKEntryActivity.finish();
319 mPUKEntryActivity = null;
320 }
321 if (mPUKEntryProgressDialog != null) {
322 mPUKEntryProgressDialog.dismiss();
323 mPUKEntryProgressDialog = null;
324 }
325 }
326 break;
327
328 case EVENT_UNSOL_CDMA_INFO_RECORD:
329 //TODO: handle message here;
330 break;
331
332 case EVENT_DOCK_STATE_CHANGED:
333 // If the phone is docked/undocked during a call, and no wired or BT headset
334 // is connected: turn on/off the speaker accordingly.
335 boolean inDockMode = false;
336 if (mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
337 inDockMode = true;
338 }
339 if (VDBG) Log.d(LOG_TAG, "received EVENT_DOCK_STATE_CHANGED. Phone inDock = "
340 + inDockMode);
341
342 phoneState = mCM.getState();
343 if (phoneState == PhoneConstants.State.OFFHOOK &&
Santos Cordon593ab382013-08-06 21:58:23 -0700344 !wiredHeadsetManager.isHeadsetPlugged() &&
345 !bluetoothManager.isBluetoothHeadsetAudioOn()) {
346 audioRouter.setSpeaker(inDockMode);
347
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700348 PhoneUtils.turnOnSpeaker(getApplicationContext(), inDockMode, true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700349 }
350 break;
351
352 case EVENT_TTY_PREFERRED_MODE_CHANGED:
353 // TTY mode is only applied if a headset is connected
354 int ttyMode;
Santos Cordon593ab382013-08-06 21:58:23 -0700355 if (wiredHeadsetManager.isHeadsetPlugged()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700356 ttyMode = mPreferredTtyMode;
357 } else {
358 ttyMode = Phone.TTY_MODE_OFF;
359 }
360 phone.setTTYMode(ttyMode, mHandler.obtainMessage(EVENT_TTY_MODE_SET));
361 break;
362
363 case EVENT_TTY_MODE_GET:
364 handleQueryTTYModeResponse(msg);
365 break;
366
367 case EVENT_TTY_MODE_SET:
368 handleSetTTYModeResponse(msg);
369 break;
370 }
371 }
372 };
373
374 public PhoneGlobals(Context context) {
375 super(context);
376 sMe = this;
377 }
378
379 public void onCreate() {
380 if (VDBG) Log.v(LOG_TAG, "onCreate()...");
381
382 ContentResolver resolver = getContentResolver();
383
384 // Cache the "voice capable" flag.
385 // This flag currently comes from a resource (which is
386 // overrideable on a per-product basis):
387 sVoiceCapable =
388 getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
389 // ...but this might eventually become a PackageManager "system
390 // feature" instead, in which case we'd do something like:
391 // sVoiceCapable =
392 // getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY_VOICE_CALLS);
393
394 if (phone == null) {
395 // Initialize the telephony framework
396 PhoneFactory.makeDefaultPhones(this);
397
398 // Get the default phone
399 phone = PhoneFactory.getDefaultPhone();
400
401 // Start TelephonyDebugService After the default phone is created.
402 Intent intent = new Intent(this, TelephonyDebugService.class);
403 startService(intent);
404
405 mCM = CallManager.getInstance();
406 mCM.registerPhone(phone);
407
408 // Create the NotificationMgr singleton, which is used to display
409 // status bar icons and control other status bar behavior.
410 notificationMgr = NotificationMgr.init(this);
411
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700412 mHandler.sendEmptyMessage(EVENT_START_SIP_SERVICE);
413
414 int phoneType = phone.getPhoneType();
415
416 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
417 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
418 cdmaPhoneCallState = new CdmaPhoneCallState();
419 cdmaPhoneCallState.CdmaPhoneCallStateInit();
420 }
421
422 if (BluetoothAdapter.getDefaultAdapter() != null) {
423 // Start BluetoothPhoneService even if device is not voice capable.
424 // The device can still support VOIP.
425 startService(new Intent(this, BluetoothPhoneService.class));
426 bindService(new Intent(this, BluetoothPhoneService.class),
427 mBluetoothPhoneConnection, 0);
428 } else {
429 // Device is not bluetooth capable
430 mBluetoothPhone = null;
431 }
432
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700433 // before registering for phone state changes
434 mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
435 mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOG_TAG);
436 // lock used to keep the processor awake, when we don't care for the display.
437 mPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
438 | PowerManager.ON_AFTER_RELEASE, LOG_TAG);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700439
440 mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
441
442 // get a handle to the service so that we can use it later when we
443 // want to set the poke lock.
444 mPowerManagerService = IPowerManager.Stub.asInterface(
445 ServiceManager.getService("power"));
446
447 // Get UpdateLock to suppress system-update related events (e.g. dialog show-up)
448 // during phone calls.
449 mUpdateLock = new UpdateLock("phone");
450
451 if (DBG) Log.d(LOG_TAG, "onCreate: mUpdateLock: " + mUpdateLock);
452
453 CallLogger callLogger = new CallLogger(this, new CallLogAsync());
454
Jay Shrauner21a75342013-11-25 16:14:43 -0800455 callGatewayManager = CallGatewayManager.getInstance();
Santos Cordon69a69192013-08-22 14:25:42 -0700456
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700457 // Create the CallController singleton, which is the interface
458 // to the telephony layer for user-initiated telephony functionality
459 // (like making outgoing calls.)
Santos Cordon69a69192013-08-22 14:25:42 -0700460 callController = CallController.init(this, callLogger, callGatewayManager);
461
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700462 // Create the CallerInfoCache singleton, which remembers custom ring tone and
463 // send-to-voicemail settings.
464 //
465 // The asynchronous caching will start just after this call.
466 callerInfoCache = CallerInfoCache.init(this);
467
468 // Monitors call activity from the telephony layer
469 callStateMonitor = new CallStateMonitor(mCM);
470
Santos Cordon63a84242013-07-23 13:32:52 -0700471 // Creates call models for use with CallHandlerService.
David Braun35272072013-09-24 17:19:26 -0700472 callModeler = new CallModeler(callStateMonitor, mCM, callGatewayManager);
Santos Cordon63a84242013-07-23 13:32:52 -0700473
Santos Cordon2eaff902013-08-05 04:37:55 -0700474 // Plays DTMF Tones
475 dtmfTonePlayer = new DTMFTonePlayer(mCM, callModeler);
476
Santos Cordon593ab382013-08-06 21:58:23 -0700477 // Manages wired headset state
478 wiredHeadsetManager = new WiredHeadsetManager(this);
479 wiredHeadsetManager.addWiredHeadsetListener(this);
480
Santos Cordon2c2d3cf2013-08-08 03:53:47 -0700481 // Bluetooth manager
482 bluetoothManager = new BluetoothManager(this, mCM, callModeler);
Santos Cordon2c2d3cf2013-08-08 03:53:47 -0700483
484 ringer = Ringer.init(this, bluetoothManager);
485
Santos Cordon9b7bac72013-08-06 08:04:52 -0700486 // Audio router
Santos Cordon593ab382013-08-06 21:58:23 -0700487 audioRouter = new AudioRouter(this, bluetoothManager, wiredHeadsetManager, mCM);
Santos Cordon9b7bac72013-08-06 08:04:52 -0700488
Santos Cordon249efd02013-08-05 03:33:56 -0700489 // Service used by in-call UI to control calls
Santos Cordon9b7bac72013-08-06 08:04:52 -0700490 callCommandService = new CallCommandService(this, mCM, callModeler, dtmfTonePlayer,
David Braun35272072013-09-24 17:19:26 -0700491 audioRouter);
Santos Cordon249efd02013-08-05 03:33:56 -0700492
Santos Cordon89647a62013-07-16 13:38:09 -0700493 // Sends call state to the UI
Santos Cordon63a84242013-07-23 13:32:52 -0700494 callHandlerServiceProxy = new CallHandlerServiceProxy(this, callModeler,
Santos Cordon593ab382013-08-06 21:58:23 -0700495 callCommandService, audioRouter);
Santos Cordon89647a62013-07-16 13:38:09 -0700496
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700497 phoneMgr = PhoneInterfaceManager.init(this, phone, callHandlerServiceProxy, callModeler,
498 dtmfTonePlayer);
Santos Cordon406c0342013-08-28 00:07:47 -0700499
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700500 // Create the CallNotifer singleton, which handles
501 // asynchronous events from the telephony layer (like
502 // launching the incoming-call UI when an incoming call comes
503 // in.)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700504 notifier = CallNotifier.init(this, phone, ringer, callLogger, callStateMonitor,
Santos Cordona5d5db82013-09-15 13:00:34 -0700505 bluetoothManager, callModeler);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700506
507 // register for ICC status
508 IccCard sim = phone.getIccCard();
509 if (sim != null) {
510 if (VDBG) Log.v(LOG_TAG, "register for ICC status");
511 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
512 }
513
514 // register for MMI/USSD
515 mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
516
517 // register connection tracking to PhoneUtils
518 PhoneUtils.initializeConnectionHandler(mCM);
519
520 // Read platform settings for TTY feature
521 mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled);
522
523 // Register for misc other intent broadcasts.
524 IntentFilter intentFilter =
525 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700526 intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700527 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
528 intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
529 intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
530 intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
531 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
532 if (mTtyEnabled) {
533 intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
534 }
535 intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
536 registerReceiver(mReceiver, intentFilter);
537
538 // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts,
539 // since we need to manually adjust its priority (to make sure
540 // we get these intents *before* the media player.)
541 IntentFilter mediaButtonIntentFilter =
542 new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
543 // TODO verify the independent priority doesn't need to be handled thanks to the
544 // private intent handler registration
545 // Make sure we're higher priority than the media player's
546 // MediaButtonIntentReceiver (which currently has the default
547 // priority of zero; see apps/Music/AndroidManifest.xml.)
548 mediaButtonIntentFilter.setPriority(1);
549 //
550 registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
551 // register the component so it gets priority for calls
552 AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
553 am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(),
554 MediaButtonBroadcastReceiver.class.getName()));
555
556 //set the default values for the preferences in the phone.
557 PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
558
559 PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
560
561 // Make sure the audio mode (along with some
562 // audio-mode-related state of our own) is initialized
563 // correctly, given the current state of the phone.
564 PhoneUtils.setAudioMode(mCM);
RoboErik5d6506f2014-05-14 12:38:54 -0700565
566 // Register a MediaSession but don't enable it yet. This is a
567 // replacement for MediaButtonReceiver
568 SessionManager msm = (SessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
569 mSession = msm.createSession(LOG_TAG);
570 mSession.addCallback(mSessionCallback);
571 mSession.setFlags(Session.FLAG_EXCLUSIVE_GLOBAL_PRIORITY
572 | Session.FLAG_HANDLES_MEDIA_BUTTONS);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700573 }
574
575 if (TelephonyCapabilities.supportsOtasp(phone)) {
576 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
577 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
578 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
579 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
580 }
581
582 // XXX pre-load the SimProvider so that it's ready
583 resolver.getType(Uri.parse("content://icc/adn"));
584
585 // start with the default value to set the mute state.
586 mShouldRestoreMuteOnInCallResume = false;
587
588 // TODO: Register for Cdma Information Records
589 // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
590
591 // Read TTY settings and store it into BP NV.
592 // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting
593 // to BP at power up (BP does not need to make the TTY setting persistent storage).
594 // This way, there is a single owner (i.e AP) for the TTY setting in the phone.
595 if (mTtyEnabled) {
596 mPreferredTtyMode = android.provider.Settings.Secure.getInt(
597 phone.getContext().getContentResolver(),
598 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
599 Phone.TTY_MODE_OFF);
600 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
601 }
602 // Read HAC settings and configure audio hardware
603 if (getResources().getBoolean(R.bool.hac_enabled)) {
604 int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(),
605 android.provider.Settings.System.HEARING_AID,
606 0);
607 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
608 audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ?
609 CallFeaturesSetting.HAC_VAL_ON :
610 CallFeaturesSetting.HAC_VAL_OFF);
611 }
612 }
613
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700614 /**
615 * Returns the singleton instance of the PhoneApp.
616 */
617 static PhoneGlobals getInstance() {
618 if (sMe == null) {
619 throw new IllegalStateException("No PhoneGlobals here!");
620 }
621 return sMe;
622 }
623
624 /**
625 * Returns the singleton instance of the PhoneApp if running as the
626 * primary user, otherwise null.
627 */
628 static PhoneGlobals getInstanceIfPrimary() {
629 return sMe;
630 }
631
632 /**
633 * Returns the Phone associated with this instance
634 */
635 static Phone getPhone() {
636 return getInstance().phone;
637 }
638
639 Ringer getRinger() {
640 return ringer;
641 }
642
643 IBluetoothHeadsetPhone getBluetoothPhoneService() {
644 return mBluetoothPhone;
645 }
646
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700647 /* package */ BluetoothManager getBluetoothManager() {
648 return bluetoothManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700649 }
650
Santos Cordon593ab382013-08-06 21:58:23 -0700651 /* package */ WiredHeadsetManager getWiredHeadsetManager() {
652 return wiredHeadsetManager;
653 }
654
655 /* package */ AudioRouter getAudioRouter() {
656 return audioRouter;
657 }
658
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700659 /* package */ CallModeler getCallModeler() {
660 return callModeler;
661 }
662
Santos Cordonde10b752013-09-19 04:11:33 -0700663 /* package */ CallManager getCallManager() {
664 return mCM;
665 }
666
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700667 /**
668 * Returns an Intent that can be used to go to the "Call log"
669 * UI (aka CallLogActivity) in the Contacts app.
670 *
671 * Watch out: there's no guarantee that the system has any activity to
672 * handle this intent. (In particular there may be no "Call log" at
673 * all on on non-voice-capable devices.)
674 */
675 /* package */ static Intent createCallLogIntent() {
676 Intent intent = new Intent(Intent.ACTION_VIEW, null);
677 intent.setType("vnd.android.cursor.dir/calls");
678 return intent;
679 }
680
Yorke Leeca6ec3b2013-08-29 14:21:43 -0700681 /* package */static PendingIntent createPendingCallLogIntent(Context context) {
682 final Intent callLogIntent = PhoneGlobals.createCallLogIntent();
683 final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
684 taskStackBuilder.addNextIntent(callLogIntent);
685 return taskStackBuilder.getPendingIntent(0, 0);
686 }
687
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700688 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700689 * Returns PendingIntent for hanging up ongoing phone call. This will typically be used from
690 * Notification context.
691 */
692 /* package */ static PendingIntent createHangUpOngoingCallPendingIntent(Context context) {
693 Intent intent = new Intent(PhoneGlobals.ACTION_HANG_UP_ONGOING_CALL, null,
694 context, NotificationBroadcastReceiver.class);
695 return PendingIntent.getBroadcast(context, 0, intent, 0);
696 }
697
698 /* package */ static PendingIntent getCallBackPendingIntent(Context context, String number) {
699 Intent intent = new Intent(ACTION_CALL_BACK_FROM_NOTIFICATION,
700 Uri.fromParts(Constants.SCHEME_TEL, number, null),
701 context, NotificationBroadcastReceiver.class);
702 return PendingIntent.getBroadcast(context, 0, intent, 0);
703 }
704
705 /* package */ static PendingIntent getSendSmsFromNotificationPendingIntent(
706 Context context, String number) {
707 Intent intent = new Intent(ACTION_SEND_SMS_FROM_NOTIFICATION,
708 Uri.fromParts(Constants.SCHEME_SMSTO, number, null),
709 context, NotificationBroadcastReceiver.class);
710 return PendingIntent.getBroadcast(context, 0, intent, 0);
711 }
712
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700713 boolean isSimPinEnabled() {
714 return mIsSimPinEnabled;
715 }
716
717 boolean authenticateAgainstCachedSimPin(String pin) {
718 return (mCachedSimPin != null && mCachedSimPin.equals(pin));
719 }
720
721 void setCachedSimPin(String pin) {
722 mCachedSimPin = pin;
723 }
724
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700725 /**
726 * Handles OTASP-related events from the telephony layer.
727 *
728 * While an OTASP call is active, the CallNotifier forwards
729 * OTASP-related telephony events to this method.
730 */
731 void handleOtaspEvent(Message msg) {
732 if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")...");
733
734 if (otaUtils == null) {
735 // We shouldn't be getting OTASP events without ever
736 // having started the OTASP call in the first place!
737 Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! "
738 + "message = " + msg);
739 return;
740 }
741
742 otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
743 }
744
745 /**
746 * Similarly, handle the disconnect event of an OTASP call
747 * by forwarding it to the OtaUtils instance.
748 */
749 /* package */ void handleOtaspDisconnect() {
750 if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()...");
751
752 if (otaUtils == null) {
753 // We shouldn't be getting OTASP events without ever
754 // having started the OTASP call in the first place!
755 Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!");
756 return;
757 }
758
759 otaUtils.onOtaspDisconnect();
760 }
761
762 /**
763 * Sets the activity responsible for un-PUK-blocking the device
764 * so that we may close it when we receive a positive result.
765 * mPUKEntryActivity is also used to indicate to the device that
766 * we are trying to un-PUK-lock the phone. In other words, iff
767 * it is NOT null, then we are trying to unlock and waiting for
768 * the SIM to move to READY state.
769 *
770 * @param activity is the activity to close when PUK has
771 * finished unlocking. Can be set to null to indicate the unlock
772 * or SIM READYing process is over.
773 */
774 void setPukEntryActivity(Activity activity) {
775 mPUKEntryActivity = activity;
776 }
777
778 Activity getPUKEntryActivity() {
779 return mPUKEntryActivity;
780 }
781
782 /**
783 * Sets the dialog responsible for notifying the user of un-PUK-
784 * blocking - SIM READYing progress, so that we may dismiss it
785 * when we receive a positive result.
786 *
787 * @param dialog indicates the progress dialog informing the user
788 * of the state of the device. Dismissed upon completion of
789 * READYing process
790 */
791 void setPukEntryProgressDialog(ProgressDialog dialog) {
792 mPUKEntryProgressDialog = dialog;
793 }
794
795 ProgressDialog getPUKEntryProgressDialog() {
796 return mPUKEntryProgressDialog;
797 }
798
799 /**
800 * Controls whether or not the screen is allowed to sleep.
801 *
802 * Once sleep is allowed (WakeState is SLEEP), it will rely on the
803 * settings for the poke lock to determine when to timeout and let
804 * the device sleep {@link PhoneGlobals#setScreenTimeout}.
805 *
806 * @param ws tells the device to how to wake.
807 */
808 /* package */ void requestWakeState(WakeState ws) {
809 if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
810 synchronized (this) {
811 if (mWakeState != ws) {
812 switch (ws) {
813 case PARTIAL:
814 // acquire the processor wake lock, and release the FULL
815 // lock if it is being held.
816 mPartialWakeLock.acquire();
817 if (mWakeLock.isHeld()) {
818 mWakeLock.release();
819 }
820 break;
821 case FULL:
822 // acquire the full wake lock, and release the PARTIAL
823 // lock if it is being held.
824 mWakeLock.acquire();
825 if (mPartialWakeLock.isHeld()) {
826 mPartialWakeLock.release();
827 }
828 break;
829 case SLEEP:
830 default:
831 // release both the PARTIAL and FULL locks.
832 if (mWakeLock.isHeld()) {
833 mWakeLock.release();
834 }
835 if (mPartialWakeLock.isHeld()) {
836 mPartialWakeLock.release();
837 }
838 break;
839 }
840 mWakeState = ws;
841 }
842 }
843 }
844
845 /**
846 * If we are not currently keeping the screen on, then poke the power
847 * manager to wake up the screen for the user activity timeout duration.
848 */
849 /* package */ void wakeUpScreen() {
850 synchronized (this) {
851 if (mWakeState == WakeState.SLEEP) {
852 if (DBG) Log.d(LOG_TAG, "pulse screen lock");
853 mPowerManager.wakeUp(SystemClock.uptimeMillis());
854 }
855 }
856 }
857
858 /**
859 * Sets the wake state and screen timeout based on the current state
860 * of the phone, and the current state of the in-call UI.
861 *
862 * This method is a "UI Policy" wrapper around
863 * {@link PhoneGlobals#requestWakeState} and {@link PhoneGlobals#setScreenTimeout}.
864 *
865 * It's safe to call this method regardless of the state of the Phone
866 * (e.g. whether or not it's idle), and regardless of the state of the
867 * Phone UI (e.g. whether or not the InCallScreen is active.)
868 */
869 /* package */ void updateWakeState() {
870 PhoneConstants.State state = mCM.getState();
871
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700872 // True if the speakerphone is in use. (If so, we *always* use
873 // the default timeout. Since the user is obviously not holding
874 // the phone up to his/her face, we don't need to worry about
875 // false touches, and thus don't need to turn the screen off so
876 // aggressively.)
877 // Note that we need to make a fresh call to this method any
878 // time the speaker state changes. (That happens in
879 // PhoneUtils.turnOnSpeaker().)
880 boolean isSpeakerInUse = (state == PhoneConstants.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
881
882 // TODO (bug 1440854): The screen timeout *might* also need to
883 // depend on the bluetooth state, but this isn't as clear-cut as
884 // the speaker state (since while using BT it's common for the
885 // user to put the phone straight into a pocket, in which case the
886 // timeout should probably still be short.)
887
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700888 // Decide whether to force the screen on or not.
889 //
890 // Force the screen to be on if the phone is ringing or dialing,
891 // or if we're displaying the "Call ended" UI for a connection in
892 // the "disconnected" state.
893 // However, if the phone is disconnected while the user is in the
894 // middle of selecting a quick response message, we should not force
895 // the screen to be on.
896 //
897 boolean isRinging = (state == PhoneConstants.State.RINGING);
898 boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING);
Jay Shrauner6fe8fd62013-09-16 19:39:30 -0700899 boolean keepScreenOn = isRinging || isDialing;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700900 // keepScreenOn == true means we'll hold a full wake lock:
901 requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
902 }
903
904 /**
905 * Manually pokes the PowerManager's userActivity method. Since we
906 * set the {@link WindowManager.LayoutParams#INPUT_FEATURE_DISABLE_USER_ACTIVITY}
907 * flag while the InCallScreen is active when there is no proximity sensor,
908 * we need to do this for touch events that really do count as user activity
909 * (like pressing any onscreen UI elements.)
910 */
911 /* package */ void pokeUserActivity() {
912 if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
913 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
914 }
915
916 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700917 * Notifies the phone app when the phone state changes.
918 *
Santos Cordonfc309812013-08-20 18:33:16 -0700919 * This method will updates various states inside Phone app (e.g. update-lock state, etc.)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700920 */
921 /* package */ void updatePhoneState(PhoneConstants.State state) {
922 if (state != mLastPhoneState) {
923 mLastPhoneState = state;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700924
925 // Try to acquire or release UpdateLock.
926 //
927 // Watch out: we don't release the lock here when the screen is still in foreground.
928 // At that time InCallScreen will release it on onPause().
929 if (state != PhoneConstants.State.IDLE) {
930 // UpdateLock is a recursive lock, while we may get "acquire" request twice and
931 // "release" request once for a single call (RINGING + OFFHOOK and IDLE).
932 // We need to manually ensure the lock is just acquired once for each (and this
933 // will prevent other possible buggy situations too).
934 if (!mUpdateLock.isHeld()) {
935 mUpdateLock.acquire();
936 }
RoboErik5d6506f2014-05-14 12:38:54 -0700937 if (!mSession.isActive()) {
938 mSession.setActive(true);
939 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700940 } else {
Jay Shraunera5d13212013-09-19 13:37:43 -0700941 if (mUpdateLock.isHeld()) {
Jay Shrauner6fe8fd62013-09-16 19:39:30 -0700942 mUpdateLock.release();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700943 }
RoboErik5d6506f2014-05-14 12:38:54 -0700944 if (mSession.isActive()) {
945 mSession.setActive(false);
946 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700947 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700948 }
949 }
950
951 /* package */ PhoneConstants.State getPhoneState() {
952 return mLastPhoneState;
953 }
954
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700955 KeyguardManager getKeyguardManager() {
956 return mKeyguardManager;
957 }
958
959 private void onMMIComplete(AsyncResult r) {
960 if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
961 MmiCode mmiCode = (MmiCode) r.result;
962 PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null);
963 }
964
965 private void initForNewRadioTechnology() {
966 if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
967
968 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
969 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
970 cdmaPhoneCallState = new CdmaPhoneCallState();
971 cdmaPhoneCallState.CdmaPhoneCallStateInit();
972 }
973 if (TelephonyCapabilities.supportsOtasp(phone)) {
974 //create instances of CDMA OTA data classes
975 if (cdmaOtaProvisionData == null) {
976 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
977 }
978 if (cdmaOtaConfigData == null) {
979 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
980 }
981 if (cdmaOtaScreenState == null) {
982 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
983 }
984 if (cdmaOtaInCallScreenUiState == null) {
985 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
986 }
987 } else {
988 //Clean up OTA data in GSM/UMTS. It is valid only for CDMA
989 clearOtaState();
990 }
991
992 ringer.updateRingerContextAfterRadioTechnologyChange(this.phone);
993 notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
994 callStateMonitor.updateAfterRadioTechnologyChange();
995
996 if (mBluetoothPhone != null) {
997 try {
998 mBluetoothPhone.updateBtHandsfreeAfterRadioTechnologyChange();
999 } catch (RemoteException e) {
1000 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
1001 }
1002 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001003
1004 // Update registration for ICC status after radio technology change
1005 IccCard sim = phone.getIccCard();
1006 if (sim != null) {
1007 if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
1008
1009 //Register all events new to the new active phone
1010 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
1011 }
1012 }
1013
1014
1015 /**
Santos Cordon593ab382013-08-06 21:58:23 -07001016 * This is called when the wired headset state changes.
1017 */
1018 @Override
1019 public void onWiredHeadsetConnection(boolean pluggedIn) {
1020 PhoneConstants.State phoneState = mCM.getState();
1021
Santos Cordon593ab382013-08-06 21:58:23 -07001022 // Force TTY state update according to new headset state
1023 if (mTtyEnabled) {
1024 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1025 }
1026 }
1027
1028 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001029 * Receiver for misc intent broadcasts the Phone app cares about.
1030 */
1031 private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
1032 @Override
1033 public void onReceive(Context context, Intent intent) {
1034 String action = intent.getAction();
1035 if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
1036 boolean enabled = System.getInt(getContentResolver(),
1037 System.AIRPLANE_MODE_ON, 0) == 0;
1038 phone.setRadioPower(enabled);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001039 } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
1040 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
1041 if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(PhoneConstants.STATE_KEY));
1042 if (VDBG) Log.d(LOG_TAG, "- reason: "
1043 + intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1044
1045 // The "data disconnected due to roaming" notification is shown
1046 // if (a) you have the "data roaming" feature turned off, and
1047 // (b) you just lost data connectivity because you're roaming.
1048 boolean disconnectedDueToRoaming =
1049 !phone.getDataRoamingEnabled()
1050 && "DISCONNECTED".equals(intent.getStringExtra(PhoneConstants.STATE_KEY))
1051 && Phone.REASON_ROAMING_ON.equals(
1052 intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1053 mHandler.sendEmptyMessage(disconnectedDueToRoaming
1054 ? EVENT_DATA_ROAMING_DISCONNECTED
1055 : EVENT_DATA_ROAMING_OK);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001056 } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
1057 (mPUKEntryActivity != null)) {
1058 // if an attempt to un-PUK-lock the device was made, while we're
1059 // receiving this state change notification, notify the handler.
1060 // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
1061 // been attempted.
1062 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
1063 intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)));
1064 } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
1065 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
1066 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
1067 initForNewRadioTechnology();
1068 } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
1069 handleServiceStateChanged(intent);
1070 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1071 if (TelephonyCapabilities.supportsEcm(phone)) {
1072 Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
1073 // Start Emergency Callback Mode service
1074 if (intent.getBooleanExtra("phoneinECMState", false)) {
1075 context.startService(new Intent(context,
1076 EmergencyCallbackModeService.class));
1077 }
1078 } else {
1079 // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED
1080 // on a device that doesn't support ECM in the first place.
1081 Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, "
1082 + "but ECM isn't supported for phone: " + phone.getPhoneName());
1083 }
1084 } else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1085 mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1086 Intent.EXTRA_DOCK_STATE_UNDOCKED);
1087 if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState);
1088 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0));
1089 } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) {
1090 mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE,
1091 Phone.TTY_MODE_OFF);
1092 if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION");
1093 if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode);
1094 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1095 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
1096 int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
1097 AudioManager.RINGER_MODE_NORMAL);
1098 if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
1099 notifier.silenceRinger();
1100 }
1101 }
1102 }
1103 }
1104
RoboErik5d6506f2014-05-14 12:38:54 -07001105 private class SessionCallback extends Session.Callback {
1106 @Override
1107 public void onMediaButton(Intent intent) {
1108 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1109 if (VDBG) Log.d(LOG_TAG, "SessionCallback.onMediaButton()... event = " + event);
1110 if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1111 if (VDBG) Log.d(LOG_TAG, "SessionCallback: HEADSETHOOK");
1112 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1113 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1114 }
1115 }
1116 }
1117
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001118 /**
1119 * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent.
1120 *
1121 * This functionality isn't lumped in with the other intents in
1122 * PhoneAppBroadcastReceiver because we instantiate this as a totally
1123 * separate BroadcastReceiver instance, since we need to manually
1124 * adjust its IntentFilter's priority (to make sure we get these
1125 * intents *before* the media player.)
1126 */
1127 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
1128 @Override
1129 public void onReceive(Context context, Intent intent) {
1130 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1131 if (VDBG) Log.d(LOG_TAG,
1132 "MediaButtonBroadcastReceiver.onReceive()... event = " + event);
1133 if ((event != null)
1134 && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1135 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK");
1136 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1137 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1138 if (consumed) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001139 abortBroadcast();
1140 }
1141 } else {
1142 if (mCM.getState() != PhoneConstants.State.IDLE) {
1143 // If the phone is anything other than completely idle,
1144 // then we consume and ignore any media key events,
1145 // Otherwise it is too easy to accidentally start
1146 // playing music while a phone call is in progress.
1147 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed");
1148 abortBroadcast();
1149 }
1150 }
1151 }
1152 }
1153
1154 /**
1155 * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus
1156 * sent from framework's notification mechanism (which is outside Phone context).
1157 * This should be visible from outside, but shouldn't be in "exported" state.
1158 *
1159 * TODO: If possible merge this into PhoneAppBroadcastReceiver.
1160 */
1161 public static class NotificationBroadcastReceiver extends BroadcastReceiver {
1162 @Override
1163 public void onReceive(Context context, Intent intent) {
1164 String action = intent.getAction();
1165 // TODO: use "if (VDBG)" here.
1166 Log.d(LOG_TAG, "Broadcast from Notification: " + action);
1167
1168 if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) {
1169 PhoneUtils.hangup(PhoneGlobals.getInstance().mCM);
1170 } else if (action.equals(ACTION_CALL_BACK_FROM_NOTIFICATION)) {
1171 // Collapse the expanded notification and the notification item itself.
1172 closeSystemDialogs(context);
1173 clearMissedCallNotification(context);
1174
1175 Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData());
1176 callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1177 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1178 context.startActivity(callIntent);
1179 } else if (action.equals(ACTION_SEND_SMS_FROM_NOTIFICATION)) {
1180 // Collapse the expanded notification and the notification item itself.
1181 closeSystemDialogs(context);
1182 clearMissedCallNotification(context);
1183
1184 Intent smsIntent = new Intent(Intent.ACTION_SENDTO, intent.getData());
1185 smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1186 context.startActivity(smsIntent);
1187 } else {
1188 Log.w(LOG_TAG, "Received hang-up request from notification,"
1189 + " but there's no call the system can hang up.");
1190 }
1191 }
1192
1193 private void closeSystemDialogs(Context context) {
1194 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1195 context.sendBroadcastAsUser(intent, UserHandle.ALL);
1196 }
1197
1198 private void clearMissedCallNotification(Context context) {
1199 Intent clearIntent = new Intent(context, ClearMissedCallsService.class);
1200 clearIntent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
1201 context.startService(clearIntent);
1202 }
1203 }
1204
1205 private void handleServiceStateChanged(Intent intent) {
1206 /**
1207 * This used to handle updating EriTextWidgetProvider this routine
1208 * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
1209 * be removed. But leaving just in case it might be needed in the near
1210 * future.
1211 */
1212
1213 // If service just returned, start sending out the queued messages
1214 ServiceState ss = ServiceState.newFromBundle(intent.getExtras());
1215
1216 if (ss != null) {
1217 int state = ss.getState();
1218 notificationMgr.updateNetworkSelection(state);
1219 }
1220 }
1221
1222 public boolean isOtaCallInActiveState() {
1223 boolean otaCallActive = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001224 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive);
1225 return otaCallActive;
1226 }
1227
1228 public boolean isOtaCallInEndState() {
1229 boolean otaCallEnded = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001230 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded);
1231 return otaCallEnded;
1232 }
1233
1234 // it is safe to call clearOtaState() even if the InCallScreen isn't active
1235 public void clearOtaState() {
1236 if (DBG) Log.d(LOG_TAG, "- clearOtaState ...");
Jay Shrauner6fe8fd62013-09-16 19:39:30 -07001237 if (otaUtils != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001238 otaUtils.cleanOtaScreen(true);
1239 if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen");
1240 }
1241 }
1242
1243 // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active
1244 public void dismissOtaDialogs() {
1245 if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ...");
Jay Shrauner6fe8fd62013-09-16 19:39:30 -07001246 if (otaUtils != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001247 otaUtils.dismissAllOtaDialogs();
1248 if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs");
1249 }
1250 }
1251
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001252 private void handleQueryTTYModeResponse(Message msg) {
1253 AsyncResult ar = (AsyncResult) msg.obj;
1254 if (ar.exception != null) {
1255 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state.");
1256 } else {
1257 if (DBG) Log.d(LOG_TAG,
1258 "handleQueryTTYModeResponse: TTY enable state successfully queried.");
1259
1260 int ttymode = ((int[]) ar.result)[0];
1261 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode);
1262
1263 Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION);
1264 ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF);
1265 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1266
1267 String audioTtyMode;
1268 switch (ttymode) {
1269 case Phone.TTY_MODE_FULL:
1270 audioTtyMode = "tty_full";
1271 break;
1272 case Phone.TTY_MODE_VCO:
1273 audioTtyMode = "tty_vco";
1274 break;
1275 case Phone.TTY_MODE_HCO:
1276 audioTtyMode = "tty_hco";
1277 break;
1278 case Phone.TTY_MODE_OFF:
1279 default:
1280 audioTtyMode = "tty_off";
1281 break;
1282 }
1283 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1284 audioManager.setParameters("tty_mode="+audioTtyMode);
1285 }
1286 }
1287
1288 private void handleSetTTYModeResponse(Message msg) {
1289 AsyncResult ar = (AsyncResult) msg.obj;
1290
1291 if (ar.exception != null) {
1292 if (DBG) Log.d (LOG_TAG,
1293 "handleSetTTYModeResponse: Error setting TTY mode, ar.exception"
1294 + ar.exception);
1295 }
1296 phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET));
1297 }
1298
1299 /**
1300 * "Call origin" may be used by Contacts app to specify where the phone call comes from.
1301 * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}.
1302 * Any other value will be ignored, to make sure that malicious apps can't trick the in-call
1303 * UI into launching some random other app after a call ends.
1304 *
1305 * TODO: make this more generic. Note that we should let the "origin" specify its package
1306 * while we are now assuming it is "com.android.contacts"
1307 */
1308 public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
1309 private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.dialer";
1310 private static final String ALLOWED_EXTRA_CALL_ORIGIN =
1311 "com.android.dialer.DialtactsActivity";
1312 /**
1313 * Used to determine if the preserved call origin is fresh enough.
1314 */
1315 private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000;
1316
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001317 /** Service connection */
1318 private final ServiceConnection mBluetoothPhoneConnection = new ServiceConnection() {
1319
1320 /** Handle the task of binding the local object to the service */
1321 public void onServiceConnected(ComponentName className, IBinder service) {
1322 Log.i(LOG_TAG, "Headset phone created, binding local service.");
1323 mBluetoothPhone = IBluetoothHeadsetPhone.Stub.asInterface(service);
1324 }
1325
1326 /** Handle the task of cleaning up the local binding */
1327 public void onServiceDisconnected(ComponentName className) {
1328 Log.i(LOG_TAG, "Headset phone disconnected, cleaning local binding.");
1329 mBluetoothPhone = null;
1330 }
1331 };
Santos Cordon83570472013-09-06 15:45:10 -07001332
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001333}