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