blob: 08edc915e8e633a89513f24bce820199b9a50b0a [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;
RoboErik51d5cec2014-05-19 12:31:01 -070037import android.media.session.MediaSession;
38import android.media.session.MediaSessionManager;
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
RoboErik51d5cec2014-05-19 12:31:01 -0700223 private MediaSession 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
Santos Cordon117fee72014-05-16 17:56:12 -0700497 phoneMgr = PhoneInterfaceManager.init(this, phone, callHandlerServiceProxy);
Santos Cordon406c0342013-08-28 00:07:47 -0700498
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700499 // Create the CallNotifer singleton, which handles
500 // asynchronous events from the telephony layer (like
501 // launching the incoming-call UI when an incoming call comes
502 // in.)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700503 notifier = CallNotifier.init(this, phone, ringer, callLogger, callStateMonitor,
Santos Cordona5d5db82013-09-15 13:00:34 -0700504 bluetoothManager, callModeler);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700505
506 // register for ICC status
507 IccCard sim = phone.getIccCard();
508 if (sim != null) {
509 if (VDBG) Log.v(LOG_TAG, "register for ICC status");
510 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
511 }
512
513 // register for MMI/USSD
514 mCM.registerForMmiComplete(mHandler, MMI_COMPLETE, null);
515
516 // register connection tracking to PhoneUtils
517 PhoneUtils.initializeConnectionHandler(mCM);
518
519 // Read platform settings for TTY feature
520 mTtyEnabled = getResources().getBoolean(R.bool.tty_enabled);
521
522 // Register for misc other intent broadcasts.
523 IntentFilter intentFilter =
524 new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700525 intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700526 intentFilter.addAction(Intent.ACTION_DOCK_EVENT);
527 intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
528 intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
529 intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
530 intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
531 if (mTtyEnabled) {
532 intentFilter.addAction(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION);
533 }
534 intentFilter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
535 registerReceiver(mReceiver, intentFilter);
536
537 // Use a separate receiver for ACTION_MEDIA_BUTTON broadcasts,
538 // since we need to manually adjust its priority (to make sure
539 // we get these intents *before* the media player.)
540 IntentFilter mediaButtonIntentFilter =
541 new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
542 // TODO verify the independent priority doesn't need to be handled thanks to the
543 // private intent handler registration
544 // Make sure we're higher priority than the media player's
545 // MediaButtonIntentReceiver (which currently has the default
546 // priority of zero; see apps/Music/AndroidManifest.xml.)
547 mediaButtonIntentFilter.setPriority(1);
548 //
549 registerReceiver(mMediaButtonReceiver, mediaButtonIntentFilter);
550 // register the component so it gets priority for calls
551 AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
552 am.registerMediaButtonEventReceiverForCalls(new ComponentName(this.getPackageName(),
553 MediaButtonBroadcastReceiver.class.getName()));
554
555 //set the default values for the preferences in the phone.
556 PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
557
558 PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
559
560 // Make sure the audio mode (along with some
561 // audio-mode-related state of our own) is initialized
562 // correctly, given the current state of the phone.
563 PhoneUtils.setAudioMode(mCM);
RoboErik5d6506f2014-05-14 12:38:54 -0700564
565 // Register a MediaSession but don't enable it yet. This is a
566 // replacement for MediaButtonReceiver
RoboErik51d5cec2014-05-19 12:31:01 -0700567 MediaSessionManager msm = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
RoboErik5d6506f2014-05-14 12:38:54 -0700568 mSession = msm.createSession(LOG_TAG);
569 mSession.addCallback(mSessionCallback);
RoboErik51d5cec2014-05-19 12:31:01 -0700570 mSession.setFlags(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY
571 | MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700572 }
573
574 if (TelephonyCapabilities.supportsOtasp(phone)) {
575 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
576 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
577 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
578 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
579 }
580
581 // XXX pre-load the SimProvider so that it's ready
582 resolver.getType(Uri.parse("content://icc/adn"));
583
584 // start with the default value to set the mute state.
585 mShouldRestoreMuteOnInCallResume = false;
586
587 // TODO: Register for Cdma Information Records
588 // phone.registerCdmaInformationRecord(mHandler, EVENT_UNSOL_CDMA_INFO_RECORD, null);
589
590 // Read TTY settings and store it into BP NV.
591 // AP owns (i.e. stores) the TTY setting in AP settings database and pushes the setting
592 // to BP at power up (BP does not need to make the TTY setting persistent storage).
593 // This way, there is a single owner (i.e AP) for the TTY setting in the phone.
594 if (mTtyEnabled) {
595 mPreferredTtyMode = android.provider.Settings.Secure.getInt(
596 phone.getContext().getContentResolver(),
597 android.provider.Settings.Secure.PREFERRED_TTY_MODE,
598 Phone.TTY_MODE_OFF);
599 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
600 }
601 // Read HAC settings and configure audio hardware
602 if (getResources().getBoolean(R.bool.hac_enabled)) {
603 int hac = android.provider.Settings.System.getInt(phone.getContext().getContentResolver(),
604 android.provider.Settings.System.HEARING_AID,
605 0);
606 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
607 audioManager.setParameter(CallFeaturesSetting.HAC_KEY, hac != 0 ?
608 CallFeaturesSetting.HAC_VAL_ON :
609 CallFeaturesSetting.HAC_VAL_OFF);
610 }
Santos Cordonff506f52013-11-21 19:13:19 -0800611 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700612
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700613 /**
614 * Returns the singleton instance of the PhoneApp.
615 */
Sailesh Nepal1eaf22b2014-02-22 17:00:49 -0800616 public static PhoneGlobals getInstance() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700617 if (sMe == null) {
618 throw new IllegalStateException("No PhoneGlobals here!");
619 }
620 return sMe;
621 }
622
623 /**
624 * Returns the singleton instance of the PhoneApp if running as the
625 * primary user, otherwise null.
626 */
627 static PhoneGlobals getInstanceIfPrimary() {
628 return sMe;
629 }
630
631 /**
632 * Returns the Phone associated with this instance
633 */
634 static Phone getPhone() {
635 return getInstance().phone;
636 }
637
638 Ringer getRinger() {
639 return ringer;
640 }
641
642 IBluetoothHeadsetPhone getBluetoothPhoneService() {
643 return mBluetoothPhone;
644 }
645
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700646 /* package */ BluetoothManager getBluetoothManager() {
647 return bluetoothManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700648 }
649
Santos Cordon593ab382013-08-06 21:58:23 -0700650 /* package */ WiredHeadsetManager getWiredHeadsetManager() {
651 return wiredHeadsetManager;
652 }
653
654 /* package */ AudioRouter getAudioRouter() {
655 return audioRouter;
656 }
657
Sailesh Nepal1eaf22b2014-02-22 17:00:49 -0800658 public CallModeler getCallModeler() {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700659 return callModeler;
660 }
661
Santos Cordonde10b752013-09-19 04:11:33 -0700662 /* package */ CallManager getCallManager() {
663 return mCM;
664 }
665
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700666 /**
667 * Returns an Intent that can be used to go to the "Call log"
668 * UI (aka CallLogActivity) in the Contacts app.
669 *
670 * Watch out: there's no guarantee that the system has any activity to
671 * handle this intent. (In particular there may be no "Call log" at
672 * all on on non-voice-capable devices.)
673 */
674 /* package */ static Intent createCallLogIntent() {
675 Intent intent = new Intent(Intent.ACTION_VIEW, null);
676 intent.setType("vnd.android.cursor.dir/calls");
677 return intent;
678 }
679
Yorke Leeca6ec3b2013-08-29 14:21:43 -0700680 /* package */static PendingIntent createPendingCallLogIntent(Context context) {
681 final Intent callLogIntent = PhoneGlobals.createCallLogIntent();
682 final TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
683 taskStackBuilder.addNextIntent(callLogIntent);
684 return taskStackBuilder.getPendingIntent(0, 0);
685 }
686
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700687 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700688 * Returns PendingIntent for hanging up ongoing phone call. This will typically be used from
689 * Notification context.
690 */
691 /* package */ static PendingIntent createHangUpOngoingCallPendingIntent(Context context) {
692 Intent intent = new Intent(PhoneGlobals.ACTION_HANG_UP_ONGOING_CALL, null,
693 context, NotificationBroadcastReceiver.class);
694 return PendingIntent.getBroadcast(context, 0, intent, 0);
695 }
696
697 /* package */ static PendingIntent getCallBackPendingIntent(Context context, String number) {
698 Intent intent = new Intent(ACTION_CALL_BACK_FROM_NOTIFICATION,
699 Uri.fromParts(Constants.SCHEME_TEL, number, null),
700 context, NotificationBroadcastReceiver.class);
701 return PendingIntent.getBroadcast(context, 0, intent, 0);
702 }
703
704 /* package */ static PendingIntent getSendSmsFromNotificationPendingIntent(
705 Context context, String number) {
706 Intent intent = new Intent(ACTION_SEND_SMS_FROM_NOTIFICATION,
707 Uri.fromParts(Constants.SCHEME_SMSTO, number, null),
708 context, NotificationBroadcastReceiver.class);
709 return PendingIntent.getBroadcast(context, 0, intent, 0);
710 }
711
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700712 boolean isSimPinEnabled() {
713 return mIsSimPinEnabled;
714 }
715
716 boolean authenticateAgainstCachedSimPin(String pin) {
717 return (mCachedSimPin != null && mCachedSimPin.equals(pin));
718 }
719
720 void setCachedSimPin(String pin) {
721 mCachedSimPin = pin;
722 }
723
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700724 /**
725 * Handles OTASP-related events from the telephony layer.
726 *
727 * While an OTASP call is active, the CallNotifier forwards
728 * OTASP-related telephony events to this method.
729 */
730 void handleOtaspEvent(Message msg) {
731 if (DBG) Log.d(LOG_TAG, "handleOtaspEvent(message " + msg + ")...");
732
733 if (otaUtils == null) {
734 // We shouldn't be getting OTASP events without ever
735 // having started the OTASP call in the first place!
736 Log.w(LOG_TAG, "handleOtaEvents: got an event but otaUtils is null! "
737 + "message = " + msg);
738 return;
739 }
740
741 otaUtils.onOtaProvisionStatusChanged((AsyncResult) msg.obj);
742 }
743
744 /**
745 * Similarly, handle the disconnect event of an OTASP call
746 * by forwarding it to the OtaUtils instance.
747 */
748 /* package */ void handleOtaspDisconnect() {
749 if (DBG) Log.d(LOG_TAG, "handleOtaspDisconnect()...");
750
751 if (otaUtils == null) {
752 // We shouldn't be getting OTASP events without ever
753 // having started the OTASP call in the first place!
754 Log.w(LOG_TAG, "handleOtaspDisconnect: otaUtils is null!");
755 return;
756 }
757
758 otaUtils.onOtaspDisconnect();
759 }
760
761 /**
762 * Sets the activity responsible for un-PUK-blocking the device
763 * so that we may close it when we receive a positive result.
764 * mPUKEntryActivity is also used to indicate to the device that
765 * we are trying to un-PUK-lock the phone. In other words, iff
766 * it is NOT null, then we are trying to unlock and waiting for
767 * the SIM to move to READY state.
768 *
769 * @param activity is the activity to close when PUK has
770 * finished unlocking. Can be set to null to indicate the unlock
771 * or SIM READYing process is over.
772 */
773 void setPukEntryActivity(Activity activity) {
774 mPUKEntryActivity = activity;
775 }
776
777 Activity getPUKEntryActivity() {
778 return mPUKEntryActivity;
779 }
780
781 /**
782 * Sets the dialog responsible for notifying the user of un-PUK-
783 * blocking - SIM READYing progress, so that we may dismiss it
784 * when we receive a positive result.
785 *
786 * @param dialog indicates the progress dialog informing the user
787 * of the state of the device. Dismissed upon completion of
788 * READYing process
789 */
790 void setPukEntryProgressDialog(ProgressDialog dialog) {
791 mPUKEntryProgressDialog = dialog;
792 }
793
794 ProgressDialog getPUKEntryProgressDialog() {
795 return mPUKEntryProgressDialog;
796 }
797
798 /**
799 * Controls whether or not the screen is allowed to sleep.
800 *
801 * Once sleep is allowed (WakeState is SLEEP), it will rely on the
802 * settings for the poke lock to determine when to timeout and let
803 * the device sleep {@link PhoneGlobals#setScreenTimeout}.
804 *
805 * @param ws tells the device to how to wake.
806 */
807 /* package */ void requestWakeState(WakeState ws) {
808 if (VDBG) Log.d(LOG_TAG, "requestWakeState(" + ws + ")...");
809 synchronized (this) {
810 if (mWakeState != ws) {
811 switch (ws) {
812 case PARTIAL:
813 // acquire the processor wake lock, and release the FULL
814 // lock if it is being held.
815 mPartialWakeLock.acquire();
816 if (mWakeLock.isHeld()) {
817 mWakeLock.release();
818 }
819 break;
820 case FULL:
821 // acquire the full wake lock, and release the PARTIAL
822 // lock if it is being held.
823 mWakeLock.acquire();
824 if (mPartialWakeLock.isHeld()) {
825 mPartialWakeLock.release();
826 }
827 break;
828 case SLEEP:
829 default:
830 // release both the PARTIAL and FULL locks.
831 if (mWakeLock.isHeld()) {
832 mWakeLock.release();
833 }
834 if (mPartialWakeLock.isHeld()) {
835 mPartialWakeLock.release();
836 }
837 break;
838 }
839 mWakeState = ws;
840 }
841 }
842 }
843
844 /**
845 * If we are not currently keeping the screen on, then poke the power
846 * manager to wake up the screen for the user activity timeout duration.
847 */
848 /* package */ void wakeUpScreen() {
849 synchronized (this) {
850 if (mWakeState == WakeState.SLEEP) {
851 if (DBG) Log.d(LOG_TAG, "pulse screen lock");
852 mPowerManager.wakeUp(SystemClock.uptimeMillis());
853 }
854 }
855 }
856
857 /**
858 * Sets the wake state and screen timeout based on the current state
859 * of the phone, and the current state of the in-call UI.
860 *
861 * This method is a "UI Policy" wrapper around
862 * {@link PhoneGlobals#requestWakeState} and {@link PhoneGlobals#setScreenTimeout}.
863 *
864 * It's safe to call this method regardless of the state of the Phone
865 * (e.g. whether or not it's idle), and regardless of the state of the
866 * Phone UI (e.g. whether or not the InCallScreen is active.)
867 */
868 /* package */ void updateWakeState() {
869 PhoneConstants.State state = mCM.getState();
870
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700871 // True if the speakerphone is in use. (If so, we *always* use
872 // the default timeout. Since the user is obviously not holding
873 // the phone up to his/her face, we don't need to worry about
874 // false touches, and thus don't need to turn the screen off so
875 // aggressively.)
876 // Note that we need to make a fresh call to this method any
877 // time the speaker state changes. (That happens in
878 // PhoneUtils.turnOnSpeaker().)
879 boolean isSpeakerInUse = (state == PhoneConstants.State.OFFHOOK) && PhoneUtils.isSpeakerOn(this);
880
881 // TODO (bug 1440854): The screen timeout *might* also need to
882 // depend on the bluetooth state, but this isn't as clear-cut as
883 // the speaker state (since while using BT it's common for the
884 // user to put the phone straight into a pocket, in which case the
885 // timeout should probably still be short.)
886
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700887 // Decide whether to force the screen on or not.
888 //
889 // Force the screen to be on if the phone is ringing or dialing,
890 // or if we're displaying the "Call ended" UI for a connection in
891 // the "disconnected" state.
892 // However, if the phone is disconnected while the user is in the
893 // middle of selecting a quick response message, we should not force
894 // the screen to be on.
895 //
896 boolean isRinging = (state == PhoneConstants.State.RINGING);
897 boolean isDialing = (phone.getForegroundCall().getState() == Call.State.DIALING);
Jay Shrauner6fe8fd62013-09-16 19:39:30 -0700898 boolean keepScreenOn = isRinging || isDialing;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700899 // keepScreenOn == true means we'll hold a full wake lock:
900 requestWakeState(keepScreenOn ? WakeState.FULL : WakeState.SLEEP);
901 }
902
903 /**
904 * Manually pokes the PowerManager's userActivity method. Since we
905 * set the {@link WindowManager.LayoutParams#INPUT_FEATURE_DISABLE_USER_ACTIVITY}
906 * flag while the InCallScreen is active when there is no proximity sensor,
907 * we need to do this for touch events that really do count as user activity
908 * (like pressing any onscreen UI elements.)
909 */
910 /* package */ void pokeUserActivity() {
911 if (VDBG) Log.d(LOG_TAG, "pokeUserActivity()...");
912 mPowerManager.userActivity(SystemClock.uptimeMillis(), false);
913 }
914
915 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700916 * Notifies the phone app when the phone state changes.
917 *
Santos Cordonfc309812013-08-20 18:33:16 -0700918 * This method will updates various states inside Phone app (e.g. update-lock state, etc.)
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700919 */
920 /* package */ void updatePhoneState(PhoneConstants.State state) {
921 if (state != mLastPhoneState) {
922 mLastPhoneState = state;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700923
924 // Try to acquire or release UpdateLock.
925 //
926 // Watch out: we don't release the lock here when the screen is still in foreground.
927 // At that time InCallScreen will release it on onPause().
928 if (state != PhoneConstants.State.IDLE) {
929 // UpdateLock is a recursive lock, while we may get "acquire" request twice and
930 // "release" request once for a single call (RINGING + OFFHOOK and IDLE).
931 // We need to manually ensure the lock is just acquired once for each (and this
932 // will prevent other possible buggy situations too).
933 if (!mUpdateLock.isHeld()) {
934 mUpdateLock.acquire();
935 }
RoboErik5d6506f2014-05-14 12:38:54 -0700936 if (!mSession.isActive()) {
937 mSession.setActive(true);
938 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700939 } else {
Jay Shraunera5d13212013-09-19 13:37:43 -0700940 if (mUpdateLock.isHeld()) {
Jay Shrauner6fe8fd62013-09-16 19:39:30 -0700941 mUpdateLock.release();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700942 }
RoboErik5d6506f2014-05-14 12:38:54 -0700943 if (mSession.isActive()) {
944 mSession.setActive(false);
945 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700946 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700947 }
948 }
949
950 /* package */ PhoneConstants.State getPhoneState() {
951 return mLastPhoneState;
952 }
953
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700954 KeyguardManager getKeyguardManager() {
955 return mKeyguardManager;
956 }
957
958 private void onMMIComplete(AsyncResult r) {
959 if (VDBG) Log.d(LOG_TAG, "onMMIComplete()...");
960 MmiCode mmiCode = (MmiCode) r.result;
961 PhoneUtils.displayMMIComplete(phone, getInstance(), mmiCode, null, null);
962 }
963
964 private void initForNewRadioTechnology() {
965 if (DBG) Log.d(LOG_TAG, "initForNewRadioTechnology...");
966
967 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
968 // Create an instance of CdmaPhoneCallState and initialize it to IDLE
969 cdmaPhoneCallState = new CdmaPhoneCallState();
970 cdmaPhoneCallState.CdmaPhoneCallStateInit();
971 }
972 if (TelephonyCapabilities.supportsOtasp(phone)) {
973 //create instances of CDMA OTA data classes
974 if (cdmaOtaProvisionData == null) {
975 cdmaOtaProvisionData = new OtaUtils.CdmaOtaProvisionData();
976 }
977 if (cdmaOtaConfigData == null) {
978 cdmaOtaConfigData = new OtaUtils.CdmaOtaConfigData();
979 }
980 if (cdmaOtaScreenState == null) {
981 cdmaOtaScreenState = new OtaUtils.CdmaOtaScreenState();
982 }
983 if (cdmaOtaInCallScreenUiState == null) {
984 cdmaOtaInCallScreenUiState = new OtaUtils.CdmaOtaInCallScreenUiState();
985 }
986 } else {
987 //Clean up OTA data in GSM/UMTS. It is valid only for CDMA
988 clearOtaState();
989 }
990
991 ringer.updateRingerContextAfterRadioTechnologyChange(this.phone);
992 notifier.updateCallNotifierRegistrationsAfterRadioTechnologyChange();
993 callStateMonitor.updateAfterRadioTechnologyChange();
994
995 if (mBluetoothPhone != null) {
996 try {
997 mBluetoothPhone.updateBtHandsfreeAfterRadioTechnologyChange();
998 } catch (RemoteException e) {
999 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
1000 }
1001 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001002
1003 // Update registration for ICC status after radio technology change
1004 IccCard sim = phone.getIccCard();
1005 if (sim != null) {
1006 if (DBG) Log.d(LOG_TAG, "Update registration for ICC status...");
1007
1008 //Register all events new to the new active phone
1009 sim.registerForNetworkLocked(mHandler, EVENT_SIM_NETWORK_LOCKED, null);
1010 }
1011 }
1012
1013
1014 /**
Santos Cordon593ab382013-08-06 21:58:23 -07001015 * This is called when the wired headset state changes.
1016 */
1017 @Override
1018 public void onWiredHeadsetConnection(boolean pluggedIn) {
1019 PhoneConstants.State phoneState = mCM.getState();
1020
Santos Cordon593ab382013-08-06 21:58:23 -07001021 // Force TTY state update according to new headset state
1022 if (mTtyEnabled) {
1023 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1024 }
1025 }
1026
1027 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001028 * Receiver for misc intent broadcasts the Phone app cares about.
1029 */
1030 private class PhoneAppBroadcastReceiver extends BroadcastReceiver {
1031 @Override
1032 public void onReceive(Context context, Intent intent) {
1033 String action = intent.getAction();
1034 if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
1035 boolean enabled = System.getInt(getContentResolver(),
1036 System.AIRPLANE_MODE_ON, 0) == 0;
1037 phone.setRadioPower(enabled);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001038 } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
1039 if (VDBG) Log.d(LOG_TAG, "mReceiver: ACTION_ANY_DATA_CONNECTION_STATE_CHANGED");
1040 if (VDBG) Log.d(LOG_TAG, "- state: " + intent.getStringExtra(PhoneConstants.STATE_KEY));
1041 if (VDBG) Log.d(LOG_TAG, "- reason: "
1042 + intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1043
1044 // The "data disconnected due to roaming" notification is shown
1045 // if (a) you have the "data roaming" feature turned off, and
1046 // (b) you just lost data connectivity because you're roaming.
1047 boolean disconnectedDueToRoaming =
1048 !phone.getDataRoamingEnabled()
1049 && "DISCONNECTED".equals(intent.getStringExtra(PhoneConstants.STATE_KEY))
1050 && Phone.REASON_ROAMING_ON.equals(
1051 intent.getStringExtra(PhoneConstants.STATE_CHANGE_REASON_KEY));
1052 mHandler.sendEmptyMessage(disconnectedDueToRoaming
1053 ? EVENT_DATA_ROAMING_DISCONNECTED
1054 : EVENT_DATA_ROAMING_OK);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001055 } else if ((action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) &&
1056 (mPUKEntryActivity != null)) {
1057 // if an attempt to un-PUK-lock the device was made, while we're
1058 // receiving this state change notification, notify the handler.
1059 // NOTE: This is ONLY triggered if an attempt to un-PUK-lock has
1060 // been attempted.
1061 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SIM_STATE_CHANGED,
1062 intent.getStringExtra(IccCardConstants.INTENT_KEY_ICC_STATE)));
1063 } else if (action.equals(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED)) {
1064 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
1065 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
1066 initForNewRadioTechnology();
1067 } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
1068 handleServiceStateChanged(intent);
1069 } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
1070 if (TelephonyCapabilities.supportsEcm(phone)) {
1071 Log.d(LOG_TAG, "Emergency Callback Mode arrived in PhoneApp.");
1072 // Start Emergency Callback Mode service
1073 if (intent.getBooleanExtra("phoneinECMState", false)) {
1074 context.startService(new Intent(context,
1075 EmergencyCallbackModeService.class));
1076 }
1077 } else {
1078 // It doesn't make sense to get ACTION_EMERGENCY_CALLBACK_MODE_CHANGED
1079 // on a device that doesn't support ECM in the first place.
1080 Log.e(LOG_TAG, "Got ACTION_EMERGENCY_CALLBACK_MODE_CHANGED, "
1081 + "but ECM isn't supported for phone: " + phone.getPhoneName());
1082 }
1083 } else if (action.equals(Intent.ACTION_DOCK_EVENT)) {
1084 mDockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
1085 Intent.EXTRA_DOCK_STATE_UNDOCKED);
1086 if (VDBG) Log.d(LOG_TAG, "ACTION_DOCK_EVENT -> mDockState = " + mDockState);
1087 mHandler.sendMessage(mHandler.obtainMessage(EVENT_DOCK_STATE_CHANGED, 0));
1088 } else if (action.equals(TtyIntent.TTY_PREFERRED_MODE_CHANGE_ACTION)) {
1089 mPreferredTtyMode = intent.getIntExtra(TtyIntent.TTY_PREFFERED_MODE,
1090 Phone.TTY_MODE_OFF);
1091 if (VDBG) Log.d(LOG_TAG, "mReceiver: TTY_PREFERRED_MODE_CHANGE_ACTION");
1092 if (VDBG) Log.d(LOG_TAG, " mode: " + mPreferredTtyMode);
1093 mHandler.sendMessage(mHandler.obtainMessage(EVENT_TTY_PREFERRED_MODE_CHANGED, 0));
1094 } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
1095 int ringerMode = intent.getIntExtra(AudioManager.EXTRA_RINGER_MODE,
1096 AudioManager.RINGER_MODE_NORMAL);
1097 if (ringerMode == AudioManager.RINGER_MODE_SILENT) {
1098 notifier.silenceRinger();
1099 }
1100 }
1101 }
1102 }
1103
RoboErik51d5cec2014-05-19 12:31:01 -07001104 private class SessionCallback extends MediaSession.Callback {
RoboErik5d6506f2014-05-14 12:38:54 -07001105 @Override
1106 public void onMediaButton(Intent intent) {
1107 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1108 if (VDBG) Log.d(LOG_TAG, "SessionCallback.onMediaButton()... event = " + event);
1109 if ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1110 if (VDBG) Log.d(LOG_TAG, "SessionCallback: HEADSETHOOK");
1111 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1112 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1113 }
1114 }
1115 }
1116
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001117 /**
1118 * Broadcast receiver for the ACTION_MEDIA_BUTTON broadcast intent.
1119 *
1120 * This functionality isn't lumped in with the other intents in
1121 * PhoneAppBroadcastReceiver because we instantiate this as a totally
1122 * separate BroadcastReceiver instance, since we need to manually
1123 * adjust its IntentFilter's priority (to make sure we get these
1124 * intents *before* the media player.)
1125 */
1126 private class MediaButtonBroadcastReceiver extends BroadcastReceiver {
1127 @Override
1128 public void onReceive(Context context, Intent intent) {
1129 KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
1130 if (VDBG) Log.d(LOG_TAG,
1131 "MediaButtonBroadcastReceiver.onReceive()... event = " + event);
1132 if ((event != null)
1133 && (event.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK)) {
1134 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: HEADSETHOOK");
1135 boolean consumed = PhoneUtils.handleHeadsetHook(phone, event);
1136 if (VDBG) Log.d(LOG_TAG, "==> handleHeadsetHook(): consumed = " + consumed);
1137 if (consumed) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001138 abortBroadcast();
1139 }
1140 } else {
1141 if (mCM.getState() != PhoneConstants.State.IDLE) {
1142 // If the phone is anything other than completely idle,
1143 // then we consume and ignore any media key events,
1144 // Otherwise it is too easy to accidentally start
1145 // playing music while a phone call is in progress.
1146 if (VDBG) Log.d(LOG_TAG, "MediaButtonBroadcastReceiver: consumed");
1147 abortBroadcast();
1148 }
1149 }
1150 }
1151 }
1152
1153 /**
1154 * Accepts broadcast Intents which will be prepared by {@link NotificationMgr} and thus
1155 * sent from framework's notification mechanism (which is outside Phone context).
1156 * This should be visible from outside, but shouldn't be in "exported" state.
1157 *
1158 * TODO: If possible merge this into PhoneAppBroadcastReceiver.
1159 */
1160 public static class NotificationBroadcastReceiver extends BroadcastReceiver {
1161 @Override
1162 public void onReceive(Context context, Intent intent) {
1163 String action = intent.getAction();
1164 // TODO: use "if (VDBG)" here.
1165 Log.d(LOG_TAG, "Broadcast from Notification: " + action);
1166
1167 if (action.equals(ACTION_HANG_UP_ONGOING_CALL)) {
1168 PhoneUtils.hangup(PhoneGlobals.getInstance().mCM);
1169 } else if (action.equals(ACTION_CALL_BACK_FROM_NOTIFICATION)) {
1170 // Collapse the expanded notification and the notification item itself.
1171 closeSystemDialogs(context);
1172 clearMissedCallNotification(context);
1173
1174 Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED, intent.getData());
1175 callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1176 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1177 context.startActivity(callIntent);
1178 } else if (action.equals(ACTION_SEND_SMS_FROM_NOTIFICATION)) {
1179 // Collapse the expanded notification and the notification item itself.
1180 closeSystemDialogs(context);
1181 clearMissedCallNotification(context);
1182
1183 Intent smsIntent = new Intent(Intent.ACTION_SENDTO, intent.getData());
1184 smsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1185 context.startActivity(smsIntent);
1186 } else {
1187 Log.w(LOG_TAG, "Received hang-up request from notification,"
1188 + " but there's no call the system can hang up.");
1189 }
1190 }
1191
1192 private void closeSystemDialogs(Context context) {
1193 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
1194 context.sendBroadcastAsUser(intent, UserHandle.ALL);
1195 }
1196
1197 private void clearMissedCallNotification(Context context) {
1198 Intent clearIntent = new Intent(context, ClearMissedCallsService.class);
1199 clearIntent.setAction(ClearMissedCallsService.ACTION_CLEAR_MISSED_CALLS);
1200 context.startService(clearIntent);
1201 }
1202 }
1203
1204 private void handleServiceStateChanged(Intent intent) {
1205 /**
1206 * This used to handle updating EriTextWidgetProvider this routine
1207 * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
1208 * be removed. But leaving just in case it might be needed in the near
1209 * future.
1210 */
1211
1212 // If service just returned, start sending out the queued messages
1213 ServiceState ss = ServiceState.newFromBundle(intent.getExtras());
1214
1215 if (ss != null) {
1216 int state = ss.getState();
1217 notificationMgr.updateNetworkSelection(state);
1218 }
1219 }
1220
1221 public boolean isOtaCallInActiveState() {
1222 boolean otaCallActive = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001223 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInActiveState " + otaCallActive);
1224 return otaCallActive;
1225 }
1226
1227 public boolean isOtaCallInEndState() {
1228 boolean otaCallEnded = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001229 if (VDBG) Log.d(LOG_TAG, "- isOtaCallInEndState " + otaCallEnded);
1230 return otaCallEnded;
1231 }
1232
1233 // it is safe to call clearOtaState() even if the InCallScreen isn't active
1234 public void clearOtaState() {
1235 if (DBG) Log.d(LOG_TAG, "- clearOtaState ...");
Jay Shrauner6fe8fd62013-09-16 19:39:30 -07001236 if (otaUtils != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001237 otaUtils.cleanOtaScreen(true);
1238 if (DBG) Log.d(LOG_TAG, " - clearOtaState clears OTA screen");
1239 }
1240 }
1241
1242 // it is safe to call dismissOtaDialogs() even if the InCallScreen isn't active
1243 public void dismissOtaDialogs() {
1244 if (DBG) Log.d(LOG_TAG, "- dismissOtaDialogs ...");
Jay Shrauner6fe8fd62013-09-16 19:39:30 -07001245 if (otaUtils != null) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001246 otaUtils.dismissAllOtaDialogs();
1247 if (DBG) Log.d(LOG_TAG, " - dismissOtaDialogs clears OTA dialogs");
1248 }
1249 }
1250
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001251 private void handleQueryTTYModeResponse(Message msg) {
1252 AsyncResult ar = (AsyncResult) msg.obj;
1253 if (ar.exception != null) {
1254 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse: Error getting TTY state.");
1255 } else {
1256 if (DBG) Log.d(LOG_TAG,
1257 "handleQueryTTYModeResponse: TTY enable state successfully queried.");
1258
1259 int ttymode = ((int[]) ar.result)[0];
1260 if (DBG) Log.d(LOG_TAG, "handleQueryTTYModeResponse:ttymode=" + ttymode);
1261
1262 Intent ttyModeChanged = new Intent(TtyIntent.TTY_ENABLED_CHANGE_ACTION);
1263 ttyModeChanged.putExtra("ttyEnabled", ttymode != Phone.TTY_MODE_OFF);
1264 sendBroadcastAsUser(ttyModeChanged, UserHandle.ALL);
1265
1266 String audioTtyMode;
1267 switch (ttymode) {
1268 case Phone.TTY_MODE_FULL:
1269 audioTtyMode = "tty_full";
1270 break;
1271 case Phone.TTY_MODE_VCO:
1272 audioTtyMode = "tty_vco";
1273 break;
1274 case Phone.TTY_MODE_HCO:
1275 audioTtyMode = "tty_hco";
1276 break;
1277 case Phone.TTY_MODE_OFF:
1278 default:
1279 audioTtyMode = "tty_off";
1280 break;
1281 }
1282 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
1283 audioManager.setParameters("tty_mode="+audioTtyMode);
1284 }
1285 }
1286
1287 private void handleSetTTYModeResponse(Message msg) {
1288 AsyncResult ar = (AsyncResult) msg.obj;
1289
1290 if (ar.exception != null) {
1291 if (DBG) Log.d (LOG_TAG,
1292 "handleSetTTYModeResponse: Error setting TTY mode, ar.exception"
1293 + ar.exception);
1294 }
1295 phone.queryTTYMode(mHandler.obtainMessage(EVENT_TTY_MODE_GET));
1296 }
1297
1298 /**
1299 * "Call origin" may be used by Contacts app to specify where the phone call comes from.
1300 * Currently, the only permitted value for this extra is {@link #ALLOWED_EXTRA_CALL_ORIGIN}.
1301 * Any other value will be ignored, to make sure that malicious apps can't trick the in-call
1302 * UI into launching some random other app after a call ends.
1303 *
1304 * TODO: make this more generic. Note that we should let the "origin" specify its package
1305 * while we are now assuming it is "com.android.contacts"
1306 */
1307 public static final String EXTRA_CALL_ORIGIN = "com.android.phone.CALL_ORIGIN";
1308 private static final String DEFAULT_CALL_ORIGIN_PACKAGE = "com.android.dialer";
1309 private static final String ALLOWED_EXTRA_CALL_ORIGIN =
1310 "com.android.dialer.DialtactsActivity";
1311 /**
1312 * Used to determine if the preserved call origin is fresh enough.
1313 */
1314 private static final long CALL_ORIGIN_EXPIRATION_MILLIS = 30 * 1000;
1315
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001316 /** Service connection */
1317 private final ServiceConnection mBluetoothPhoneConnection = new ServiceConnection() {
1318
1319 /** Handle the task of binding the local object to the service */
1320 public void onServiceConnected(ComponentName className, IBinder service) {
1321 Log.i(LOG_TAG, "Headset phone created, binding local service.");
1322 mBluetoothPhone = IBluetoothHeadsetPhone.Stub.asInterface(service);
1323 }
1324
1325 /** Handle the task of cleaning up the local binding */
1326 public void onServiceDisconnected(ComponentName className) {
1327 Log.i(LOG_TAG, "Headset phone disconnected, cleaning local binding.");
1328 mBluetoothPhone = null;
1329 }
1330 };
Santos Cordon83570472013-09-06 15:45:10 -07001331
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001332}