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