blob: aa4270e5340bf55943806eb34db1e796b1dee704 [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;
Anders Kristensen0b35f042014-02-27 14:31:07 -080049import android.telephony.DisconnectCause;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070050import 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
Christine Chenb5e4b652013-09-19 11:20:18 -0700440 startIncomingCallQuery(c);
Chiao Cheng312b9c92013-09-16 15:40:53 -0700441
Christine Chenb5e4b652013-09-19 11:20:18 -0700442
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700443
444 // Note we *don't* post a status bar notification here, since
445 // we're not necessarily ready to actually show the incoming call
446 // to the user. (For calls in the INCOMING state, at least, we
447 // still need to run a caller-id query, and we may not even ring
448 // at all if the "send directly to voicemail" flag is set.)
449 //
450 // Instead, we update the notification (and potentially launch the
451 // InCallScreen) from the showIncomingCall() method, which runs
452 // when the caller-id query completes or times out.
453
454 if (VDBG) log("- onNewRingingConnection() done.");
455 }
456
457 /**
458 * Determines whether or not we're allowed to present incoming calls to the
459 * user, based on the capabilities and/or current state of the device.
460 *
461 * If this method returns true, that means we should immediately reject the
462 * current incoming call, without even indicating to the user that an
463 * incoming call occurred.
464 *
465 * (We only reject incoming calls in a few cases, like during an OTASP call
466 * when we can't interrupt the user, or if the device hasn't completed the
467 * SetupWizard yet. We also don't allow incoming calls on non-voice-capable
468 * devices. But note that we *always* allow incoming calls while in ECM.)
469 *
470 * @return true if we're *not* allowed to present an incoming call to
471 * the user.
472 */
473 private boolean ignoreAllIncomingCalls(Phone phone) {
474 // Incoming calls are totally ignored on non-voice-capable devices.
475 if (!PhoneGlobals.sVoiceCapable) {
476 // ...but still log a warning, since we shouldn't have gotten this
477 // event in the first place! (Incoming calls *should* be blocked at
478 // the telephony layer on non-voice-capable capable devices.)
479 Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring...");
480 return true;
481 }
482
483 // In ECM (emergency callback mode), we ALWAYS allow incoming calls
484 // to get through to the user. (Note that ECM is applicable only to
485 // voice-capable CDMA devices).
486 if (PhoneUtils.isPhoneInEcm(phone)) {
487 if (DBG) log("Incoming call while in ECM: always allow...");
488 return false;
489 }
490
491 // Incoming calls are totally ignored if the device isn't provisioned yet.
492 boolean provisioned = Settings.Global.getInt(mApplication.getContentResolver(),
493 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
494 if (!provisioned) {
495 Log.i(LOG_TAG, "Ignoring incoming call: not provisioned");
496 return true;
497 }
498
499 // Incoming calls are totally ignored if an OTASP call is active.
500 if (TelephonyCapabilities.supportsOtasp(phone)) {
501 boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState
502 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
503 boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState
504 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG);
505 boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState;
506
507 if (spcState) {
508 Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active");
509 return true;
510 } else if (activateState || dialogState) {
511 // We *are* allowed to receive incoming calls at this point.
512 // But clear out any residual OTASP UI first.
513 // TODO: It's an MVC violation to twiddle the OTA UI state here;
514 // we should instead provide a higher-level API via OtaUtils.
515 if (dialogState) mApplication.dismissOtaDialogs();
516 mApplication.clearOtaState();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700517 return false;
518 }
519 }
520
521 // Normal case: allow this call to be presented to the user.
522 return false;
523 }
524
525 /**
526 * Helper method to manage the start of incoming call queries
527 */
528 private void startIncomingCallQuery(Connection c) {
529 // TODO: cache the custom ringer object so that subsequent
530 // calls will not need to do this query work. We can keep
531 // the MRU ringtones in memory. We'll still need to hit
532 // the database to get the callerinfo to act as a key,
533 // but at least we can save the time required for the
534 // Media player setup. The only issue with this is that
535 // we may need to keep an eye on the resources the Media
536 // player uses to keep these ringtones around.
537
538 // make sure we're in a state where we can be ready to
539 // query a ringtone uri.
540 boolean shouldStartQuery = false;
541 synchronized (mCallerInfoQueryStateGuard) {
542 if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) {
543 mCallerInfoQueryState = CALLERINFO_QUERYING;
544 shouldStartQuery = true;
545 }
546 }
547 if (shouldStartQuery) {
548 // Reset the ringtone to the default first.
549 mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI);
550
551 // query the callerinfo to try to get the ringer.
552 PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700553 mApplication, c, this, c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700554
555 // if this has already been queried then just ring, otherwise
556 // we wait for the alloted time before ringing.
557 if (cit.isFinal) {
558 if (VDBG) log("- CallerInfo already up to date, using available data");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700559 onQueryComplete(0, c, cit.currentInfo);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700560 } else {
561 if (VDBG) log("- Starting query, posting timeout message.");
562
563 // Phone number (via getAddress()) is stored in the message to remember which
564 // number is actually used for the look up.
565 sendMessageDelayed(
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700566 Message.obtain(this, RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT, c),
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700567 RINGTONE_QUERY_WAIT_TIME);
568 }
569 // The call to showIncomingCall() will happen after the
570 // queries are complete (or time out).
571 } else {
572 // This should never happen; its the case where an incoming call
573 // arrives at the same time that the query is still being run,
574 // and before the timeout window has closed.
575 EventLog.writeEvent(EventLogTags.PHONE_UI_MULTIPLE_QUERY);
576
Christine Chenb5e4b652013-09-19 11:20:18 -0700577 ringAndNotifyOfIncomingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700578 }
579 }
580
581 /**
582 * Performs the final steps of the onNewRingingConnection sequence:
583 * starts the ringer, and brings up the "incoming call" UI.
584 *
585 * Normally, this is called when the CallerInfo query completes (see
586 * onQueryComplete()). In this case, onQueryComplete() has already
587 * configured the Ringer object to use the custom ringtone (if there
588 * is one) for this caller. So we just tell the Ringer to start, and
589 * proceed to the InCallScreen.
590 *
591 * But this method can *also* be called if the
592 * RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the
593 * CallerInfo query is taking too long. In that case, we log a
594 * warning but otherwise we behave the same as in the normal case.
595 * (We still tell the Ringer to start, but it's going to use the
596 * default ringtone.)
597 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700598 private void onCustomRingQueryComplete(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700599 boolean isQueryExecutionTimeExpired = false;
600 synchronized (mCallerInfoQueryStateGuard) {
601 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
602 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
603 isQueryExecutionTimeExpired = true;
604 }
605 }
606 if (isQueryExecutionTimeExpired) {
607 // There may be a problem with the query here, since the
608 // default ringtone is playing instead of the custom one.
609 Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone");
610 EventLog.writeEvent(EventLogTags.PHONE_UI_RINGER_QUERY_ELAPSED);
611 }
612
613 // Make sure we still have an incoming call!
614 //
615 // (It's possible for the incoming call to have been disconnected
616 // while we were running the query. In that case we better not
617 // start the ringer here, since there won't be any future
618 // DISCONNECT event to stop it!)
619 //
620 // Note we don't have to worry about the incoming call going away
621 // *after* this check but before we call mRinger.ring() below,
622 // since in that case we *will* still get a DISCONNECT message sent
623 // to our handler. (And we will correctly stop the ringer when we
624 // process that event.)
625 if (mCM.getState() != PhoneConstants.State.RINGING) {
626 Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out...");
627 // Don't start the ringer *or* bring up the "incoming call" UI.
628 // Just bail out.
629 return;
630 }
631
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700632 // If the ringing call still does not have any connection anymore, do not send the
633 // notification to the CallModeler.
634 final Call ringingCall = mCM.getFirstActiveRingingCall();
635
636 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
Christine Chenb5e4b652013-09-19 11:20:18 -0700637 ringAndNotifyOfIncomingCall(c);
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700638 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700639 }
640
641 private void onUnknownConnectionAppeared(AsyncResult r) {
642 PhoneConstants.State state = mCM.getState();
643
644 if (state == PhoneConstants.State.OFFHOOK) {
Santos Cordon54fdb592013-09-19 05:16:18 -0700645 if (DBG) log("unknown connection appeared...");
Chiao Cheng312b9c92013-09-16 15:40:53 -0700646
Santos Cordon54fdb592013-09-19 05:16:18 -0700647 onPhoneStateChanged(r);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700648 }
649 }
650
Christine Chenb5e4b652013-09-19 11:20:18 -0700651 /**
652 * Notifies the Call Modeler that there is a new ringing connection.
653 * If it is not a waiting call (there is no other active call in foreground), we will ring the
654 * ringtone. Otherwise we will play the call waiting tone instead.
655 * @param c The new ringing connection.
656 */
657 private void ringAndNotifyOfIncomingCall(Connection c) {
658 if (PhoneUtils.isRealIncomingCall(c.getState())) {
659 mRinger.ring();
660 } else {
661 if (VDBG) log("- starting call waiting tone...");
662 if (mCallWaitingTonePlayer == null) {
663 mCallWaitingTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING);
664 mCallWaitingTonePlayer.start();
665 }
666 }
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700667 mCallModeler.onNewRingingConnection(c);
668 }
669
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700670 /**
671 * Updates the phone UI in response to phone state changes.
672 *
673 * Watch out: certain state changes are actually handled by their own
674 * specific methods:
675 * - see onNewRingingConnection() for new incoming calls
676 * - see onDisconnect() for calls being hung up or disconnected
677 */
678 private void onPhoneStateChanged(AsyncResult r) {
679 PhoneConstants.State state = mCM.getState();
680 if (VDBG) log("onPhoneStateChanged: state = " + state);
681
682 // Turn status bar notifications on or off depending upon the state
683 // of the phone. Notification Alerts (audible or vibrating) should
684 // be on if and only if the phone is IDLE.
685 mApplication.notificationMgr.statusBarHelper
686 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
687
688 Phone fgPhone = mCM.getFgPhone();
689 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
690 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
691 && ((mPreviousCdmaCallState == Call.State.DIALING)
692 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
693 if (mIsCdmaRedialCall) {
694 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
695 new InCallTonePlayer(toneToPlay).start();
696 }
697 // Stop any signal info tone when call moves to ACTIVE state
698 stopSignalInfoTone();
699 }
700 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
701 }
702
703 // Have the PhoneApp recompute its mShowBluetoothIndication
704 // flag based on the (new) telephony state.
705 // There's no need to force a UI update since we update the
706 // in-call notification ourselves (below), and the InCallScreen
707 // listens for phone state changes itself.
Christine Chen91db67d2013-09-18 12:01:11 -0700708 // TODO: Have BluetoothManager listen to CallModeler instead of relying on
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700709 // CallNotifier
710 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700711
712
713 // Update the phone state and other sensor/lock.
714 mApplication.updatePhoneState(state);
715
716 if (state == PhoneConstants.State.OFFHOOK) {
717 // stop call waiting tone if needed when answering
718 if (mCallWaitingTonePlayer != null) {
719 mCallWaitingTonePlayer.stopTone();
720 mCallWaitingTonePlayer = null;
721 }
722
723 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
724 // make sure audio is in in-call mode now
725 PhoneUtils.setAudioMode(mCM);
726
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700727 // Since we're now in-call, the Ringer should definitely *not*
728 // be ringing any more. (This is just a sanity-check; we
729 // already stopped the ringer explicitly back in
730 // PhoneUtils.answerCall(), before the call to phone.acceptCall().)
731 // TODO: Confirm that this call really *is* unnecessary, and if so,
732 // remove it!
733 if (DBG) log("stopRing()... (OFFHOOK state)");
734 mRinger.stopRing();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700735 }
736
737 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
738 Connection c = fgPhone.getForegroundCall().getLatestConnection();
739 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
740 mApplication))) {
741 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
742 Call.State callState = fgPhone.getForegroundCall().getState();
743 if (mEmergencyTonePlayerVibrator == null) {
744 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
745 }
746
747 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
748 mIsEmergencyToneOn = Settings.Global.getInt(
749 mApplication.getContentResolver(),
750 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
751 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
752 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
753 if (mEmergencyTonePlayerVibrator != null) {
754 mEmergencyTonePlayerVibrator.start();
755 }
756 }
757 } else if (callState == Call.State.ACTIVE) {
758 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
759 if (mEmergencyTonePlayerVibrator != null) {
760 mEmergencyTonePlayerVibrator.stop();
761 }
762 }
763 }
764 }
765 }
766
767 if ((fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)
768 || (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP)) {
769 Call.State callState = mCM.getActiveFgCallState();
770 if (!callState.isDialing()) {
771 // If call get activated or disconnected before the ringback
772 // tone stops, we have to stop it to prevent disturbing.
773 if (mInCallRingbackTonePlayer != null) {
774 mInCallRingbackTonePlayer.stopTone();
775 mInCallRingbackTonePlayer = null;
776 }
777 }
778 }
779 }
780
781 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
782 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
783
784 // Clear ringback tone player
785 mInCallRingbackTonePlayer = null;
786
787 // Clear call waiting tone player
788 mCallWaitingTonePlayer = null;
789
790 // Instantiate mSignalInfoToneGenerator
791 createSignalInfoToneGenerator();
792 }
793
794 /**
795 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
796 * refreshes the CallCard data when it called. If called with this
797 * class itself, it is assumed that we have been waiting for the ringtone
798 * and direct to voicemail settings to update.
799 */
800 @Override
801 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
802 if (cookie instanceof Long) {
803 if (VDBG) log("CallerInfo query complete, posting missed call notification");
804
805 mApplication.notificationMgr.notifyMissedCall(ci.name, ci.phoneNumber,
Christine Chendaf4c1d2013-10-29 11:56:24 -0700806 ci.numberPresentation, ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon,
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700807 ((Long) cookie).longValue());
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700808 } else if (cookie instanceof Connection) {
809 final Connection c = (Connection) cookie;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700810 if (VDBG) log("CallerInfo query complete (for CallNotifier), "
811 + "updating state for incoming call..");
812
813 // get rid of the timeout messages
814 removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
815
816 boolean isQueryExecutionTimeOK = false;
817 synchronized (mCallerInfoQueryStateGuard) {
818 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
819 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
820 isQueryExecutionTimeOK = true;
821 }
822 }
823 //if we're in the right state
824 if (isQueryExecutionTimeOK) {
825
826 // send directly to voicemail.
827 if (ci.shouldSendToVoicemail) {
828 if (DBG) log("send to voicemail flag detected. hanging up.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700829 final Call ringingCall = mCM.getFirstActiveRingingCall();
830 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
831 PhoneUtils.hangupRingingCall(ringingCall);
832 return;
833 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700834 }
835
836 // set the ringtone uri to prepare for the ring.
837 if (ci.contactRingtoneUri != null) {
838 if (DBG) log("custom ringtone found, setting up ringer.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700839 Ringer r = mRinger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700840 r.setCustomRingtoneUri(ci.contactRingtoneUri);
841 }
842 // ring, and other post-ring actions.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700843 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700844 }
845 }
846 }
847
848 /**
849 * Called when asynchronous CallerInfo query is taking too long (more than
850 * {@link #RINGTONE_QUERY_WAIT_TIME} msec), but we cannot wait any more.
851 *
852 * This looks up in-memory fallback cache and use it when available. If not, it just calls
853 * {@link #onCustomRingQueryComplete()} with default ringtone ("Send to voicemail" flag will
854 * be just ignored).
855 *
856 * @param number The phone number used for the async query. This method will take care of
857 * formatting or normalization of the number.
858 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700859 private void onCustomRingtoneQueryTimeout(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700860 // First of all, this case itself should be rare enough, though we cannot avoid it in
861 // some situations (e.g. IPC is slow due to system overload, database is in sync, etc.)
862 Log.w(LOG_TAG, "CallerInfo query took too long; look up local fallback cache.");
863
864 // This method is intentionally verbose for now to detect possible bad side-effect for it.
865 // TODO: Remove the verbose log when it looks stable and reliable enough.
866
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700867
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700868 if (c != null) {
869 final CallerInfoCache.CacheEntry entry =
870 mApplication.callerInfoCache.getCacheEntry(c.getAddress());
871 if (entry != null) {
872 if (entry.sendToVoicemail) {
873 log("send to voicemail flag detected (in fallback cache). hanging up.");
874 if (mCM.getFirstActiveRingingCall().getLatestConnection() == c) {
875 PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
876 return;
877 }
878 }
879
880 if (entry.customRingtone != null) {
881 log("custom ringtone found (in fallback cache), setting up ringer: "
882 + entry.customRingtone);
883 this.mRinger.setCustomRingtoneUri(Uri.parse(entry.customRingtone));
884 }
885 } else {
886 // In this case we call onCustomRingQueryComplete(), just
887 // like if the query had completed normally. (But we're
888 // going to get the default ringtone, since we never got
889 // the chance to call Ringer.setCustomRingtoneUri()).
890 log("Failed to find fallback cache. Use default ringer tone.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700891 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700892 }
893
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700894 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700895 }
896
897 private void onDisconnect(AsyncResult r) {
898 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
899
900 mVoicePrivacyState = false;
901 Connection c = (Connection) r.result;
902 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800903 log("onDisconnect: cause = " + DisconnectCause.toString(c.getDisconnectCause())
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700904 + ", incoming = " + c.isIncoming()
905 + ", date = " + c.getCreateTime());
906 } else {
907 Log.w(LOG_TAG, "onDisconnect: null connection");
908 }
909
910 int autoretrySetting = 0;
911 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
912 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
913 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
914 }
915
916 // Stop any signalInfo tone being played when a call gets ended
917 stopSignalInfoTone();
918
919 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
920 // Resetting the CdmaPhoneCallState members
921 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
922
923 // Remove Call waiting timers
924 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
925 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
926 }
927
928 // Stop the ringer if it was ringing (for an incoming call that
929 // either disconnected by itself, or was rejected by the user.)
930 //
931 // TODO: We technically *shouldn't* stop the ringer if the
932 // foreground or background call disconnects while an incoming call
933 // is still ringing, but that's a really rare corner case.
934 // It's safest to just unconditionally stop the ringer here.
935
936 // CDMA: For Call collision cases i.e. when the user makes an out going call
937 // and at the same time receives an Incoming Call, the Incoming Call is given
938 // higher preference. At this time framework sends a disconnect for the Out going
939 // call connection hence we should *not* be stopping the ringer being played for
940 // the Incoming Call
941 Call ringingCall = mCM.getFirstActiveRingingCall();
942 if (ringingCall.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
943 if (PhoneUtils.isRealIncomingCall(ringingCall.getState())) {
944 // Also we need to take off the "In Call" icon from the Notification
945 // area as the Out going Call never got connected
946 if (DBG) log("cancelCallInProgressNotifications()... (onDisconnect)");
947 mApplication.notificationMgr.cancelCallInProgressNotifications();
948 } else {
949 if (DBG) log("stopRing()... (onDisconnect)");
950 mRinger.stopRing();
951 }
952 } else { // GSM
953 if (DBG) log("stopRing()... (onDisconnect)");
954 mRinger.stopRing();
955 }
956
957 // stop call waiting tone if needed when disconnecting
958 if (mCallWaitingTonePlayer != null) {
959 mCallWaitingTonePlayer.stopTone();
960 mCallWaitingTonePlayer = null;
961 }
962
963 // If this is the end of an OTASP call, pass it on to the PhoneApp.
964 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
965 final String number = c.getAddress();
966 if (c.getCall().getPhone().isOtaSpNumber(number)) {
967 if (DBG) log("onDisconnect: this was an OTASP call!");
968 mApplication.handleOtaspDisconnect();
969 }
970 }
971
972 // Check for the various tones we might need to play (thru the
973 // earpiece) after a call disconnects.
974 int toneToPlay = InCallTonePlayer.TONE_NONE;
975
976 // The "Busy" or "Congestion" tone is the highest priority:
977 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800978 int cause = c.getDisconnectCause();
979 if (cause == DisconnectCause.BUSY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700980 if (DBG) log("- need to play BUSY tone!");
981 toneToPlay = InCallTonePlayer.TONE_BUSY;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800982 } else if (cause == DisconnectCause.CONGESTION) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700983 if (DBG) log("- need to play CONGESTION tone!");
984 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800985 } else if (((cause == DisconnectCause.NORMAL)
986 || (cause == DisconnectCause.LOCAL))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700987 && (mApplication.isOtaCallInActiveState())) {
988 if (DBG) log("- need to play OTA_CALL_END tone!");
989 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800990 } else if (cause == DisconnectCause.CDMA_REORDER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700991 if (DBG) log("- need to play CDMA_REORDER tone!");
992 toneToPlay = InCallTonePlayer.TONE_REORDER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800993 } else if (cause == DisconnectCause.CDMA_INTERCEPT) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700994 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
995 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800996 } else if (cause == DisconnectCause.CDMA_DROP) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700997 if (DBG) log("- need to play CDMA_DROP tone!");
998 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800999 } else if (cause == DisconnectCause.OUT_OF_SERVICE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001000 if (DBG) log("- need to play OUT OF SERVICE tone!");
1001 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
Anders Kristensen0b35f042014-02-27 14:31:07 -08001002 } else if (cause == DisconnectCause.UNOBTAINABLE_NUMBER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001003 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
1004 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
Anders Kristensen0b35f042014-02-27 14:31:07 -08001005 } else if (cause == DisconnectCause.ERROR_UNSPECIFIED) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001006 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
1007 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1008 }
1009 }
1010
1011 // If we don't need to play BUSY or CONGESTION, then play the
1012 // "call ended" tone if this was a "regular disconnect" (i.e. a
1013 // normal call where one end or the other hung up) *and* this
1014 // disconnect event caused the phone to become idle. (In other
1015 // words, we *don't* play the sound if one call hangs up but
1016 // there's still an active call on the other line.)
1017 // TODO: We may eventually want to disable this via a preference.
1018 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
1019 && (mCM.getState() == PhoneConstants.State.IDLE)
1020 && (c != null)) {
Anders Kristensen0b35f042014-02-27 14:31:07 -08001021 int cause = c.getDisconnectCause();
1022 if ((cause == DisconnectCause.NORMAL) // remote hangup
1023 || (cause == DisconnectCause.LOCAL)) { // local hangup
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001024 if (VDBG) log("- need to play CALL_ENDED tone!");
1025 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1026 mIsCdmaRedialCall = false;
1027 }
1028 }
1029
1030 // All phone calls are disconnected.
1031 if (mCM.getState() == PhoneConstants.State.IDLE) {
1032 // Don't reset the audio mode or bluetooth/speakerphone state
1033 // if we still need to let the user hear a tone through the earpiece.
1034 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
1035 resetAudioStateAfterDisconnect();
1036 }
1037
1038 mApplication.notificationMgr.cancelCallInProgressNotifications();
1039 }
1040
1041 if (c != null) {
1042 mCallLogger.logCall(c);
1043
1044 final String number = c.getAddress();
1045 final Phone phone = c.getCall().getPhone();
1046 final boolean isEmergencyNumber =
1047 PhoneNumberUtils.isLocalEmergencyNumber(number, mApplication);
1048
1049 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1050 if ((isEmergencyNumber)
1051 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
1052 if (mEmergencyTonePlayerVibrator != null) {
1053 mEmergencyTonePlayerVibrator.stop();
1054 }
1055 }
1056 }
1057
1058 final long date = c.getCreateTime();
Anders Kristensen0b35f042014-02-27 14:31:07 -08001059 final int cause = c.getDisconnectCause();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001060 final boolean missedCall = c.isIncoming() &&
Anders Kristensen0b35f042014-02-27 14:31:07 -08001061 (cause == DisconnectCause.INCOMING_MISSED);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001062 if (missedCall) {
1063 // Show the "Missed call" notification.
1064 // (Note we *don't* do this if this was an incoming call that
1065 // the user deliberately rejected.)
1066 showMissedCallNotification(c, date);
1067 }
1068
1069 // Possibly play a "post-disconnect tone" thru the earpiece.
1070 // We do this here, rather than from the InCallScreen
1071 // activity, since we need to do this even if you're not in
1072 // the Phone UI at the moment the connection ends.
1073 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
1074 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
1075 new InCallTonePlayer(toneToPlay).start();
1076
1077 // TODO: alternatively, we could start an InCallTonePlayer
1078 // here with an "unlimited" tone length,
1079 // and manually stop it later when this connection truly goes
1080 // away. (The real connection over the network was closed as soon
1081 // as we got the BUSY message. But our telephony layer keeps the
1082 // connection open for a few extra seconds so we can show the
1083 // "busy" indication to the user. We could stop the busy tone
1084 // when *that* connection's "disconnect" event comes in.)
1085 }
1086
1087 if (((mPreviousCdmaCallState == Call.State.DIALING)
1088 || (mPreviousCdmaCallState == Call.State.ALERTING))
1089 && (!isEmergencyNumber)
Anders Kristensen0b35f042014-02-27 14:31:07 -08001090 && (cause != DisconnectCause.INCOMING_MISSED )
1091 && (cause != DisconnectCause.NORMAL)
1092 && (cause != DisconnectCause.LOCAL)
1093 && (cause != DisconnectCause.INCOMING_REJECTED)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001094 if (!mIsCdmaRedialCall) {
1095 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
1096 // TODO: (Moto): The contact reference data may need to be stored and use
1097 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordonce02f3a2013-09-19 01:58:42 -07001098 final int status =
1099 PhoneUtils.placeCall(mApplication, phone, number, null, false);
1100 if (status != PhoneUtils.CALL_STATUS_FAILED) {
1101 mIsCdmaRedialCall = true;
1102 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001103 } else {
1104 mIsCdmaRedialCall = false;
1105 }
1106 } else {
1107 mIsCdmaRedialCall = false;
1108 }
1109 }
1110 }
1111 }
1112
1113 /**
1114 * Resets the audio mode and speaker state when a call ends.
1115 */
1116 private void resetAudioStateAfterDisconnect() {
1117 if (VDBG) log("resetAudioStateAfterDisconnect()...");
1118
1119 if (mBluetoothHeadset != null) {
1120 mBluetoothHeadset.disconnectAudio();
1121 }
1122
1123 // call turnOnSpeaker() with state=false and store=true even if speaker
1124 // is already off to reset user requested speaker state.
1125 PhoneUtils.turnOnSpeaker(mApplication, false, true);
1126
1127 PhoneUtils.setAudioMode(mCM);
1128 }
1129
1130 private void onMwiChanged(boolean visible) {
1131 if (VDBG) log("onMwiChanged(): " + visible);
1132
1133 // "Voicemail" is meaningless on non-voice-capable devices,
1134 // so ignore MWI events.
1135 if (!PhoneGlobals.sVoiceCapable) {
1136 // ...but still log a warning, since we shouldn't have gotten this
1137 // event in the first place!
1138 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
1139 // *should* be blocked at the telephony layer on non-voice-capable
1140 // capable devices.)
1141 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
1142 return;
1143 }
1144
1145 mApplication.notificationMgr.updateMwi(visible);
1146 }
1147
1148 /**
1149 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
1150 * failed NotificationMgr.updateMwi() call.
1151 */
1152 /* package */ void sendMwiChangedDelayed(long delayMillis) {
1153 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
1154 sendMessageDelayed(message, delayMillis);
1155 }
1156
1157 private void onCfiChanged(boolean visible) {
1158 if (VDBG) log("onCfiChanged(): " + visible);
1159 mApplication.notificationMgr.updateCfi(visible);
1160 }
1161
1162 /**
1163 * Indicates whether or not this ringer is ringing.
1164 */
1165 boolean isRinging() {
1166 return mRinger.isRinging();
1167 }
1168
1169 /**
1170 * Stops the current ring, and tells the notifier that future
1171 * ring requests should be ignored.
1172 */
1173 void silenceRinger() {
1174 mSilentRingerRequested = true;
1175 if (DBG) log("stopRing()... (silenceRinger)");
1176 mRinger.stopRing();
1177 }
1178
1179 /**
1180 * Restarts the ringer after having previously silenced it.
1181 *
1182 * (This is a no-op if the ringer is actually still ringing, or if the
1183 * incoming ringing call no longer exists.)
1184 */
1185 /* package */ void restartRinger() {
1186 if (DBG) log("restartRinger()...");
1187 // Already ringing or Silent requested; no need to restart.
1188 if (isRinging() || mSilentRingerRequested) return;
1189
1190 final Call ringingCall = mCM.getFirstActiveRingingCall();
1191 // Don't check ringingCall.isRinging() here, since that'll be true
1192 // for the WAITING state also. We only allow the ringer for
1193 // regular INCOMING calls.
1194 if (DBG) log("- ringingCall state: " + ringingCall.getState());
1195 if (ringingCall.getState() == Call.State.INCOMING) {
1196 mRinger.ring();
1197 }
1198 }
1199
1200 /**
1201 * Helper class to play tones through the earpiece (or speaker / BT)
1202 * during a call, using the ToneGenerator.
1203 *
1204 * To use, just instantiate a new InCallTonePlayer
1205 * (passing in the TONE_* constant for the tone you want)
1206 * and start() it.
1207 *
1208 * When we're done playing the tone, if the phone is idle at that
1209 * point, we'll reset the audio routing and speaker state.
1210 * (That means that for tones that get played *after* a call
1211 * disconnects, like "busy" or "congestion" or "call ended", you
1212 * should NOT call resetAudioStateAfterDisconnect() yourself.
1213 * Instead, just start the InCallTonePlayer, which will automatically
1214 * defer the resetAudioStateAfterDisconnect() call until the tone
1215 * finishes playing.)
1216 */
1217 private class InCallTonePlayer extends Thread {
1218 private int mToneId;
1219 private int mState;
1220 // The possible tones we can play.
1221 public static final int TONE_NONE = 0;
1222 public static final int TONE_CALL_WAITING = 1;
1223 public static final int TONE_BUSY = 2;
1224 public static final int TONE_CONGESTION = 3;
1225 public static final int TONE_CALL_ENDED = 4;
1226 public static final int TONE_VOICE_PRIVACY = 5;
1227 public static final int TONE_REORDER = 6;
1228 public static final int TONE_INTERCEPT = 7;
1229 public static final int TONE_CDMA_DROP = 8;
1230 public static final int TONE_OUT_OF_SERVICE = 9;
1231 public static final int TONE_REDIAL = 10;
1232 public static final int TONE_OTA_CALL_END = 11;
1233 public static final int TONE_RING_BACK = 12;
1234 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
1235
1236 // The tone volume relative to other sounds in the stream
1237 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
1238 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
1239 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
1240
1241 // Buffer time (in msec) to add on to tone timeout value.
1242 // Needed mainly when the timeout value for a tone is the
1243 // exact duration of the tone itself.
1244 static final int TONE_TIMEOUT_BUFFER = 20;
1245
1246 // The tone state
1247 static final int TONE_OFF = 0;
1248 static final int TONE_ON = 1;
1249 static final int TONE_STOPPED = 2;
1250
1251 InCallTonePlayer(int toneId) {
1252 super();
1253 mToneId = toneId;
1254 mState = TONE_OFF;
1255 }
1256
1257 @Override
1258 public void run() {
1259 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
1260
1261 int toneType = 0; // passed to ToneGenerator.startTone()
1262 int toneVolume; // passed to the ToneGenerator constructor
1263 int toneLengthMillis;
1264 int phoneType = mCM.getFgPhone().getPhoneType();
1265
1266 switch (mToneId) {
1267 case TONE_CALL_WAITING:
1268 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
1269 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1270 // Call waiting tone is stopped by stopTone() method
1271 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1272 break;
1273 case TONE_BUSY:
1274 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1275 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
1276 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1277 toneLengthMillis = 1000;
1278 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
1279 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
1280 toneType = ToneGenerator.TONE_SUP_BUSY;
1281 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1282 toneLengthMillis = 4000;
1283 } else {
1284 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1285 }
1286 break;
1287 case TONE_CONGESTION:
1288 toneType = ToneGenerator.TONE_SUP_CONGESTION;
1289 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1290 toneLengthMillis = 4000;
1291 break;
1292
1293 case TONE_CALL_ENDED:
1294 toneType = ToneGenerator.TONE_PROP_PROMPT;
1295 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1296 toneLengthMillis = 200;
1297 break;
1298 case TONE_OTA_CALL_END:
1299 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
1300 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
1301 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
1302 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1303 toneLengthMillis = 750;
1304 } else {
1305 toneType = ToneGenerator.TONE_PROP_PROMPT;
1306 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1307 toneLengthMillis = 200;
1308 }
1309 break;
1310 case TONE_VOICE_PRIVACY:
1311 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
1312 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1313 toneLengthMillis = 5000;
1314 break;
1315 case TONE_REORDER:
1316 toneType = ToneGenerator.TONE_CDMA_REORDER;
1317 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1318 toneLengthMillis = 4000;
1319 break;
1320 case TONE_INTERCEPT:
1321 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
1322 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1323 toneLengthMillis = 500;
1324 break;
1325 case TONE_CDMA_DROP:
1326 case TONE_OUT_OF_SERVICE:
1327 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
1328 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1329 toneLengthMillis = 375;
1330 break;
1331 case TONE_REDIAL:
1332 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
1333 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1334 toneLengthMillis = 5000;
1335 break;
1336 case TONE_RING_BACK:
1337 toneType = ToneGenerator.TONE_SUP_RINGTONE;
1338 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1339 // Call ring back tone is stopped by stopTone() method
1340 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1341 break;
1342 case TONE_UNOBTAINABLE_NUMBER:
1343 toneType = ToneGenerator.TONE_SUP_ERROR;
1344 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1345 toneLengthMillis = 4000;
1346 break;
1347 default:
1348 throw new IllegalArgumentException("Bad toneId: " + mToneId);
1349 }
1350
1351 // If the mToneGenerator creation fails, just continue without it. It is
1352 // a local audio signal, and is not as important.
1353 ToneGenerator toneGenerator;
1354 try {
1355 int stream;
1356 if (mBluetoothHeadset != null) {
1357 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
1358 AudioManager.STREAM_VOICE_CALL;
1359 } else {
1360 stream = AudioManager.STREAM_VOICE_CALL;
1361 }
1362 toneGenerator = new ToneGenerator(stream, toneVolume);
1363 // if (DBG) log("- created toneGenerator: " + toneGenerator);
1364 } catch (RuntimeException e) {
1365 Log.w(LOG_TAG,
1366 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
1367 toneGenerator = null;
1368 }
1369
1370 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
1371 // CONGESTION tones at least), the ToneGenerator itself knows
1372 // the right pattern of tones to play; we do NOT need to
1373 // manually start/stop each individual tone, or manually
1374 // insert the correct delay between tones. (We just start it
1375 // and let it run for however long we want the tone pattern to
1376 // continue.)
1377 //
1378 // TODO: When we stop the ToneGenerator in the middle of a
1379 // "tone pattern", it sounds bad if we cut if off while the
1380 // tone is actually playing. Consider adding API to the
1381 // ToneGenerator to say "stop at the next silent part of the
1382 // pattern", or simply "play the pattern N times and then
1383 // stop."
1384 boolean needToStopTone = true;
1385 boolean okToPlayTone = false;
1386
1387 if (toneGenerator != null) {
1388 int ringerMode = mAudioManager.getRingerMode();
1389 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1390 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
1391 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1392 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1393 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
1394 okToPlayTone = true;
1395 needToStopTone = false;
1396 }
1397 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
1398 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
1399 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
1400 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
1401 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
1402 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
1403 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
1404 okToPlayTone = true;
1405 needToStopTone = false;
1406 }
1407 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
1408 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
1409 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1410 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1411 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
1412 okToPlayTone = true;
1413 needToStopTone = false;
1414 }
1415 } else { // For the rest of the tones, always OK to play.
1416 okToPlayTone = true;
1417 }
1418 } else { // Not "CDMA"
1419 okToPlayTone = true;
1420 }
1421
1422 synchronized (this) {
1423 if (okToPlayTone && mState != TONE_STOPPED) {
1424 mState = TONE_ON;
1425 toneGenerator.startTone(toneType);
1426 try {
1427 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
1428 } catch (InterruptedException e) {
1429 Log.w(LOG_TAG,
1430 "InCallTonePlayer stopped: " + e);
1431 }
1432 if (needToStopTone) {
1433 toneGenerator.stopTone();
1434 }
1435 }
1436 // if (DBG) log("- InCallTonePlayer: done playing.");
1437 toneGenerator.release();
1438 mState = TONE_OFF;
1439 }
1440 }
1441
1442 // Finally, do the same cleanup we otherwise would have done
1443 // in onDisconnect().
1444 //
1445 // (But watch out: do NOT do this if the phone is in use,
1446 // since some of our tones get played *during* a call (like
1447 // CALL_WAITING) and we definitely *don't*
1448 // want to reset the audio mode / speaker / bluetooth after
1449 // playing those!
1450 // This call is really here for use with tones that get played
1451 // *after* a call disconnects, like "busy" or "congestion" or
1452 // "call ended", where the phone has already become idle but
1453 // we need to defer the resetAudioStateAfterDisconnect() call
1454 // till the tone finishes playing.)
1455 if (mCM.getState() == PhoneConstants.State.IDLE) {
1456 resetAudioStateAfterDisconnect();
1457 }
1458 }
1459
1460 public void stopTone() {
1461 synchronized (this) {
1462 if (mState == TONE_ON) {
1463 notify();
1464 }
1465 mState = TONE_STOPPED;
1466 }
1467 }
1468 }
1469
1470 /**
1471 * Displays a notification when the phone receives a DisplayInfo record.
1472 */
1473 private void onDisplayInfo(AsyncResult r) {
1474 // Extract the DisplayInfo String from the message
1475 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1476
1477 if (displayInfoRec != null) {
1478 String displayInfo = displayInfoRec.alpha;
1479 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1480 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1481
1482 // start a 2 second timer
1483 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1484 DISPLAYINFO_NOTIFICATION_TIME);
1485 }
1486 }
1487
1488 /**
1489 * Helper class to play SignalInfo tones using the ToneGenerator.
1490 *
1491 * To use, just instantiate a new SignalInfoTonePlayer
1492 * (passing in the ToneID constant for the tone you want)
1493 * and start() it.
1494 */
1495 private class SignalInfoTonePlayer extends Thread {
1496 private int mToneId;
1497
1498 SignalInfoTonePlayer(int toneId) {
1499 super();
1500 mToneId = toneId;
1501 }
1502
1503 @Override
1504 public void run() {
1505 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1506
1507 if (mSignalInfoToneGenerator != null) {
1508 //First stop any ongoing SignalInfo tone
1509 mSignalInfoToneGenerator.stopTone();
1510
1511 //Start playing the new tone if its a valid tone
1512 mSignalInfoToneGenerator.startTone(mToneId);
1513 }
1514 }
1515 }
1516
1517 /**
1518 * Plays a tone when the phone receives a SignalInfo record.
1519 */
1520 private void onSignalInfo(AsyncResult r) {
1521 // Signal Info are totally ignored on non-voice-capable devices.
1522 if (!PhoneGlobals.sVoiceCapable) {
1523 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1524 return;
1525 }
1526
1527 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1528 // Do not start any new SignalInfo tone when Call state is INCOMING
1529 // and stop any previous SignalInfo tone which is being played
1530 stopSignalInfoTone();
1531 } else {
1532 // Extract the SignalInfo String from the message
1533 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1534 // Only proceed if a Signal info is present.
1535 if (signalInfoRec != null) {
1536 boolean isPresent = signalInfoRec.isPresent;
1537 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1538 if (isPresent) {// if tone is valid
1539 int uSignalType = signalInfoRec.signalType;
1540 int uAlertPitch = signalInfoRec.alertPitch;
1541 int uSignal = signalInfoRec.signal;
1542
1543 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1544 uAlertPitch + ", uSignal=" + uSignal);
1545 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1546 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1547 (uSignalType, uAlertPitch, uSignal);
1548
1549 //Create the SignalInfo tone player and pass the ToneID
1550 new SignalInfoTonePlayer(toneID).start();
1551 }
1552 }
1553 }
1554 }
1555
1556 /**
1557 * Stops a SignalInfo tone in the following condition
1558 * 1 - On receiving a New Ringing Call
1559 * 2 - On disconnecting a call
1560 * 3 - On answering a Call Waiting Call
1561 */
1562 /* package */ void stopSignalInfoTone() {
1563 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1564 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1565 }
1566
1567 /**
1568 * Plays a Call waiting tone if it is present in the second incoming call.
1569 */
1570 private void onCdmaCallWaiting(AsyncResult r) {
1571 // Remove any previous Call waiting timers in the queue
1572 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1573 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1574
1575 // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
1576 // else we would not have received Call waiting
1577 mApplication.cdmaPhoneCallState.setCurrentCallState(
1578 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
1579
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001580 // Start timer for CW display
1581 mCallWaitingTimeOut = false;
1582 sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
1583 CALLWAITING_CALLERINFO_DISPLAY_TIME);
1584
1585 // Set the mAddCallMenuStateAfterCW state to false
1586 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
1587
1588 // Start the timer for disabling "Add Call" menu option
1589 sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
1590 CALLWAITING_ADDCALL_DISABLE_TIME);
1591
1592 // Extract the Call waiting information
1593 CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
1594 int isPresent = infoCW.isPresent;
1595 if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
1596 if (isPresent == 1 ) {//'1' if tone is valid
1597 int uSignalType = infoCW.signalType;
1598 int uAlertPitch = infoCW.alertPitch;
1599 int uSignal = infoCW.signal;
1600 if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
1601 + uAlertPitch + ", uSignal=" + uSignal);
1602 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1603 int toneID =
1604 SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
1605
1606 //Create the SignalInfo tone player and pass the ToneID
1607 new SignalInfoTonePlayer(toneID).start();
1608 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001609
1610 mCallModeler.onCdmaCallWaiting(infoCW);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001611 }
1612
1613 /**
1614 * Posts a event causing us to clean up after rejecting (or timing-out) a
1615 * CDMA call-waiting call.
1616 *
1617 * This method is safe to call from any thread.
1618 * @see #onCdmaCallWaitingReject()
1619 */
1620 /* package */ void sendCdmaCallWaitingReject() {
1621 sendEmptyMessage(CDMA_CALL_WAITING_REJECT);
1622 }
1623
1624 /**
1625 * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
1626 * and finally calls Hangup on the Call Waiting connection.
1627 *
1628 * This method should be called only from the UI thread.
1629 * @see #sendCdmaCallWaitingReject()
1630 */
1631 private void onCdmaCallWaitingReject() {
1632 final Call ringingCall = mCM.getFirstActiveRingingCall();
1633
1634 // Call waiting timeout scenario
1635 if (ringingCall.getState() == Call.State.WAITING) {
1636 // Code for perform Call logging and missed call notification
1637 Connection c = ringingCall.getLatestConnection();
1638
1639 if (c != null) {
1640 final int callLogType = mCallWaitingTimeOut ?
1641 Calls.MISSED_TYPE : Calls.INCOMING_TYPE;
1642
1643 // TODO: This callLogType override is not ideal. Connection should be astracted away
1644 // at a telephony-phone layer that can understand and edit the callTypes within
1645 // the abstraction for CDMA devices.
1646 mCallLogger.logCall(c, callLogType);
1647
1648 final long date = c.getCreateTime();
1649 if (callLogType == Calls.MISSED_TYPE) {
1650 // Add missed call notification
1651 showMissedCallNotification(c, date);
1652 } else {
1653 // Remove Call waiting 20 second display timer in the queue
1654 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1655 }
1656
1657 // Hangup the RingingCall connection for CW
1658 PhoneUtils.hangup(c);
1659 }
1660
1661 //Reset the mCallWaitingTimeOut boolean
1662 mCallWaitingTimeOut = false;
1663 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001664
1665 // Call modeler needs to know about this event regardless of the
1666 // state conditionals in the previous code.
1667 mCallModeler.onCdmaCallWaitingReject();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001668 }
1669
1670 /**
1671 * Return the private variable mPreviousCdmaCallState.
1672 */
1673 /* package */ Call.State getPreviousCdmaCallState() {
1674 return mPreviousCdmaCallState;
1675 }
1676
1677 /**
1678 * Return the private variable mVoicePrivacyState.
1679 */
1680 /* package */ boolean getVoicePrivacyState() {
1681 return mVoicePrivacyState;
1682 }
1683
1684 /**
1685 * Return the private variable mIsCdmaRedialCall.
1686 */
1687 /* package */ boolean getIsCdmaRedialCall() {
1688 return mIsCdmaRedialCall;
1689 }
1690
1691 /**
1692 * Helper function used to show a missed call notification.
1693 */
1694 private void showMissedCallNotification(Connection c, final long date) {
1695 PhoneUtils.CallerInfoToken info =
1696 PhoneUtils.startGetCallerInfo(mApplication, c, this, Long.valueOf(date));
1697 if (info != null) {
1698 // at this point, we've requested to start a query, but it makes no
1699 // sense to log this missed call until the query comes back.
1700 if (VDBG) log("showMissedCallNotification: Querying for CallerInfo on missed call...");
1701 if (info.isFinal) {
1702 // it seems that the query we have actually is up to date.
1703 // send the notification then.
1704 CallerInfo ci = info.currentInfo;
1705
1706 // Check number presentation value; if we have a non-allowed presentation,
1707 // then display an appropriate presentation string instead as the missed
1708 // call.
1709 String name = ci.name;
1710 String number = ci.phoneNumber;
1711 if (ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1712 name = mApplication.getString(R.string.private_num);
1713 } else if (ci.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1714 name = mApplication.getString(R.string.unknown);
1715 } else {
1716 number = PhoneUtils.modifyForSpecialCnapCases(mApplication,
1717 ci, number, ci.numberPresentation);
1718 }
Christine Chendaf4c1d2013-10-29 11:56:24 -07001719 mApplication.notificationMgr.notifyMissedCall(name, number, ci.numberPresentation,
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001720 ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon, date);
1721 }
1722 } else {
1723 // getCallerInfo() can return null in rare cases, like if we weren't
1724 // able to get a valid phone number out of the specified Connection.
1725 Log.w(LOG_TAG, "showMissedCallNotification: got null CallerInfo for Connection " + c);
1726 }
1727 }
1728
1729 /**
1730 * Inner class to handle emergency call tone and vibrator
1731 */
1732 private class EmergencyTonePlayerVibrator {
1733 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1734 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1735 private final long[] mVibratePattern =
1736 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1737
1738 private ToneGenerator mToneGenerator;
1739 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1740 // object will be isolated from others.
1741 private Vibrator mEmgVibrator = new SystemVibrator();
1742 private int mInCallVolume;
1743
1744 /**
1745 * constructor
1746 */
1747 public EmergencyTonePlayerVibrator() {
1748 }
1749
1750 /**
1751 * Start the emergency tone or vibrator.
1752 */
1753 private void start() {
1754 if (VDBG) log("call startEmergencyToneOrVibrate.");
1755 int ringerMode = mAudioManager.getRingerMode();
1756
1757 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1758 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1759 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1760 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1761 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1762 if (mToneGenerator != null) {
1763 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1764 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1765 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1766 0);
1767 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1768 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1769 }
1770 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1771 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1772 if (mEmgVibrator != null) {
1773 mEmgVibrator.vibrate(mVibratePattern, 0);
1774 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1775 }
1776 }
1777 }
1778
1779 /**
1780 * If the emergency tone is active, stop the tone or vibrator accordingly.
1781 */
1782 private void stop() {
1783 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1784
1785 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1786 && (mToneGenerator != null)) {
1787 mToneGenerator.stopTone();
1788 mToneGenerator.release();
1789 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1790 mInCallVolume,
1791 0);
1792 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1793 && (mEmgVibrator != null)) {
1794 mEmgVibrator.cancel();
1795 }
1796 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1797 }
1798 }
1799
1800 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1801 new BluetoothProfile.ServiceListener() {
1802 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1803 mBluetoothHeadset = (BluetoothHeadset) proxy;
1804 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1805 }
1806
1807 public void onServiceDisconnected(int profile) {
1808 mBluetoothHeadset = null;
1809 }
1810 };
1811
1812 private void onRingbackTone(AsyncResult r) {
1813 boolean playTone = (Boolean)(r.result);
1814
1815 if (playTone == true) {
1816 // Only play when foreground call is in DIALING or ALERTING.
1817 // to prevent a late coming playtone after ALERTING.
1818 // Don't play ringback tone if it is in play, otherwise it will cut
1819 // the current tone and replay it
1820 if (mCM.getActiveFgCallState().isDialing() &&
1821 mInCallRingbackTonePlayer == null) {
1822 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1823 mInCallRingbackTonePlayer.start();
1824 }
1825 } else {
1826 if (mInCallRingbackTonePlayer != null) {
1827 mInCallRingbackTonePlayer.stopTone();
1828 mInCallRingbackTonePlayer = null;
1829 }
1830 }
1831 }
1832
1833 /**
1834 * Toggle mute and unmute requests while keeping the same mute state
1835 */
1836 private void onResendMute() {
1837 boolean muteState = PhoneUtils.getMute();
1838 PhoneUtils.setMute(!muteState);
1839 PhoneUtils.setMute(muteState);
1840 }
1841
1842 private void log(String msg) {
1843 Log.d(LOG_TAG, msg);
1844 }
1845}