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