blob: 674f66d43e8bf554959359edc99990e413200f07 [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
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700355 default:
356 // super.handleMessage(msg);
357 }
358 }
359
360 PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
361 @Override
362 public void onMessageWaitingIndicatorChanged(boolean mwi) {
363 onMwiChanged(mwi);
364 }
365
366 @Override
367 public void onCallForwardingIndicatorChanged(boolean cfi) {
368 onCfiChanged(cfi);
369 }
370 };
371
372 /**
373 * Handles a "new ringing connection" event from the telephony layer.
374 */
375 private void onNewRingingConnection(AsyncResult r) {
376 Connection c = (Connection) r.result;
377 log("onNewRingingConnection(): state = " + mCM.getState() + ", conn = { " + c + " }");
378 Call ringing = c.getCall();
379 Phone phone = ringing.getPhone();
380
381 // Check for a few cases where we totally ignore incoming calls.
382 if (ignoreAllIncomingCalls(phone)) {
383 // Immediately reject the call, without even indicating to the user
384 // that an incoming call occurred. (This will generally send the
385 // caller straight to voicemail, just as if we *had* shown the
386 // incoming-call UI and the user had declined the call.)
387 PhoneUtils.hangupRingingCall(ringing);
388 return;
389 }
390
391 if (!c.isRinging()) {
392 Log.i(LOG_TAG, "CallNotifier.onNewRingingConnection(): connection not ringing!");
393 // This is a very strange case: an incoming call that stopped
394 // ringing almost instantly after the onNewRingingConnection()
395 // event. There's nothing we can do here, so just bail out
396 // without doing anything. (But presumably we'll log it in
397 // the call log when the disconnect event comes in...)
398 return;
399 }
400
401 // Stop any signalInfo tone being played on receiving a Call
402 stopSignalInfoTone();
403
404 Call.State state = c.getState();
405 // State will be either INCOMING or WAITING.
406 if (VDBG) log("- connection is ringing! state = " + state);
407 // if (DBG) PhoneUtils.dumpCallState(mPhone);
408
409 // No need to do any service state checks here (like for
410 // "emergency mode"), since in those states the SIM won't let
411 // us get incoming connections in the first place.
412
413 // TODO: Consider sending out a serialized broadcast Intent here
414 // (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the
415 // ringer and going to the in-call UI. The intent should contain
416 // the caller-id info for the current connection, and say whether
417 // it would be a "call waiting" call or a regular ringing call.
418 // If anybody consumed the broadcast, we'd bail out without
419 // ringing or bringing up the in-call UI.
420 //
421 // This would give 3rd party apps a chance to listen for (and
422 // intercept) new ringing connections. An app could reject the
423 // incoming call by consuming the broadcast and doing nothing, or
424 // it could "pick up" the call (without any action by the user!)
425 // via some future TelephonyManager API.
426 //
427 // See bug 1312336 for more details.
428 // We'd need to protect this with a new "intercept incoming calls"
429 // system permission.
430
431 // Obtain a partial wake lock to make sure the CPU doesn't go to
432 // sleep before we finish bringing up the InCallScreen.
433 // (This will be upgraded soon to a full wake lock; see
434 // showIncomingCall().)
435 if (VDBG) log("Holding wake lock on new incoming connection.");
436 mApplication.requestWakeState(PhoneGlobals.WakeState.PARTIAL);
437
438 // - don't ring for call waiting connections
439 // - do this before showing the incoming call panel
Christine Chenb5e4b652013-09-19 11:20:18 -0700440 startIncomingCallQuery(c);
Chiao Cheng312b9c92013-09-16 15:40:53 -0700441
Christine Chenb5e4b652013-09-19 11:20:18 -0700442
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700443
444 // Note we *don't* post a status bar notification here, since
445 // we're not necessarily ready to actually show the incoming call
446 // to the user. (For calls in the INCOMING state, at least, we
447 // still need to run a caller-id query, and we may not even ring
448 // at all if the "send directly to voicemail" flag is set.)
449 //
450 // Instead, we update the notification (and potentially launch the
451 // InCallScreen) from the showIncomingCall() method, which runs
452 // when the caller-id query completes or times out.
453
454 if (VDBG) log("- onNewRingingConnection() done.");
455 }
456
457 /**
458 * Determines whether or not we're allowed to present incoming calls to the
459 * user, based on the capabilities and/or current state of the device.
460 *
461 * If this method returns true, that means we should immediately reject the
462 * current incoming call, without even indicating to the user that an
463 * incoming call occurred.
464 *
465 * (We only reject incoming calls in a few cases, like during an OTASP call
466 * when we can't interrupt the user, or if the device hasn't completed the
467 * SetupWizard yet. We also don't allow incoming calls on non-voice-capable
468 * devices. But note that we *always* allow incoming calls while in ECM.)
469 *
470 * @return true if we're *not* allowed to present an incoming call to
471 * the user.
472 */
473 private boolean ignoreAllIncomingCalls(Phone phone) {
474 // Incoming calls are totally ignored on non-voice-capable devices.
475 if (!PhoneGlobals.sVoiceCapable) {
476 // ...but still log a warning, since we shouldn't have gotten this
477 // event in the first place! (Incoming calls *should* be blocked at
478 // the telephony layer on non-voice-capable capable devices.)
479 Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring...");
480 return true;
481 }
482
483 // In ECM (emergency callback mode), we ALWAYS allow incoming calls
484 // to get through to the user. (Note that ECM is applicable only to
485 // voice-capable CDMA devices).
486 if (PhoneUtils.isPhoneInEcm(phone)) {
487 if (DBG) log("Incoming call while in ECM: always allow...");
488 return false;
489 }
490
491 // Incoming calls are totally ignored if the device isn't provisioned yet.
492 boolean provisioned = Settings.Global.getInt(mApplication.getContentResolver(),
493 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
494 if (!provisioned) {
495 Log.i(LOG_TAG, "Ignoring incoming call: not provisioned");
496 return true;
497 }
498
499 // Incoming calls are totally ignored if an OTASP call is active.
500 if (TelephonyCapabilities.supportsOtasp(phone)) {
501 boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState
502 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
503 boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState
504 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG);
505 boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState;
506
507 if (spcState) {
508 Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active");
509 return true;
510 } else if (activateState || dialogState) {
511 // We *are* allowed to receive incoming calls at this point.
512 // But clear out any residual OTASP UI first.
513 // TODO: It's an MVC violation to twiddle the OTA UI state here;
514 // we should instead provide a higher-level API via OtaUtils.
515 if (dialogState) mApplication.dismissOtaDialogs();
516 mApplication.clearOtaState();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700517 return false;
518 }
519 }
520
521 // Normal case: allow this call to be presented to the user.
522 return false;
523 }
524
525 /**
526 * Helper method to manage the start of incoming call queries
527 */
528 private void startIncomingCallQuery(Connection c) {
529 // TODO: cache the custom ringer object so that subsequent
530 // calls will not need to do this query work. We can keep
531 // the MRU ringtones in memory. We'll still need to hit
532 // the database to get the callerinfo to act as a key,
533 // but at least we can save the time required for the
534 // Media player setup. The only issue with this is that
535 // we may need to keep an eye on the resources the Media
536 // player uses to keep these ringtones around.
537
538 // make sure we're in a state where we can be ready to
539 // query a ringtone uri.
540 boolean shouldStartQuery = false;
541 synchronized (mCallerInfoQueryStateGuard) {
542 if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) {
543 mCallerInfoQueryState = CALLERINFO_QUERYING;
544 shouldStartQuery = true;
545 }
546 }
547 if (shouldStartQuery) {
548 // Reset the ringtone to the default first.
549 mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI);
550
551 // query the callerinfo to try to get the ringer.
552 PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700553 mApplication, c, this, c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700554
555 // if this has already been queried then just ring, otherwise
556 // we wait for the alloted time before ringing.
557 if (cit.isFinal) {
558 if (VDBG) log("- CallerInfo already up to date, using available data");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700559 onQueryComplete(0, c, cit.currentInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700560 } else {
561 if (VDBG) log("- Starting query, posting timeout message.");
562
563 // Phone number (via getAddress()) is stored in the message to remember which
564 // number is actually used for the look up.
565 sendMessageDelayed(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700566 Message.obtain(this, RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT, c),
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700567 RINGTONE_QUERY_WAIT_TIME);
568 }
569 // The call to showIncomingCall() will happen after the
570 // queries are complete (or time out).
571 } else {
572 // This should never happen; its the case where an incoming call
573 // arrives at the same time that the query is still being run,
574 // and before the timeout window has closed.
575 EventLog.writeEvent(EventLogTags.PHONE_UI_MULTIPLE_QUERY);
576
Christine Chenb5e4b652013-09-19 11:20:18 -0700577 ringAndNotifyOfIncomingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700578 }
579 }
580
581 /**
582 * Performs the final steps of the onNewRingingConnection sequence:
583 * starts the ringer, and brings up the "incoming call" UI.
584 *
585 * Normally, this is called when the CallerInfo query completes (see
586 * onQueryComplete()). In this case, onQueryComplete() has already
587 * configured the Ringer object to use the custom ringtone (if there
588 * is one) for this caller. So we just tell the Ringer to start, and
589 * proceed to the InCallScreen.
590 *
591 * But this method can *also* be called if the
592 * RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the
593 * CallerInfo query is taking too long. In that case, we log a
594 * warning but otherwise we behave the same as in the normal case.
595 * (We still tell the Ringer to start, but it's going to use the
596 * default ringtone.)
597 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700598 private void onCustomRingQueryComplete(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700599 boolean isQueryExecutionTimeExpired = false;
600 synchronized (mCallerInfoQueryStateGuard) {
601 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
602 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
603 isQueryExecutionTimeExpired = true;
604 }
605 }
606 if (isQueryExecutionTimeExpired) {
607 // There may be a problem with the query here, since the
608 // default ringtone is playing instead of the custom one.
609 Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone");
610 EventLog.writeEvent(EventLogTags.PHONE_UI_RINGER_QUERY_ELAPSED);
611 }
612
613 // Make sure we still have an incoming call!
614 //
615 // (It's possible for the incoming call to have been disconnected
616 // while we were running the query. In that case we better not
617 // start the ringer here, since there won't be any future
618 // DISCONNECT event to stop it!)
619 //
620 // Note we don't have to worry about the incoming call going away
621 // *after* this check but before we call mRinger.ring() below,
622 // since in that case we *will* still get a DISCONNECT message sent
623 // to our handler. (And we will correctly stop the ringer when we
624 // process that event.)
625 if (mCM.getState() != PhoneConstants.State.RINGING) {
626 Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out...");
627 // Don't start the ringer *or* bring up the "incoming call" UI.
628 // Just bail out.
629 return;
630 }
631
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700632 // If the ringing call still does not have any connection anymore, do not send the
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700633 // notification.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700634 final Call ringingCall = mCM.getFirstActiveRingingCall();
635
636 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
Christine Chenb5e4b652013-09-19 11:20:18 -0700637 ringAndNotifyOfIncomingCall(c);
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700638 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700639 }
640
641 private void onUnknownConnectionAppeared(AsyncResult r) {
642 PhoneConstants.State state = mCM.getState();
643
644 if (state == PhoneConstants.State.OFFHOOK) {
Santos Cordon54fdb592013-09-19 05:16:18 -0700645 if (DBG) log("unknown connection appeared...");
Chiao Cheng312b9c92013-09-16 15:40:53 -0700646
Santos Cordon54fdb592013-09-19 05:16:18 -0700647 onPhoneStateChanged(r);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700648 }
649 }
650
Christine Chenb5e4b652013-09-19 11:20:18 -0700651 /**
Christine Chenb5e4b652013-09-19 11:20:18 -0700652 * If it is not a waiting call (there is no other active call in foreground), we will ring the
653 * ringtone. Otherwise we will play the call waiting tone instead.
654 * @param c The new ringing connection.
655 */
656 private void ringAndNotifyOfIncomingCall(Connection c) {
657 if (PhoneUtils.isRealIncomingCall(c.getState())) {
658 mRinger.ring();
659 } else {
660 if (VDBG) log("- starting call waiting tone...");
661 if (mCallWaitingTonePlayer == null) {
662 mCallWaitingTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING);
663 mCallWaitingTonePlayer.start();
664 }
665 }
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700666 }
667
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700668 /**
669 * Updates the phone UI in response to phone state changes.
670 *
671 * Watch out: certain state changes are actually handled by their own
672 * specific methods:
673 * - see onNewRingingConnection() for new incoming calls
674 * - see onDisconnect() for calls being hung up or disconnected
675 */
676 private void onPhoneStateChanged(AsyncResult r) {
677 PhoneConstants.State state = mCM.getState();
678 if (VDBG) log("onPhoneStateChanged: state = " + state);
679
680 // Turn status bar notifications on or off depending upon the state
681 // of the phone. Notification Alerts (audible or vibrating) should
682 // be on if and only if the phone is IDLE.
683 mApplication.notificationMgr.statusBarHelper
684 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
685
686 Phone fgPhone = mCM.getFgPhone();
687 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
688 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
689 && ((mPreviousCdmaCallState == Call.State.DIALING)
690 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
691 if (mIsCdmaRedialCall) {
692 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
693 new InCallTonePlayer(toneToPlay).start();
694 }
695 // Stop any signal info tone when call moves to ACTIVE state
696 stopSignalInfoTone();
697 }
698 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
699 }
700
701 // Have the PhoneApp recompute its mShowBluetoothIndication
702 // flag based on the (new) telephony state.
703 // There's no need to force a UI update since we update the
704 // in-call notification ourselves (below), and the InCallScreen
705 // listens for phone state changes itself.
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700706 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700707
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700708 // Update the phone state and other sensor/lock.
709 mApplication.updatePhoneState(state);
710
711 if (state == PhoneConstants.State.OFFHOOK) {
712 // stop call waiting tone if needed when answering
713 if (mCallWaitingTonePlayer != null) {
714 mCallWaitingTonePlayer.stopTone();
715 mCallWaitingTonePlayer = null;
716 }
717
718 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
719 // make sure audio is in in-call mode now
720 PhoneUtils.setAudioMode(mCM);
721
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700722 // Since we're now in-call, the Ringer should definitely *not*
723 // be ringing any more. (This is just a sanity-check; we
724 // already stopped the ringer explicitly back in
725 // PhoneUtils.answerCall(), before the call to phone.acceptCall().)
726 // TODO: Confirm that this call really *is* unnecessary, and if so,
727 // remove it!
728 if (DBG) log("stopRing()... (OFFHOOK state)");
729 mRinger.stopRing();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700730 }
731
732 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
733 Connection c = fgPhone.getForegroundCall().getLatestConnection();
Yorke Lee36bb2542014-06-05 08:09:52 -0700734 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(mApplication,
735 c.getAddress()))) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700736 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
737 Call.State callState = fgPhone.getForegroundCall().getState();
738 if (mEmergencyTonePlayerVibrator == null) {
739 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
740 }
741
742 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
743 mIsEmergencyToneOn = Settings.Global.getInt(
744 mApplication.getContentResolver(),
745 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
746 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
747 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
748 if (mEmergencyTonePlayerVibrator != null) {
749 mEmergencyTonePlayerVibrator.start();
750 }
751 }
752 } else if (callState == Call.State.ACTIVE) {
753 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
754 if (mEmergencyTonePlayerVibrator != null) {
755 mEmergencyTonePlayerVibrator.stop();
756 }
757 }
758 }
759 }
760 }
761
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800762 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM
763 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -0700764 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800765 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700766 Call.State callState = mCM.getActiveFgCallState();
767 if (!callState.isDialing()) {
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800768 // If call gets activated or disconnected before the ringback
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700769 // tone stops, we have to stop it to prevent disturbing.
770 if (mInCallRingbackTonePlayer != null) {
771 mInCallRingbackTonePlayer.stopTone();
772 mInCallRingbackTonePlayer = null;
773 }
774 }
775 }
776 }
777
778 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
779 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
780
781 // Clear ringback tone player
782 mInCallRingbackTonePlayer = null;
783
784 // Clear call waiting tone player
785 mCallWaitingTonePlayer = null;
786
787 // Instantiate mSignalInfoToneGenerator
788 createSignalInfoToneGenerator();
789 }
790
791 /**
792 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
793 * refreshes the CallCard data when it called. If called with this
794 * class itself, it is assumed that we have been waiting for the ringtone
795 * and direct to voicemail settings to update.
796 */
797 @Override
798 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
799 if (cookie instanceof Long) {
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700800 } else if (cookie instanceof Connection) {
801 final Connection c = (Connection) cookie;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700802 if (VDBG) log("CallerInfo query complete (for CallNotifier), "
803 + "updating state for incoming call..");
804
805 // get rid of the timeout messages
806 removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
807
808 boolean isQueryExecutionTimeOK = false;
809 synchronized (mCallerInfoQueryStateGuard) {
810 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
811 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
812 isQueryExecutionTimeOK = true;
813 }
814 }
815 //if we're in the right state
816 if (isQueryExecutionTimeOK) {
817
818 // send directly to voicemail.
819 if (ci.shouldSendToVoicemail) {
820 if (DBG) log("send to voicemail flag detected. hanging up.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700821 final Call ringingCall = mCM.getFirstActiveRingingCall();
822 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
823 PhoneUtils.hangupRingingCall(ringingCall);
824 return;
825 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700826 }
827
828 // set the ringtone uri to prepare for the ring.
829 if (ci.contactRingtoneUri != null) {
830 if (DBG) log("custom ringtone found, setting up ringer.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700831 Ringer r = mRinger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700832 r.setCustomRingtoneUri(ci.contactRingtoneUri);
833 }
834 // ring, and other post-ring actions.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700835 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700836 }
837 }
838 }
839
840 /**
841 * Called when asynchronous CallerInfo query is taking too long (more than
842 * {@link #RINGTONE_QUERY_WAIT_TIME} msec), but we cannot wait any more.
843 *
844 * This looks up in-memory fallback cache and use it when available. If not, it just calls
845 * {@link #onCustomRingQueryComplete()} with default ringtone ("Send to voicemail" flag will
846 * be just ignored).
847 *
848 * @param number The phone number used for the async query. This method will take care of
849 * formatting or normalization of the number.
850 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700851 private void onCustomRingtoneQueryTimeout(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700852 // First of all, this case itself should be rare enough, though we cannot avoid it in
853 // some situations (e.g. IPC is slow due to system overload, database is in sync, etc.)
854 Log.w(LOG_TAG, "CallerInfo query took too long; look up local fallback cache.");
855
856 // This method is intentionally verbose for now to detect possible bad side-effect for it.
857 // TODO: Remove the verbose log when it looks stable and reliable enough.
858
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700859
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700860 if (c != null) {
861 final CallerInfoCache.CacheEntry entry =
862 mApplication.callerInfoCache.getCacheEntry(c.getAddress());
863 if (entry != null) {
864 if (entry.sendToVoicemail) {
865 log("send to voicemail flag detected (in fallback cache). hanging up.");
866 if (mCM.getFirstActiveRingingCall().getLatestConnection() == c) {
867 PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
868 return;
869 }
870 }
871
872 if (entry.customRingtone != null) {
873 log("custom ringtone found (in fallback cache), setting up ringer: "
874 + entry.customRingtone);
875 this.mRinger.setCustomRingtoneUri(Uri.parse(entry.customRingtone));
876 }
877 } else {
878 // In this case we call onCustomRingQueryComplete(), just
879 // like if the query had completed normally. (But we're
880 // going to get the default ringtone, since we never got
881 // the chance to call Ringer.setCustomRingtoneUri()).
882 log("Failed to find fallback cache. Use default ringer tone.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700883 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700884 }
885
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700886 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700887 }
888
889 private void onDisconnect(AsyncResult r) {
890 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
891
892 mVoicePrivacyState = false;
893 Connection c = (Connection) r.result;
894 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800895 log("onDisconnect: cause = " + DisconnectCause.toString(c.getDisconnectCause())
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700896 + ", incoming = " + c.isIncoming()
897 + ", date = " + c.getCreateTime());
898 } else {
899 Log.w(LOG_TAG, "onDisconnect: null connection");
900 }
901
902 int autoretrySetting = 0;
903 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
904 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
905 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
906 }
907
908 // Stop any signalInfo tone being played when a call gets ended
909 stopSignalInfoTone();
910
911 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
912 // Resetting the CdmaPhoneCallState members
913 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
914
915 // Remove Call waiting timers
916 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
917 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
918 }
919
920 // Stop the ringer if it was ringing (for an incoming call that
921 // either disconnected by itself, or was rejected by the user.)
922 //
923 // TODO: We technically *shouldn't* stop the ringer if the
924 // foreground or background call disconnects while an incoming call
925 // is still ringing, but that's a really rare corner case.
926 // It's safest to just unconditionally stop the ringer here.
927
928 // CDMA: For Call collision cases i.e. when the user makes an out going call
929 // and at the same time receives an Incoming Call, the Incoming Call is given
930 // higher preference. At this time framework sends a disconnect for the Out going
931 // call connection hence we should *not* be stopping the ringer being played for
932 // the Incoming Call
933 Call ringingCall = mCM.getFirstActiveRingingCall();
934 if (ringingCall.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordon352ff652014-05-30 01:41:45 -0700935 if (!PhoneUtils.isRealIncomingCall(ringingCall.getState())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700936 if (DBG) log("stopRing()... (onDisconnect)");
937 mRinger.stopRing();
938 }
939 } else { // GSM
940 if (DBG) log("stopRing()... (onDisconnect)");
941 mRinger.stopRing();
942 }
943
944 // stop call waiting tone if needed when disconnecting
945 if (mCallWaitingTonePlayer != null) {
946 mCallWaitingTonePlayer.stopTone();
947 mCallWaitingTonePlayer = null;
948 }
949
950 // If this is the end of an OTASP call, pass it on to the PhoneApp.
951 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
952 final String number = c.getAddress();
953 if (c.getCall().getPhone().isOtaSpNumber(number)) {
954 if (DBG) log("onDisconnect: this was an OTASP call!");
955 mApplication.handleOtaspDisconnect();
956 }
957 }
958
959 // Check for the various tones we might need to play (thru the
960 // earpiece) after a call disconnects.
961 int toneToPlay = InCallTonePlayer.TONE_NONE;
962
963 // The "Busy" or "Congestion" tone is the highest priority:
964 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800965 int cause = c.getDisconnectCause();
966 if (cause == DisconnectCause.BUSY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700967 if (DBG) log("- need to play BUSY tone!");
968 toneToPlay = InCallTonePlayer.TONE_BUSY;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800969 } else if (cause == DisconnectCause.CONGESTION) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700970 if (DBG) log("- need to play CONGESTION tone!");
971 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800972 } else if (((cause == DisconnectCause.NORMAL)
973 || (cause == DisconnectCause.LOCAL))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700974 && (mApplication.isOtaCallInActiveState())) {
975 if (DBG) log("- need to play OTA_CALL_END tone!");
976 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800977 } else if (cause == DisconnectCause.CDMA_REORDER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700978 if (DBG) log("- need to play CDMA_REORDER tone!");
979 toneToPlay = InCallTonePlayer.TONE_REORDER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800980 } else if (cause == DisconnectCause.CDMA_INTERCEPT) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700981 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
982 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800983 } else if (cause == DisconnectCause.CDMA_DROP) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700984 if (DBG) log("- need to play CDMA_DROP tone!");
985 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800986 } else if (cause == DisconnectCause.OUT_OF_SERVICE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700987 if (DBG) log("- need to play OUT OF SERVICE tone!");
988 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800989 } else if (cause == DisconnectCause.UNOBTAINABLE_NUMBER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700990 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
991 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800992 } else if (cause == DisconnectCause.ERROR_UNSPECIFIED) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700993 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
994 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
995 }
996 }
997
998 // If we don't need to play BUSY or CONGESTION, then play the
999 // "call ended" tone if this was a "regular disconnect" (i.e. a
1000 // normal call where one end or the other hung up) *and* this
1001 // disconnect event caused the phone to become idle. (In other
1002 // words, we *don't* play the sound if one call hangs up but
1003 // there's still an active call on the other line.)
1004 // TODO: We may eventually want to disable this via a preference.
1005 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
1006 && (mCM.getState() == PhoneConstants.State.IDLE)
1007 && (c != null)) {
Anders Kristensen0b35f042014-02-27 14:31:07 -08001008 int cause = c.getDisconnectCause();
1009 if ((cause == DisconnectCause.NORMAL) // remote hangup
1010 || (cause == DisconnectCause.LOCAL)) { // local hangup
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001011 if (VDBG) log("- need to play CALL_ENDED tone!");
1012 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1013 mIsCdmaRedialCall = false;
1014 }
1015 }
1016
1017 // All phone calls are disconnected.
1018 if (mCM.getState() == PhoneConstants.State.IDLE) {
1019 // Don't reset the audio mode or bluetooth/speakerphone state
1020 // if we still need to let the user hear a tone through the earpiece.
1021 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
1022 resetAudioStateAfterDisconnect();
1023 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001024 }
1025
1026 if (c != null) {
1027 mCallLogger.logCall(c);
1028
1029 final String number = c.getAddress();
1030 final Phone phone = c.getCall().getPhone();
1031 final boolean isEmergencyNumber =
Yorke Lee36bb2542014-06-05 08:09:52 -07001032 PhoneNumberUtils.isLocalEmergencyNumber(mApplication, number);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001033
1034 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1035 if ((isEmergencyNumber)
1036 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
1037 if (mEmergencyTonePlayerVibrator != null) {
1038 mEmergencyTonePlayerVibrator.stop();
1039 }
1040 }
1041 }
1042
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001043 // Possibly play a "post-disconnect tone" thru the earpiece.
1044 // We do this here, rather than from the InCallScreen
1045 // activity, since we need to do this even if you're not in
1046 // the Phone UI at the moment the connection ends.
1047 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
1048 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
1049 new InCallTonePlayer(toneToPlay).start();
1050
1051 // TODO: alternatively, we could start an InCallTonePlayer
1052 // here with an "unlimited" tone length,
1053 // and manually stop it later when this connection truly goes
1054 // away. (The real connection over the network was closed as soon
1055 // as we got the BUSY message. But our telephony layer keeps the
1056 // connection open for a few extra seconds so we can show the
1057 // "busy" indication to the user. We could stop the busy tone
1058 // when *that* connection's "disconnect" event comes in.)
1059 }
1060
Santos Cordonf68db2e2014-07-02 14:40:44 -07001061 final int cause = c.getDisconnectCause();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001062 if (((mPreviousCdmaCallState == Call.State.DIALING)
1063 || (mPreviousCdmaCallState == Call.State.ALERTING))
1064 && (!isEmergencyNumber)
Anders Kristensen0b35f042014-02-27 14:31:07 -08001065 && (cause != DisconnectCause.INCOMING_MISSED )
1066 && (cause != DisconnectCause.NORMAL)
1067 && (cause != DisconnectCause.LOCAL)
1068 && (cause != DisconnectCause.INCOMING_REJECTED)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001069 if (!mIsCdmaRedialCall) {
1070 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
1071 // TODO: (Moto): The contact reference data may need to be stored and use
1072 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordonce02f3a2013-09-19 01:58:42 -07001073 final int status =
1074 PhoneUtils.placeCall(mApplication, phone, number, null, false);
1075 if (status != PhoneUtils.CALL_STATUS_FAILED) {
1076 mIsCdmaRedialCall = true;
1077 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001078 } else {
1079 mIsCdmaRedialCall = false;
1080 }
1081 } else {
1082 mIsCdmaRedialCall = false;
1083 }
1084 }
1085 }
1086 }
1087
1088 /**
1089 * Resets the audio mode and speaker state when a call ends.
1090 */
1091 private void resetAudioStateAfterDisconnect() {
1092 if (VDBG) log("resetAudioStateAfterDisconnect()...");
1093
1094 if (mBluetoothHeadset != null) {
1095 mBluetoothHeadset.disconnectAudio();
1096 }
1097
1098 // call turnOnSpeaker() with state=false and store=true even if speaker
1099 // is already off to reset user requested speaker state.
1100 PhoneUtils.turnOnSpeaker(mApplication, false, true);
1101
1102 PhoneUtils.setAudioMode(mCM);
1103 }
1104
1105 private void onMwiChanged(boolean visible) {
1106 if (VDBG) log("onMwiChanged(): " + visible);
1107
1108 // "Voicemail" is meaningless on non-voice-capable devices,
1109 // so ignore MWI events.
1110 if (!PhoneGlobals.sVoiceCapable) {
1111 // ...but still log a warning, since we shouldn't have gotten this
1112 // event in the first place!
1113 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
1114 // *should* be blocked at the telephony layer on non-voice-capable
1115 // capable devices.)
1116 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
1117 return;
1118 }
1119
1120 mApplication.notificationMgr.updateMwi(visible);
1121 }
1122
1123 /**
1124 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
1125 * failed NotificationMgr.updateMwi() call.
1126 */
1127 /* package */ void sendMwiChangedDelayed(long delayMillis) {
1128 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
1129 sendMessageDelayed(message, delayMillis);
1130 }
1131
1132 private void onCfiChanged(boolean visible) {
1133 if (VDBG) log("onCfiChanged(): " + visible);
1134 mApplication.notificationMgr.updateCfi(visible);
1135 }
1136
1137 /**
1138 * Indicates whether or not this ringer is ringing.
1139 */
1140 boolean isRinging() {
1141 return mRinger.isRinging();
1142 }
1143
1144 /**
1145 * Stops the current ring, and tells the notifier that future
1146 * ring requests should be ignored.
1147 */
1148 void silenceRinger() {
1149 mSilentRingerRequested = true;
1150 if (DBG) log("stopRing()... (silenceRinger)");
1151 mRinger.stopRing();
1152 }
1153
1154 /**
1155 * Restarts the ringer after having previously silenced it.
1156 *
1157 * (This is a no-op if the ringer is actually still ringing, or if the
1158 * incoming ringing call no longer exists.)
1159 */
1160 /* package */ void restartRinger() {
1161 if (DBG) log("restartRinger()...");
1162 // Already ringing or Silent requested; no need to restart.
1163 if (isRinging() || mSilentRingerRequested) return;
1164
1165 final Call ringingCall = mCM.getFirstActiveRingingCall();
1166 // Don't check ringingCall.isRinging() here, since that'll be true
1167 // for the WAITING state also. We only allow the ringer for
1168 // regular INCOMING calls.
1169 if (DBG) log("- ringingCall state: " + ringingCall.getState());
1170 if (ringingCall.getState() == Call.State.INCOMING) {
1171 mRinger.ring();
1172 }
1173 }
1174
1175 /**
1176 * Helper class to play tones through the earpiece (or speaker / BT)
1177 * during a call, using the ToneGenerator.
1178 *
1179 * To use, just instantiate a new InCallTonePlayer
1180 * (passing in the TONE_* constant for the tone you want)
1181 * and start() it.
1182 *
1183 * When we're done playing the tone, if the phone is idle at that
1184 * point, we'll reset the audio routing and speaker state.
1185 * (That means that for tones that get played *after* a call
1186 * disconnects, like "busy" or "congestion" or "call ended", you
1187 * should NOT call resetAudioStateAfterDisconnect() yourself.
1188 * Instead, just start the InCallTonePlayer, which will automatically
1189 * defer the resetAudioStateAfterDisconnect() call until the tone
1190 * finishes playing.)
1191 */
1192 private class InCallTonePlayer extends Thread {
1193 private int mToneId;
1194 private int mState;
1195 // The possible tones we can play.
1196 public static final int TONE_NONE = 0;
1197 public static final int TONE_CALL_WAITING = 1;
1198 public static final int TONE_BUSY = 2;
1199 public static final int TONE_CONGESTION = 3;
1200 public static final int TONE_CALL_ENDED = 4;
1201 public static final int TONE_VOICE_PRIVACY = 5;
1202 public static final int TONE_REORDER = 6;
1203 public static final int TONE_INTERCEPT = 7;
1204 public static final int TONE_CDMA_DROP = 8;
1205 public static final int TONE_OUT_OF_SERVICE = 9;
1206 public static final int TONE_REDIAL = 10;
1207 public static final int TONE_OTA_CALL_END = 11;
1208 public static final int TONE_RING_BACK = 12;
1209 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
1210
1211 // The tone volume relative to other sounds in the stream
1212 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
1213 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
1214 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
1215
1216 // Buffer time (in msec) to add on to tone timeout value.
1217 // Needed mainly when the timeout value for a tone is the
1218 // exact duration of the tone itself.
1219 static final int TONE_TIMEOUT_BUFFER = 20;
1220
1221 // The tone state
1222 static final int TONE_OFF = 0;
1223 static final int TONE_ON = 1;
1224 static final int TONE_STOPPED = 2;
1225
1226 InCallTonePlayer(int toneId) {
1227 super();
1228 mToneId = toneId;
1229 mState = TONE_OFF;
1230 }
1231
1232 @Override
1233 public void run() {
1234 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
1235
1236 int toneType = 0; // passed to ToneGenerator.startTone()
1237 int toneVolume; // passed to the ToneGenerator constructor
1238 int toneLengthMillis;
1239 int phoneType = mCM.getFgPhone().getPhoneType();
1240
1241 switch (mToneId) {
1242 case TONE_CALL_WAITING:
1243 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
1244 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1245 // Call waiting tone is stopped by stopTone() method
1246 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1247 break;
1248 case TONE_BUSY:
1249 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1250 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
1251 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1252 toneLengthMillis = 1000;
Sailesh Nepalcc0375f2013-11-13 09:15:18 -08001253 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM
1254 || phoneType == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -07001255 || phoneType == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -08001256 || phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001257 toneType = ToneGenerator.TONE_SUP_BUSY;
1258 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1259 toneLengthMillis = 4000;
1260 } else {
1261 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1262 }
1263 break;
1264 case TONE_CONGESTION:
1265 toneType = ToneGenerator.TONE_SUP_CONGESTION;
1266 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1267 toneLengthMillis = 4000;
1268 break;
1269
1270 case TONE_CALL_ENDED:
1271 toneType = ToneGenerator.TONE_PROP_PROMPT;
1272 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1273 toneLengthMillis = 200;
1274 break;
1275 case TONE_OTA_CALL_END:
1276 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
1277 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
1278 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
1279 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1280 toneLengthMillis = 750;
1281 } else {
1282 toneType = ToneGenerator.TONE_PROP_PROMPT;
1283 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1284 toneLengthMillis = 200;
1285 }
1286 break;
1287 case TONE_VOICE_PRIVACY:
1288 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
1289 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1290 toneLengthMillis = 5000;
1291 break;
1292 case TONE_REORDER:
1293 toneType = ToneGenerator.TONE_CDMA_REORDER;
1294 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1295 toneLengthMillis = 4000;
1296 break;
1297 case TONE_INTERCEPT:
1298 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
1299 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1300 toneLengthMillis = 500;
1301 break;
1302 case TONE_CDMA_DROP:
1303 case TONE_OUT_OF_SERVICE:
1304 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
1305 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1306 toneLengthMillis = 375;
1307 break;
1308 case TONE_REDIAL:
1309 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
1310 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1311 toneLengthMillis = 5000;
1312 break;
1313 case TONE_RING_BACK:
1314 toneType = ToneGenerator.TONE_SUP_RINGTONE;
1315 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1316 // Call ring back tone is stopped by stopTone() method
1317 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1318 break;
1319 case TONE_UNOBTAINABLE_NUMBER:
1320 toneType = ToneGenerator.TONE_SUP_ERROR;
1321 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1322 toneLengthMillis = 4000;
1323 break;
1324 default:
1325 throw new IllegalArgumentException("Bad toneId: " + mToneId);
1326 }
1327
1328 // If the mToneGenerator creation fails, just continue without it. It is
1329 // a local audio signal, and is not as important.
1330 ToneGenerator toneGenerator;
1331 try {
1332 int stream;
1333 if (mBluetoothHeadset != null) {
1334 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
1335 AudioManager.STREAM_VOICE_CALL;
1336 } else {
1337 stream = AudioManager.STREAM_VOICE_CALL;
1338 }
1339 toneGenerator = new ToneGenerator(stream, toneVolume);
1340 // if (DBG) log("- created toneGenerator: " + toneGenerator);
1341 } catch (RuntimeException e) {
1342 Log.w(LOG_TAG,
1343 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
1344 toneGenerator = null;
1345 }
1346
1347 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
1348 // CONGESTION tones at least), the ToneGenerator itself knows
1349 // the right pattern of tones to play; we do NOT need to
1350 // manually start/stop each individual tone, or manually
1351 // insert the correct delay between tones. (We just start it
1352 // and let it run for however long we want the tone pattern to
1353 // continue.)
1354 //
1355 // TODO: When we stop the ToneGenerator in the middle of a
1356 // "tone pattern", it sounds bad if we cut if off while the
1357 // tone is actually playing. Consider adding API to the
1358 // ToneGenerator to say "stop at the next silent part of the
1359 // pattern", or simply "play the pattern N times and then
1360 // stop."
1361 boolean needToStopTone = true;
1362 boolean okToPlayTone = false;
1363
1364 if (toneGenerator != null) {
1365 int ringerMode = mAudioManager.getRingerMode();
1366 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1367 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
1368 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1369 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1370 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
1371 okToPlayTone = true;
1372 needToStopTone = false;
1373 }
1374 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
1375 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
1376 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
1377 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
1378 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
1379 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
1380 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
1381 okToPlayTone = true;
1382 needToStopTone = false;
1383 }
1384 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
1385 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
1386 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1387 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1388 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
1389 okToPlayTone = true;
1390 needToStopTone = false;
1391 }
1392 } else { // For the rest of the tones, always OK to play.
1393 okToPlayTone = true;
1394 }
1395 } else { // Not "CDMA"
1396 okToPlayTone = true;
1397 }
1398
1399 synchronized (this) {
1400 if (okToPlayTone && mState != TONE_STOPPED) {
1401 mState = TONE_ON;
1402 toneGenerator.startTone(toneType);
1403 try {
1404 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
1405 } catch (InterruptedException e) {
1406 Log.w(LOG_TAG,
1407 "InCallTonePlayer stopped: " + e);
1408 }
1409 if (needToStopTone) {
1410 toneGenerator.stopTone();
1411 }
1412 }
1413 // if (DBG) log("- InCallTonePlayer: done playing.");
1414 toneGenerator.release();
1415 mState = TONE_OFF;
1416 }
1417 }
1418
1419 // Finally, do the same cleanup we otherwise would have done
1420 // in onDisconnect().
1421 //
1422 // (But watch out: do NOT do this if the phone is in use,
1423 // since some of our tones get played *during* a call (like
1424 // CALL_WAITING) and we definitely *don't*
1425 // want to reset the audio mode / speaker / bluetooth after
1426 // playing those!
1427 // This call is really here for use with tones that get played
1428 // *after* a call disconnects, like "busy" or "congestion" or
1429 // "call ended", where the phone has already become idle but
1430 // we need to defer the resetAudioStateAfterDisconnect() call
1431 // till the tone finishes playing.)
1432 if (mCM.getState() == PhoneConstants.State.IDLE) {
1433 resetAudioStateAfterDisconnect();
1434 }
1435 }
1436
1437 public void stopTone() {
1438 synchronized (this) {
1439 if (mState == TONE_ON) {
1440 notify();
1441 }
1442 mState = TONE_STOPPED;
1443 }
1444 }
1445 }
1446
1447 /**
1448 * Displays a notification when the phone receives a DisplayInfo record.
1449 */
1450 private void onDisplayInfo(AsyncResult r) {
1451 // Extract the DisplayInfo String from the message
1452 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1453
1454 if (displayInfoRec != null) {
1455 String displayInfo = displayInfoRec.alpha;
1456 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1457 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1458
1459 // start a 2 second timer
1460 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1461 DISPLAYINFO_NOTIFICATION_TIME);
1462 }
1463 }
1464
1465 /**
1466 * Helper class to play SignalInfo tones using the ToneGenerator.
1467 *
1468 * To use, just instantiate a new SignalInfoTonePlayer
1469 * (passing in the ToneID constant for the tone you want)
1470 * and start() it.
1471 */
1472 private class SignalInfoTonePlayer extends Thread {
1473 private int mToneId;
1474
1475 SignalInfoTonePlayer(int toneId) {
1476 super();
1477 mToneId = toneId;
1478 }
1479
1480 @Override
1481 public void run() {
1482 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1483
1484 if (mSignalInfoToneGenerator != null) {
1485 //First stop any ongoing SignalInfo tone
1486 mSignalInfoToneGenerator.stopTone();
1487
1488 //Start playing the new tone if its a valid tone
1489 mSignalInfoToneGenerator.startTone(mToneId);
1490 }
1491 }
1492 }
1493
1494 /**
1495 * Plays a tone when the phone receives a SignalInfo record.
1496 */
1497 private void onSignalInfo(AsyncResult r) {
1498 // Signal Info are totally ignored on non-voice-capable devices.
1499 if (!PhoneGlobals.sVoiceCapable) {
1500 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1501 return;
1502 }
1503
1504 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1505 // Do not start any new SignalInfo tone when Call state is INCOMING
1506 // and stop any previous SignalInfo tone which is being played
1507 stopSignalInfoTone();
1508 } else {
1509 // Extract the SignalInfo String from the message
1510 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1511 // Only proceed if a Signal info is present.
1512 if (signalInfoRec != null) {
1513 boolean isPresent = signalInfoRec.isPresent;
1514 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1515 if (isPresent) {// if tone is valid
1516 int uSignalType = signalInfoRec.signalType;
1517 int uAlertPitch = signalInfoRec.alertPitch;
1518 int uSignal = signalInfoRec.signal;
1519
1520 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1521 uAlertPitch + ", uSignal=" + uSignal);
1522 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1523 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1524 (uSignalType, uAlertPitch, uSignal);
1525
1526 //Create the SignalInfo tone player and pass the ToneID
1527 new SignalInfoTonePlayer(toneID).start();
1528 }
1529 }
1530 }
1531 }
1532
1533 /**
1534 * Stops a SignalInfo tone in the following condition
1535 * 1 - On receiving a New Ringing Call
1536 * 2 - On disconnecting a call
1537 * 3 - On answering a Call Waiting Call
1538 */
1539 /* package */ void stopSignalInfoTone() {
1540 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1541 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1542 }
1543
1544 /**
1545 * Plays a Call waiting tone if it is present in the second incoming call.
1546 */
1547 private void onCdmaCallWaiting(AsyncResult r) {
1548 // Remove any previous Call waiting timers in the queue
1549 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1550 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1551
1552 // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
1553 // else we would not have received Call waiting
1554 mApplication.cdmaPhoneCallState.setCurrentCallState(
1555 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
1556
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001557 // Start timer for CW display
1558 mCallWaitingTimeOut = false;
1559 sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
1560 CALLWAITING_CALLERINFO_DISPLAY_TIME);
1561
1562 // Set the mAddCallMenuStateAfterCW state to false
1563 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
1564
1565 // Start the timer for disabling "Add Call" menu option
1566 sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
1567 CALLWAITING_ADDCALL_DISABLE_TIME);
1568
1569 // Extract the Call waiting information
1570 CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
1571 int isPresent = infoCW.isPresent;
1572 if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
1573 if (isPresent == 1 ) {//'1' if tone is valid
1574 int uSignalType = infoCW.signalType;
1575 int uAlertPitch = infoCW.alertPitch;
1576 int uSignal = infoCW.signal;
1577 if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
1578 + uAlertPitch + ", uSignal=" + uSignal);
1579 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1580 int toneID =
1581 SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
1582
1583 //Create the SignalInfo tone player and pass the ToneID
1584 new SignalInfoTonePlayer(toneID).start();
1585 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001586
Santos Cordonda120f42014-08-06 04:44:34 -07001587 // TODO: Remove this.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -07001588 //mCallModeler.onCdmaCallWaiting(infoCW);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001589 }
1590
1591 /**
1592 * Posts a event causing us to clean up after rejecting (or timing-out) a
1593 * CDMA call-waiting call.
1594 *
1595 * This method is safe to call from any thread.
1596 * @see #onCdmaCallWaitingReject()
1597 */
1598 /* package */ void sendCdmaCallWaitingReject() {
1599 sendEmptyMessage(CDMA_CALL_WAITING_REJECT);
1600 }
1601
1602 /**
1603 * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
1604 * and finally calls Hangup on the Call Waiting connection.
1605 *
1606 * This method should be called only from the UI thread.
1607 * @see #sendCdmaCallWaitingReject()
1608 */
1609 private void onCdmaCallWaitingReject() {
1610 final Call ringingCall = mCM.getFirstActiveRingingCall();
1611
1612 // Call waiting timeout scenario
1613 if (ringingCall.getState() == Call.State.WAITING) {
1614 // Code for perform Call logging and missed call notification
1615 Connection c = ringingCall.getLatestConnection();
1616
1617 if (c != null) {
1618 final int callLogType = mCallWaitingTimeOut ?
1619 Calls.MISSED_TYPE : Calls.INCOMING_TYPE;
1620
1621 // TODO: This callLogType override is not ideal. Connection should be astracted away
1622 // at a telephony-phone layer that can understand and edit the callTypes within
1623 // the abstraction for CDMA devices.
1624 mCallLogger.logCall(c, callLogType);
1625
Santos Cordonf68db2e2014-07-02 14:40:44 -07001626 if (callLogType != Calls.MISSED_TYPE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001627 // Remove Call waiting 20 second display timer in the queue
1628 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1629 }
1630
1631 // Hangup the RingingCall connection for CW
1632 PhoneUtils.hangup(c);
1633 }
1634
1635 //Reset the mCallWaitingTimeOut boolean
1636 mCallWaitingTimeOut = false;
1637 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001638
1639 // Call modeler needs to know about this event regardless of the
1640 // state conditionals in the previous code.
Santos Cordonda120f42014-08-06 04:44:34 -07001641 // TODO: Remove this.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -07001642 //mCallModeler.onCdmaCallWaitingReject();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001643 }
1644
1645 /**
1646 * Return the private variable mPreviousCdmaCallState.
1647 */
1648 /* package */ Call.State getPreviousCdmaCallState() {
1649 return mPreviousCdmaCallState;
1650 }
1651
1652 /**
1653 * Return the private variable mVoicePrivacyState.
1654 */
1655 /* package */ boolean getVoicePrivacyState() {
1656 return mVoicePrivacyState;
1657 }
1658
1659 /**
1660 * Return the private variable mIsCdmaRedialCall.
1661 */
1662 /* package */ boolean getIsCdmaRedialCall() {
1663 return mIsCdmaRedialCall;
1664 }
1665
1666 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001667 * Inner class to handle emergency call tone and vibrator
1668 */
1669 private class EmergencyTonePlayerVibrator {
1670 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1671 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1672 private final long[] mVibratePattern =
1673 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1674
1675 private ToneGenerator mToneGenerator;
1676 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1677 // object will be isolated from others.
1678 private Vibrator mEmgVibrator = new SystemVibrator();
1679 private int mInCallVolume;
1680
1681 /**
1682 * constructor
1683 */
1684 public EmergencyTonePlayerVibrator() {
1685 }
1686
1687 /**
1688 * Start the emergency tone or vibrator.
1689 */
1690 private void start() {
1691 if (VDBG) log("call startEmergencyToneOrVibrate.");
1692 int ringerMode = mAudioManager.getRingerMode();
1693
1694 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1695 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1696 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1697 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1698 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1699 if (mToneGenerator != null) {
1700 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1701 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1702 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1703 0);
1704 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1705 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1706 }
1707 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1708 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1709 if (mEmgVibrator != null) {
John Spurlock6ee06d02014-07-18 20:06:20 -04001710 mEmgVibrator.vibrate(mVibratePattern, 0, VIBRATION_ATTRIBUTES);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001711 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1712 }
1713 }
1714 }
1715
1716 /**
1717 * If the emergency tone is active, stop the tone or vibrator accordingly.
1718 */
1719 private void stop() {
1720 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1721
1722 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1723 && (mToneGenerator != null)) {
1724 mToneGenerator.stopTone();
1725 mToneGenerator.release();
1726 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1727 mInCallVolume,
1728 0);
1729 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1730 && (mEmgVibrator != null)) {
1731 mEmgVibrator.cancel();
1732 }
1733 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1734 }
1735 }
1736
1737 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1738 new BluetoothProfile.ServiceListener() {
1739 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1740 mBluetoothHeadset = (BluetoothHeadset) proxy;
1741 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1742 }
1743
1744 public void onServiceDisconnected(int profile) {
1745 mBluetoothHeadset = null;
1746 }
1747 };
1748
1749 private void onRingbackTone(AsyncResult r) {
1750 boolean playTone = (Boolean)(r.result);
1751
1752 if (playTone == true) {
1753 // Only play when foreground call is in DIALING or ALERTING.
1754 // to prevent a late coming playtone after ALERTING.
1755 // Don't play ringback tone if it is in play, otherwise it will cut
1756 // the current tone and replay it
1757 if (mCM.getActiveFgCallState().isDialing() &&
1758 mInCallRingbackTonePlayer == null) {
1759 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1760 mInCallRingbackTonePlayer.start();
1761 }
1762 } else {
1763 if (mInCallRingbackTonePlayer != null) {
1764 mInCallRingbackTonePlayer.stopTone();
1765 mInCallRingbackTonePlayer = null;
1766 }
1767 }
1768 }
1769
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001770 private void log(String msg) {
1771 Log.d(LOG_TAG, msg);
1772 }
1773}