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