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