blob: 8baded66301eb796335c2c567584e1009388378f [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 com.android.internal.telephony.Call;
20import com.android.internal.telephony.CallManager;
21import com.android.internal.telephony.CallerInfo;
22import com.android.internal.telephony.CallerInfoAsyncQuery;
23import com.android.internal.telephony.Connection;
24import com.android.internal.telephony.Phone;
25import com.android.internal.telephony.PhoneConstants;
26import com.android.internal.telephony.PhoneBase;
27import com.android.internal.telephony.TelephonyCapabilities;
28import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
29import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaDisplayInfoRec;
30import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaSignalInfoRec;
31import com.android.internal.telephony.cdma.SignalToneUtil;
32
33import android.app.ActivityManagerNative;
34import android.bluetooth.BluetoothAdapter;
35import android.bluetooth.BluetoothHeadset;
36import android.bluetooth.BluetoothProfile;
37import android.content.Context;
John Spurlock6ee06d02014-07-18 20:06:20 -040038import android.media.AudioAttributes;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070039import android.media.AudioManager;
40import android.media.ToneGenerator;
41import android.net.Uri;
42import android.os.AsyncResult;
43import android.os.Handler;
44import android.os.Message;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070045import android.os.SystemProperties;
46import android.os.SystemVibrator;
47import android.os.Vibrator;
48import android.provider.CallLog.Calls;
49import android.provider.Settings;
Anders Kristensen0b35f042014-02-27 14:31:07 -080050import android.telephony.DisconnectCause;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070051import android.telephony.PhoneNumberUtils;
52import android.telephony.PhoneStateListener;
53import android.telephony.TelephonyManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070054import android.util.EventLog;
55import android.util.Log;
56
57/**
58 * Phone app module that listens for phone state changes and various other
59 * events from the telephony layer, and triggers any resulting UI behavior
60 * (like starting the Ringer and Incoming Call UI, playing in-call tones,
61 * updating notifications, writing call log entries, etc.)
62 */
63public class CallNotifier extends Handler
64 implements CallerInfoAsyncQuery.OnQueryCompleteListener {
65 private static final String LOG_TAG = "CallNotifier";
66 private static final boolean DBG =
67 (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
68 private static final boolean VDBG = (PhoneGlobals.DBG_LEVEL >= 2);
69
70 // Maximum time we allow the CallerInfo query to run,
71 // before giving up and falling back to the default ringtone.
72 private static final int RINGTONE_QUERY_WAIT_TIME = 500; // msec
73
74 // Timers related to CDMA Call Waiting
75 // 1) For displaying Caller Info
76 // 2) For disabling "Add Call" menu option once User selects Ignore or CW Timeout occures
77 private static final int CALLWAITING_CALLERINFO_DISPLAY_TIME = 20000; // msec
78 private static final int CALLWAITING_ADDCALL_DISABLE_TIME = 30000; // msec
79
80 // Time to display the DisplayInfo Record sent by CDMA network
81 private static final int DISPLAYINFO_NOTIFICATION_TIME = 2000; // msec
82
John Spurlock6ee06d02014-07-18 20:06:20 -040083 private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
84 .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
85 .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
86 .build();
87
Santos Cordon7d4ddf62013-07-10 11:58:08 -070088 /** The singleton instance. */
89 private static CallNotifier sInstance;
90
91 // Boolean to keep track of whether or not a CDMA Call Waiting call timed out.
92 //
93 // This is CDMA-specific, because with CDMA we *don't* get explicit
94 // notification from the telephony layer that a call-waiting call has
95 // stopped ringing. Instead, when a call-waiting call first comes in we
96 // start a 20-second timer (see CALLWAITING_CALLERINFO_DISPLAY_DONE), and
97 // if the timer expires we clean up the call and treat it as a missed call.
98 //
99 // If this field is true, that means that the current Call Waiting call
100 // "timed out" and should be logged in Call Log as a missed call. If it's
101 // false when we reach onCdmaCallWaitingReject(), we can assume the user
102 // explicitly rejected this call-waiting call.
103 //
104 // This field is reset to false any time a call-waiting call first comes
105 // in, and after cleaning up a missed call-waiting call. It's only ever
106 // set to true when the CALLWAITING_CALLERINFO_DISPLAY_DONE timer fires.
107 //
108 // TODO: do we really need a member variable for this? Don't we always
109 // know at the moment we call onCdmaCallWaitingReject() whether this is an
110 // explicit rejection or not?
111 // (Specifically: when we call onCdmaCallWaitingReject() from
112 // PhoneUtils.hangupRingingCall() that means the user deliberately rejected
113 // the call, and if we call onCdmaCallWaitingReject() because of a
114 // CALLWAITING_CALLERINFO_DISPLAY_DONE event that means that it timed
115 // out...)
116 private boolean mCallWaitingTimeOut = false;
117
118 // values used to track the query state
119 private static final int CALLERINFO_QUERY_READY = 0;
120 private static final int CALLERINFO_QUERYING = -1;
121
122 // the state of the CallerInfo Query.
123 private int mCallerInfoQueryState;
124
125 // object used to synchronize access to mCallerInfoQueryState
126 private Object mCallerInfoQueryStateGuard = new Object();
127
128 // Event used to indicate a query timeout.
129 private static final int RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT = 100;
130
131 // Events generated internally:
132 private static final int PHONE_MWI_CHANGED = 21;
133 private static final int CALLWAITING_CALLERINFO_DISPLAY_DONE = 22;
134 private static final int CALLWAITING_ADDCALL_DISABLE_TIMEOUT = 23;
135 private static final int DISPLAYINFO_NOTIFICATION_DONE = 24;
136 private static final int CDMA_CALL_WAITING_REJECT = 26;
137 private static final int UPDATE_IN_CALL_NOTIFICATION = 27;
138
139 // Emergency call related defines:
140 private static final int EMERGENCY_TONE_OFF = 0;
141 private static final int EMERGENCY_TONE_ALERT = 1;
142 private static final int EMERGENCY_TONE_VIBRATE = 2;
143
144 private PhoneGlobals mApplication;
145 private CallManager mCM;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700146 private Ringer mRinger;
147 private BluetoothHeadset mBluetoothHeadset;
148 private CallLogger mCallLogger;
149 private boolean mSilentRingerRequested;
150
151 // ToneGenerator instance for playing SignalInfo tones
152 private ToneGenerator mSignalInfoToneGenerator;
153
154 // The tone volume relative to other sounds in the stream SignalInfo
155 private static final int TONE_RELATIVE_VOLUME_SIGNALINFO = 80;
156
157 private Call.State mPreviousCdmaCallState;
158 private boolean mVoicePrivacyState = false;
159 private boolean mIsCdmaRedialCall = false;
160
161 // Emergency call tone and vibrate:
162 private int mIsEmergencyToneOn;
163 private int mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
164 private EmergencyTonePlayerVibrator mEmergencyTonePlayerVibrator;
165
166 // Ringback tone player
167 private InCallTonePlayer mInCallRingbackTonePlayer;
168
169 // Call waiting tone player
170 private InCallTonePlayer mCallWaitingTonePlayer;
171
172 // Cached AudioManager
173 private AudioManager mAudioManager;
174
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700175 private final BluetoothManager mBluetoothManager;
176
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700177 /**
178 * Initialize the singleton CallNotifier instance.
179 * This is only done once, at startup, from PhoneApp.onCreate().
180 */
181 /* package */ static CallNotifier init(PhoneGlobals app, Phone phone, Ringer ringer,
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700182 CallLogger callLogger, CallStateMonitor callStateMonitor,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700183 BluetoothManager bluetoothManager) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700184 synchronized (CallNotifier.class) {
185 if (sInstance == null) {
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700186 sInstance = new CallNotifier(app, phone, ringer, callLogger, callStateMonitor,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700187 bluetoothManager);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700188 } else {
189 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
190 }
191 return sInstance;
192 }
193 }
194
195 /** Private constructor; @see init() */
196 private CallNotifier(PhoneGlobals app, Phone phone, Ringer ringer, CallLogger callLogger,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700197 CallStateMonitor callStateMonitor, BluetoothManager bluetoothManager) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700198 mApplication = app;
199 mCM = app.mCM;
200 mCallLogger = callLogger;
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700201 mBluetoothManager = bluetoothManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700202
203 mAudioManager = (AudioManager) mApplication.getSystemService(Context.AUDIO_SERVICE);
204
205 callStateMonitor.addListener(this);
206
207 createSignalInfoToneGenerator();
208
209 mRinger = ringer;
210 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
211 if (adapter != null) {
212 adapter.getProfileProxy(mApplication.getApplicationContext(),
213 mBluetoothProfileServiceListener,
214 BluetoothProfile.HEADSET);
215 }
216
217 TelephonyManager telephonyManager = (TelephonyManager)app.getSystemService(
218 Context.TELEPHONY_SERVICE);
219 telephonyManager.listen(mPhoneStateListener,
220 PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
221 | PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
222 }
223
224 private void createSignalInfoToneGenerator() {
225 // Instantiate the ToneGenerator for SignalInfo and CallWaiting
226 // TODO: We probably don't need the mSignalInfoToneGenerator instance
227 // around forever. Need to change it so as to create a ToneGenerator instance only
228 // when a tone is being played and releases it after its done playing.
229 if (mSignalInfoToneGenerator == null) {
230 try {
231 mSignalInfoToneGenerator = new ToneGenerator(AudioManager.STREAM_VOICE_CALL,
232 TONE_RELATIVE_VOLUME_SIGNALINFO);
233 Log.d(LOG_TAG, "CallNotifier: mSignalInfoToneGenerator created when toneplay");
234 } catch (RuntimeException e) {
235 Log.w(LOG_TAG, "CallNotifier: Exception caught while creating " +
236 "mSignalInfoToneGenerator: " + e);
237 mSignalInfoToneGenerator = null;
238 }
239 } else {
240 Log.d(LOG_TAG, "mSignalInfoToneGenerator created already, hence skipping");
241 }
242 }
243
244 @Override
245 public void handleMessage(Message msg) {
246 switch (msg.what) {
247 case CallStateMonitor.PHONE_NEW_RINGING_CONNECTION:
248 log("RINGING... (new)");
249 onNewRingingConnection((AsyncResult) msg.obj);
250 mSilentRingerRequested = false;
251 break;
252
253 case CallStateMonitor.PHONE_INCOMING_RING:
254 // repeat the ring when requested by the RIL, and when the user has NOT
255 // specifically requested silence.
256 if (msg.obj != null && ((AsyncResult) msg.obj).result != null) {
257 PhoneBase pb = (PhoneBase)((AsyncResult)msg.obj).result;
258
259 if ((pb.getState() == PhoneConstants.State.RINGING)
260 && (mSilentRingerRequested == false)) {
261 if (DBG) log("RINGING... (PHONE_INCOMING_RING event)");
262 mRinger.ring();
263 } else {
264 if (DBG) log("RING before NEW_RING, skipping");
265 }
266 }
267 break;
268
269 case CallStateMonitor.PHONE_STATE_CHANGED:
270 onPhoneStateChanged((AsyncResult) msg.obj);
271 break;
272
273 case CallStateMonitor.PHONE_DISCONNECT:
274 if (DBG) log("DISCONNECT");
275 onDisconnect((AsyncResult) msg.obj);
276 break;
277
278 case CallStateMonitor.PHONE_UNKNOWN_CONNECTION_APPEARED:
279 onUnknownConnectionAppeared((AsyncResult) msg.obj);
280 break;
281
282 case RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT:
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700283 onCustomRingtoneQueryTimeout((Connection) msg.obj);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700284 break;
285
286 case PHONE_MWI_CHANGED:
287 onMwiChanged(mApplication.phone.getMessageWaitingIndicator());
288 break;
289
290 case CallStateMonitor.PHONE_CDMA_CALL_WAITING:
291 if (DBG) log("Received PHONE_CDMA_CALL_WAITING event");
292 onCdmaCallWaiting((AsyncResult) msg.obj);
293 break;
294
295 case CDMA_CALL_WAITING_REJECT:
296 Log.i(LOG_TAG, "Received CDMA_CALL_WAITING_REJECT event");
297 onCdmaCallWaitingReject();
298 break;
299
300 case CALLWAITING_CALLERINFO_DISPLAY_DONE:
301 Log.i(LOG_TAG, "Received CALLWAITING_CALLERINFO_DISPLAY_DONE event");
302 mCallWaitingTimeOut = true;
303 onCdmaCallWaitingReject();
304 break;
305
306 case CALLWAITING_ADDCALL_DISABLE_TIMEOUT:
307 if (DBG) log("Received CALLWAITING_ADDCALL_DISABLE_TIMEOUT event ...");
308 // Set the mAddCallMenuStateAfterCW state to true
309 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700310 break;
311
312 case CallStateMonitor.PHONE_STATE_DISPLAYINFO:
313 if (DBG) log("Received PHONE_STATE_DISPLAYINFO event");
314 onDisplayInfo((AsyncResult) msg.obj);
315 break;
316
317 case CallStateMonitor.PHONE_STATE_SIGNALINFO:
318 if (DBG) log("Received PHONE_STATE_SIGNALINFO event");
319 onSignalInfo((AsyncResult) msg.obj);
320 break;
321
322 case DISPLAYINFO_NOTIFICATION_DONE:
323 if (DBG) log("Received Display Info notification done event ...");
324 CdmaDisplayInfo.dismissDisplayInfoRecord();
325 break;
326
327 case CallStateMonitor.EVENT_OTA_PROVISION_CHANGE:
328 if (DBG) log("EVENT_OTA_PROVISION_CHANGE...");
329 mApplication.handleOtaspEvent(msg);
330 break;
331
332 case CallStateMonitor.PHONE_ENHANCED_VP_ON:
333 if (DBG) log("PHONE_ENHANCED_VP_ON...");
334 if (!mVoicePrivacyState) {
335 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
336 new InCallTonePlayer(toneToPlay).start();
337 mVoicePrivacyState = true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700338 }
339 break;
340
341 case CallStateMonitor.PHONE_ENHANCED_VP_OFF:
342 if (DBG) log("PHONE_ENHANCED_VP_OFF...");
343 if (mVoicePrivacyState) {
344 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
345 new InCallTonePlayer(toneToPlay).start();
346 mVoicePrivacyState = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700347 }
348 break;
349
350 case CallStateMonitor.PHONE_RINGBACK_TONE:
Ihab Awad277011f2014-05-28 16:51:33 -0700351 // DISABLED. The Telecomm and new ConnectionService layers are now responsible.
352 // onRingbackTone((AsyncResult) msg.obj);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700353 break;
354
355 case CallStateMonitor.PHONE_RESEND_MUTE:
356 onResendMute();
357 break;
358
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700359 default:
360 // super.handleMessage(msg);
361 }
362 }
363
364 PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
365 @Override
366 public void onMessageWaitingIndicatorChanged(boolean mwi) {
367 onMwiChanged(mwi);
368 }
369
370 @Override
371 public void onCallForwardingIndicatorChanged(boolean cfi) {
372 onCfiChanged(cfi);
373 }
374 };
375
376 /**
377 * Handles a "new ringing connection" event from the telephony layer.
378 */
379 private void onNewRingingConnection(AsyncResult r) {
380 Connection c = (Connection) r.result;
381 log("onNewRingingConnection(): state = " + mCM.getState() + ", conn = { " + c + " }");
382 Call ringing = c.getCall();
383 Phone phone = ringing.getPhone();
384
385 // Check for a few cases where we totally ignore incoming calls.
386 if (ignoreAllIncomingCalls(phone)) {
387 // Immediately reject the call, without even indicating to the user
388 // that an incoming call occurred. (This will generally send the
389 // caller straight to voicemail, just as if we *had* shown the
390 // incoming-call UI and the user had declined the call.)
391 PhoneUtils.hangupRingingCall(ringing);
392 return;
393 }
394
395 if (!c.isRinging()) {
396 Log.i(LOG_TAG, "CallNotifier.onNewRingingConnection(): connection not ringing!");
397 // This is a very strange case: an incoming call that stopped
398 // ringing almost instantly after the onNewRingingConnection()
399 // event. There's nothing we can do here, so just bail out
400 // without doing anything. (But presumably we'll log it in
401 // the call log when the disconnect event comes in...)
402 return;
403 }
404
405 // Stop any signalInfo tone being played on receiving a Call
406 stopSignalInfoTone();
407
408 Call.State state = c.getState();
409 // State will be either INCOMING or WAITING.
410 if (VDBG) log("- connection is ringing! state = " + state);
411 // if (DBG) PhoneUtils.dumpCallState(mPhone);
412
413 // No need to do any service state checks here (like for
414 // "emergency mode"), since in those states the SIM won't let
415 // us get incoming connections in the first place.
416
417 // TODO: Consider sending out a serialized broadcast Intent here
418 // (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the
419 // ringer and going to the in-call UI. The intent should contain
420 // the caller-id info for the current connection, and say whether
421 // it would be a "call waiting" call or a regular ringing call.
422 // If anybody consumed the broadcast, we'd bail out without
423 // ringing or bringing up the in-call UI.
424 //
425 // This would give 3rd party apps a chance to listen for (and
426 // intercept) new ringing connections. An app could reject the
427 // incoming call by consuming the broadcast and doing nothing, or
428 // it could "pick up" the call (without any action by the user!)
429 // via some future TelephonyManager API.
430 //
431 // See bug 1312336 for more details.
432 // We'd need to protect this with a new "intercept incoming calls"
433 // system permission.
434
435 // Obtain a partial wake lock to make sure the CPU doesn't go to
436 // sleep before we finish bringing up the InCallScreen.
437 // (This will be upgraded soon to a full wake lock; see
438 // showIncomingCall().)
439 if (VDBG) log("Holding wake lock on new incoming connection.");
440 mApplication.requestWakeState(PhoneGlobals.WakeState.PARTIAL);
441
442 // - don't ring for call waiting connections
443 // - do this before showing the incoming call panel
Christine Chenb5e4b652013-09-19 11:20:18 -0700444 startIncomingCallQuery(c);
Chiao Cheng312b9c92013-09-16 15:40:53 -0700445
Christine Chenb5e4b652013-09-19 11:20:18 -0700446
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700447
448 // Note we *don't* post a status bar notification here, since
449 // we're not necessarily ready to actually show the incoming call
450 // to the user. (For calls in the INCOMING state, at least, we
451 // still need to run a caller-id query, and we may not even ring
452 // at all if the "send directly to voicemail" flag is set.)
453 //
454 // Instead, we update the notification (and potentially launch the
455 // InCallScreen) from the showIncomingCall() method, which runs
456 // when the caller-id query completes or times out.
457
458 if (VDBG) log("- onNewRingingConnection() done.");
459 }
460
461 /**
462 * Determines whether or not we're allowed to present incoming calls to the
463 * user, based on the capabilities and/or current state of the device.
464 *
465 * If this method returns true, that means we should immediately reject the
466 * current incoming call, without even indicating to the user that an
467 * incoming call occurred.
468 *
469 * (We only reject incoming calls in a few cases, like during an OTASP call
470 * when we can't interrupt the user, or if the device hasn't completed the
471 * SetupWizard yet. We also don't allow incoming calls on non-voice-capable
472 * devices. But note that we *always* allow incoming calls while in ECM.)
473 *
474 * @return true if we're *not* allowed to present an incoming call to
475 * the user.
476 */
477 private boolean ignoreAllIncomingCalls(Phone phone) {
478 // Incoming calls are totally ignored on non-voice-capable devices.
479 if (!PhoneGlobals.sVoiceCapable) {
480 // ...but still log a warning, since we shouldn't have gotten this
481 // event in the first place! (Incoming calls *should* be blocked at
482 // the telephony layer on non-voice-capable capable devices.)
483 Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring...");
484 return true;
485 }
486
487 // In ECM (emergency callback mode), we ALWAYS allow incoming calls
488 // to get through to the user. (Note that ECM is applicable only to
489 // voice-capable CDMA devices).
490 if (PhoneUtils.isPhoneInEcm(phone)) {
491 if (DBG) log("Incoming call while in ECM: always allow...");
492 return false;
493 }
494
495 // Incoming calls are totally ignored if the device isn't provisioned yet.
496 boolean provisioned = Settings.Global.getInt(mApplication.getContentResolver(),
497 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
498 if (!provisioned) {
499 Log.i(LOG_TAG, "Ignoring incoming call: not provisioned");
500 return true;
501 }
502
503 // Incoming calls are totally ignored if an OTASP call is active.
504 if (TelephonyCapabilities.supportsOtasp(phone)) {
505 boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState
506 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
507 boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState
508 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG);
509 boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState;
510
511 if (spcState) {
512 Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active");
513 return true;
514 } else if (activateState || dialogState) {
515 // We *are* allowed to receive incoming calls at this point.
516 // But clear out any residual OTASP UI first.
517 // TODO: It's an MVC violation to twiddle the OTA UI state here;
518 // we should instead provide a higher-level API via OtaUtils.
519 if (dialogState) mApplication.dismissOtaDialogs();
520 mApplication.clearOtaState();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700521 return false;
522 }
523 }
524
525 // Normal case: allow this call to be presented to the user.
526 return false;
527 }
528
529 /**
530 * Helper method to manage the start of incoming call queries
531 */
532 private void startIncomingCallQuery(Connection c) {
533 // TODO: cache the custom ringer object so that subsequent
534 // calls will not need to do this query work. We can keep
535 // the MRU ringtones in memory. We'll still need to hit
536 // the database to get the callerinfo to act as a key,
537 // but at least we can save the time required for the
538 // Media player setup. The only issue with this is that
539 // we may need to keep an eye on the resources the Media
540 // player uses to keep these ringtones around.
541
542 // make sure we're in a state where we can be ready to
543 // query a ringtone uri.
544 boolean shouldStartQuery = false;
545 synchronized (mCallerInfoQueryStateGuard) {
546 if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) {
547 mCallerInfoQueryState = CALLERINFO_QUERYING;
548 shouldStartQuery = true;
549 }
550 }
551 if (shouldStartQuery) {
552 // Reset the ringtone to the default first.
553 mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI);
554
555 // query the callerinfo to try to get the ringer.
556 PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700557 mApplication, c, this, c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700558
559 // if this has already been queried then just ring, otherwise
560 // we wait for the alloted time before ringing.
561 if (cit.isFinal) {
562 if (VDBG) log("- CallerInfo already up to date, using available data");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700563 onQueryComplete(0, c, cit.currentInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700564 } else {
565 if (VDBG) log("- Starting query, posting timeout message.");
566
567 // Phone number (via getAddress()) is stored in the message to remember which
568 // number is actually used for the look up.
569 sendMessageDelayed(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700570 Message.obtain(this, RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT, c),
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700571 RINGTONE_QUERY_WAIT_TIME);
572 }
573 // The call to showIncomingCall() will happen after the
574 // queries are complete (or time out).
575 } else {
576 // This should never happen; its the case where an incoming call
577 // arrives at the same time that the query is still being run,
578 // and before the timeout window has closed.
579 EventLog.writeEvent(EventLogTags.PHONE_UI_MULTIPLE_QUERY);
580
Christine Chenb5e4b652013-09-19 11:20:18 -0700581 ringAndNotifyOfIncomingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700582 }
583 }
584
585 /**
586 * Performs the final steps of the onNewRingingConnection sequence:
587 * starts the ringer, and brings up the "incoming call" UI.
588 *
589 * Normally, this is called when the CallerInfo query completes (see
590 * onQueryComplete()). In this case, onQueryComplete() has already
591 * configured the Ringer object to use the custom ringtone (if there
592 * is one) for this caller. So we just tell the Ringer to start, and
593 * proceed to the InCallScreen.
594 *
595 * But this method can *also* be called if the
596 * RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the
597 * CallerInfo query is taking too long. In that case, we log a
598 * warning but otherwise we behave the same as in the normal case.
599 * (We still tell the Ringer to start, but it's going to use the
600 * default ringtone.)
601 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700602 private void onCustomRingQueryComplete(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700603 boolean isQueryExecutionTimeExpired = false;
604 synchronized (mCallerInfoQueryStateGuard) {
605 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
606 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
607 isQueryExecutionTimeExpired = true;
608 }
609 }
610 if (isQueryExecutionTimeExpired) {
611 // There may be a problem with the query here, since the
612 // default ringtone is playing instead of the custom one.
613 Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone");
614 EventLog.writeEvent(EventLogTags.PHONE_UI_RINGER_QUERY_ELAPSED);
615 }
616
617 // Make sure we still have an incoming call!
618 //
619 // (It's possible for the incoming call to have been disconnected
620 // while we were running the query. In that case we better not
621 // start the ringer here, since there won't be any future
622 // DISCONNECT event to stop it!)
623 //
624 // Note we don't have to worry about the incoming call going away
625 // *after* this check but before we call mRinger.ring() below,
626 // since in that case we *will* still get a DISCONNECT message sent
627 // to our handler. (And we will correctly stop the ringer when we
628 // process that event.)
629 if (mCM.getState() != PhoneConstants.State.RINGING) {
630 Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out...");
631 // Don't start the ringer *or* bring up the "incoming call" UI.
632 // Just bail out.
633 return;
634 }
635
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700636 // If the ringing call still does not have any connection anymore, do not send the
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700637 // notification.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700638 final Call ringingCall = mCM.getFirstActiveRingingCall();
639
640 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
Christine Chenb5e4b652013-09-19 11:20:18 -0700641 ringAndNotifyOfIncomingCall(c);
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700642 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700643 }
644
645 private void onUnknownConnectionAppeared(AsyncResult r) {
646 PhoneConstants.State state = mCM.getState();
647
648 if (state == PhoneConstants.State.OFFHOOK) {
Santos Cordon54fdb592013-09-19 05:16:18 -0700649 if (DBG) log("unknown connection appeared...");
Chiao Cheng312b9c92013-09-16 15:40:53 -0700650
Santos Cordon54fdb592013-09-19 05:16:18 -0700651 onPhoneStateChanged(r);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700652 }
653 }
654
Christine Chenb5e4b652013-09-19 11:20:18 -0700655 /**
Christine Chenb5e4b652013-09-19 11:20:18 -0700656 * If it is not a waiting call (there is no other active call in foreground), we will ring the
657 * ringtone. Otherwise we will play the call waiting tone instead.
658 * @param c The new ringing connection.
659 */
660 private void ringAndNotifyOfIncomingCall(Connection c) {
661 if (PhoneUtils.isRealIncomingCall(c.getState())) {
662 mRinger.ring();
663 } else {
664 if (VDBG) log("- starting call waiting tone...");
665 if (mCallWaitingTonePlayer == null) {
666 mCallWaitingTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING);
667 mCallWaitingTonePlayer.start();
668 }
669 }
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700670 }
671
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700672 /**
673 * Updates the phone UI in response to phone state changes.
674 *
675 * Watch out: certain state changes are actually handled by their own
676 * specific methods:
677 * - see onNewRingingConnection() for new incoming calls
678 * - see onDisconnect() for calls being hung up or disconnected
679 */
680 private void onPhoneStateChanged(AsyncResult r) {
681 PhoneConstants.State state = mCM.getState();
682 if (VDBG) log("onPhoneStateChanged: state = " + state);
683
684 // Turn status bar notifications on or off depending upon the state
685 // of the phone. Notification Alerts (audible or vibrating) should
686 // be on if and only if the phone is IDLE.
687 mApplication.notificationMgr.statusBarHelper
688 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
689
690 Phone fgPhone = mCM.getFgPhone();
691 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
692 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
693 && ((mPreviousCdmaCallState == Call.State.DIALING)
694 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
695 if (mIsCdmaRedialCall) {
696 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
697 new InCallTonePlayer(toneToPlay).start();
698 }
699 // Stop any signal info tone when call moves to ACTIVE state
700 stopSignalInfoTone();
701 }
702 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
703 }
704
705 // Have the PhoneApp recompute its mShowBluetoothIndication
706 // flag based on the (new) telephony state.
707 // There's no need to force a UI update since we update the
708 // in-call notification ourselves (below), and the InCallScreen
709 // listens for phone state changes itself.
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700710 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700711
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700712 // Update the phone state and other sensor/lock.
713 mApplication.updatePhoneState(state);
714
715 if (state == PhoneConstants.State.OFFHOOK) {
716 // stop call waiting tone if needed when answering
717 if (mCallWaitingTonePlayer != null) {
718 mCallWaitingTonePlayer.stopTone();
719 mCallWaitingTonePlayer = null;
720 }
721
722 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
723 // make sure audio is in in-call mode now
724 PhoneUtils.setAudioMode(mCM);
725
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700726 // Since we're now in-call, the Ringer should definitely *not*
727 // be ringing any more. (This is just a sanity-check; we
728 // already stopped the ringer explicitly back in
729 // PhoneUtils.answerCall(), before the call to phone.acceptCall().)
730 // TODO: Confirm that this call really *is* unnecessary, and if so,
731 // remove it!
732 if (DBG) log("stopRing()... (OFFHOOK state)");
733 mRinger.stopRing();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700734 }
735
736 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
737 Connection c = fgPhone.getForegroundCall().getLatestConnection();
Yorke Lee36bb2542014-06-05 08:09:52 -0700738 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(mApplication,
739 c.getAddress()))) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700740 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
741 Call.State callState = fgPhone.getForegroundCall().getState();
742 if (mEmergencyTonePlayerVibrator == null) {
743 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
744 }
745
746 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
747 mIsEmergencyToneOn = Settings.Global.getInt(
748 mApplication.getContentResolver(),
749 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
750 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
751 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
752 if (mEmergencyTonePlayerVibrator != null) {
753 mEmergencyTonePlayerVibrator.start();
754 }
755 }
756 } else if (callState == Call.State.ACTIVE) {
757 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
758 if (mEmergencyTonePlayerVibrator != null) {
759 mEmergencyTonePlayerVibrator.stop();
760 }
761 }
762 }
763 }
764 }
765
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800766 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM
767 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -0700768 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800769 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700770 Call.State callState = mCM.getActiveFgCallState();
771 if (!callState.isDialing()) {
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800772 // If call gets activated or disconnected before the ringback
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700773 // tone stops, we have to stop it to prevent disturbing.
774 if (mInCallRingbackTonePlayer != null) {
775 mInCallRingbackTonePlayer.stopTone();
776 mInCallRingbackTonePlayer = null;
777 }
778 }
779 }
780 }
781
782 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
783 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
784
785 // Clear ringback tone player
786 mInCallRingbackTonePlayer = null;
787
788 // Clear call waiting tone player
789 mCallWaitingTonePlayer = null;
790
791 // Instantiate mSignalInfoToneGenerator
792 createSignalInfoToneGenerator();
793 }
794
795 /**
796 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
797 * refreshes the CallCard data when it called. If called with this
798 * class itself, it is assumed that we have been waiting for the ringtone
799 * and direct to voicemail settings to update.
800 */
801 @Override
802 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
803 if (cookie instanceof Long) {
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700804 } else if (cookie instanceof Connection) {
805 final Connection c = (Connection) cookie;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700806 if (VDBG) log("CallerInfo query complete (for CallNotifier), "
807 + "updating state for incoming call..");
808
809 // get rid of the timeout messages
810 removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
811
812 boolean isQueryExecutionTimeOK = false;
813 synchronized (mCallerInfoQueryStateGuard) {
814 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
815 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
816 isQueryExecutionTimeOK = true;
817 }
818 }
819 //if we're in the right state
820 if (isQueryExecutionTimeOK) {
821
822 // send directly to voicemail.
823 if (ci.shouldSendToVoicemail) {
824 if (DBG) log("send to voicemail flag detected. hanging up.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700825 final Call ringingCall = mCM.getFirstActiveRingingCall();
826 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
827 PhoneUtils.hangupRingingCall(ringingCall);
828 return;
829 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700830 }
831
832 // set the ringtone uri to prepare for the ring.
833 if (ci.contactRingtoneUri != null) {
834 if (DBG) log("custom ringtone found, setting up ringer.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700835 Ringer r = mRinger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700836 r.setCustomRingtoneUri(ci.contactRingtoneUri);
837 }
838 // ring, and other post-ring actions.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700839 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700840 }
841 }
842 }
843
844 /**
845 * Called when asynchronous CallerInfo query is taking too long (more than
846 * {@link #RINGTONE_QUERY_WAIT_TIME} msec), but we cannot wait any more.
847 *
848 * This looks up in-memory fallback cache and use it when available. If not, it just calls
849 * {@link #onCustomRingQueryComplete()} with default ringtone ("Send to voicemail" flag will
850 * be just ignored).
851 *
852 * @param number The phone number used for the async query. This method will take care of
853 * formatting or normalization of the number.
854 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700855 private void onCustomRingtoneQueryTimeout(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700856 // First of all, this case itself should be rare enough, though we cannot avoid it in
857 // some situations (e.g. IPC is slow due to system overload, database is in sync, etc.)
858 Log.w(LOG_TAG, "CallerInfo query took too long; look up local fallback cache.");
859
860 // This method is intentionally verbose for now to detect possible bad side-effect for it.
861 // TODO: Remove the verbose log when it looks stable and reliable enough.
862
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700863
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700864 if (c != null) {
865 final CallerInfoCache.CacheEntry entry =
866 mApplication.callerInfoCache.getCacheEntry(c.getAddress());
867 if (entry != null) {
868 if (entry.sendToVoicemail) {
869 log("send to voicemail flag detected (in fallback cache). hanging up.");
870 if (mCM.getFirstActiveRingingCall().getLatestConnection() == c) {
871 PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
872 return;
873 }
874 }
875
876 if (entry.customRingtone != null) {
877 log("custom ringtone found (in fallback cache), setting up ringer: "
878 + entry.customRingtone);
879 this.mRinger.setCustomRingtoneUri(Uri.parse(entry.customRingtone));
880 }
881 } else {
882 // In this case we call onCustomRingQueryComplete(), just
883 // like if the query had completed normally. (But we're
884 // going to get the default ringtone, since we never got
885 // the chance to call Ringer.setCustomRingtoneUri()).
886 log("Failed to find fallback cache. Use default ringer tone.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700887 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700888 }
889
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700890 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700891 }
892
893 private void onDisconnect(AsyncResult r) {
894 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
895
896 mVoicePrivacyState = false;
897 Connection c = (Connection) r.result;
898 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800899 log("onDisconnect: cause = " + DisconnectCause.toString(c.getDisconnectCause())
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700900 + ", incoming = " + c.isIncoming()
901 + ", date = " + c.getCreateTime());
902 } else {
903 Log.w(LOG_TAG, "onDisconnect: null connection");
904 }
905
906 int autoretrySetting = 0;
907 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
908 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
909 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
910 }
911
912 // Stop any signalInfo tone being played when a call gets ended
913 stopSignalInfoTone();
914
915 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
916 // Resetting the CdmaPhoneCallState members
917 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
918
919 // Remove Call waiting timers
920 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
921 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
922 }
923
924 // Stop the ringer if it was ringing (for an incoming call that
925 // either disconnected by itself, or was rejected by the user.)
926 //
927 // TODO: We technically *shouldn't* stop the ringer if the
928 // foreground or background call disconnects while an incoming call
929 // is still ringing, but that's a really rare corner case.
930 // It's safest to just unconditionally stop the ringer here.
931
932 // CDMA: For Call collision cases i.e. when the user makes an out going call
933 // and at the same time receives an Incoming Call, the Incoming Call is given
934 // higher preference. At this time framework sends a disconnect for the Out going
935 // call connection hence we should *not* be stopping the ringer being played for
936 // the Incoming Call
937 Call ringingCall = mCM.getFirstActiveRingingCall();
938 if (ringingCall.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordon352ff652014-05-30 01:41:45 -0700939 if (!PhoneUtils.isRealIncomingCall(ringingCall.getState())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700940 if (DBG) log("stopRing()... (onDisconnect)");
941 mRinger.stopRing();
942 }
943 } else { // GSM
944 if (DBG) log("stopRing()... (onDisconnect)");
945 mRinger.stopRing();
946 }
947
948 // stop call waiting tone if needed when disconnecting
949 if (mCallWaitingTonePlayer != null) {
950 mCallWaitingTonePlayer.stopTone();
951 mCallWaitingTonePlayer = null;
952 }
953
954 // If this is the end of an OTASP call, pass it on to the PhoneApp.
955 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
956 final String number = c.getAddress();
957 if (c.getCall().getPhone().isOtaSpNumber(number)) {
958 if (DBG) log("onDisconnect: this was an OTASP call!");
959 mApplication.handleOtaspDisconnect();
960 }
961 }
962
963 // Check for the various tones we might need to play (thru the
964 // earpiece) after a call disconnects.
965 int toneToPlay = InCallTonePlayer.TONE_NONE;
966
967 // The "Busy" or "Congestion" tone is the highest priority:
968 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800969 int cause = c.getDisconnectCause();
970 if (cause == DisconnectCause.BUSY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700971 if (DBG) log("- need to play BUSY tone!");
972 toneToPlay = InCallTonePlayer.TONE_BUSY;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800973 } else if (cause == DisconnectCause.CONGESTION) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700974 if (DBG) log("- need to play CONGESTION tone!");
975 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800976 } else if (((cause == DisconnectCause.NORMAL)
977 || (cause == DisconnectCause.LOCAL))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700978 && (mApplication.isOtaCallInActiveState())) {
979 if (DBG) log("- need to play OTA_CALL_END tone!");
980 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800981 } else if (cause == DisconnectCause.CDMA_REORDER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700982 if (DBG) log("- need to play CDMA_REORDER tone!");
983 toneToPlay = InCallTonePlayer.TONE_REORDER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800984 } else if (cause == DisconnectCause.CDMA_INTERCEPT) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700985 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
986 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800987 } else if (cause == DisconnectCause.CDMA_DROP) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700988 if (DBG) log("- need to play CDMA_DROP tone!");
989 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800990 } else if (cause == DisconnectCause.OUT_OF_SERVICE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700991 if (DBG) log("- need to play OUT OF SERVICE tone!");
992 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800993 } else if (cause == DisconnectCause.UNOBTAINABLE_NUMBER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700994 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
995 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800996 } else if (cause == DisconnectCause.ERROR_UNSPECIFIED) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700997 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
998 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
999 }
1000 }
1001
1002 // If we don't need to play BUSY or CONGESTION, then play the
1003 // "call ended" tone if this was a "regular disconnect" (i.e. a
1004 // normal call where one end or the other hung up) *and* this
1005 // disconnect event caused the phone to become idle. (In other
1006 // words, we *don't* play the sound if one call hangs up but
1007 // there's still an active call on the other line.)
1008 // TODO: We may eventually want to disable this via a preference.
1009 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
1010 && (mCM.getState() == PhoneConstants.State.IDLE)
1011 && (c != null)) {
Anders Kristensen0b35f042014-02-27 14:31:07 -08001012 int cause = c.getDisconnectCause();
1013 if ((cause == DisconnectCause.NORMAL) // remote hangup
1014 || (cause == DisconnectCause.LOCAL)) { // local hangup
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001015 if (VDBG) log("- need to play CALL_ENDED tone!");
1016 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1017 mIsCdmaRedialCall = false;
1018 }
1019 }
1020
1021 // All phone calls are disconnected.
1022 if (mCM.getState() == PhoneConstants.State.IDLE) {
1023 // Don't reset the audio mode or bluetooth/speakerphone state
1024 // if we still need to let the user hear a tone through the earpiece.
1025 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
1026 resetAudioStateAfterDisconnect();
1027 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001028 }
1029
1030 if (c != null) {
1031 mCallLogger.logCall(c);
1032
1033 final String number = c.getAddress();
1034 final Phone phone = c.getCall().getPhone();
1035 final boolean isEmergencyNumber =
Yorke Lee36bb2542014-06-05 08:09:52 -07001036 PhoneNumberUtils.isLocalEmergencyNumber(mApplication, number);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001037
1038 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1039 if ((isEmergencyNumber)
1040 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
1041 if (mEmergencyTonePlayerVibrator != null) {
1042 mEmergencyTonePlayerVibrator.stop();
1043 }
1044 }
1045 }
1046
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001047 // Possibly play a "post-disconnect tone" thru the earpiece.
1048 // We do this here, rather than from the InCallScreen
1049 // activity, since we need to do this even if you're not in
1050 // the Phone UI at the moment the connection ends.
1051 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
1052 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
1053 new InCallTonePlayer(toneToPlay).start();
1054
1055 // TODO: alternatively, we could start an InCallTonePlayer
1056 // here with an "unlimited" tone length,
1057 // and manually stop it later when this connection truly goes
1058 // away. (The real connection over the network was closed as soon
1059 // as we got the BUSY message. But our telephony layer keeps the
1060 // connection open for a few extra seconds so we can show the
1061 // "busy" indication to the user. We could stop the busy tone
1062 // when *that* connection's "disconnect" event comes in.)
1063 }
1064
Santos Cordonf68db2e2014-07-02 14:40:44 -07001065 final int cause = c.getDisconnectCause();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001066 if (((mPreviousCdmaCallState == Call.State.DIALING)
1067 || (mPreviousCdmaCallState == Call.State.ALERTING))
1068 && (!isEmergencyNumber)
Anders Kristensen0b35f042014-02-27 14:31:07 -08001069 && (cause != DisconnectCause.INCOMING_MISSED )
1070 && (cause != DisconnectCause.NORMAL)
1071 && (cause != DisconnectCause.LOCAL)
1072 && (cause != DisconnectCause.INCOMING_REJECTED)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001073 if (!mIsCdmaRedialCall) {
1074 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
1075 // TODO: (Moto): The contact reference data may need to be stored and use
1076 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordonce02f3a2013-09-19 01:58:42 -07001077 final int status =
1078 PhoneUtils.placeCall(mApplication, phone, number, null, false);
1079 if (status != PhoneUtils.CALL_STATUS_FAILED) {
1080 mIsCdmaRedialCall = true;
1081 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001082 } else {
1083 mIsCdmaRedialCall = false;
1084 }
1085 } else {
1086 mIsCdmaRedialCall = false;
1087 }
1088 }
1089 }
1090 }
1091
1092 /**
1093 * Resets the audio mode and speaker state when a call ends.
1094 */
1095 private void resetAudioStateAfterDisconnect() {
1096 if (VDBG) log("resetAudioStateAfterDisconnect()...");
1097
1098 if (mBluetoothHeadset != null) {
1099 mBluetoothHeadset.disconnectAudio();
1100 }
1101
1102 // call turnOnSpeaker() with state=false and store=true even if speaker
1103 // is already off to reset user requested speaker state.
1104 PhoneUtils.turnOnSpeaker(mApplication, false, true);
1105
1106 PhoneUtils.setAudioMode(mCM);
1107 }
1108
1109 private void onMwiChanged(boolean visible) {
1110 if (VDBG) log("onMwiChanged(): " + visible);
1111
1112 // "Voicemail" is meaningless on non-voice-capable devices,
1113 // so ignore MWI events.
1114 if (!PhoneGlobals.sVoiceCapable) {
1115 // ...but still log a warning, since we shouldn't have gotten this
1116 // event in the first place!
1117 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
1118 // *should* be blocked at the telephony layer on non-voice-capable
1119 // capable devices.)
1120 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
1121 return;
1122 }
1123
1124 mApplication.notificationMgr.updateMwi(visible);
1125 }
1126
1127 /**
1128 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
1129 * failed NotificationMgr.updateMwi() call.
1130 */
1131 /* package */ void sendMwiChangedDelayed(long delayMillis) {
1132 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
1133 sendMessageDelayed(message, delayMillis);
1134 }
1135
1136 private void onCfiChanged(boolean visible) {
1137 if (VDBG) log("onCfiChanged(): " + visible);
1138 mApplication.notificationMgr.updateCfi(visible);
1139 }
1140
1141 /**
1142 * Indicates whether or not this ringer is ringing.
1143 */
1144 boolean isRinging() {
1145 return mRinger.isRinging();
1146 }
1147
1148 /**
1149 * Stops the current ring, and tells the notifier that future
1150 * ring requests should be ignored.
1151 */
1152 void silenceRinger() {
1153 mSilentRingerRequested = true;
1154 if (DBG) log("stopRing()... (silenceRinger)");
1155 mRinger.stopRing();
1156 }
1157
1158 /**
1159 * Restarts the ringer after having previously silenced it.
1160 *
1161 * (This is a no-op if the ringer is actually still ringing, or if the
1162 * incoming ringing call no longer exists.)
1163 */
1164 /* package */ void restartRinger() {
1165 if (DBG) log("restartRinger()...");
1166 // Already ringing or Silent requested; no need to restart.
1167 if (isRinging() || mSilentRingerRequested) return;
1168
1169 final Call ringingCall = mCM.getFirstActiveRingingCall();
1170 // Don't check ringingCall.isRinging() here, since that'll be true
1171 // for the WAITING state also. We only allow the ringer for
1172 // regular INCOMING calls.
1173 if (DBG) log("- ringingCall state: " + ringingCall.getState());
1174 if (ringingCall.getState() == Call.State.INCOMING) {
1175 mRinger.ring();
1176 }
1177 }
1178
1179 /**
1180 * Helper class to play tones through the earpiece (or speaker / BT)
1181 * during a call, using the ToneGenerator.
1182 *
1183 * To use, just instantiate a new InCallTonePlayer
1184 * (passing in the TONE_* constant for the tone you want)
1185 * and start() it.
1186 *
1187 * When we're done playing the tone, if the phone is idle at that
1188 * point, we'll reset the audio routing and speaker state.
1189 * (That means that for tones that get played *after* a call
1190 * disconnects, like "busy" or "congestion" or "call ended", you
1191 * should NOT call resetAudioStateAfterDisconnect() yourself.
1192 * Instead, just start the InCallTonePlayer, which will automatically
1193 * defer the resetAudioStateAfterDisconnect() call until the tone
1194 * finishes playing.)
1195 */
1196 private class InCallTonePlayer extends Thread {
1197 private int mToneId;
1198 private int mState;
1199 // The possible tones we can play.
1200 public static final int TONE_NONE = 0;
1201 public static final int TONE_CALL_WAITING = 1;
1202 public static final int TONE_BUSY = 2;
1203 public static final int TONE_CONGESTION = 3;
1204 public static final int TONE_CALL_ENDED = 4;
1205 public static final int TONE_VOICE_PRIVACY = 5;
1206 public static final int TONE_REORDER = 6;
1207 public static final int TONE_INTERCEPT = 7;
1208 public static final int TONE_CDMA_DROP = 8;
1209 public static final int TONE_OUT_OF_SERVICE = 9;
1210 public static final int TONE_REDIAL = 10;
1211 public static final int TONE_OTA_CALL_END = 11;
1212 public static final int TONE_RING_BACK = 12;
1213 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
1214
1215 // The tone volume relative to other sounds in the stream
1216 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
1217 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
1218 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
1219
1220 // Buffer time (in msec) to add on to tone timeout value.
1221 // Needed mainly when the timeout value for a tone is the
1222 // exact duration of the tone itself.
1223 static final int TONE_TIMEOUT_BUFFER = 20;
1224
1225 // The tone state
1226 static final int TONE_OFF = 0;
1227 static final int TONE_ON = 1;
1228 static final int TONE_STOPPED = 2;
1229
1230 InCallTonePlayer(int toneId) {
1231 super();
1232 mToneId = toneId;
1233 mState = TONE_OFF;
1234 }
1235
1236 @Override
1237 public void run() {
1238 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
1239
1240 int toneType = 0; // passed to ToneGenerator.startTone()
1241 int toneVolume; // passed to the ToneGenerator constructor
1242 int toneLengthMillis;
1243 int phoneType = mCM.getFgPhone().getPhoneType();
1244
1245 switch (mToneId) {
1246 case TONE_CALL_WAITING:
1247 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
1248 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1249 // Call waiting tone is stopped by stopTone() method
1250 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1251 break;
1252 case TONE_BUSY:
1253 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1254 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
1255 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1256 toneLengthMillis = 1000;
Sailesh Nepalcc0375f2013-11-13 09:15:18 -08001257 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM
1258 || phoneType == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -07001259 || phoneType == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -08001260 || phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001261 toneType = ToneGenerator.TONE_SUP_BUSY;
1262 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1263 toneLengthMillis = 4000;
1264 } else {
1265 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1266 }
1267 break;
1268 case TONE_CONGESTION:
1269 toneType = ToneGenerator.TONE_SUP_CONGESTION;
1270 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1271 toneLengthMillis = 4000;
1272 break;
1273
1274 case TONE_CALL_ENDED:
1275 toneType = ToneGenerator.TONE_PROP_PROMPT;
1276 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1277 toneLengthMillis = 200;
1278 break;
1279 case TONE_OTA_CALL_END:
1280 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
1281 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
1282 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
1283 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1284 toneLengthMillis = 750;
1285 } else {
1286 toneType = ToneGenerator.TONE_PROP_PROMPT;
1287 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1288 toneLengthMillis = 200;
1289 }
1290 break;
1291 case TONE_VOICE_PRIVACY:
1292 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
1293 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1294 toneLengthMillis = 5000;
1295 break;
1296 case TONE_REORDER:
1297 toneType = ToneGenerator.TONE_CDMA_REORDER;
1298 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1299 toneLengthMillis = 4000;
1300 break;
1301 case TONE_INTERCEPT:
1302 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
1303 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1304 toneLengthMillis = 500;
1305 break;
1306 case TONE_CDMA_DROP:
1307 case TONE_OUT_OF_SERVICE:
1308 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
1309 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1310 toneLengthMillis = 375;
1311 break;
1312 case TONE_REDIAL:
1313 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
1314 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1315 toneLengthMillis = 5000;
1316 break;
1317 case TONE_RING_BACK:
1318 toneType = ToneGenerator.TONE_SUP_RINGTONE;
1319 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1320 // Call ring back tone is stopped by stopTone() method
1321 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1322 break;
1323 case TONE_UNOBTAINABLE_NUMBER:
1324 toneType = ToneGenerator.TONE_SUP_ERROR;
1325 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1326 toneLengthMillis = 4000;
1327 break;
1328 default:
1329 throw new IllegalArgumentException("Bad toneId: " + mToneId);
1330 }
1331
1332 // If the mToneGenerator creation fails, just continue without it. It is
1333 // a local audio signal, and is not as important.
1334 ToneGenerator toneGenerator;
1335 try {
1336 int stream;
1337 if (mBluetoothHeadset != null) {
1338 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
1339 AudioManager.STREAM_VOICE_CALL;
1340 } else {
1341 stream = AudioManager.STREAM_VOICE_CALL;
1342 }
1343 toneGenerator = new ToneGenerator(stream, toneVolume);
1344 // if (DBG) log("- created toneGenerator: " + toneGenerator);
1345 } catch (RuntimeException e) {
1346 Log.w(LOG_TAG,
1347 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
1348 toneGenerator = null;
1349 }
1350
1351 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
1352 // CONGESTION tones at least), the ToneGenerator itself knows
1353 // the right pattern of tones to play; we do NOT need to
1354 // manually start/stop each individual tone, or manually
1355 // insert the correct delay between tones. (We just start it
1356 // and let it run for however long we want the tone pattern to
1357 // continue.)
1358 //
1359 // TODO: When we stop the ToneGenerator in the middle of a
1360 // "tone pattern", it sounds bad if we cut if off while the
1361 // tone is actually playing. Consider adding API to the
1362 // ToneGenerator to say "stop at the next silent part of the
1363 // pattern", or simply "play the pattern N times and then
1364 // stop."
1365 boolean needToStopTone = true;
1366 boolean okToPlayTone = false;
1367
1368 if (toneGenerator != null) {
1369 int ringerMode = mAudioManager.getRingerMode();
1370 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1371 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
1372 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1373 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1374 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
1375 okToPlayTone = true;
1376 needToStopTone = false;
1377 }
1378 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
1379 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
1380 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
1381 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
1382 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
1383 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
1384 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
1385 okToPlayTone = true;
1386 needToStopTone = false;
1387 }
1388 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
1389 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
1390 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1391 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1392 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
1393 okToPlayTone = true;
1394 needToStopTone = false;
1395 }
1396 } else { // For the rest of the tones, always OK to play.
1397 okToPlayTone = true;
1398 }
1399 } else { // Not "CDMA"
1400 okToPlayTone = true;
1401 }
1402
1403 synchronized (this) {
1404 if (okToPlayTone && mState != TONE_STOPPED) {
1405 mState = TONE_ON;
1406 toneGenerator.startTone(toneType);
1407 try {
1408 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
1409 } catch (InterruptedException e) {
1410 Log.w(LOG_TAG,
1411 "InCallTonePlayer stopped: " + e);
1412 }
1413 if (needToStopTone) {
1414 toneGenerator.stopTone();
1415 }
1416 }
1417 // if (DBG) log("- InCallTonePlayer: done playing.");
1418 toneGenerator.release();
1419 mState = TONE_OFF;
1420 }
1421 }
1422
1423 // Finally, do the same cleanup we otherwise would have done
1424 // in onDisconnect().
1425 //
1426 // (But watch out: do NOT do this if the phone is in use,
1427 // since some of our tones get played *during* a call (like
1428 // CALL_WAITING) and we definitely *don't*
1429 // want to reset the audio mode / speaker / bluetooth after
1430 // playing those!
1431 // This call is really here for use with tones that get played
1432 // *after* a call disconnects, like "busy" or "congestion" or
1433 // "call ended", where the phone has already become idle but
1434 // we need to defer the resetAudioStateAfterDisconnect() call
1435 // till the tone finishes playing.)
1436 if (mCM.getState() == PhoneConstants.State.IDLE) {
1437 resetAudioStateAfterDisconnect();
1438 }
1439 }
1440
1441 public void stopTone() {
1442 synchronized (this) {
1443 if (mState == TONE_ON) {
1444 notify();
1445 }
1446 mState = TONE_STOPPED;
1447 }
1448 }
1449 }
1450
1451 /**
1452 * Displays a notification when the phone receives a DisplayInfo record.
1453 */
1454 private void onDisplayInfo(AsyncResult r) {
1455 // Extract the DisplayInfo String from the message
1456 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1457
1458 if (displayInfoRec != null) {
1459 String displayInfo = displayInfoRec.alpha;
1460 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1461 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1462
1463 // start a 2 second timer
1464 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1465 DISPLAYINFO_NOTIFICATION_TIME);
1466 }
1467 }
1468
1469 /**
1470 * Helper class to play SignalInfo tones using the ToneGenerator.
1471 *
1472 * To use, just instantiate a new SignalInfoTonePlayer
1473 * (passing in the ToneID constant for the tone you want)
1474 * and start() it.
1475 */
1476 private class SignalInfoTonePlayer extends Thread {
1477 private int mToneId;
1478
1479 SignalInfoTonePlayer(int toneId) {
1480 super();
1481 mToneId = toneId;
1482 }
1483
1484 @Override
1485 public void run() {
1486 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1487
1488 if (mSignalInfoToneGenerator != null) {
1489 //First stop any ongoing SignalInfo tone
1490 mSignalInfoToneGenerator.stopTone();
1491
1492 //Start playing the new tone if its a valid tone
1493 mSignalInfoToneGenerator.startTone(mToneId);
1494 }
1495 }
1496 }
1497
1498 /**
1499 * Plays a tone when the phone receives a SignalInfo record.
1500 */
1501 private void onSignalInfo(AsyncResult r) {
1502 // Signal Info are totally ignored on non-voice-capable devices.
1503 if (!PhoneGlobals.sVoiceCapable) {
1504 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1505 return;
1506 }
1507
1508 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1509 // Do not start any new SignalInfo tone when Call state is INCOMING
1510 // and stop any previous SignalInfo tone which is being played
1511 stopSignalInfoTone();
1512 } else {
1513 // Extract the SignalInfo String from the message
1514 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1515 // Only proceed if a Signal info is present.
1516 if (signalInfoRec != null) {
1517 boolean isPresent = signalInfoRec.isPresent;
1518 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1519 if (isPresent) {// if tone is valid
1520 int uSignalType = signalInfoRec.signalType;
1521 int uAlertPitch = signalInfoRec.alertPitch;
1522 int uSignal = signalInfoRec.signal;
1523
1524 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1525 uAlertPitch + ", uSignal=" + uSignal);
1526 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1527 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1528 (uSignalType, uAlertPitch, uSignal);
1529
1530 //Create the SignalInfo tone player and pass the ToneID
1531 new SignalInfoTonePlayer(toneID).start();
1532 }
1533 }
1534 }
1535 }
1536
1537 /**
1538 * Stops a SignalInfo tone in the following condition
1539 * 1 - On receiving a New Ringing Call
1540 * 2 - On disconnecting a call
1541 * 3 - On answering a Call Waiting Call
1542 */
1543 /* package */ void stopSignalInfoTone() {
1544 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1545 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1546 }
1547
1548 /**
1549 * Plays a Call waiting tone if it is present in the second incoming call.
1550 */
1551 private void onCdmaCallWaiting(AsyncResult r) {
1552 // Remove any previous Call waiting timers in the queue
1553 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1554 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1555
1556 // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
1557 // else we would not have received Call waiting
1558 mApplication.cdmaPhoneCallState.setCurrentCallState(
1559 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
1560
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001561 // Start timer for CW display
1562 mCallWaitingTimeOut = false;
1563 sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
1564 CALLWAITING_CALLERINFO_DISPLAY_TIME);
1565
1566 // Set the mAddCallMenuStateAfterCW state to false
1567 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
1568
1569 // Start the timer for disabling "Add Call" menu option
1570 sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
1571 CALLWAITING_ADDCALL_DISABLE_TIME);
1572
1573 // Extract the Call waiting information
1574 CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
1575 int isPresent = infoCW.isPresent;
1576 if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
1577 if (isPresent == 1 ) {//'1' if tone is valid
1578 int uSignalType = infoCW.signalType;
1579 int uAlertPitch = infoCW.alertPitch;
1580 int uSignal = infoCW.signal;
1581 if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
1582 + uAlertPitch + ", uSignal=" + uSignal);
1583 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1584 int toneID =
1585 SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
1586
1587 //Create the SignalInfo tone player and pass the ToneID
1588 new SignalInfoTonePlayer(toneID).start();
1589 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001590
Sailesh Nepal23d9ed72014-07-03 09:40:26 -07001591 // TODO(sail): Remove this.
1592 //mCallModeler.onCdmaCallWaiting(infoCW);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001593 }
1594
1595 /**
1596 * Posts a event causing us to clean up after rejecting (or timing-out) a
1597 * CDMA call-waiting call.
1598 *
1599 * This method is safe to call from any thread.
1600 * @see #onCdmaCallWaitingReject()
1601 */
1602 /* package */ void sendCdmaCallWaitingReject() {
1603 sendEmptyMessage(CDMA_CALL_WAITING_REJECT);
1604 }
1605
1606 /**
1607 * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
1608 * and finally calls Hangup on the Call Waiting connection.
1609 *
1610 * This method should be called only from the UI thread.
1611 * @see #sendCdmaCallWaitingReject()
1612 */
1613 private void onCdmaCallWaitingReject() {
1614 final Call ringingCall = mCM.getFirstActiveRingingCall();
1615
1616 // Call waiting timeout scenario
1617 if (ringingCall.getState() == Call.State.WAITING) {
1618 // Code for perform Call logging and missed call notification
1619 Connection c = ringingCall.getLatestConnection();
1620
1621 if (c != null) {
1622 final int callLogType = mCallWaitingTimeOut ?
1623 Calls.MISSED_TYPE : Calls.INCOMING_TYPE;
1624
1625 // TODO: This callLogType override is not ideal. Connection should be astracted away
1626 // at a telephony-phone layer that can understand and edit the callTypes within
1627 // the abstraction for CDMA devices.
1628 mCallLogger.logCall(c, callLogType);
1629
Santos Cordonf68db2e2014-07-02 14:40:44 -07001630 if (callLogType != Calls.MISSED_TYPE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001631 // Remove Call waiting 20 second display timer in the queue
1632 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1633 }
1634
1635 // Hangup the RingingCall connection for CW
1636 PhoneUtils.hangup(c);
1637 }
1638
1639 //Reset the mCallWaitingTimeOut boolean
1640 mCallWaitingTimeOut = false;
1641 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001642
1643 // Call modeler needs to know about this event regardless of the
1644 // state conditionals in the previous code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -07001645 // TODO(sail): Remove this.
1646 //mCallModeler.onCdmaCallWaitingReject();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001647 }
1648
1649 /**
1650 * Return the private variable mPreviousCdmaCallState.
1651 */
1652 /* package */ Call.State getPreviousCdmaCallState() {
1653 return mPreviousCdmaCallState;
1654 }
1655
1656 /**
1657 * Return the private variable mVoicePrivacyState.
1658 */
1659 /* package */ boolean getVoicePrivacyState() {
1660 return mVoicePrivacyState;
1661 }
1662
1663 /**
1664 * Return the private variable mIsCdmaRedialCall.
1665 */
1666 /* package */ boolean getIsCdmaRedialCall() {
1667 return mIsCdmaRedialCall;
1668 }
1669
1670 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001671 * Inner class to handle emergency call tone and vibrator
1672 */
1673 private class EmergencyTonePlayerVibrator {
1674 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1675 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1676 private final long[] mVibratePattern =
1677 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1678
1679 private ToneGenerator mToneGenerator;
1680 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1681 // object will be isolated from others.
1682 private Vibrator mEmgVibrator = new SystemVibrator();
1683 private int mInCallVolume;
1684
1685 /**
1686 * constructor
1687 */
1688 public EmergencyTonePlayerVibrator() {
1689 }
1690
1691 /**
1692 * Start the emergency tone or vibrator.
1693 */
1694 private void start() {
1695 if (VDBG) log("call startEmergencyToneOrVibrate.");
1696 int ringerMode = mAudioManager.getRingerMode();
1697
1698 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1699 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1700 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1701 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1702 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1703 if (mToneGenerator != null) {
1704 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1705 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1706 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1707 0);
1708 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1709 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1710 }
1711 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1712 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1713 if (mEmgVibrator != null) {
John Spurlock6ee06d02014-07-18 20:06:20 -04001714 mEmgVibrator.vibrate(mVibratePattern, 0, VIBRATION_ATTRIBUTES);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001715 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1716 }
1717 }
1718 }
1719
1720 /**
1721 * If the emergency tone is active, stop the tone or vibrator accordingly.
1722 */
1723 private void stop() {
1724 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1725
1726 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1727 && (mToneGenerator != null)) {
1728 mToneGenerator.stopTone();
1729 mToneGenerator.release();
1730 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1731 mInCallVolume,
1732 0);
1733 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1734 && (mEmgVibrator != null)) {
1735 mEmgVibrator.cancel();
1736 }
1737 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1738 }
1739 }
1740
1741 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1742 new BluetoothProfile.ServiceListener() {
1743 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1744 mBluetoothHeadset = (BluetoothHeadset) proxy;
1745 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1746 }
1747
1748 public void onServiceDisconnected(int profile) {
1749 mBluetoothHeadset = null;
1750 }
1751 };
1752
1753 private void onRingbackTone(AsyncResult r) {
1754 boolean playTone = (Boolean)(r.result);
1755
1756 if (playTone == true) {
1757 // Only play when foreground call is in DIALING or ALERTING.
1758 // to prevent a late coming playtone after ALERTING.
1759 // Don't play ringback tone if it is in play, otherwise it will cut
1760 // the current tone and replay it
1761 if (mCM.getActiveFgCallState().isDialing() &&
1762 mInCallRingbackTonePlayer == null) {
1763 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1764 mInCallRingbackTonePlayer.start();
1765 }
1766 } else {
1767 if (mInCallRingbackTonePlayer != null) {
1768 mInCallRingbackTonePlayer.stopTone();
1769 mInCallRingbackTonePlayer = null;
1770 }
1771 }
1772 }
1773
1774 /**
1775 * Toggle mute and unmute requests while keeping the same mute state
1776 */
1777 private void onResendMute() {
1778 boolean muteState = PhoneUtils.getMute();
1779 PhoneUtils.setMute(!muteState);
1780 PhoneUtils.setMute(muteState);
1781 }
1782
1783 private void log(String msg) {
1784 Log.d(LOG_TAG, msg);
1785 }
1786}