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