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