blob: 300329092fc6c1ceb52f6f5041fb99f909a97659 [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
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700661 // If the ringing call still does not have any connection anymore, do not send the
662 // notification to the CallModeler.
663 final Call ringingCall = mCM.getFirstActiveRingingCall();
664
665 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
Christine Chen3ae08d42013-09-18 15:15:55 -0700666 // Ring, either with the queried ringtone or default one.
667 if (VDBG) log("RINGING... (onCustomRingQueryComplete)");
668 mRinger.ring();
669
670 // ...and display the incoming call to the user:
671 if (DBG) log("- showing incoming call (custom ring query complete)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700672 notifyCallModelerOfNewRingingCall(c);
673 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700674 }
675
676 private void onUnknownConnectionAppeared(AsyncResult r) {
677 PhoneConstants.State state = mCM.getState();
678
679 if (state == PhoneConstants.State.OFFHOOK) {
680 // basically do onPhoneStateChanged + display the incoming call UI
681 onPhoneStateChanged(r);
682 if (DBG) log("- showing incoming call (unknown connection appeared)...");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700683 final Connection c = (Connection) r.result;
684 notifyCallModelerOfNewRingingCall(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700685 }
686 }
687
688 /**
689 * Informs the user about a new incoming call.
690 *
691 * In most cases this means "bring up the full-screen incoming call
692 * UI". However, if an immersive activity is running, the system
693 * NotificationManager will instead pop up a small notification window
694 * on top of the activity.
695 *
696 * Watch out: be sure to call this method only once per incoming call,
697 * or otherwise we may end up launching the InCallScreen multiple
698 * times (which can lead to slow responsiveness and/or visible
699 * glitches.)
700 *
701 * Note this method handles only the onscreen UI for incoming calls;
702 * the ringer and/or vibrator are started separately (see the various
703 * calls to Ringer.ring() in this class.)
704 *
705 * @see NotificationMgr#updateNotificationAndLaunchIncomingCallUi()
706 */
707 private void showIncomingCall() {
708 log("showIncomingCall()... phone state = " + mCM.getState());
709
710 // Before bringing up the "incoming call" UI, force any system
711 // dialogs (like "recent tasks" or the power dialog) to close first.
712 try {
713 ActivityManagerNative.getDefault().closeSystemDialogs("call");
714 } catch (RemoteException e) {
715 }
716
717 // Go directly to the in-call screen.
718 // (No need to do anything special if we're already on the in-call
719 // screen; it'll notice the phone state change and update itself.)
720 mApplication.requestWakeState(PhoneGlobals.WakeState.FULL);
721
722 // Post the "incoming call" notification *and* include the
723 // fullScreenIntent that'll launch the incoming-call UI.
724 // (This will usually take us straight to the incoming call
725 // screen, but if an immersive activity is running it'll just
726 // appear as a notification.)
727 if (DBG) log("- updating notification from showIncomingCall()...");
728 mApplication.notificationMgr.updateNotificationAndLaunchIncomingCallUi();
729 }
730
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700731 private void notifyCallModelerOfNewRingingCall(Connection c) {
732 mCallModeler.onNewRingingConnection(c);
733 }
734
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700735 /**
736 * Updates the phone UI in response to phone state changes.
737 *
738 * Watch out: certain state changes are actually handled by their own
739 * specific methods:
740 * - see onNewRingingConnection() for new incoming calls
741 * - see onDisconnect() for calls being hung up or disconnected
742 */
743 private void onPhoneStateChanged(AsyncResult r) {
744 PhoneConstants.State state = mCM.getState();
745 if (VDBG) log("onPhoneStateChanged: state = " + state);
746
747 // Turn status bar notifications on or off depending upon the state
748 // of the phone. Notification Alerts (audible or vibrating) should
749 // be on if and only if the phone is IDLE.
750 mApplication.notificationMgr.statusBarHelper
751 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
752
753 Phone fgPhone = mCM.getFgPhone();
754 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
755 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
756 && ((mPreviousCdmaCallState == Call.State.DIALING)
757 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
758 if (mIsCdmaRedialCall) {
759 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
760 new InCallTonePlayer(toneToPlay).start();
761 }
762 // Stop any signal info tone when call moves to ACTIVE state
763 stopSignalInfoTone();
764 }
765 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
766 }
767
768 // Have the PhoneApp recompute its mShowBluetoothIndication
769 // flag based on the (new) telephony state.
770 // There's no need to force a UI update since we update the
771 // in-call notification ourselves (below), and the InCallScreen
772 // listens for phone state changes itself.
Christine Chen91db67d2013-09-18 12:01:11 -0700773 // TODO: Have BluetoothManager listen to CallModeler instead of relying on
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700774 // CallNotifier
775 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700776
777
778 // Update the phone state and other sensor/lock.
779 mApplication.updatePhoneState(state);
780
781 if (state == PhoneConstants.State.OFFHOOK) {
782 // stop call waiting tone if needed when answering
783 if (mCallWaitingTonePlayer != null) {
784 mCallWaitingTonePlayer.stopTone();
785 mCallWaitingTonePlayer = null;
786 }
787
788 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
789 // make sure audio is in in-call mode now
790 PhoneUtils.setAudioMode(mCM);
791
792 // if the call screen is showing, let it handle the event,
793 // otherwise handle it here.
794 if (!mApplication.isShowingCallScreen()) {
795 mApplication.requestWakeState(PhoneGlobals.WakeState.SLEEP);
796 }
797
798 // Since we're now in-call, the Ringer should definitely *not*
799 // be ringing any more. (This is just a sanity-check; we
800 // already stopped the ringer explicitly back in
801 // PhoneUtils.answerCall(), before the call to phone.acceptCall().)
802 // TODO: Confirm that this call really *is* unnecessary, and if so,
803 // remove it!
804 if (DBG) log("stopRing()... (OFFHOOK state)");
805 mRinger.stopRing();
806
807 // Post a request to update the "in-call" status bar icon.
808 //
809 // We don't call NotificationMgr.updateInCallNotification()
810 // directly here, for two reasons:
811 // (1) a single phone state change might actually trigger multiple
812 // onPhoneStateChanged() callbacks, so this prevents redundant
813 // updates of the notification.
814 // (2) we suppress the status bar icon while the in-call UI is
815 // visible (see updateInCallNotification()). But when launching
816 // an outgoing call the phone actually goes OFFHOOK slightly
817 // *before* the InCallScreen comes up, so the delay here avoids a
818 // brief flicker of the icon at that point.
819
820 if (DBG) log("- posting UPDATE_IN_CALL_NOTIFICATION request...");
821 // Remove any previous requests in the queue
822 removeMessages(UPDATE_IN_CALL_NOTIFICATION);
823 final int IN_CALL_NOTIFICATION_UPDATE_DELAY = 1000; // msec
824 sendEmptyMessageDelayed(UPDATE_IN_CALL_NOTIFICATION,
825 IN_CALL_NOTIFICATION_UPDATE_DELAY);
826 }
827
828 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
829 Connection c = fgPhone.getForegroundCall().getLatestConnection();
830 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
831 mApplication))) {
832 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
833 Call.State callState = fgPhone.getForegroundCall().getState();
834 if (mEmergencyTonePlayerVibrator == null) {
835 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
836 }
837
838 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
839 mIsEmergencyToneOn = Settings.Global.getInt(
840 mApplication.getContentResolver(),
841 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
842 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
843 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
844 if (mEmergencyTonePlayerVibrator != null) {
845 mEmergencyTonePlayerVibrator.start();
846 }
847 }
848 } else if (callState == Call.State.ACTIVE) {
849 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
850 if (mEmergencyTonePlayerVibrator != null) {
851 mEmergencyTonePlayerVibrator.stop();
852 }
853 }
854 }
855 }
856 }
857
858 if ((fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM)
859 || (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP)) {
860 Call.State callState = mCM.getActiveFgCallState();
861 if (!callState.isDialing()) {
862 // If call get activated or disconnected before the ringback
863 // tone stops, we have to stop it to prevent disturbing.
864 if (mInCallRingbackTonePlayer != null) {
865 mInCallRingbackTonePlayer.stopTone();
866 mInCallRingbackTonePlayer = null;
867 }
868 }
869 }
870 }
871
872 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
873 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
874
875 // Clear ringback tone player
876 mInCallRingbackTonePlayer = null;
877
878 // Clear call waiting tone player
879 mCallWaitingTonePlayer = null;
880
881 // Instantiate mSignalInfoToneGenerator
882 createSignalInfoToneGenerator();
883 }
884
885 /**
886 * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
887 * refreshes the CallCard data when it called. If called with this
888 * class itself, it is assumed that we have been waiting for the ringtone
889 * and direct to voicemail settings to update.
890 */
891 @Override
892 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
893 if (cookie instanceof Long) {
894 if (VDBG) log("CallerInfo query complete, posting missed call notification");
895
896 mApplication.notificationMgr.notifyMissedCall(ci.name, ci.phoneNumber,
897 ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon,
898 ((Long) cookie).longValue());
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700899 } else if (cookie instanceof Connection) {
900 final Connection c = (Connection) cookie;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700901 if (VDBG) log("CallerInfo query complete (for CallNotifier), "
902 + "updating state for incoming call..");
903
904 // get rid of the timeout messages
905 removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT);
906
907 boolean isQueryExecutionTimeOK = false;
908 synchronized (mCallerInfoQueryStateGuard) {
909 if (mCallerInfoQueryState == CALLERINFO_QUERYING) {
910 mCallerInfoQueryState = CALLERINFO_QUERY_READY;
911 isQueryExecutionTimeOK = true;
912 }
913 }
914 //if we're in the right state
915 if (isQueryExecutionTimeOK) {
916
917 // send directly to voicemail.
918 if (ci.shouldSendToVoicemail) {
919 if (DBG) log("send to voicemail flag detected. hanging up.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700920 final Call ringingCall = mCM.getFirstActiveRingingCall();
921 if (ringingCall != null && ringingCall.getLatestConnection() == c) {
922 PhoneUtils.hangupRingingCall(ringingCall);
923 return;
924 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700925 }
926
927 // set the ringtone uri to prepare for the ring.
928 if (ci.contactRingtoneUri != null) {
929 if (DBG) log("custom ringtone found, setting up ringer.");
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700930 Ringer r = mRinger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700931 r.setCustomRingtoneUri(ci.contactRingtoneUri);
932 }
933 // ring, and other post-ring actions.
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700934 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700935 }
936 }
937 }
938
939 /**
940 * Called when asynchronous CallerInfo query is taking too long (more than
941 * {@link #RINGTONE_QUERY_WAIT_TIME} msec), but we cannot wait any more.
942 *
943 * This looks up in-memory fallback cache and use it when available. If not, it just calls
944 * {@link #onCustomRingQueryComplete()} with default ringtone ("Send to voicemail" flag will
945 * be just ignored).
946 *
947 * @param number The phone number used for the async query. This method will take care of
948 * formatting or normalization of the number.
949 */
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700950 private void onCustomRingtoneQueryTimeout(Connection c) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700951 // First of all, this case itself should be rare enough, though we cannot avoid it in
952 // some situations (e.g. IPC is slow due to system overload, database is in sync, etc.)
953 Log.w(LOG_TAG, "CallerInfo query took too long; look up local fallback cache.");
954
955 // This method is intentionally verbose for now to detect possible bad side-effect for it.
956 // TODO: Remove the verbose log when it looks stable and reliable enough.
957
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700958
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700959 if (c != null) {
960 final CallerInfoCache.CacheEntry entry =
961 mApplication.callerInfoCache.getCacheEntry(c.getAddress());
962 if (entry != null) {
963 if (entry.sendToVoicemail) {
964 log("send to voicemail flag detected (in fallback cache). hanging up.");
965 if (mCM.getFirstActiveRingingCall().getLatestConnection() == c) {
966 PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall());
967 return;
968 }
969 }
970
971 if (entry.customRingtone != null) {
972 log("custom ringtone found (in fallback cache), setting up ringer: "
973 + entry.customRingtone);
974 this.mRinger.setCustomRingtoneUri(Uri.parse(entry.customRingtone));
975 }
976 } else {
977 // In this case we call onCustomRingQueryComplete(), just
978 // like if the query had completed normally. (But we're
979 // going to get the default ringtone, since we never got
980 // the chance to call Ringer.setCustomRingtoneUri()).
981 log("Failed to find fallback cache. Use default ringer tone.");
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700982 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700983 }
984
Christine Chenfb0cc2b2013-09-16 14:21:29 -0700985 onCustomRingQueryComplete(c);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700986 }
987
988 private void onDisconnect(AsyncResult r) {
989 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
990
991 mVoicePrivacyState = false;
992 Connection c = (Connection) r.result;
993 if (c != null) {
994 log("onDisconnect: cause = " + c.getDisconnectCause()
995 + ", incoming = " + c.isIncoming()
996 + ", date = " + c.getCreateTime());
997 } else {
998 Log.w(LOG_TAG, "onDisconnect: null connection");
999 }
1000
1001 int autoretrySetting = 0;
1002 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
1003 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
1004 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
1005 }
1006
1007 // Stop any signalInfo tone being played when a call gets ended
1008 stopSignalInfoTone();
1009
1010 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
1011 // Resetting the CdmaPhoneCallState members
1012 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
1013
1014 // Remove Call waiting timers
1015 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1016 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1017 }
1018
1019 // Stop the ringer if it was ringing (for an incoming call that
1020 // either disconnected by itself, or was rejected by the user.)
1021 //
1022 // TODO: We technically *shouldn't* stop the ringer if the
1023 // foreground or background call disconnects while an incoming call
1024 // is still ringing, but that's a really rare corner case.
1025 // It's safest to just unconditionally stop the ringer here.
1026
1027 // CDMA: For Call collision cases i.e. when the user makes an out going call
1028 // and at the same time receives an Incoming Call, the Incoming Call is given
1029 // higher preference. At this time framework sends a disconnect for the Out going
1030 // call connection hence we should *not* be stopping the ringer being played for
1031 // the Incoming Call
1032 Call ringingCall = mCM.getFirstActiveRingingCall();
1033 if (ringingCall.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1034 if (PhoneUtils.isRealIncomingCall(ringingCall.getState())) {
1035 // Also we need to take off the "In Call" icon from the Notification
1036 // area as the Out going Call never got connected
1037 if (DBG) log("cancelCallInProgressNotifications()... (onDisconnect)");
1038 mApplication.notificationMgr.cancelCallInProgressNotifications();
1039 } else {
1040 if (DBG) log("stopRing()... (onDisconnect)");
1041 mRinger.stopRing();
1042 }
1043 } else { // GSM
1044 if (DBG) log("stopRing()... (onDisconnect)");
1045 mRinger.stopRing();
1046 }
1047
1048 // stop call waiting tone if needed when disconnecting
1049 if (mCallWaitingTonePlayer != null) {
1050 mCallWaitingTonePlayer.stopTone();
1051 mCallWaitingTonePlayer = null;
1052 }
1053
1054 // If this is the end of an OTASP call, pass it on to the PhoneApp.
1055 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
1056 final String number = c.getAddress();
1057 if (c.getCall().getPhone().isOtaSpNumber(number)) {
1058 if (DBG) log("onDisconnect: this was an OTASP call!");
1059 mApplication.handleOtaspDisconnect();
1060 }
1061 }
1062
1063 // Check for the various tones we might need to play (thru the
1064 // earpiece) after a call disconnects.
1065 int toneToPlay = InCallTonePlayer.TONE_NONE;
1066
1067 // The "Busy" or "Congestion" tone is the highest priority:
1068 if (c != null) {
1069 Connection.DisconnectCause cause = c.getDisconnectCause();
1070 if (cause == Connection.DisconnectCause.BUSY) {
1071 if (DBG) log("- need to play BUSY tone!");
1072 toneToPlay = InCallTonePlayer.TONE_BUSY;
1073 } else if (cause == Connection.DisconnectCause.CONGESTION) {
1074 if (DBG) log("- need to play CONGESTION tone!");
1075 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
1076 } else if (((cause == Connection.DisconnectCause.NORMAL)
1077 || (cause == Connection.DisconnectCause.LOCAL))
1078 && (mApplication.isOtaCallInActiveState())) {
1079 if (DBG) log("- need to play OTA_CALL_END tone!");
1080 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
1081 } else if (cause == Connection.DisconnectCause.CDMA_REORDER) {
1082 if (DBG) log("- need to play CDMA_REORDER tone!");
1083 toneToPlay = InCallTonePlayer.TONE_REORDER;
1084 } else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) {
1085 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
1086 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
1087 } else if (cause == Connection.DisconnectCause.CDMA_DROP) {
1088 if (DBG) log("- need to play CDMA_DROP tone!");
1089 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
1090 } else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) {
1091 if (DBG) log("- need to play OUT OF SERVICE tone!");
1092 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
1093 } else if (cause == Connection.DisconnectCause.UNOBTAINABLE_NUMBER) {
1094 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
1095 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
1096 } else if (cause == Connection.DisconnectCause.ERROR_UNSPECIFIED) {
1097 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
1098 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1099 }
1100 }
1101
1102 // If we don't need to play BUSY or CONGESTION, then play the
1103 // "call ended" tone if this was a "regular disconnect" (i.e. a
1104 // normal call where one end or the other hung up) *and* this
1105 // disconnect event caused the phone to become idle. (In other
1106 // words, we *don't* play the sound if one call hangs up but
1107 // there's still an active call on the other line.)
1108 // TODO: We may eventually want to disable this via a preference.
1109 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
1110 && (mCM.getState() == PhoneConstants.State.IDLE)
1111 && (c != null)) {
1112 Connection.DisconnectCause cause = c.getDisconnectCause();
1113 if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup
1114 || (cause == Connection.DisconnectCause.LOCAL)) { // local hangup
1115 if (VDBG) log("- need to play CALL_ENDED tone!");
1116 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
1117 mIsCdmaRedialCall = false;
1118 }
1119 }
1120
1121 // All phone calls are disconnected.
1122 if (mCM.getState() == PhoneConstants.State.IDLE) {
1123 // Don't reset the audio mode or bluetooth/speakerphone state
1124 // if we still need to let the user hear a tone through the earpiece.
1125 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
1126 resetAudioStateAfterDisconnect();
1127 }
1128
1129 mApplication.notificationMgr.cancelCallInProgressNotifications();
1130 }
1131
1132 if (c != null) {
1133 mCallLogger.logCall(c);
1134
1135 final String number = c.getAddress();
1136 final Phone phone = c.getCall().getPhone();
1137 final boolean isEmergencyNumber =
1138 PhoneNumberUtils.isLocalEmergencyNumber(number, mApplication);
1139
1140 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
1141 if ((isEmergencyNumber)
1142 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
1143 if (mEmergencyTonePlayerVibrator != null) {
1144 mEmergencyTonePlayerVibrator.stop();
1145 }
1146 }
1147 }
1148
1149 final long date = c.getCreateTime();
1150 final Connection.DisconnectCause cause = c.getDisconnectCause();
1151 final boolean missedCall = c.isIncoming() &&
1152 (cause == Connection.DisconnectCause.INCOMING_MISSED);
1153 if (missedCall) {
1154 // Show the "Missed call" notification.
1155 // (Note we *don't* do this if this was an incoming call that
1156 // the user deliberately rejected.)
1157 showMissedCallNotification(c, date);
1158 }
1159
1160 // Possibly play a "post-disconnect tone" thru the earpiece.
1161 // We do this here, rather than from the InCallScreen
1162 // activity, since we need to do this even if you're not in
1163 // the Phone UI at the moment the connection ends.
1164 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
1165 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
1166 new InCallTonePlayer(toneToPlay).start();
1167
1168 // TODO: alternatively, we could start an InCallTonePlayer
1169 // here with an "unlimited" tone length,
1170 // and manually stop it later when this connection truly goes
1171 // away. (The real connection over the network was closed as soon
1172 // as we got the BUSY message. But our telephony layer keeps the
1173 // connection open for a few extra seconds so we can show the
1174 // "busy" indication to the user. We could stop the busy tone
1175 // when *that* connection's "disconnect" event comes in.)
1176 }
1177
1178 if (((mPreviousCdmaCallState == Call.State.DIALING)
1179 || (mPreviousCdmaCallState == Call.State.ALERTING))
1180 && (!isEmergencyNumber)
1181 && (cause != Connection.DisconnectCause.INCOMING_MISSED )
1182 && (cause != Connection.DisconnectCause.NORMAL)
1183 && (cause != Connection.DisconnectCause.LOCAL)
1184 && (cause != Connection.DisconnectCause.INCOMING_REJECTED)) {
1185 if (!mIsCdmaRedialCall) {
1186 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
1187 // TODO: (Moto): The contact reference data may need to be stored and use
1188 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordon69a69192013-08-22 14:25:42 -07001189 PhoneUtils.placeCall(mApplication, phone, number, null, false);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001190 mIsCdmaRedialCall = true;
1191 } else {
1192 mIsCdmaRedialCall = false;
1193 }
1194 } else {
1195 mIsCdmaRedialCall = false;
1196 }
1197 }
1198 }
1199 }
1200
1201 /**
1202 * Resets the audio mode and speaker state when a call ends.
1203 */
1204 private void resetAudioStateAfterDisconnect() {
1205 if (VDBG) log("resetAudioStateAfterDisconnect()...");
1206
1207 if (mBluetoothHeadset != null) {
1208 mBluetoothHeadset.disconnectAudio();
1209 }
1210
1211 // call turnOnSpeaker() with state=false and store=true even if speaker
1212 // is already off to reset user requested speaker state.
1213 PhoneUtils.turnOnSpeaker(mApplication, false, true);
1214
1215 PhoneUtils.setAudioMode(mCM);
1216 }
1217
1218 private void onMwiChanged(boolean visible) {
1219 if (VDBG) log("onMwiChanged(): " + visible);
1220
1221 // "Voicemail" is meaningless on non-voice-capable devices,
1222 // so ignore MWI events.
1223 if (!PhoneGlobals.sVoiceCapable) {
1224 // ...but still log a warning, since we shouldn't have gotten this
1225 // event in the first place!
1226 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
1227 // *should* be blocked at the telephony layer on non-voice-capable
1228 // capable devices.)
1229 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
1230 return;
1231 }
1232
1233 mApplication.notificationMgr.updateMwi(visible);
1234 }
1235
1236 /**
1237 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
1238 * failed NotificationMgr.updateMwi() call.
1239 */
1240 /* package */ void sendMwiChangedDelayed(long delayMillis) {
1241 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
1242 sendMessageDelayed(message, delayMillis);
1243 }
1244
1245 private void onCfiChanged(boolean visible) {
1246 if (VDBG) log("onCfiChanged(): " + visible);
1247 mApplication.notificationMgr.updateCfi(visible);
1248 }
1249
1250 /**
1251 * Indicates whether or not this ringer is ringing.
1252 */
1253 boolean isRinging() {
1254 return mRinger.isRinging();
1255 }
1256
1257 /**
1258 * Stops the current ring, and tells the notifier that future
1259 * ring requests should be ignored.
1260 */
1261 void silenceRinger() {
1262 mSilentRingerRequested = true;
1263 if (DBG) log("stopRing()... (silenceRinger)");
1264 mRinger.stopRing();
1265 }
1266
1267 /**
1268 * Restarts the ringer after having previously silenced it.
1269 *
1270 * (This is a no-op if the ringer is actually still ringing, or if the
1271 * incoming ringing call no longer exists.)
1272 */
1273 /* package */ void restartRinger() {
1274 if (DBG) log("restartRinger()...");
1275 // Already ringing or Silent requested; no need to restart.
1276 if (isRinging() || mSilentRingerRequested) return;
1277
1278 final Call ringingCall = mCM.getFirstActiveRingingCall();
1279 // Don't check ringingCall.isRinging() here, since that'll be true
1280 // for the WAITING state also. We only allow the ringer for
1281 // regular INCOMING calls.
1282 if (DBG) log("- ringingCall state: " + ringingCall.getState());
1283 if (ringingCall.getState() == Call.State.INCOMING) {
1284 mRinger.ring();
1285 }
1286 }
1287
1288 /**
1289 * Helper class to play tones through the earpiece (or speaker / BT)
1290 * during a call, using the ToneGenerator.
1291 *
1292 * To use, just instantiate a new InCallTonePlayer
1293 * (passing in the TONE_* constant for the tone you want)
1294 * and start() it.
1295 *
1296 * When we're done playing the tone, if the phone is idle at that
1297 * point, we'll reset the audio routing and speaker state.
1298 * (That means that for tones that get played *after* a call
1299 * disconnects, like "busy" or "congestion" or "call ended", you
1300 * should NOT call resetAudioStateAfterDisconnect() yourself.
1301 * Instead, just start the InCallTonePlayer, which will automatically
1302 * defer the resetAudioStateAfterDisconnect() call until the tone
1303 * finishes playing.)
1304 */
1305 private class InCallTonePlayer extends Thread {
1306 private int mToneId;
1307 private int mState;
1308 // The possible tones we can play.
1309 public static final int TONE_NONE = 0;
1310 public static final int TONE_CALL_WAITING = 1;
1311 public static final int TONE_BUSY = 2;
1312 public static final int TONE_CONGESTION = 3;
1313 public static final int TONE_CALL_ENDED = 4;
1314 public static final int TONE_VOICE_PRIVACY = 5;
1315 public static final int TONE_REORDER = 6;
1316 public static final int TONE_INTERCEPT = 7;
1317 public static final int TONE_CDMA_DROP = 8;
1318 public static final int TONE_OUT_OF_SERVICE = 9;
1319 public static final int TONE_REDIAL = 10;
1320 public static final int TONE_OTA_CALL_END = 11;
1321 public static final int TONE_RING_BACK = 12;
1322 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
1323
1324 // The tone volume relative to other sounds in the stream
1325 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
1326 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
1327 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
1328
1329 // Buffer time (in msec) to add on to tone timeout value.
1330 // Needed mainly when the timeout value for a tone is the
1331 // exact duration of the tone itself.
1332 static final int TONE_TIMEOUT_BUFFER = 20;
1333
1334 // The tone state
1335 static final int TONE_OFF = 0;
1336 static final int TONE_ON = 1;
1337 static final int TONE_STOPPED = 2;
1338
1339 InCallTonePlayer(int toneId) {
1340 super();
1341 mToneId = toneId;
1342 mState = TONE_OFF;
1343 }
1344
1345 @Override
1346 public void run() {
1347 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
1348
1349 int toneType = 0; // passed to ToneGenerator.startTone()
1350 int toneVolume; // passed to the ToneGenerator constructor
1351 int toneLengthMillis;
1352 int phoneType = mCM.getFgPhone().getPhoneType();
1353
1354 switch (mToneId) {
1355 case TONE_CALL_WAITING:
1356 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
1357 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1358 // Call waiting tone is stopped by stopTone() method
1359 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1360 break;
1361 case TONE_BUSY:
1362 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1363 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
1364 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1365 toneLengthMillis = 1000;
1366 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
1367 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
1368 toneType = ToneGenerator.TONE_SUP_BUSY;
1369 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1370 toneLengthMillis = 4000;
1371 } else {
1372 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1373 }
1374 break;
1375 case TONE_CONGESTION:
1376 toneType = ToneGenerator.TONE_SUP_CONGESTION;
1377 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1378 toneLengthMillis = 4000;
1379 break;
1380
1381 case TONE_CALL_ENDED:
1382 toneType = ToneGenerator.TONE_PROP_PROMPT;
1383 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1384 toneLengthMillis = 200;
1385 break;
1386 case TONE_OTA_CALL_END:
1387 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
1388 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
1389 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
1390 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1391 toneLengthMillis = 750;
1392 } else {
1393 toneType = ToneGenerator.TONE_PROP_PROMPT;
1394 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1395 toneLengthMillis = 200;
1396 }
1397 break;
1398 case TONE_VOICE_PRIVACY:
1399 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
1400 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1401 toneLengthMillis = 5000;
1402 break;
1403 case TONE_REORDER:
1404 toneType = ToneGenerator.TONE_CDMA_REORDER;
1405 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1406 toneLengthMillis = 4000;
1407 break;
1408 case TONE_INTERCEPT:
1409 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
1410 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1411 toneLengthMillis = 500;
1412 break;
1413 case TONE_CDMA_DROP:
1414 case TONE_OUT_OF_SERVICE:
1415 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
1416 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1417 toneLengthMillis = 375;
1418 break;
1419 case TONE_REDIAL:
1420 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
1421 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
1422 toneLengthMillis = 5000;
1423 break;
1424 case TONE_RING_BACK:
1425 toneType = ToneGenerator.TONE_SUP_RINGTONE;
1426 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1427 // Call ring back tone is stopped by stopTone() method
1428 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
1429 break;
1430 case TONE_UNOBTAINABLE_NUMBER:
1431 toneType = ToneGenerator.TONE_SUP_ERROR;
1432 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
1433 toneLengthMillis = 4000;
1434 break;
1435 default:
1436 throw new IllegalArgumentException("Bad toneId: " + mToneId);
1437 }
1438
1439 // If the mToneGenerator creation fails, just continue without it. It is
1440 // a local audio signal, and is not as important.
1441 ToneGenerator toneGenerator;
1442 try {
1443 int stream;
1444 if (mBluetoothHeadset != null) {
1445 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
1446 AudioManager.STREAM_VOICE_CALL;
1447 } else {
1448 stream = AudioManager.STREAM_VOICE_CALL;
1449 }
1450 toneGenerator = new ToneGenerator(stream, toneVolume);
1451 // if (DBG) log("- created toneGenerator: " + toneGenerator);
1452 } catch (RuntimeException e) {
1453 Log.w(LOG_TAG,
1454 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
1455 toneGenerator = null;
1456 }
1457
1458 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
1459 // CONGESTION tones at least), the ToneGenerator itself knows
1460 // the right pattern of tones to play; we do NOT need to
1461 // manually start/stop each individual tone, or manually
1462 // insert the correct delay between tones. (We just start it
1463 // and let it run for however long we want the tone pattern to
1464 // continue.)
1465 //
1466 // TODO: When we stop the ToneGenerator in the middle of a
1467 // "tone pattern", it sounds bad if we cut if off while the
1468 // tone is actually playing. Consider adding API to the
1469 // ToneGenerator to say "stop at the next silent part of the
1470 // pattern", or simply "play the pattern N times and then
1471 // stop."
1472 boolean needToStopTone = true;
1473 boolean okToPlayTone = false;
1474
1475 if (toneGenerator != null) {
1476 int ringerMode = mAudioManager.getRingerMode();
1477 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1478 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
1479 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1480 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1481 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
1482 okToPlayTone = true;
1483 needToStopTone = false;
1484 }
1485 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
1486 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
1487 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
1488 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
1489 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
1490 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
1491 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
1492 okToPlayTone = true;
1493 needToStopTone = false;
1494 }
1495 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
1496 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
1497 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
1498 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
1499 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
1500 okToPlayTone = true;
1501 needToStopTone = false;
1502 }
1503 } else { // For the rest of the tones, always OK to play.
1504 okToPlayTone = true;
1505 }
1506 } else { // Not "CDMA"
1507 okToPlayTone = true;
1508 }
1509
1510 synchronized (this) {
1511 if (okToPlayTone && mState != TONE_STOPPED) {
1512 mState = TONE_ON;
1513 toneGenerator.startTone(toneType);
1514 try {
1515 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
1516 } catch (InterruptedException e) {
1517 Log.w(LOG_TAG,
1518 "InCallTonePlayer stopped: " + e);
1519 }
1520 if (needToStopTone) {
1521 toneGenerator.stopTone();
1522 }
1523 }
1524 // if (DBG) log("- InCallTonePlayer: done playing.");
1525 toneGenerator.release();
1526 mState = TONE_OFF;
1527 }
1528 }
1529
1530 // Finally, do the same cleanup we otherwise would have done
1531 // in onDisconnect().
1532 //
1533 // (But watch out: do NOT do this if the phone is in use,
1534 // since some of our tones get played *during* a call (like
1535 // CALL_WAITING) and we definitely *don't*
1536 // want to reset the audio mode / speaker / bluetooth after
1537 // playing those!
1538 // This call is really here for use with tones that get played
1539 // *after* a call disconnects, like "busy" or "congestion" or
1540 // "call ended", where the phone has already become idle but
1541 // we need to defer the resetAudioStateAfterDisconnect() call
1542 // till the tone finishes playing.)
1543 if (mCM.getState() == PhoneConstants.State.IDLE) {
1544 resetAudioStateAfterDisconnect();
1545 }
1546 }
1547
1548 public void stopTone() {
1549 synchronized (this) {
1550 if (mState == TONE_ON) {
1551 notify();
1552 }
1553 mState = TONE_STOPPED;
1554 }
1555 }
1556 }
1557
1558 /**
1559 * Displays a notification when the phone receives a DisplayInfo record.
1560 */
1561 private void onDisplayInfo(AsyncResult r) {
1562 // Extract the DisplayInfo String from the message
1563 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1564
1565 if (displayInfoRec != null) {
1566 String displayInfo = displayInfoRec.alpha;
1567 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1568 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1569
1570 // start a 2 second timer
1571 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1572 DISPLAYINFO_NOTIFICATION_TIME);
1573 }
1574 }
1575
1576 /**
1577 * Helper class to play SignalInfo tones using the ToneGenerator.
1578 *
1579 * To use, just instantiate a new SignalInfoTonePlayer
1580 * (passing in the ToneID constant for the tone you want)
1581 * and start() it.
1582 */
1583 private class SignalInfoTonePlayer extends Thread {
1584 private int mToneId;
1585
1586 SignalInfoTonePlayer(int toneId) {
1587 super();
1588 mToneId = toneId;
1589 }
1590
1591 @Override
1592 public void run() {
1593 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1594
1595 if (mSignalInfoToneGenerator != null) {
1596 //First stop any ongoing SignalInfo tone
1597 mSignalInfoToneGenerator.stopTone();
1598
1599 //Start playing the new tone if its a valid tone
1600 mSignalInfoToneGenerator.startTone(mToneId);
1601 }
1602 }
1603 }
1604
1605 /**
1606 * Plays a tone when the phone receives a SignalInfo record.
1607 */
1608 private void onSignalInfo(AsyncResult r) {
1609 // Signal Info are totally ignored on non-voice-capable devices.
1610 if (!PhoneGlobals.sVoiceCapable) {
1611 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1612 return;
1613 }
1614
1615 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1616 // Do not start any new SignalInfo tone when Call state is INCOMING
1617 // and stop any previous SignalInfo tone which is being played
1618 stopSignalInfoTone();
1619 } else {
1620 // Extract the SignalInfo String from the message
1621 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1622 // Only proceed if a Signal info is present.
1623 if (signalInfoRec != null) {
1624 boolean isPresent = signalInfoRec.isPresent;
1625 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1626 if (isPresent) {// if tone is valid
1627 int uSignalType = signalInfoRec.signalType;
1628 int uAlertPitch = signalInfoRec.alertPitch;
1629 int uSignal = signalInfoRec.signal;
1630
1631 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1632 uAlertPitch + ", uSignal=" + uSignal);
1633 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1634 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1635 (uSignalType, uAlertPitch, uSignal);
1636
1637 //Create the SignalInfo tone player and pass the ToneID
1638 new SignalInfoTonePlayer(toneID).start();
1639 }
1640 }
1641 }
1642 }
1643
1644 /**
1645 * Stops a SignalInfo tone in the following condition
1646 * 1 - On receiving a New Ringing Call
1647 * 2 - On disconnecting a call
1648 * 3 - On answering a Call Waiting Call
1649 */
1650 /* package */ void stopSignalInfoTone() {
1651 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1652 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1653 }
1654
1655 /**
1656 * Plays a Call waiting tone if it is present in the second incoming call.
1657 */
1658 private void onCdmaCallWaiting(AsyncResult r) {
1659 // Remove any previous Call waiting timers in the queue
1660 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1661 removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT);
1662
1663 // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection
1664 // else we would not have received Call waiting
1665 mApplication.cdmaPhoneCallState.setCurrentCallState(
1666 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
1667
1668 // Display the incoming call to the user if the InCallScreen isn't
1669 // already in the foreground.
1670 if (!mApplication.isShowingCallScreen()) {
1671 if (DBG) log("- showing incoming call (CDMA call waiting)...");
1672 showIncomingCall();
1673 }
1674
1675 // Start timer for CW display
1676 mCallWaitingTimeOut = false;
1677 sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE,
1678 CALLWAITING_CALLERINFO_DISPLAY_TIME);
1679
1680 // Set the mAddCallMenuStateAfterCW state to false
1681 mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false);
1682
1683 // Start the timer for disabling "Add Call" menu option
1684 sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT,
1685 CALLWAITING_ADDCALL_DISABLE_TIME);
1686
1687 // Extract the Call waiting information
1688 CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result;
1689 int isPresent = infoCW.isPresent;
1690 if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent);
1691 if (isPresent == 1 ) {//'1' if tone is valid
1692 int uSignalType = infoCW.signalType;
1693 int uAlertPitch = infoCW.alertPitch;
1694 int uSignal = infoCW.signal;
1695 if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch="
1696 + uAlertPitch + ", uSignal=" + uSignal);
1697 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1698 int toneID =
1699 SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal);
1700
1701 //Create the SignalInfo tone player and pass the ToneID
1702 new SignalInfoTonePlayer(toneID).start();
1703 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001704
1705 mCallModeler.onCdmaCallWaiting(infoCW);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001706 }
1707
1708 /**
1709 * Posts a event causing us to clean up after rejecting (or timing-out) a
1710 * CDMA call-waiting call.
1711 *
1712 * This method is safe to call from any thread.
1713 * @see #onCdmaCallWaitingReject()
1714 */
1715 /* package */ void sendCdmaCallWaitingReject() {
1716 sendEmptyMessage(CDMA_CALL_WAITING_REJECT);
1717 }
1718
1719 /**
1720 * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA,
1721 * and finally calls Hangup on the Call Waiting connection.
1722 *
1723 * This method should be called only from the UI thread.
1724 * @see #sendCdmaCallWaitingReject()
1725 */
1726 private void onCdmaCallWaitingReject() {
1727 final Call ringingCall = mCM.getFirstActiveRingingCall();
1728
1729 // Call waiting timeout scenario
1730 if (ringingCall.getState() == Call.State.WAITING) {
1731 // Code for perform Call logging and missed call notification
1732 Connection c = ringingCall.getLatestConnection();
1733
1734 if (c != null) {
1735 final int callLogType = mCallWaitingTimeOut ?
1736 Calls.MISSED_TYPE : Calls.INCOMING_TYPE;
1737
1738 // TODO: This callLogType override is not ideal. Connection should be astracted away
1739 // at a telephony-phone layer that can understand and edit the callTypes within
1740 // the abstraction for CDMA devices.
1741 mCallLogger.logCall(c, callLogType);
1742
1743 final long date = c.getCreateTime();
1744 if (callLogType == Calls.MISSED_TYPE) {
1745 // Add missed call notification
1746 showMissedCallNotification(c, date);
1747 } else {
1748 // Remove Call waiting 20 second display timer in the queue
1749 removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE);
1750 }
1751
1752 // Hangup the RingingCall connection for CW
1753 PhoneUtils.hangup(c);
1754 }
1755
1756 //Reset the mCallWaitingTimeOut boolean
1757 mCallWaitingTimeOut = false;
1758 }
Santos Cordona5d5db82013-09-15 13:00:34 -07001759
1760 // Call modeler needs to know about this event regardless of the
1761 // state conditionals in the previous code.
1762 mCallModeler.onCdmaCallWaitingReject();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001763 }
1764
1765 /**
1766 * Return the private variable mPreviousCdmaCallState.
1767 */
1768 /* package */ Call.State getPreviousCdmaCallState() {
1769 return mPreviousCdmaCallState;
1770 }
1771
1772 /**
1773 * Return the private variable mVoicePrivacyState.
1774 */
1775 /* package */ boolean getVoicePrivacyState() {
1776 return mVoicePrivacyState;
1777 }
1778
1779 /**
1780 * Return the private variable mIsCdmaRedialCall.
1781 */
1782 /* package */ boolean getIsCdmaRedialCall() {
1783 return mIsCdmaRedialCall;
1784 }
1785
1786 /**
1787 * Helper function used to show a missed call notification.
1788 */
1789 private void showMissedCallNotification(Connection c, final long date) {
1790 PhoneUtils.CallerInfoToken info =
1791 PhoneUtils.startGetCallerInfo(mApplication, c, this, Long.valueOf(date));
1792 if (info != null) {
1793 // at this point, we've requested to start a query, but it makes no
1794 // sense to log this missed call until the query comes back.
1795 if (VDBG) log("showMissedCallNotification: Querying for CallerInfo on missed call...");
1796 if (info.isFinal) {
1797 // it seems that the query we have actually is up to date.
1798 // send the notification then.
1799 CallerInfo ci = info.currentInfo;
1800
1801 // Check number presentation value; if we have a non-allowed presentation,
1802 // then display an appropriate presentation string instead as the missed
1803 // call.
1804 String name = ci.name;
1805 String number = ci.phoneNumber;
1806 if (ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1807 name = mApplication.getString(R.string.private_num);
1808 } else if (ci.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1809 name = mApplication.getString(R.string.unknown);
1810 } else {
1811 number = PhoneUtils.modifyForSpecialCnapCases(mApplication,
1812 ci, number, ci.numberPresentation);
1813 }
1814 mApplication.notificationMgr.notifyMissedCall(name, number,
1815 ci.phoneLabel, ci.cachedPhoto, ci.cachedPhotoIcon, date);
1816 }
1817 } else {
1818 // getCallerInfo() can return null in rare cases, like if we weren't
1819 // able to get a valid phone number out of the specified Connection.
1820 Log.w(LOG_TAG, "showMissedCallNotification: got null CallerInfo for Connection " + c);
1821 }
1822 }
1823
1824 /**
1825 * Inner class to handle emergency call tone and vibrator
1826 */
1827 private class EmergencyTonePlayerVibrator {
1828 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1829 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1830 private final long[] mVibratePattern =
1831 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1832
1833 private ToneGenerator mToneGenerator;
1834 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1835 // object will be isolated from others.
1836 private Vibrator mEmgVibrator = new SystemVibrator();
1837 private int mInCallVolume;
1838
1839 /**
1840 * constructor
1841 */
1842 public EmergencyTonePlayerVibrator() {
1843 }
1844
1845 /**
1846 * Start the emergency tone or vibrator.
1847 */
1848 private void start() {
1849 if (VDBG) log("call startEmergencyToneOrVibrate.");
1850 int ringerMode = mAudioManager.getRingerMode();
1851
1852 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1853 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1854 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1855 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1856 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1857 if (mToneGenerator != null) {
1858 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1859 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1860 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1861 0);
1862 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1863 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1864 }
1865 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1866 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1867 if (mEmgVibrator != null) {
1868 mEmgVibrator.vibrate(mVibratePattern, 0);
1869 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1870 }
1871 }
1872 }
1873
1874 /**
1875 * If the emergency tone is active, stop the tone or vibrator accordingly.
1876 */
1877 private void stop() {
1878 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1879
1880 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1881 && (mToneGenerator != null)) {
1882 mToneGenerator.stopTone();
1883 mToneGenerator.release();
1884 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1885 mInCallVolume,
1886 0);
1887 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1888 && (mEmgVibrator != null)) {
1889 mEmgVibrator.cancel();
1890 }
1891 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1892 }
1893 }
1894
1895 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1896 new BluetoothProfile.ServiceListener() {
1897 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1898 mBluetoothHeadset = (BluetoothHeadset) proxy;
1899 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1900 }
1901
1902 public void onServiceDisconnected(int profile) {
1903 mBluetoothHeadset = null;
1904 }
1905 };
1906
1907 private void onRingbackTone(AsyncResult r) {
1908 boolean playTone = (Boolean)(r.result);
1909
1910 if (playTone == true) {
1911 // Only play when foreground call is in DIALING or ALERTING.
1912 // to prevent a late coming playtone after ALERTING.
1913 // Don't play ringback tone if it is in play, otherwise it will cut
1914 // the current tone and replay it
1915 if (mCM.getActiveFgCallState().isDialing() &&
1916 mInCallRingbackTonePlayer == null) {
1917 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1918 mInCallRingbackTonePlayer.start();
1919 }
1920 } else {
1921 if (mInCallRingbackTonePlayer != null) {
1922 mInCallRingbackTonePlayer.stopTone();
1923 mInCallRingbackTonePlayer = null;
1924 }
1925 }
1926 }
1927
1928 /**
1929 * Toggle mute and unmute requests while keeping the same mute state
1930 */
1931 private void onResendMute() {
1932 boolean muteState = PhoneUtils.getMute();
1933 PhoneUtils.setMute(!muteState);
1934 PhoneUtils.setMute(muteState);
1935 }
1936
1937 private void log(String msg) {
1938 Log.d(LOG_TAG, msg);
1939 }
1940}