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