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