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