blob: bbffbd201a1cd5d5f77b9849286da20787a1f8d4 [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;
44import android.os.RemoteException;
45import android.os.SystemProperties;
46import android.os.SystemVibrator;
47import android.os.Vibrator;
48import android.provider.CallLog.Calls;
49import android.provider.Settings;
50import 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);
307 mApplication.updateInCallScreen();
308 break;
309
310 case CallStateMonitor.PHONE_STATE_DISPLAYINFO:
311 if (DBG) log("Received PHONE_STATE_DISPLAYINFO event");
312 onDisplayInfo((AsyncResult) msg.obj);
313 break;
314
315 case CallStateMonitor.PHONE_STATE_SIGNALINFO:
316 if (DBG) log("Received PHONE_STATE_SIGNALINFO event");
317 onSignalInfo((AsyncResult) msg.obj);
318 break;
319
320 case DISPLAYINFO_NOTIFICATION_DONE:
321 if (DBG) log("Received Display Info notification done event ...");
322 CdmaDisplayInfo.dismissDisplayInfoRecord();
323 break;
324
325 case CallStateMonitor.EVENT_OTA_PROVISION_CHANGE:
326 if (DBG) log("EVENT_OTA_PROVISION_CHANGE...");
327 mApplication.handleOtaspEvent(msg);
328 break;
329
330 case CallStateMonitor.PHONE_ENHANCED_VP_ON:
331 if (DBG) log("PHONE_ENHANCED_VP_ON...");
332 if (!mVoicePrivacyState) {
333 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
334 new InCallTonePlayer(toneToPlay).start();
335 mVoicePrivacyState = true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700336 }
337 break;
338
339 case CallStateMonitor.PHONE_ENHANCED_VP_OFF:
340 if (DBG) log("PHONE_ENHANCED_VP_OFF...");
341 if (mVoicePrivacyState) {
342 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
343 new InCallTonePlayer(toneToPlay).start();
344 mVoicePrivacyState = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700345 }
346 break;
347
348 case CallStateMonitor.PHONE_RINGBACK_TONE:
349 onRingbackTone((AsyncResult) msg.obj);
350 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
441 if (PhoneUtils.isRealIncomingCall(state)) {
442 startIncomingCallQuery(c);
443 } else {
444 if (VDBG) log("- starting call waiting tone...");
445 if (mCallWaitingTonePlayer == null) {
446 mCallWaitingTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING);
447 mCallWaitingTonePlayer.start();
448 }
Chiao Cheng312b9c92013-09-16 15:40:53 -0700449
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700450 // in this case, just fall through like before, and call
451 // showIncomingCall().
452 if (DBG) log("- showing incoming call (this is a WAITING call)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700453 notifyCallModelerOfNewRingingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700454 }
455
456 // Note we *don't* post a status bar notification here, since
457 // we're not necessarily ready to actually show the incoming call
458 // to the user. (For calls in the INCOMING state, at least, we
459 // still need to run a caller-id query, and we may not even ring
460 // at all if the "send directly to voicemail" flag is set.)
461 //
462 // Instead, we update the notification (and potentially launch the
463 // InCallScreen) from the showIncomingCall() method, which runs
464 // when the caller-id query completes or times out.
465
466 if (VDBG) log("- onNewRingingConnection() done.");
467 }
468
469 /**
470 * Determines whether or not we're allowed to present incoming calls to the
471 * user, based on the capabilities and/or current state of the device.
472 *
473 * If this method returns true, that means we should immediately reject the
474 * current incoming call, without even indicating to the user that an
475 * incoming call occurred.
476 *
477 * (We only reject incoming calls in a few cases, like during an OTASP call
478 * when we can't interrupt the user, or if the device hasn't completed the
479 * SetupWizard yet. We also don't allow incoming calls on non-voice-capable
480 * devices. But note that we *always* allow incoming calls while in ECM.)
481 *
482 * @return true if we're *not* allowed to present an incoming call to
483 * the user.
484 */
485 private boolean ignoreAllIncomingCalls(Phone phone) {
486 // Incoming calls are totally ignored on non-voice-capable devices.
487 if (!PhoneGlobals.sVoiceCapable) {
488 // ...but still log a warning, since we shouldn't have gotten this
489 // event in the first place! (Incoming calls *should* be blocked at
490 // the telephony layer on non-voice-capable capable devices.)
491 Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring...");
492 return true;
493 }
494
495 // In ECM (emergency callback mode), we ALWAYS allow incoming calls
496 // to get through to the user. (Note that ECM is applicable only to
497 // voice-capable CDMA devices).
498 if (PhoneUtils.isPhoneInEcm(phone)) {
499 if (DBG) log("Incoming call while in ECM: always allow...");
500 return false;
501 }
502
503 // Incoming calls are totally ignored if the device isn't provisioned yet.
504 boolean provisioned = Settings.Global.getInt(mApplication.getContentResolver(),
505 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
506 if (!provisioned) {
507 Log.i(LOG_TAG, "Ignoring incoming call: not provisioned");
508 return true;
509 }
510
511 // Incoming calls are totally ignored if an OTASP call is active.
512 if (TelephonyCapabilities.supportsOtasp(phone)) {
513 boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState
514 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
515 boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState
516 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG);
517 boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState;
518
519 if (spcState) {
520 Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active");
521 return true;
522 } else if (activateState || dialogState) {
523 // We *are* allowed to receive incoming calls at this point.
524 // But clear out any residual OTASP UI first.
525 // TODO: It's an MVC violation to twiddle the OTA UI state here;
526 // we should instead provide a higher-level API via OtaUtils.
527 if (dialogState) mApplication.dismissOtaDialogs();
528 mApplication.clearOtaState();
529 mApplication.clearInCallScreenMode();
530 return false;
531 }
532 }
533
534 // Normal case: allow this call to be presented to the user.
535 return false;
536 }
537
538 /**
539 * Helper method to manage the start of incoming call queries
540 */
541 private void startIncomingCallQuery(Connection c) {
542 // TODO: cache the custom ringer object so that subsequent
543 // calls will not need to do this query work. We can keep
544 // the MRU ringtones in memory. We'll still need to hit
545 // the database to get the callerinfo to act as a key,
546 // but at least we can save the time required for the
547 // Media player setup. The only issue with this is that
548 // we may need to keep an eye on the resources the Media
549 // player uses to keep these ringtones around.
550
551 // make sure we're in a state where we can be ready to
552 // query a ringtone uri.
553 boolean shouldStartQuery = false;
554 synchronized (mCallerInfoQueryStateGuard) {
555 if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) {
556 mCallerInfoQueryState = CALLERINFO_QUERYING;
557 shouldStartQuery = true;
558 }
559 }
560 if (shouldStartQuery) {
561 // Reset the ringtone to the default first.
562 mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI);
563
564 // query the callerinfo to try to get the ringer.
565 PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700566 mApplication, c, this, c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700567
568 // if this has already been queried then just ring, otherwise
569 // we wait for the alloted time before ringing.
570 if (cit.isFinal) {
571 if (VDBG) log("- CallerInfo already up to date, using available data");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700572 onQueryComplete(0, c, cit.currentInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700573 } else {
574 if (VDBG) log("- Starting query, posting timeout message.");
575
576 // Phone number (via getAddress()) is stored in the message to remember which
577 // number is actually used for the look up.
578 sendMessageDelayed(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700579 Message.obtain(this, RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT, c),
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700580 RINGTONE_QUERY_WAIT_TIME);
581 }
582 // The call to showIncomingCall() will happen after the
583 // queries are complete (or time out).
584 } else {
585 // This should never happen; its the case where an incoming call
586 // arrives at the same time that the query is still being run,
587 // and before the timeout window has closed.
588 EventLog.writeEvent(EventLogTags.PHONE_UI_MULTIPLE_QUERY);
589
590 // In this case, just log the request and ring.
591 if (VDBG) log("RINGING... (request to ring arrived while query is running)");
592 mRinger.ring();
593
594 // in this case, just fall through like before, and call
595 // showIncomingCall().
596 if (DBG) log("- showing incoming call (couldn't start query)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700597 notifyCallModelerOfNewRingingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700598 }
599 }
600
601 /**
602 * Performs the final steps of the onNewRingingConnection sequence:
603 * starts the ringer, and brings up the "incoming call" UI.
604 *
605 * Normally, this is called when the CallerInfo query completes (see
606 * onQueryComplete()). In this case, onQueryComplete() has already
607 * configured the Ringer object to use the custom ringtone (if there
608 * is one) for this caller. So we just tell the Ringer to start, and
609 * proceed to the InCallScreen.
610 *
611 * But this method can *also* be called if the
612 * RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the
613 * CallerInfo query is taking too long. In that case, we log a
614 * warning but otherwise we behave the same as in the normal case.
615 * (We still tell the Ringer to start, but it's going to use the
616 * default ringtone.)
617 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700618 private void onCustomRingQueryComplete(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700619 boolean isQueryExecutionTimeExpired = false;
620 synchronized (mCallerInfoQueryStateGuard) {
621 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
622 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
623 isQueryExecutionTimeExpired = true;
624 }
625 }
626 if (isQueryExecutionTimeExpired) {
627 // There may be a problem with the query here, since the
628 // default ringtone is playing instead of the custom one.
629 Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone");
630 EventLog.writeEvent(EventLogTags.PHONE_UI_RINGER_QUERY_ELAPSED);
631 }
632
633 // Make sure we still have an incoming call!
634 //
635 // (It's possible for the incoming call to have been disconnected
636 // while we were running the query. In that case we better not
637 // start the ringer here, since there won't be any future
638 // DISCONNECT event to stop it!)
639 //
640 // Note we don't have to worry about the incoming call going away
641 // *after* this check but before we call mRinger.ring() below,
642 // since in that case we *will* still get a DISCONNECT message sent
643 // to our handler. (And we will correctly stop the ringer when we
644 // process that event.)
645 if (mCM.getState() != PhoneConstants.State.RINGING) {
646 Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out...");
647 // Don't start the ringer *or* bring up the "incoming call" UI.
648 // Just bail out.
649 return;
650 }
651
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700652 // If the ringing call still does not have any connection anymore, do not send the
653 // notification to the CallModeler.
654 final Call ringingCall = mCM.getFirstActiveRingingCall();
655
656 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
Christine Chen3ae08d42013-09-18 15:15:55 -0700657 // Ring, either with the queried ringtone or default one.
658 if (VDBG) log("RINGING... (onCustomRingQueryComplete)");
659 mRinger.ring();
660
661 // ...and display the incoming call to the user:
662 if (DBG) log("- showing incoming call (custom ring query complete)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700663 notifyCallModelerOfNewRingingCall(c);
664 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700665 }
666
667 private void onUnknownConnectionAppeared(AsyncResult r) {
668 PhoneConstants.State state = mCM.getState();
669
670 if (state == PhoneConstants.State.OFFHOOK) {
671 // basically do onPhoneStateChanged + display the incoming call UI
672 onPhoneStateChanged(r);
Chiao Cheng312b9c92013-09-16 15:40:53 -0700673
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700674 if (DBG) log("- showing incoming call (unknown connection appeared)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700675 final Connection c = (Connection) r.result;
676 notifyCallModelerOfNewRingingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700677 }
678 }
679
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700680 private void notifyCallModelerOfNewRingingCall(Connection c) {
681 mCallModeler.onNewRingingConnection(c);
682 }
683
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700684 /**
685 * Updates the phone UI in response to phone state changes.
686 *
687 * Watch out: certain state changes are actually handled by their own
688 * specific methods:
689 * - see onNewRingingConnection() for new incoming calls
690 * - see onDisconnect() for calls being hung up or disconnected
691 */
692 private void onPhoneStateChanged(AsyncResult r) {
693 PhoneConstants.State state = mCM.getState();
694 if (VDBG) log("onPhoneStateChanged: state = " + state);
695
696 // Turn status bar notifications on or off depending upon the state
697 // of the phone. Notification Alerts (audible or vibrating) should
698 // be on if and only if the phone is IDLE.
699 mApplication.notificationMgr.statusBarHelper
700 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
701
702 Phone fgPhone = mCM.getFgPhone();
703 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
704 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
705 && ((mPreviousCdmaCallState == Call.State.DIALING)
706 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
707 if (mIsCdmaRedialCall) {
708 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
709 new InCallTonePlayer(toneToPlay).start();
710 }
711 // Stop any signal info tone when call moves to ACTIVE state
712 stopSignalInfoTone();
713 }
714 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
715 }
716
717 // Have the PhoneApp recompute its mShowBluetoothIndication
718 // flag based on the (new) telephony state.
719 // There's no need to force a UI update since we update the
720 // in-call notification ourselves (below), and the InCallScreen
721 // listens for phone state changes itself.
Christine Chen91db67d2013-09-18 12:01:11 -0700722 // TODO: Have BluetoothManager listen to CallModeler instead of relying on
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700723 // CallNotifier
724 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700725
726
727 // Update the phone state and other sensor/lock.
728 mApplication.updatePhoneState(state);
729
730 if (state == PhoneConstants.State.OFFHOOK) {
731 // stop call waiting tone if needed when answering
732 if (mCallWaitingTonePlayer != null) {
733 mCallWaitingTonePlayer.stopTone();
734 mCallWaitingTonePlayer = null;
735 }
736
737 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
738 // make sure audio is in in-call mode now
739 PhoneUtils.setAudioMode(mCM);
740
741 // if the call screen is showing, let it handle the event,
742 // otherwise handle it here.
743 if (!mApplication.isShowingCallScreen()) {
744 mApplication.requestWakeState(PhoneGlobals.WakeState.SLEEP);
745 }
746
747 // Since we're now in-call, the Ringer should definitely *not*
748 // be ringing any more. (This is just a sanity-check; we
749 // already stopped the ringer explicitly back in
750 // PhoneUtils.answerCall(), before the call to phone.acceptCall().)
751 // TODO: Confirm that this call really *is* unnecessary, and if so,
752 // remove it!
753 if (DBG) log("stopRing()... (OFFHOOK state)");
754 mRinger.stopRing();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700755 }
756
757 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
758 Connection c = fgPhone.getForegroundCall().getLatestConnection();
759 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
760 mApplication))) {
761 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
762 Call.State callState = fgPhone.getForegroundCall().getState();
763 if (mEmergencyTonePlayerVibrator == null) {
764 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
765 }
766
767 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
768 mIsEmergencyToneOn = Settings.Global.getInt(
769 mApplication.getContentResolver(),
770 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
771 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
772 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
773 if (mEmergencyTonePlayerVibrator != null) {
774 mEmergencyTonePlayerVibrator.start();
775 }
776 }
777 } else if (callState == Call.State.ACTIVE) {
778 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
779 if (mEmergencyTonePlayerVibrator != null) {
780 mEmergencyTonePlayerVibrator.stop();
781 }
782 }
783 }
784 }
785 }
786
787 if ((fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)
788 || (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP)) {
789 Call.State callState = mCM.getActiveFgCallState();
790 if (!callState.isDialing()) {
791 // If call get activated or disconnected before the ringback
792 // tone stops, we have to stop it to prevent disturbing.
793 if (mInCallRingbackTonePlayer != null) {
794 mInCallRingbackTonePlayer.stopTone();
795 mInCallRingbackTonePlayer = null;
796 }
797 }
798 }
799 }
800
801 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
802 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
803
804 // Clear ringback tone player
805 mInCallRingbackTonePlayer = null;
806
807 // Clear call waiting tone player
808 mCallWaitingTonePlayer = null;
809
810 // Instantiate mSignalInfoToneGenerator
811 createSignalInfoToneGenerator();
812 }
813
814 /**
815 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
816 * refreshes the CallCard data when it called. If called with this
817 * class itself, it is assumed that we have been waiting for the ringtone
818 * and direct to voicemail settings to update.
819 */
820 @Override
821 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
822 if (cookie instanceof Long) {
823 if (VDBG) log("CallerInfo query complete, posting missed call notification");
824
825 mApplication.notificationMgr.notifyMissedCall(ci.name, ci.phoneNumber,
826 ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon,
827 ((Long) cookie).longValue());
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700828 } else if (cookie instanceof Connection) {
829 final Connection c = (Connection) cookie;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700830 if (VDBG) log("CallerInfo query complete (for CallNotifier), "
831 + "updating state for incoming call..");
832
833 // get rid of the timeout messages
834 removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
835
836 boolean isQueryExecutionTimeOK = false;
837 synchronized (mCallerInfoQueryStateGuard) {
838 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
839 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
840 isQueryExecutionTimeOK = true;
841 }
842 }
843 //if we're in the right state
844 if (isQueryExecutionTimeOK) {
845
846 // send directly to voicemail.
847 if (ci.shouldSendToVoicemail) {
848 if (DBG) log("send to voicemail flag detected. hanging up.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700849 final Call ringingCall = mCM.getFirstActiveRingingCall();
850 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
851 PhoneUtils.hangupRingingCall(ringingCall);
852 return;
853 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700854 }
855
856 // set the ringtone uri to prepare for the ring.
857 if (ci.contactRingtoneUri != null) {
858 if (DBG) log("custom ringtone found, setting up ringer.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700859 Ringer r = mRinger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700860 r.setCustomRingtoneUri(ci.contactRingtoneUri);
861 }
862 // ring, and other post-ring actions.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700863 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700864 }
865 }
866 }
867
868 /**
869 * Called when asynchronous CallerInfo query is taking too long (more than
870 * {@link #RINGTONE_QUERY_WAIT_TIME} msec), but we cannot wait any more.
871 *
872 * This looks up in-memory fallback cache and use it when available. If not, it just calls
873 * {@link #onCustomRingQueryComplete()} with default ringtone ("Send to voicemail" flag will
874 * be just ignored).
875 *
876 * @param number The phone number used for the async query. This method will take care of
877 * formatting or normalization of the number.
878 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700879 private void onCustomRingtoneQueryTimeout(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700880 // First of all, this case itself should be rare enough, though we cannot avoid it in
881 // some situations (e.g. IPC is slow due to system overload, database is in sync, etc.)
882 Log.w(LOG_TAG, "CallerInfo query took too long; look up local fallback cache.");
883
884 // This method is intentionally verbose for now to detect possible bad side-effect for it.
885 // TODO: Remove the verbose log when it looks stable and reliable enough.
886
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700887
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700888 if (c != null) {
889 final CallerInfoCache.CacheEntry entry =
890 mApplication.callerInfoCache.getCacheEntry(c.getAddress());
891 if (entry != null) {
892 if (entry.sendToVoicemail) {
893 log("send to voicemail flag detected (in fallback cache). hanging up.");
894 if (mCM.getFirstActiveRingingCall().getLatestConnection() == c) {
895 PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
896 return;
897 }
898 }
899
900 if (entry.customRingtone != null) {
901 log("custom ringtone found (in fallback cache), setting up ringer: "
902 + entry.customRingtone);
903 this.mRinger.setCustomRingtoneUri(Uri.parse(entry.customRingtone));
904 }
905 } else {
906 // In this case we call onCustomRingQueryComplete(), just
907 // like if the query had completed normally. (But we're
908 // going to get the default ringtone, since we never got
909 // the chance to call Ringer.setCustomRingtoneUri()).
910 log("Failed to find fallback cache. Use default ringer tone.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700911 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700912 }
913
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700914 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700915 }
916
917 private void onDisconnect(AsyncResult r) {
918 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
919
920 mVoicePrivacyState = false;
921 Connection c = (Connection) r.result;
922 if (c != null) {
923 log("onDisconnect: cause = " + c.getDisconnectCause()
924 + ", incoming = " + c.isIncoming()
925 + ", date = " + c.getCreateTime());
926 } else {
927 Log.w(LOG_TAG, "onDisconnect: null connection");
928 }
929
930 int autoretrySetting = 0;
931 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
932 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
933 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
934 }
935
936 // Stop any signalInfo tone being played when a call gets ended
937 stopSignalInfoTone();
938
939 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
940 // Resetting the CdmaPhoneCallState members
941 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
942
943 // Remove Call waiting timers
944 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
945 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
946 }
947
948 // Stop the ringer if it was ringing (for an incoming call that
949 // either disconnected by itself, or was rejected by the user.)
950 //
951 // TODO: We technically *shouldn't* stop the ringer if the
952 // foreground or background call disconnects while an incoming call
953 // is still ringing, but that's a really rare corner case.
954 // It's safest to just unconditionally stop the ringer here.
955
956 // CDMA: For Call collision cases i.e. when the user makes an out going call
957 // and at the same time receives an Incoming Call, the Incoming Call is given
958 // higher preference. At this time framework sends a disconnect for the Out going
959 // call connection hence we should *not* be stopping the ringer being played for
960 // the Incoming Call
961 Call ringingCall = mCM.getFirstActiveRingingCall();
962 if (ringingCall.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
963 if (PhoneUtils.isRealIncomingCall(ringingCall.getState())) {
964 // Also we need to take off the "In Call" icon from the Notification
965 // area as the Out going Call never got connected
966 if (DBG) log("cancelCallInProgressNotifications()... (onDisconnect)");
967 mApplication.notificationMgr.cancelCallInProgressNotifications();
968 } else {
969 if (DBG) log("stopRing()... (onDisconnect)");
970 mRinger.stopRing();
971 }
972 } else { // GSM
973 if (DBG) log("stopRing()... (onDisconnect)");
974 mRinger.stopRing();
975 }
976
977 // stop call waiting tone if needed when disconnecting
978 if (mCallWaitingTonePlayer != null) {
979 mCallWaitingTonePlayer.stopTone();
980 mCallWaitingTonePlayer = null;
981 }
982
983 // If this is the end of an OTASP call, pass it on to the PhoneApp.
984 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
985 final String number = c.getAddress();
986 if (c.getCall().getPhone().isOtaSpNumber(number)) {
987 if (DBG) log("onDisconnect: this was an OTASP call!");
988 mApplication.handleOtaspDisconnect();
989 }
990 }
991
992 // Check for the various tones we might need to play (thru the
993 // earpiece) after a call disconnects.
994 int toneToPlay = InCallTonePlayer.TONE_NONE;
995
996 // The "Busy" or "Congestion" tone is the highest priority:
997 if (c != null) {
998 Connection.DisconnectCause cause = c.getDisconnectCause();
999 if (cause == Connection.DisconnectCause.BUSY) {
1000 if (DBG) log("- need to play BUSY tone!");
1001 toneToPlay = InCallTonePlayer.TONE_BUSY;
1002 } else if (cause == Connection.DisconnectCause.CONGESTION) {
1003 if (DBG) log("- need to play CONGESTION tone!");
1004 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
1005 } else if (((cause == Connection.DisconnectCause.NORMAL)
1006 || (cause == Connection.DisconnectCause.LOCAL))
1007 && (mApplication.isOtaCallInActiveState())) {
1008 if (DBG) log("- need to play OTA_CALL_END tone!");
1009 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
1010 } else if (cause == Connection.DisconnectCause.CDMA_REORDER) {
1011 if (DBG) log("- need to play CDMA_REORDER tone!");
1012 toneToPlay = InCallTonePlayer.TONE_REORDER;
1013 } else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) {
1014 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
1015 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
1016 } else if (cause == Connection.DisconnectCause.CDMA_DROP) {
1017 if (DBG) log("- need to play CDMA_DROP tone!");
1018 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
1019 } else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
1020 if (DBG) log("- need to play OUT OF SERVICE tone!");
1021 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
1022 } else if (cause == Connection.DisconnectCause.UNOBTAINABLE_NUMBER) {
1023 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
1024 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
1025 } else if (cause == Connection.DisconnectCause.ERROR_UNSPECIFIED) {
1026 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
1027 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1028 }
1029 }
1030
1031 // If we don't need to play BUSY or CONGESTION, then play the
1032 // "call ended" tone if this was a "regular disconnect" (i.e. a
1033 // normal call where one end or the other hung up) *and* this
1034 // disconnect event caused the phone to become idle. (In other
1035 // words, we *don't* play the sound if one call hangs up but
1036 // there's still an active call on the other line.)
1037 // TODO: We may eventually want to disable this via a preference.
1038 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
1039 && (mCM.getState() == PhoneConstants.State.IDLE)
1040 && (c != null)) {
1041 Connection.DisconnectCause cause = c.getDisconnectCause();
1042 if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup
1043 || (cause == Connection.DisconnectCause.LOCAL)) { // local hangup
1044 if (VDBG) log("- need to play CALL_ENDED tone!");
1045 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1046 mIsCdmaRedialCall = false;
1047 }
1048 }
1049
1050 // All phone calls are disconnected.
1051 if (mCM.getState() == PhoneConstants.State.IDLE) {
1052 // Don't reset the audio mode or bluetooth/speakerphone state
1053 // if we still need to let the user hear a tone through the earpiece.
1054 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
1055 resetAudioStateAfterDisconnect();
1056 }
1057
1058 mApplication.notificationMgr.cancelCallInProgressNotifications();
1059 }
1060
1061 if (c != null) {
1062 mCallLogger.logCall(c);
1063
1064 final String number = c.getAddress();
1065 final Phone phone = c.getCall().getPhone();
1066 final boolean isEmergencyNumber =
1067 PhoneNumberUtils.isLocalEmergencyNumber(number, mApplication);
1068
1069 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1070 if ((isEmergencyNumber)
1071 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
1072 if (mEmergencyTonePlayerVibrator != null) {
1073 mEmergencyTonePlayerVibrator.stop();
1074 }
1075 }
1076 }
1077
1078 final long date = c.getCreateTime();
1079 final Connection.DisconnectCause cause = c.getDisconnectCause();
1080 final boolean missedCall = c.isIncoming() &&
1081 (cause == Connection.DisconnectCause.INCOMING_MISSED);
1082 if (missedCall) {
1083 // Show the "Missed call" notification.
1084 // (Note we *don't* do this if this was an incoming call that
1085 // the user deliberately rejected.)
1086 showMissedCallNotification(c, date);
1087 }
1088
1089 // Possibly play a "post-disconnect tone" thru the earpiece.
1090 // We do this here, rather than from the InCallScreen
1091 // activity, since we need to do this even if you're not in
1092 // the Phone UI at the moment the connection ends.
1093 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
1094 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
1095 new InCallTonePlayer(toneToPlay).start();
1096
1097 // TODO: alternatively, we could start an InCallTonePlayer
1098 // here with an "unlimited" tone length,
1099 // and manually stop it later when this connection truly goes
1100 // away. (The real connection over the network was closed as soon
1101 // as we got the BUSY message. But our telephony layer keeps the
1102 // connection open for a few extra seconds so we can show the
1103 // "busy" indication to the user. We could stop the busy tone
1104 // when *that* connection's "disconnect" event comes in.)
1105 }
1106
1107 if (((mPreviousCdmaCallState == Call.State.DIALING)
1108 || (mPreviousCdmaCallState == Call.State.ALERTING))
1109 && (!isEmergencyNumber)
1110 && (cause != Connection.DisconnectCause.INCOMING_MISSED )
1111 && (cause != Connection.DisconnectCause.NORMAL)
1112 && (cause != Connection.DisconnectCause.LOCAL)
1113 && (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
1114 if (!mIsCdmaRedialCall) {
1115 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
1116 // TODO: (Moto): The contact reference data may need to be stored and use
1117 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordon69a69192013-08-22 14:25:42 -07001118 PhoneUtils.placeCall(mApplication, phone, number, null, false);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001119 mIsCdmaRedialCall = true;
1120 } else {
1121 mIsCdmaRedialCall = false;
1122 }
1123 } else {
1124 mIsCdmaRedialCall = false;
1125 }
1126 }
1127 }
1128 }
1129
1130 /**
1131 * Resets the audio mode and speaker state when a call ends.
1132 */
1133 private void resetAudioStateAfterDisconnect() {
1134 if (VDBG) log("resetAudioStateAfterDisconnect()...");
1135
1136 if (mBluetoothHeadset != null) {
1137 mBluetoothHeadset.disconnectAudio();
1138 }
1139
1140 // call turnOnSpeaker() with state=false and store=true even if speaker
1141 // is already off to reset user requested speaker state.
1142 PhoneUtils.turnOnSpeaker(mApplication, false, true);
1143
1144 PhoneUtils.setAudioMode(mCM);
1145 }
1146
1147 private void onMwiChanged(boolean visible) {
1148 if (VDBG) log("onMwiChanged(): " + visible);
1149
1150 // "Voicemail" is meaningless on non-voice-capable devices,
1151 // so ignore MWI events.
1152 if (!PhoneGlobals.sVoiceCapable) {
1153 // ...but still log a warning, since we shouldn't have gotten this
1154 // event in the first place!
1155 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
1156 // *should* be blocked at the telephony layer on non-voice-capable
1157 // capable devices.)
1158 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
1159 return;
1160 }
1161
1162 mApplication.notificationMgr.updateMwi(visible);
1163 }
1164
1165 /**
1166 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
1167 * failed NotificationMgr.updateMwi() call.
1168 */
1169 /* package */ void sendMwiChangedDelayed(long delayMillis) {
1170 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
1171 sendMessageDelayed(message, delayMillis);
1172 }
1173
1174 private void onCfiChanged(boolean visible) {
1175 if (VDBG) log("onCfiChanged(): " + visible);
1176 mApplication.notificationMgr.updateCfi(visible);
1177 }
1178
1179 /**
1180 * Indicates whether or not this ringer is ringing.
1181 */
1182 boolean isRinging() {
1183 return mRinger.isRinging();
1184 }
1185
1186 /**
1187 * Stops the current ring, and tells the notifier that future
1188 * ring requests should be ignored.
1189 */
1190 void silenceRinger() {
1191 mSilentRingerRequested = true;
1192 if (DBG) log("stopRing()... (silenceRinger)");
1193 mRinger.stopRing();
1194 }
1195
1196 /**
1197 * Restarts the ringer after having previously silenced it.
1198 *
1199 * (This is a no-op if the ringer is actually still ringing, or if the
1200 * incoming ringing call no longer exists.)
1201 */
1202 /* package */ void restartRinger() {
1203 if (DBG) log("restartRinger()...");
1204 // Already ringing or Silent requested; no need to restart.
1205 if (isRinging() || mSilentRingerRequested) return;
1206
1207 final Call ringingCall = mCM.getFirstActiveRingingCall();
1208 // Don't check ringingCall.isRinging() here, since that'll be true
1209 // for the WAITING state also. We only allow the ringer for
1210 // regular INCOMING calls.
1211 if (DBG) log("- ringingCall state: " + ringingCall.getState());
1212 if (ringingCall.getState() == Call.State.INCOMING) {
1213 mRinger.ring();
1214 }
1215 }
1216
1217 /**
1218 * Helper class to play tones through the earpiece (or speaker / BT)
1219 * during a call, using the ToneGenerator.
1220 *
1221 * To use, just instantiate a new InCallTonePlayer
1222 * (passing in the TONE_* constant for the tone you want)
1223 * and start() it.
1224 *
1225 * When we're done playing the tone, if the phone is idle at that
1226 * point, we'll reset the audio routing and speaker state.
1227 * (That means that for tones that get played *after* a call
1228 * disconnects, like "busy" or "congestion" or "call ended", you
1229 * should NOT call resetAudioStateAfterDisconnect() yourself.
1230 * Instead, just start the InCallTonePlayer, which will automatically
1231 * defer the resetAudioStateAfterDisconnect() call until the tone
1232 * finishes playing.)
1233 */
1234 private class InCallTonePlayer extends Thread {
1235 private int mToneId;
1236 private int mState;
1237 // The possible tones we can play.
1238 public static final int TONE_NONE = 0;
1239 public static final int TONE_CALL_WAITING = 1;
1240 public static final int TONE_BUSY = 2;
1241 public static final int TONE_CONGESTION = 3;
1242 public static final int TONE_CALL_ENDED = 4;
1243 public static final int TONE_VOICE_PRIVACY = 5;
1244 public static final int TONE_REORDER = 6;
1245 public static final int TONE_INTERCEPT = 7;
1246 public static final int TONE_CDMA_DROP = 8;
1247 public static final int TONE_OUT_OF_SERVICE = 9;
1248 public static final int TONE_REDIAL = 10;
1249 public static final int TONE_OTA_CALL_END = 11;
1250 public static final int TONE_RING_BACK = 12;
1251 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
1252
1253 // The tone volume relative to other sounds in the stream
1254 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
1255 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
1256 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
1257
1258 // Buffer time (in msec) to add on to tone timeout value.
1259 // Needed mainly when the timeout value for a tone is the
1260 // exact duration of the tone itself.
1261 static final int TONE_TIMEOUT_BUFFER = 20;
1262
1263 // The tone state
1264 static final int TONE_OFF = 0;
1265 static final int TONE_ON = 1;
1266 static final int TONE_STOPPED = 2;
1267
1268 InCallTonePlayer(int toneId) {
1269 super();
1270 mToneId = toneId;
1271 mState = TONE_OFF;
1272 }
1273
1274 @Override
1275 public void run() {
1276 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
1277
1278 int toneType = 0; // passed to ToneGenerator.startTone()
1279 int toneVolume; // passed to the ToneGenerator constructor
1280 int toneLengthMillis;
1281 int phoneType = mCM.getFgPhone().getPhoneType();
1282
1283 switch (mToneId) {
1284 case TONE_CALL_WAITING:
1285 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
1286 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1287 // Call waiting tone is stopped by stopTone() method
1288 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1289 break;
1290 case TONE_BUSY:
1291 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1292 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
1293 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1294 toneLengthMillis = 1000;
1295 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
1296 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
1297 toneType = ToneGenerator.TONE_SUP_BUSY;
1298 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1299 toneLengthMillis = 4000;
1300 } else {
1301 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1302 }
1303 break;
1304 case TONE_CONGESTION:
1305 toneType = ToneGenerator.TONE_SUP_CONGESTION;
1306 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1307 toneLengthMillis = 4000;
1308 break;
1309
1310 case TONE_CALL_ENDED:
1311 toneType = ToneGenerator.TONE_PROP_PROMPT;
1312 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1313 toneLengthMillis = 200;
1314 break;
1315 case TONE_OTA_CALL_END:
1316 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
1317 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
1318 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
1319 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1320 toneLengthMillis = 750;
1321 } else {
1322 toneType = ToneGenerator.TONE_PROP_PROMPT;
1323 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1324 toneLengthMillis = 200;
1325 }
1326 break;
1327 case TONE_VOICE_PRIVACY:
1328 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
1329 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1330 toneLengthMillis = 5000;
1331 break;
1332 case TONE_REORDER:
1333 toneType = ToneGenerator.TONE_CDMA_REORDER;
1334 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1335 toneLengthMillis = 4000;
1336 break;
1337 case TONE_INTERCEPT:
1338 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
1339 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1340 toneLengthMillis = 500;
1341 break;
1342 case TONE_CDMA_DROP:
1343 case TONE_OUT_OF_SERVICE:
1344 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
1345 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1346 toneLengthMillis = 375;
1347 break;
1348 case TONE_REDIAL:
1349 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
1350 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1351 toneLengthMillis = 5000;
1352 break;
1353 case TONE_RING_BACK:
1354 toneType = ToneGenerator.TONE_SUP_RINGTONE;
1355 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1356 // Call ring back tone is stopped by stopTone() method
1357 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1358 break;
1359 case TONE_UNOBTAINABLE_NUMBER:
1360 toneType = ToneGenerator.TONE_SUP_ERROR;
1361 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1362 toneLengthMillis = 4000;
1363 break;
1364 default:
1365 throw new IllegalArgumentException("Bad toneId: " + mToneId);
1366 }
1367
1368 // If the mToneGenerator creation fails, just continue without it. It is
1369 // a local audio signal, and is not as important.
1370 ToneGenerator toneGenerator;
1371 try {
1372 int stream;
1373 if (mBluetoothHeadset != null) {
1374 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
1375 AudioManager.STREAM_VOICE_CALL;
1376 } else {
1377 stream = AudioManager.STREAM_VOICE_CALL;
1378 }
1379 toneGenerator = new ToneGenerator(stream, toneVolume);
1380 // if (DBG) log("- created toneGenerator: " + toneGenerator);
1381 } catch (RuntimeException e) {
1382 Log.w(LOG_TAG,
1383 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
1384 toneGenerator = null;
1385 }
1386
1387 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
1388 // CONGESTION tones at least), the ToneGenerator itself knows
1389 // the right pattern of tones to play; we do NOT need to
1390 // manually start/stop each individual tone, or manually
1391 // insert the correct delay between tones. (We just start it
1392 // and let it run for however long we want the tone pattern to
1393 // continue.)
1394 //
1395 // TODO: When we stop the ToneGenerator in the middle of a
1396 // "tone pattern", it sounds bad if we cut if off while the
1397 // tone is actually playing. Consider adding API to the
1398 // ToneGenerator to say "stop at the next silent part of the
1399 // pattern", or simply "play the pattern N times and then
1400 // stop."
1401 boolean needToStopTone = true;
1402 boolean okToPlayTone = false;
1403
1404 if (toneGenerator != null) {
1405 int ringerMode = mAudioManager.getRingerMode();
1406 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1407 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
1408 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1409 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1410 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
1411 okToPlayTone = true;
1412 needToStopTone = false;
1413 }
1414 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
1415 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
1416 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
1417 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
1418 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
1419 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
1420 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
1421 okToPlayTone = true;
1422 needToStopTone = false;
1423 }
1424 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
1425 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
1426 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1427 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1428 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
1429 okToPlayTone = true;
1430 needToStopTone = false;
1431 }
1432 } else { // For the rest of the tones, always OK to play.
1433 okToPlayTone = true;
1434 }
1435 } else { // Not "CDMA"
1436 okToPlayTone = true;
1437 }
1438
1439 synchronized (this) {
1440 if (okToPlayTone && mState != TONE_STOPPED) {
1441 mState = TONE_ON;
1442 toneGenerator.startTone(toneType);
1443 try {
1444 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
1445 } catch (InterruptedException e) {
1446 Log.w(LOG_TAG,
1447 "InCallTonePlayer stopped: " + e);
1448 }
1449 if (needToStopTone) {
1450 toneGenerator.stopTone();
1451 }
1452 }
1453 // if (DBG) log("- InCallTonePlayer: done playing.");
1454 toneGenerator.release();
1455 mState = TONE_OFF;
1456 }
1457 }
1458
1459 // Finally, do the same cleanup we otherwise would have done
1460 // in onDisconnect().
1461 //
1462 // (But watch out: do NOT do this if the phone is in use,
1463 // since some of our tones get played *during* a call (like
1464 // CALL_WAITING) and we definitely *don't*
1465 // want to reset the audio mode / speaker / bluetooth after
1466 // playing those!
1467 // This call is really here for use with tones that get played
1468 // *after* a call disconnects, like "busy" or "congestion" or
1469 // "call ended", where the phone has already become idle but
1470 // we need to defer the resetAudioStateAfterDisconnect() call
1471 // till the tone finishes playing.)
1472 if (mCM.getState() == PhoneConstants.State.IDLE) {
1473 resetAudioStateAfterDisconnect();
1474 }
1475 }
1476
1477 public void stopTone() {
1478 synchronized (this) {
1479 if (mState == TONE_ON) {
1480 notify();
1481 }
1482 mState = TONE_STOPPED;
1483 }
1484 }
1485 }
1486
1487 /**
1488 * Displays a notification when the phone receives a DisplayInfo record.
1489 */
1490 private void onDisplayInfo(AsyncResult r) {
1491 // Extract the DisplayInfo String from the message
1492 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1493
1494 if (displayInfoRec != null) {
1495 String displayInfo = displayInfoRec.alpha;
1496 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1497 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1498
1499 // start a 2 second timer
1500 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1501 DISPLAYINFO_NOTIFICATION_TIME);
1502 }
1503 }
1504
1505 /**
1506 * Helper class to play SignalInfo tones using the ToneGenerator.
1507 *
1508 * To use, just instantiate a new SignalInfoTonePlayer
1509 * (passing in the ToneID constant for the tone you want)
1510 * and start() it.
1511 */
1512 private class SignalInfoTonePlayer extends Thread {
1513 private int mToneId;
1514
1515 SignalInfoTonePlayer(int toneId) {
1516 super();
1517 mToneId = toneId;
1518 }
1519
1520 @Override
1521 public void run() {
1522 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1523
1524 if (mSignalInfoToneGenerator != null) {
1525 //First stop any ongoing SignalInfo tone
1526 mSignalInfoToneGenerator.stopTone();
1527
1528 //Start playing the new tone if its a valid tone
1529 mSignalInfoToneGenerator.startTone(mToneId);
1530 }
1531 }
1532 }
1533
1534 /**
1535 * Plays a tone when the phone receives a SignalInfo record.
1536 */
1537 private void onSignalInfo(AsyncResult r) {
1538 // Signal Info are totally ignored on non-voice-capable devices.
1539 if (!PhoneGlobals.sVoiceCapable) {
1540 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1541 return;
1542 }
1543
1544 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1545 // Do not start any new SignalInfo tone when Call state is INCOMING
1546 // and stop any previous SignalInfo tone which is being played
1547 stopSignalInfoTone();
1548 } else {
1549 // Extract the SignalInfo String from the message
1550 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1551 // Only proceed if a Signal info is present.
1552 if (signalInfoRec != null) {
1553 boolean isPresent = signalInfoRec.isPresent;
1554 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1555 if (isPresent) {// if tone is valid
1556 int uSignalType = signalInfoRec.signalType;
1557 int uAlertPitch = signalInfoRec.alertPitch;
1558 int uSignal = signalInfoRec.signal;
1559
1560 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1561 uAlertPitch + ", uSignal=" + uSignal);
1562 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1563 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1564 (uSignalType, uAlertPitch, uSignal);
1565
1566 //Create the SignalInfo tone player and pass the ToneID
1567 new SignalInfoTonePlayer(toneID).start();
1568 }
1569 }
1570 }
1571 }
1572
1573 /**
1574 * Stops a SignalInfo tone in the following condition
1575 * 1 - On receiving a New Ringing Call
1576 * 2 - On disconnecting a call
1577 * 3 - On answering a Call Waiting Call
1578 */
1579 /* package */ void stopSignalInfoTone() {
1580 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1581 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1582 }
1583
1584 /**
1585 * Plays a Call waiting tone if it is present in the second incoming call.
1586 */
1587 private void onCdmaCallWaiting(AsyncResult r) {
1588 // Remove any previous Call waiting timers in the queue
1589 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1590 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1591
1592 // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
1593 // else we would not have received Call waiting
1594 mApplication.cdmaPhoneCallState.setCurrentCallState(
1595 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
1596
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001597 // Start timer for CW display
1598 mCallWaitingTimeOut = false;
1599 sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
1600 CALLWAITING_CALLERINFO_DISPLAY_TIME);
1601
1602 // Set the mAddCallMenuStateAfterCW state to false
1603 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
1604
1605 // Start the timer for disabling "Add Call" menu option
1606 sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
1607 CALLWAITING_ADDCALL_DISABLE_TIME);
1608
1609 // Extract the Call waiting information
1610 CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
1611 int isPresent = infoCW.isPresent;
1612 if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
1613 if (isPresent == 1 ) {//'1' if tone is valid
1614 int uSignalType = infoCW.signalType;
1615 int uAlertPitch = infoCW.alertPitch;
1616 int uSignal = infoCW.signal;
1617 if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
1618 + uAlertPitch + ", uSignal=" + uSignal);
1619 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1620 int toneID =
1621 SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
1622
1623 //Create the SignalInfo tone player and pass the ToneID
1624 new SignalInfoTonePlayer(toneID).start();
1625 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001626
1627 mCallModeler.onCdmaCallWaiting(infoCW);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001628 }
1629
1630 /**
1631 * Posts a event causing us to clean up after rejecting (or timing-out) a
1632 * CDMA call-waiting call.
1633 *
1634 * This method is safe to call from any thread.
1635 * @see #onCdmaCallWaitingReject()
1636 */
1637 /* package */ void sendCdmaCallWaitingReject() {
1638 sendEmptyMessage(CDMA_CALL_WAITING_REJECT);
1639 }
1640
1641 /**
1642 * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
1643 * and finally calls Hangup on the Call Waiting connection.
1644 *
1645 * This method should be called only from the UI thread.
1646 * @see #sendCdmaCallWaitingReject()
1647 */
1648 private void onCdmaCallWaitingReject() {
1649 final Call ringingCall = mCM.getFirstActiveRingingCall();
1650
1651 // Call waiting timeout scenario
1652 if (ringingCall.getState() == Call.State.WAITING) {
1653 // Code for perform Call logging and missed call notification
1654 Connection c = ringingCall.getLatestConnection();
1655
1656 if (c != null) {
1657 final int callLogType = mCallWaitingTimeOut ?
1658 Calls.MISSED_TYPE : Calls.INCOMING_TYPE;
1659
1660 // TODO: This callLogType override is not ideal. Connection should be astracted away
1661 // at a telephony-phone layer that can understand and edit the callTypes within
1662 // the abstraction for CDMA devices.
1663 mCallLogger.logCall(c, callLogType);
1664
1665 final long date = c.getCreateTime();
1666 if (callLogType == Calls.MISSED_TYPE) {
1667 // Add missed call notification
1668 showMissedCallNotification(c, date);
1669 } else {
1670 // Remove Call waiting 20 second display timer in the queue
1671 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1672 }
1673
1674 // Hangup the RingingCall connection for CW
1675 PhoneUtils.hangup(c);
1676 }
1677
1678 //Reset the mCallWaitingTimeOut boolean
1679 mCallWaitingTimeOut = false;
1680 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001681
1682 // Call modeler needs to know about this event regardless of the
1683 // state conditionals in the previous code.
1684 mCallModeler.onCdmaCallWaitingReject();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001685 }
1686
1687 /**
1688 * Return the private variable mPreviousCdmaCallState.
1689 */
1690 /* package */ Call.State getPreviousCdmaCallState() {
1691 return mPreviousCdmaCallState;
1692 }
1693
1694 /**
1695 * Return the private variable mVoicePrivacyState.
1696 */
1697 /* package */ boolean getVoicePrivacyState() {
1698 return mVoicePrivacyState;
1699 }
1700
1701 /**
1702 * Return the private variable mIsCdmaRedialCall.
1703 */
1704 /* package */ boolean getIsCdmaRedialCall() {
1705 return mIsCdmaRedialCall;
1706 }
1707
1708 /**
1709 * Helper function used to show a missed call notification.
1710 */
1711 private void showMissedCallNotification(Connection c, final long date) {
1712 PhoneUtils.CallerInfoToken info =
1713 PhoneUtils.startGetCallerInfo(mApplication, c, this, Long.valueOf(date));
1714 if (info != null) {
1715 // at this point, we've requested to start a query, but it makes no
1716 // sense to log this missed call until the query comes back.
1717 if (VDBG) log("showMissedCallNotification: Querying for CallerInfo on missed call...");
1718 if (info.isFinal) {
1719 // it seems that the query we have actually is up to date.
1720 // send the notification then.
1721 CallerInfo ci = info.currentInfo;
1722
1723 // Check number presentation value; if we have a non-allowed presentation,
1724 // then display an appropriate presentation string instead as the missed
1725 // call.
1726 String name = ci.name;
1727 String number = ci.phoneNumber;
1728 if (ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1729 name = mApplication.getString(R.string.private_num);
1730 } else if (ci.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1731 name = mApplication.getString(R.string.unknown);
1732 } else {
1733 number = PhoneUtils.modifyForSpecialCnapCases(mApplication,
1734 ci, number, ci.numberPresentation);
1735 }
1736 mApplication.notificationMgr.notifyMissedCall(name, number,
1737 ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon, date);
1738 }
1739 } else {
1740 // getCallerInfo() can return null in rare cases, like if we weren't
1741 // able to get a valid phone number out of the specified Connection.
1742 Log.w(LOG_TAG, "showMissedCallNotification: got null CallerInfo for Connection " + c);
1743 }
1744 }
1745
1746 /**
1747 * Inner class to handle emergency call tone and vibrator
1748 */
1749 private class EmergencyTonePlayerVibrator {
1750 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1751 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1752 private final long[] mVibratePattern =
1753 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1754
1755 private ToneGenerator mToneGenerator;
1756 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1757 // object will be isolated from others.
1758 private Vibrator mEmgVibrator = new SystemVibrator();
1759 private int mInCallVolume;
1760
1761 /**
1762 * constructor
1763 */
1764 public EmergencyTonePlayerVibrator() {
1765 }
1766
1767 /**
1768 * Start the emergency tone or vibrator.
1769 */
1770 private void start() {
1771 if (VDBG) log("call startEmergencyToneOrVibrate.");
1772 int ringerMode = mAudioManager.getRingerMode();
1773
1774 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1775 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1776 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1777 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1778 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1779 if (mToneGenerator != null) {
1780 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1781 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1782 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1783 0);
1784 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1785 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1786 }
1787 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1788 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1789 if (mEmgVibrator != null) {
1790 mEmgVibrator.vibrate(mVibratePattern, 0);
1791 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1792 }
1793 }
1794 }
1795
1796 /**
1797 * If the emergency tone is active, stop the tone or vibrator accordingly.
1798 */
1799 private void stop() {
1800 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1801
1802 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1803 && (mToneGenerator != null)) {
1804 mToneGenerator.stopTone();
1805 mToneGenerator.release();
1806 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1807 mInCallVolume,
1808 0);
1809 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1810 && (mEmgVibrator != null)) {
1811 mEmgVibrator.cancel();
1812 }
1813 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1814 }
1815 }
1816
1817 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1818 new BluetoothProfile.ServiceListener() {
1819 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1820 mBluetoothHeadset = (BluetoothHeadset) proxy;
1821 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1822 }
1823
1824 public void onServiceDisconnected(int profile) {
1825 mBluetoothHeadset = null;
1826 }
1827 };
1828
1829 private void onRingbackTone(AsyncResult r) {
1830 boolean playTone = (Boolean)(r.result);
1831
1832 if (playTone == true) {
1833 // Only play when foreground call is in DIALING or ALERTING.
1834 // to prevent a late coming playtone after ALERTING.
1835 // Don't play ringback tone if it is in play, otherwise it will cut
1836 // the current tone and replay it
1837 if (mCM.getActiveFgCallState().isDialing() &&
1838 mInCallRingbackTonePlayer == null) {
1839 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1840 mInCallRingbackTonePlayer.start();
1841 }
1842 } else {
1843 if (mInCallRingbackTonePlayer != null) {
1844 mInCallRingbackTonePlayer.stopTone();
1845 mInCallRingbackTonePlayer = null;
1846 }
1847 }
1848 }
1849
1850 /**
1851 * Toggle mute and unmute requests while keeping the same mute state
1852 */
1853 private void onResendMute() {
1854 boolean muteState = PhoneUtils.getMute();
1855 PhoneUtils.setMute(!muteState);
1856 PhoneUtils.setMute(muteState);
1857 }
1858
1859 private void log(String msg) {
1860 Log.d(LOG_TAG, msg);
1861 }
1862}