blob: 1a641662447c817c9b835c0685d724666bba4115 [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;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070028import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaDisplayInfoRec;
29import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaSignalInfoRec;
30import com.android.internal.telephony.cdma.SignalToneUtil;
31
32import android.app.ActivityManagerNative;
33import android.bluetooth.BluetoothAdapter;
34import android.bluetooth.BluetoothHeadset;
35import android.bluetooth.BluetoothProfile;
36import android.content.Context;
John Spurlock6ee06d02014-07-18 20:06:20 -040037import android.media.AudioAttributes;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070038import android.media.AudioManager;
39import android.media.ToneGenerator;
40import android.net.Uri;
41import android.os.AsyncResult;
42import android.os.Handler;
43import android.os.Message;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070044import android.os.SystemProperties;
45import android.os.SystemVibrator;
46import android.os.Vibrator;
47import android.provider.CallLog.Calls;
48import android.provider.Settings;
Anders Kristensen0b35f042014-02-27 14:31:07 -080049import android.telephony.DisconnectCause;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070050import android.telephony.PhoneNumberUtils;
51import android.telephony.PhoneStateListener;
52import android.telephony.TelephonyManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070053import android.util.EventLog;
54import android.util.Log;
55
56/**
57 * Phone app module that listens for phone state changes and various other
58 * events from the telephony layer, and triggers any resulting UI behavior
Santos Cordon5422a8d2014-09-12 04:20:56 -070059 * (like starting the Incoming Call UI, playing in-call tones,
Santos Cordon7d4ddf62013-07-10 11:58:08 -070060 * updating notifications, writing call log entries, etc.)
61 */
Santos Cordon5422a8d2014-09-12 04:20:56 -070062public class CallNotifier extends Handler {
Santos Cordon7d4ddf62013-07-10 11:58:08 -070063 private static final String LOG_TAG = "CallNotifier";
64 private static final boolean DBG =
65 (PhoneGlobals.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
66 private static final boolean VDBG = (PhoneGlobals.DBG_LEVEL >= 2);
67
Santos Cordon7d4ddf62013-07-10 11:58:08 -070068 // Time to display the DisplayInfo Record sent by CDMA network
69 private static final int DISPLAYINFO_NOTIFICATION_TIME = 2000; // msec
70
John Spurlock6ee06d02014-07-18 20:06:20 -040071 private static final AudioAttributes VIBRATION_ATTRIBUTES = new AudioAttributes.Builder()
72 .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
73 .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
74 .build();
75
Santos Cordon7d4ddf62013-07-10 11:58:08 -070076 /** The singleton instance. */
77 private static CallNotifier sInstance;
78
Santos Cordon7d4ddf62013-07-10 11:58:08 -070079 // values used to track the query state
80 private static final int CALLERINFO_QUERY_READY = 0;
81 private static final int CALLERINFO_QUERYING = -1;
82
83 // the state of the CallerInfo Query.
84 private int mCallerInfoQueryState;
85
86 // object used to synchronize access to mCallerInfoQueryState
87 private Object mCallerInfoQueryStateGuard = new Object();
88
Santos Cordon7d4ddf62013-07-10 11:58:08 -070089 // Events generated internally:
90 private static final int PHONE_MWI_CHANGED = 21;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070091 private static final int DISPLAYINFO_NOTIFICATION_DONE = 24;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070092 private static final int UPDATE_IN_CALL_NOTIFICATION = 27;
93
94 // Emergency call related defines:
95 private static final int EMERGENCY_TONE_OFF = 0;
96 private static final int EMERGENCY_TONE_ALERT = 1;
97 private static final int EMERGENCY_TONE_VIBRATE = 2;
98
99 private PhoneGlobals mApplication;
100 private CallManager mCM;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700101 private BluetoothHeadset mBluetoothHeadset;
102 private CallLogger mCallLogger;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700103
104 // ToneGenerator instance for playing SignalInfo tones
105 private ToneGenerator mSignalInfoToneGenerator;
106
107 // The tone volume relative to other sounds in the stream SignalInfo
108 private static final int TONE_RELATIVE_VOLUME_SIGNALINFO = 80;
109
110 private Call.State mPreviousCdmaCallState;
111 private boolean mVoicePrivacyState = false;
112 private boolean mIsCdmaRedialCall = false;
113
114 // Emergency call tone and vibrate:
115 private int mIsEmergencyToneOn;
116 private int mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
117 private EmergencyTonePlayerVibrator mEmergencyTonePlayerVibrator;
118
119 // Ringback tone player
120 private InCallTonePlayer mInCallRingbackTonePlayer;
121
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700122 // Cached AudioManager
123 private AudioManager mAudioManager;
124
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700125 private final BluetoothManager mBluetoothManager;
126
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700127 /**
128 * Initialize the singleton CallNotifier instance.
129 * This is only done once, at startup, from PhoneApp.onCreate().
130 */
Santos Cordon5422a8d2014-09-12 04:20:56 -0700131 /* package */ static CallNotifier init(PhoneGlobals app, Phone phone,
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700132 CallLogger callLogger, CallStateMonitor callStateMonitor,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700133 BluetoothManager bluetoothManager) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700134 synchronized (CallNotifier.class) {
135 if (sInstance == null) {
Santos Cordon5422a8d2014-09-12 04:20:56 -0700136 sInstance = new CallNotifier(app, phone, callLogger, callStateMonitor,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700137 bluetoothManager);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700138 } else {
139 Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance);
140 }
141 return sInstance;
142 }
143 }
144
145 /** Private constructor; @see init() */
Santos Cordon5422a8d2014-09-12 04:20:56 -0700146 private CallNotifier(PhoneGlobals app, Phone phone, CallLogger callLogger,
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700147 CallStateMonitor callStateMonitor, BluetoothManager bluetoothManager) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700148 mApplication = app;
149 mCM = app.mCM;
150 mCallLogger = callLogger;
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700151 mBluetoothManager = bluetoothManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700152
153 mAudioManager = (AudioManager) mApplication.getSystemService(Context.AUDIO_SERVICE);
154
155 callStateMonitor.addListener(this);
156
157 createSignalInfoToneGenerator();
158
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700159 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
160 if (adapter != null) {
161 adapter.getProfileProxy(mApplication.getApplicationContext(),
162 mBluetoothProfileServiceListener,
163 BluetoothProfile.HEADSET);
164 }
165
166 TelephonyManager telephonyManager = (TelephonyManager)app.getSystemService(
167 Context.TELEPHONY_SERVICE);
168 telephonyManager.listen(mPhoneStateListener,
169 PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
170 | PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR);
171 }
172
173 private void createSignalInfoToneGenerator() {
174 // Instantiate the ToneGenerator for SignalInfo and CallWaiting
175 // TODO: We probably don't need the mSignalInfoToneGenerator instance
176 // around forever. Need to change it so as to create a ToneGenerator instance only
177 // when a tone is being played and releases it after its done playing.
178 if (mSignalInfoToneGenerator == null) {
179 try {
180 mSignalInfoToneGenerator = new ToneGenerator(AudioManager.STREAM_VOICE_CALL,
181 TONE_RELATIVE_VOLUME_SIGNALINFO);
182 Log.d(LOG_TAG, "CallNotifier: mSignalInfoToneGenerator created when toneplay");
183 } catch (RuntimeException e) {
184 Log.w(LOG_TAG, "CallNotifier: Exception caught while creating " +
185 "mSignalInfoToneGenerator: " + e);
186 mSignalInfoToneGenerator = null;
187 }
188 } else {
189 Log.d(LOG_TAG, "mSignalInfoToneGenerator created already, hence skipping");
190 }
191 }
192
193 @Override
194 public void handleMessage(Message msg) {
195 switch (msg.what) {
196 case CallStateMonitor.PHONE_NEW_RINGING_CONNECTION:
197 log("RINGING... (new)");
198 onNewRingingConnection((AsyncResult) msg.obj);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700199 break;
200
201 case CallStateMonitor.PHONE_STATE_CHANGED:
202 onPhoneStateChanged((AsyncResult) msg.obj);
203 break;
204
205 case CallStateMonitor.PHONE_DISCONNECT:
206 if (DBG) log("DISCONNECT");
207 onDisconnect((AsyncResult) msg.obj);
208 break;
209
210 case CallStateMonitor.PHONE_UNKNOWN_CONNECTION_APPEARED:
211 onUnknownConnectionAppeared((AsyncResult) msg.obj);
212 break;
213
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700214 case PHONE_MWI_CHANGED:
215 onMwiChanged(mApplication.phone.getMessageWaitingIndicator());
216 break;
217
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700218 case CallStateMonitor.PHONE_STATE_DISPLAYINFO:
219 if (DBG) log("Received PHONE_STATE_DISPLAYINFO event");
220 onDisplayInfo((AsyncResult) msg.obj);
221 break;
222
223 case CallStateMonitor.PHONE_STATE_SIGNALINFO:
224 if (DBG) log("Received PHONE_STATE_SIGNALINFO event");
225 onSignalInfo((AsyncResult) msg.obj);
226 break;
227
228 case DISPLAYINFO_NOTIFICATION_DONE:
229 if (DBG) log("Received Display Info notification done event ...");
230 CdmaDisplayInfo.dismissDisplayInfoRecord();
231 break;
232
233 case CallStateMonitor.EVENT_OTA_PROVISION_CHANGE:
234 if (DBG) log("EVENT_OTA_PROVISION_CHANGE...");
235 mApplication.handleOtaspEvent(msg);
236 break;
237
238 case CallStateMonitor.PHONE_ENHANCED_VP_ON:
239 if (DBG) log("PHONE_ENHANCED_VP_ON...");
240 if (!mVoicePrivacyState) {
241 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
242 new InCallTonePlayer(toneToPlay).start();
243 mVoicePrivacyState = true;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700244 }
245 break;
246
247 case CallStateMonitor.PHONE_ENHANCED_VP_OFF:
248 if (DBG) log("PHONE_ENHANCED_VP_OFF...");
249 if (mVoicePrivacyState) {
250 int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY;
251 new InCallTonePlayer(toneToPlay).start();
252 mVoicePrivacyState = false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700253 }
254 break;
255
256 case CallStateMonitor.PHONE_RINGBACK_TONE:
Ihab Awad277011f2014-05-28 16:51:33 -0700257 // DISABLED. The Telecomm and new ConnectionService layers are now responsible.
258 // onRingbackTone((AsyncResult) msg.obj);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700259 break;
260
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700261 default:
262 // super.handleMessage(msg);
263 }
264 }
265
266 PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
267 @Override
268 public void onMessageWaitingIndicatorChanged(boolean mwi) {
269 onMwiChanged(mwi);
270 }
271
272 @Override
273 public void onCallForwardingIndicatorChanged(boolean cfi) {
274 onCfiChanged(cfi);
275 }
276 };
277
278 /**
279 * Handles a "new ringing connection" event from the telephony layer.
280 */
281 private void onNewRingingConnection(AsyncResult r) {
282 Connection c = (Connection) r.result;
283 log("onNewRingingConnection(): state = " + mCM.getState() + ", conn = { " + c + " }");
284 Call ringing = c.getCall();
285 Phone phone = ringing.getPhone();
286
287 // Check for a few cases where we totally ignore incoming calls.
288 if (ignoreAllIncomingCalls(phone)) {
289 // Immediately reject the call, without even indicating to the user
290 // that an incoming call occurred. (This will generally send the
291 // caller straight to voicemail, just as if we *had* shown the
292 // incoming-call UI and the user had declined the call.)
293 PhoneUtils.hangupRingingCall(ringing);
294 return;
295 }
296
297 if (!c.isRinging()) {
298 Log.i(LOG_TAG, "CallNotifier.onNewRingingConnection(): connection not ringing!");
299 // This is a very strange case: an incoming call that stopped
300 // ringing almost instantly after the onNewRingingConnection()
301 // event. There's nothing we can do here, so just bail out
302 // without doing anything. (But presumably we'll log it in
303 // the call log when the disconnect event comes in...)
304 return;
305 }
306
307 // Stop any signalInfo tone being played on receiving a Call
308 stopSignalInfoTone();
309
310 Call.State state = c.getState();
311 // State will be either INCOMING or WAITING.
312 if (VDBG) log("- connection is ringing! state = " + state);
313 // if (DBG) PhoneUtils.dumpCallState(mPhone);
314
315 // No need to do any service state checks here (like for
316 // "emergency mode"), since in those states the SIM won't let
317 // us get incoming connections in the first place.
318
319 // TODO: Consider sending out a serialized broadcast Intent here
320 // (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the
321 // ringer and going to the in-call UI. The intent should contain
322 // the caller-id info for the current connection, and say whether
323 // it would be a "call waiting" call or a regular ringing call.
324 // If anybody consumed the broadcast, we'd bail out without
325 // ringing or bringing up the in-call UI.
326 //
327 // This would give 3rd party apps a chance to listen for (and
328 // intercept) new ringing connections. An app could reject the
329 // incoming call by consuming the broadcast and doing nothing, or
330 // it could "pick up" the call (without any action by the user!)
331 // via some future TelephonyManager API.
332 //
333 // See bug 1312336 for more details.
334 // We'd need to protect this with a new "intercept incoming calls"
335 // system permission.
336
337 // Obtain a partial wake lock to make sure the CPU doesn't go to
338 // sleep before we finish bringing up the InCallScreen.
339 // (This will be upgraded soon to a full wake lock; see
340 // showIncomingCall().)
341 if (VDBG) log("Holding wake lock on new incoming connection.");
342 mApplication.requestWakeState(PhoneGlobals.WakeState.PARTIAL);
343
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700344 // Note we *don't* post a status bar notification here, since
345 // we're not necessarily ready to actually show the incoming call
346 // to the user. (For calls in the INCOMING state, at least, we
347 // still need to run a caller-id query, and we may not even ring
348 // at all if the "send directly to voicemail" flag is set.)
349 //
350 // Instead, we update the notification (and potentially launch the
351 // InCallScreen) from the showIncomingCall() method, which runs
352 // when the caller-id query completes or times out.
353
354 if (VDBG) log("- onNewRingingConnection() done.");
355 }
356
357 /**
358 * Determines whether or not we're allowed to present incoming calls to the
359 * user, based on the capabilities and/or current state of the device.
360 *
361 * If this method returns true, that means we should immediately reject the
362 * current incoming call, without even indicating to the user that an
363 * incoming call occurred.
364 *
365 * (We only reject incoming calls in a few cases, like during an OTASP call
366 * when we can't interrupt the user, or if the device hasn't completed the
367 * SetupWizard yet. We also don't allow incoming calls on non-voice-capable
368 * devices. But note that we *always* allow incoming calls while in ECM.)
369 *
370 * @return true if we're *not* allowed to present an incoming call to
371 * the user.
372 */
373 private boolean ignoreAllIncomingCalls(Phone phone) {
374 // Incoming calls are totally ignored on non-voice-capable devices.
375 if (!PhoneGlobals.sVoiceCapable) {
376 // ...but still log a warning, since we shouldn't have gotten this
377 // event in the first place! (Incoming calls *should* be blocked at
378 // the telephony layer on non-voice-capable capable devices.)
379 Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring...");
380 return true;
381 }
382
383 // In ECM (emergency callback mode), we ALWAYS allow incoming calls
384 // to get through to the user. (Note that ECM is applicable only to
385 // voice-capable CDMA devices).
386 if (PhoneUtils.isPhoneInEcm(phone)) {
387 if (DBG) log("Incoming call while in ECM: always allow...");
388 return false;
389 }
390
391 // Incoming calls are totally ignored if the device isn't provisioned yet.
392 boolean provisioned = Settings.Global.getInt(mApplication.getContentResolver(),
393 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
394 if (!provisioned) {
395 Log.i(LOG_TAG, "Ignoring incoming call: not provisioned");
396 return true;
397 }
398
399 // Incoming calls are totally ignored if an OTASP call is active.
400 if (TelephonyCapabilities.supportsOtasp(phone)) {
401 boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState
402 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION);
403 boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState
404 == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG);
405 boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState;
406
407 if (spcState) {
408 Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active");
409 return true;
410 } else if (activateState || dialogState) {
411 // We *are* allowed to receive incoming calls at this point.
412 // But clear out any residual OTASP UI first.
413 // TODO: It's an MVC violation to twiddle the OTA UI state here;
414 // we should instead provide a higher-level API via OtaUtils.
415 if (dialogState) mApplication.dismissOtaDialogs();
416 mApplication.clearOtaState();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700417 return false;
418 }
419 }
420
421 // Normal case: allow this call to be presented to the user.
422 return false;
423 }
424
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700425 private void onUnknownConnectionAppeared(AsyncResult r) {
426 PhoneConstants.State state = mCM.getState();
427
428 if (state == PhoneConstants.State.OFFHOOK) {
Santos Cordon54fdb592013-09-19 05:16:18 -0700429 if (DBG) log("unknown connection appeared...");
Chiao Cheng312b9c92013-09-16 15:40:53 -0700430
Santos Cordon54fdb592013-09-19 05:16:18 -0700431 onPhoneStateChanged(r);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700432 }
433 }
434
Christine Chenb5e4b652013-09-19 11:20:18 -0700435 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700436 * Updates the phone UI in response to phone state changes.
437 *
438 * Watch out: certain state changes are actually handled by their own
439 * specific methods:
440 * - see onNewRingingConnection() for new incoming calls
441 * - see onDisconnect() for calls being hung up or disconnected
442 */
443 private void onPhoneStateChanged(AsyncResult r) {
444 PhoneConstants.State state = mCM.getState();
445 if (VDBG) log("onPhoneStateChanged: state = " + state);
446
447 // Turn status bar notifications on or off depending upon the state
448 // of the phone. Notification Alerts (audible or vibrating) should
449 // be on if and only if the phone is IDLE.
450 mApplication.notificationMgr.statusBarHelper
451 .enableNotificationAlerts(state == PhoneConstants.State.IDLE);
452
453 Phone fgPhone = mCM.getFgPhone();
454 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
455 if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE)
456 && ((mPreviousCdmaCallState == Call.State.DIALING)
457 || (mPreviousCdmaCallState == Call.State.ALERTING))) {
458 if (mIsCdmaRedialCall) {
459 int toneToPlay = InCallTonePlayer.TONE_REDIAL;
460 new InCallTonePlayer(toneToPlay).start();
461 }
462 // Stop any signal info tone when call moves to ACTIVE state
463 stopSignalInfoTone();
464 }
465 mPreviousCdmaCallState = fgPhone.getForegroundCall().getState();
466 }
467
468 // Have the PhoneApp recompute its mShowBluetoothIndication
469 // flag based on the (new) telephony state.
470 // There's no need to force a UI update since we update the
471 // in-call notification ourselves (below), and the InCallScreen
472 // listens for phone state changes itself.
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700473 mBluetoothManager.updateBluetoothIndication();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700474
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700475 // Update the phone state and other sensor/lock.
476 mApplication.updatePhoneState(state);
477
478 if (state == PhoneConstants.State.OFFHOOK) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700479
480 if (VDBG) log("onPhoneStateChanged: OFF HOOK");
481 // make sure audio is in in-call mode now
482 PhoneUtils.setAudioMode(mCM);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700483 }
484
485 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
486 Connection c = fgPhone.getForegroundCall().getLatestConnection();
Yorke Lee36bb2542014-06-05 08:09:52 -0700487 if ((c != null) && (PhoneNumberUtils.isLocalEmergencyNumber(mApplication,
488 c.getAddress()))) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700489 if (VDBG) log("onPhoneStateChanged: it is an emergency call.");
490 Call.State callState = fgPhone.getForegroundCall().getState();
491 if (mEmergencyTonePlayerVibrator == null) {
492 mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator();
493 }
494
495 if (callState == Call.State.DIALING || callState == Call.State.ALERTING) {
496 mIsEmergencyToneOn = Settings.Global.getInt(
497 mApplication.getContentResolver(),
498 Settings.Global.EMERGENCY_TONE, EMERGENCY_TONE_OFF);
499 if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF &&
500 mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) {
501 if (mEmergencyTonePlayerVibrator != null) {
502 mEmergencyTonePlayerVibrator.start();
503 }
504 }
505 } else if (callState == Call.State.ACTIVE) {
506 if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) {
507 if (mEmergencyTonePlayerVibrator != null) {
508 mEmergencyTonePlayerVibrator.stop();
509 }
510 }
511 }
512 }
513 }
514
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800515 if (fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_GSM
516 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -0700517 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800518 || fgPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700519 Call.State callState = mCM.getActiveFgCallState();
520 if (!callState.isDialing()) {
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800521 // If call gets activated or disconnected before the ringback
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700522 // tone stops, we have to stop it to prevent disturbing.
523 if (mInCallRingbackTonePlayer != null) {
524 mInCallRingbackTonePlayer.stopTone();
525 mInCallRingbackTonePlayer = null;
526 }
527 }
528 }
529 }
530
531 void updateCallNotifierRegistrationsAfterRadioTechnologyChange() {
532 if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange...");
533
534 // Clear ringback tone player
535 mInCallRingbackTonePlayer = null;
536
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700537 // Instantiate mSignalInfoToneGenerator
538 createSignalInfoToneGenerator();
539 }
540
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700541 private void onDisconnect(AsyncResult r) {
542 if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState());
543
544 mVoicePrivacyState = false;
545 Connection c = (Connection) r.result;
546 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800547 log("onDisconnect: cause = " + DisconnectCause.toString(c.getDisconnectCause())
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700548 + ", incoming = " + c.isIncoming()
549 + ", date = " + c.getCreateTime());
550 } else {
551 Log.w(LOG_TAG, "onDisconnect: null connection");
552 }
553
554 int autoretrySetting = 0;
555 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
556 autoretrySetting = android.provider.Settings.Global.getInt(mApplication.
557 getContentResolver(),android.provider.Settings.Global.CALL_AUTO_RETRY, 0);
558 }
559
560 // Stop any signalInfo tone being played when a call gets ended
561 stopSignalInfoTone();
562
563 if ((c != null) && (c.getCall().getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA)) {
564 // Resetting the CdmaPhoneCallState members
565 mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700566 }
567
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700568 // If this is the end of an OTASP call, pass it on to the PhoneApp.
569 if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) {
570 final String number = c.getAddress();
571 if (c.getCall().getPhone().isOtaSpNumber(number)) {
572 if (DBG) log("onDisconnect: this was an OTASP call!");
573 mApplication.handleOtaspDisconnect();
574 }
575 }
576
577 // Check for the various tones we might need to play (thru the
578 // earpiece) after a call disconnects.
579 int toneToPlay = InCallTonePlayer.TONE_NONE;
580
581 // The "Busy" or "Congestion" tone is the highest priority:
582 if (c != null) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800583 int cause = c.getDisconnectCause();
584 if (cause == DisconnectCause.BUSY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700585 if (DBG) log("- need to play BUSY tone!");
586 toneToPlay = InCallTonePlayer.TONE_BUSY;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800587 } else if (cause == DisconnectCause.CONGESTION) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700588 if (DBG) log("- need to play CONGESTION tone!");
589 toneToPlay = InCallTonePlayer.TONE_CONGESTION;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800590 } else if (((cause == DisconnectCause.NORMAL)
591 || (cause == DisconnectCause.LOCAL))
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700592 && (mApplication.isOtaCallInActiveState())) {
593 if (DBG) log("- need to play OTA_CALL_END tone!");
594 toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800595 } else if (cause == DisconnectCause.CDMA_REORDER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700596 if (DBG) log("- need to play CDMA_REORDER tone!");
597 toneToPlay = InCallTonePlayer.TONE_REORDER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800598 } else if (cause == DisconnectCause.CDMA_INTERCEPT) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700599 if (DBG) log("- need to play CDMA_INTERCEPT tone!");
600 toneToPlay = InCallTonePlayer.TONE_INTERCEPT;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800601 } else if (cause == DisconnectCause.CDMA_DROP) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700602 if (DBG) log("- need to play CDMA_DROP tone!");
603 toneToPlay = InCallTonePlayer.TONE_CDMA_DROP;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800604 } else if (cause == DisconnectCause.OUT_OF_SERVICE) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700605 if (DBG) log("- need to play OUT OF SERVICE tone!");
606 toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800607 } else if (cause == DisconnectCause.UNOBTAINABLE_NUMBER) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700608 if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!");
609 toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER;
Anders Kristensen0b35f042014-02-27 14:31:07 -0800610 } else if (cause == DisconnectCause.ERROR_UNSPECIFIED) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700611 if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!");
612 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
613 }
614 }
615
616 // If we don't need to play BUSY or CONGESTION, then play the
617 // "call ended" tone if this was a "regular disconnect" (i.e. a
618 // normal call where one end or the other hung up) *and* this
619 // disconnect event caused the phone to become idle. (In other
620 // words, we *don't* play the sound if one call hangs up but
621 // there's still an active call on the other line.)
622 // TODO: We may eventually want to disable this via a preference.
623 if ((toneToPlay == InCallTonePlayer.TONE_NONE)
624 && (mCM.getState() == PhoneConstants.State.IDLE)
625 && (c != null)) {
Anders Kristensen0b35f042014-02-27 14:31:07 -0800626 int cause = c.getDisconnectCause();
627 if ((cause == DisconnectCause.NORMAL) // remote hangup
628 || (cause == DisconnectCause.LOCAL)) { // local hangup
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700629 if (VDBG) log("- need to play CALL_ENDED tone!");
630 toneToPlay = InCallTonePlayer.TONE_CALL_ENDED;
631 mIsCdmaRedialCall = false;
632 }
633 }
634
635 // All phone calls are disconnected.
636 if (mCM.getState() == PhoneConstants.State.IDLE) {
637 // Don't reset the audio mode or bluetooth/speakerphone state
638 // if we still need to let the user hear a tone through the earpiece.
639 if (toneToPlay == InCallTonePlayer.TONE_NONE) {
640 resetAudioStateAfterDisconnect();
641 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700642 }
643
644 if (c != null) {
645 mCallLogger.logCall(c);
646
647 final String number = c.getAddress();
648 final Phone phone = c.getCall().getPhone();
649 final boolean isEmergencyNumber =
Yorke Lee36bb2542014-06-05 08:09:52 -0700650 PhoneNumberUtils.isLocalEmergencyNumber(mApplication, number);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700651
652 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
653 if ((isEmergencyNumber)
654 && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) {
655 if (mEmergencyTonePlayerVibrator != null) {
656 mEmergencyTonePlayerVibrator.stop();
657 }
658 }
659 }
660
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700661 // Possibly play a "post-disconnect tone" thru the earpiece.
662 // We do this here, rather than from the InCallScreen
663 // activity, since we need to do this even if you're not in
664 // the Phone UI at the moment the connection ends.
665 if (toneToPlay != InCallTonePlayer.TONE_NONE) {
666 if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")...");
667 new InCallTonePlayer(toneToPlay).start();
668
669 // TODO: alternatively, we could start an InCallTonePlayer
670 // here with an "unlimited" tone length,
671 // and manually stop it later when this connection truly goes
672 // away. (The real connection over the network was closed as soon
673 // as we got the BUSY message. But our telephony layer keeps the
674 // connection open for a few extra seconds so we can show the
675 // "busy" indication to the user. We could stop the busy tone
676 // when *that* connection's "disconnect" event comes in.)
677 }
678
Santos Cordonf68db2e2014-07-02 14:40:44 -0700679 final int cause = c.getDisconnectCause();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700680 if (((mPreviousCdmaCallState == Call.State.DIALING)
681 || (mPreviousCdmaCallState == Call.State.ALERTING))
682 && (!isEmergencyNumber)
Anders Kristensen0b35f042014-02-27 14:31:07 -0800683 && (cause != DisconnectCause.INCOMING_MISSED )
684 && (cause != DisconnectCause.NORMAL)
685 && (cause != DisconnectCause.LOCAL)
686 && (cause != DisconnectCause.INCOMING_REJECTED)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700687 if (!mIsCdmaRedialCall) {
688 if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) {
689 // TODO: (Moto): The contact reference data may need to be stored and use
690 // here when redialing a call. For now, pass in NULL as the URI parameter.
Santos Cordonce02f3a2013-09-19 01:58:42 -0700691 final int status =
692 PhoneUtils.placeCall(mApplication, phone, number, null, false);
693 if (status != PhoneUtils.CALL_STATUS_FAILED) {
694 mIsCdmaRedialCall = true;
695 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700696 } else {
697 mIsCdmaRedialCall = false;
698 }
699 } else {
700 mIsCdmaRedialCall = false;
701 }
702 }
703 }
704 }
705
706 /**
707 * Resets the audio mode and speaker state when a call ends.
708 */
709 private void resetAudioStateAfterDisconnect() {
710 if (VDBG) log("resetAudioStateAfterDisconnect()...");
711
712 if (mBluetoothHeadset != null) {
713 mBluetoothHeadset.disconnectAudio();
714 }
715
716 // call turnOnSpeaker() with state=false and store=true even if speaker
717 // is already off to reset user requested speaker state.
718 PhoneUtils.turnOnSpeaker(mApplication, false, true);
719
720 PhoneUtils.setAudioMode(mCM);
721 }
722
723 private void onMwiChanged(boolean visible) {
724 if (VDBG) log("onMwiChanged(): " + visible);
725
726 // "Voicemail" is meaningless on non-voice-capable devices,
727 // so ignore MWI events.
728 if (!PhoneGlobals.sVoiceCapable) {
729 // ...but still log a warning, since we shouldn't have gotten this
730 // event in the first place!
731 // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events
732 // *should* be blocked at the telephony layer on non-voice-capable
733 // capable devices.)
734 Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring...");
735 return;
736 }
737
738 mApplication.notificationMgr.updateMwi(visible);
739 }
740
741 /**
742 * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a
743 * failed NotificationMgr.updateMwi() call.
744 */
745 /* package */ void sendMwiChangedDelayed(long delayMillis) {
746 Message message = Message.obtain(this, PHONE_MWI_CHANGED);
747 sendMessageDelayed(message, delayMillis);
748 }
749
750 private void onCfiChanged(boolean visible) {
751 if (VDBG) log("onCfiChanged(): " + visible);
752 mApplication.notificationMgr.updateCfi(visible);
753 }
754
755 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700756 * Helper class to play tones through the earpiece (or speaker / BT)
757 * during a call, using the ToneGenerator.
758 *
759 * To use, just instantiate a new InCallTonePlayer
760 * (passing in the TONE_* constant for the tone you want)
761 * and start() it.
762 *
763 * When we're done playing the tone, if the phone is idle at that
764 * point, we'll reset the audio routing and speaker state.
765 * (That means that for tones that get played *after* a call
766 * disconnects, like "busy" or "congestion" or "call ended", you
767 * should NOT call resetAudioStateAfterDisconnect() yourself.
768 * Instead, just start the InCallTonePlayer, which will automatically
769 * defer the resetAudioStateAfterDisconnect() call until the tone
770 * finishes playing.)
771 */
772 private class InCallTonePlayer extends Thread {
773 private int mToneId;
774 private int mState;
775 // The possible tones we can play.
776 public static final int TONE_NONE = 0;
777 public static final int TONE_CALL_WAITING = 1;
778 public static final int TONE_BUSY = 2;
779 public static final int TONE_CONGESTION = 3;
780 public static final int TONE_CALL_ENDED = 4;
781 public static final int TONE_VOICE_PRIVACY = 5;
782 public static final int TONE_REORDER = 6;
783 public static final int TONE_INTERCEPT = 7;
784 public static final int TONE_CDMA_DROP = 8;
785 public static final int TONE_OUT_OF_SERVICE = 9;
786 public static final int TONE_REDIAL = 10;
787 public static final int TONE_OTA_CALL_END = 11;
788 public static final int TONE_RING_BACK = 12;
789 public static final int TONE_UNOBTAINABLE_NUMBER = 13;
790
791 // The tone volume relative to other sounds in the stream
792 static final int TONE_RELATIVE_VOLUME_EMERGENCY = 100;
793 static final int TONE_RELATIVE_VOLUME_HIPRI = 80;
794 static final int TONE_RELATIVE_VOLUME_LOPRI = 50;
795
796 // Buffer time (in msec) to add on to tone timeout value.
797 // Needed mainly when the timeout value for a tone is the
798 // exact duration of the tone itself.
799 static final int TONE_TIMEOUT_BUFFER = 20;
800
801 // The tone state
802 static final int TONE_OFF = 0;
803 static final int TONE_ON = 1;
804 static final int TONE_STOPPED = 2;
805
806 InCallTonePlayer(int toneId) {
807 super();
808 mToneId = toneId;
809 mState = TONE_OFF;
810 }
811
812 @Override
813 public void run() {
814 log("InCallTonePlayer.run(toneId = " + mToneId + ")...");
815
816 int toneType = 0; // passed to ToneGenerator.startTone()
817 int toneVolume; // passed to the ToneGenerator constructor
818 int toneLengthMillis;
819 int phoneType = mCM.getFgPhone().getPhoneType();
820
821 switch (mToneId) {
822 case TONE_CALL_WAITING:
823 toneType = ToneGenerator.TONE_SUP_CALL_WAITING;
824 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
825 // Call waiting tone is stopped by stopTone() method
826 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
827 break;
828 case TONE_BUSY:
829 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
830 toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT;
831 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
832 toneLengthMillis = 1000;
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800833 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM
834 || phoneType == PhoneConstants.PHONE_TYPE_SIP
Etan Cohen0ca1c802014-07-07 15:35:48 -0700835 || phoneType == PhoneConstants.PHONE_TYPE_IMS
Sailesh Nepalcc0375f2013-11-13 09:15:18 -0800836 || phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700837 toneType = ToneGenerator.TONE_SUP_BUSY;
838 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
839 toneLengthMillis = 4000;
840 } else {
841 throw new IllegalStateException("Unexpected phone type: " + phoneType);
842 }
843 break;
844 case TONE_CONGESTION:
845 toneType = ToneGenerator.TONE_SUP_CONGESTION;
846 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
847 toneLengthMillis = 4000;
848 break;
849
850 case TONE_CALL_ENDED:
851 toneType = ToneGenerator.TONE_PROP_PROMPT;
852 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
853 toneLengthMillis = 200;
854 break;
855 case TONE_OTA_CALL_END:
856 if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone ==
857 OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) {
858 toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD;
859 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
860 toneLengthMillis = 750;
861 } else {
862 toneType = ToneGenerator.TONE_PROP_PROMPT;
863 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
864 toneLengthMillis = 200;
865 }
866 break;
867 case TONE_VOICE_PRIVACY:
868 toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE;
869 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
870 toneLengthMillis = 5000;
871 break;
872 case TONE_REORDER:
873 toneType = ToneGenerator.TONE_CDMA_REORDER;
874 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
875 toneLengthMillis = 4000;
876 break;
877 case TONE_INTERCEPT:
878 toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT;
879 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
880 toneLengthMillis = 500;
881 break;
882 case TONE_CDMA_DROP:
883 case TONE_OUT_OF_SERVICE:
884 toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE;
885 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
886 toneLengthMillis = 375;
887 break;
888 case TONE_REDIAL:
889 toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE;
890 toneVolume = TONE_RELATIVE_VOLUME_LOPRI;
891 toneLengthMillis = 5000;
892 break;
893 case TONE_RING_BACK:
894 toneType = ToneGenerator.TONE_SUP_RINGTONE;
895 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
896 // Call ring back tone is stopped by stopTone() method
897 toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER;
898 break;
899 case TONE_UNOBTAINABLE_NUMBER:
900 toneType = ToneGenerator.TONE_SUP_ERROR;
901 toneVolume = TONE_RELATIVE_VOLUME_HIPRI;
902 toneLengthMillis = 4000;
903 break;
904 default:
905 throw new IllegalArgumentException("Bad toneId: " + mToneId);
906 }
907
908 // If the mToneGenerator creation fails, just continue without it. It is
909 // a local audio signal, and is not as important.
910 ToneGenerator toneGenerator;
911 try {
912 int stream;
913 if (mBluetoothHeadset != null) {
914 stream = mBluetoothHeadset.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO:
915 AudioManager.STREAM_VOICE_CALL;
916 } else {
917 stream = AudioManager.STREAM_VOICE_CALL;
918 }
919 toneGenerator = new ToneGenerator(stream, toneVolume);
920 // if (DBG) log("- created toneGenerator: " + toneGenerator);
921 } catch (RuntimeException e) {
922 Log.w(LOG_TAG,
923 "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e);
924 toneGenerator = null;
925 }
926
927 // Using the ToneGenerator (with the CALL_WAITING / BUSY /
928 // CONGESTION tones at least), the ToneGenerator itself knows
929 // the right pattern of tones to play; we do NOT need to
930 // manually start/stop each individual tone, or manually
931 // insert the correct delay between tones. (We just start it
932 // and let it run for however long we want the tone pattern to
933 // continue.)
934 //
935 // TODO: When we stop the ToneGenerator in the middle of a
936 // "tone pattern", it sounds bad if we cut if off while the
937 // tone is actually playing. Consider adding API to the
938 // ToneGenerator to say "stop at the next silent part of the
939 // pattern", or simply "play the pattern N times and then
940 // stop."
941 boolean needToStopTone = true;
942 boolean okToPlayTone = false;
943
944 if (toneGenerator != null) {
945 int ringerMode = mAudioManager.getRingerMode();
946 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
947 if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) {
948 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
949 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
950 if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType);
951 okToPlayTone = true;
952 needToStopTone = false;
953 }
954 } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) ||
955 (toneType == ToneGenerator.TONE_CDMA_REORDER) ||
956 (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) ||
957 (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) ||
958 (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) {
959 if (ringerMode != AudioManager.RINGER_MODE_SILENT) {
960 if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType);
961 okToPlayTone = true;
962 needToStopTone = false;
963 }
964 } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) ||
965 (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) {
966 if ((ringerMode != AudioManager.RINGER_MODE_SILENT) &&
967 (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) {
968 if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType);
969 okToPlayTone = true;
970 needToStopTone = false;
971 }
972 } else { // For the rest of the tones, always OK to play.
973 okToPlayTone = true;
974 }
975 } else { // Not "CDMA"
976 okToPlayTone = true;
977 }
978
979 synchronized (this) {
980 if (okToPlayTone && mState != TONE_STOPPED) {
981 mState = TONE_ON;
982 toneGenerator.startTone(toneType);
983 try {
984 wait(toneLengthMillis + TONE_TIMEOUT_BUFFER);
985 } catch (InterruptedException e) {
986 Log.w(LOG_TAG,
987 "InCallTonePlayer stopped: " + e);
988 }
989 if (needToStopTone) {
990 toneGenerator.stopTone();
991 }
992 }
993 // if (DBG) log("- InCallTonePlayer: done playing.");
994 toneGenerator.release();
995 mState = TONE_OFF;
996 }
997 }
998
999 // Finally, do the same cleanup we otherwise would have done
1000 // in onDisconnect().
1001 //
1002 // (But watch out: do NOT do this if the phone is in use,
1003 // since some of our tones get played *during* a call (like
1004 // CALL_WAITING) and we definitely *don't*
1005 // want to reset the audio mode / speaker / bluetooth after
1006 // playing those!
1007 // This call is really here for use with tones that get played
1008 // *after* a call disconnects, like "busy" or "congestion" or
1009 // "call ended", where the phone has already become idle but
1010 // we need to defer the resetAudioStateAfterDisconnect() call
1011 // till the tone finishes playing.)
1012 if (mCM.getState() == PhoneConstants.State.IDLE) {
1013 resetAudioStateAfterDisconnect();
1014 }
1015 }
1016
1017 public void stopTone() {
1018 synchronized (this) {
1019 if (mState == TONE_ON) {
1020 notify();
1021 }
1022 mState = TONE_STOPPED;
1023 }
1024 }
1025 }
1026
1027 /**
1028 * Displays a notification when the phone receives a DisplayInfo record.
1029 */
1030 private void onDisplayInfo(AsyncResult r) {
1031 // Extract the DisplayInfo String from the message
1032 CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result);
1033
1034 if (displayInfoRec != null) {
1035 String displayInfo = displayInfoRec.alpha;
1036 if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo);
1037 CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo);
1038
1039 // start a 2 second timer
1040 sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE,
1041 DISPLAYINFO_NOTIFICATION_TIME);
1042 }
1043 }
1044
1045 /**
1046 * Helper class to play SignalInfo tones using the ToneGenerator.
1047 *
1048 * To use, just instantiate a new SignalInfoTonePlayer
1049 * (passing in the ToneID constant for the tone you want)
1050 * and start() it.
1051 */
1052 private class SignalInfoTonePlayer extends Thread {
1053 private int mToneId;
1054
1055 SignalInfoTonePlayer(int toneId) {
1056 super();
1057 mToneId = toneId;
1058 }
1059
1060 @Override
1061 public void run() {
1062 log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")...");
1063
1064 if (mSignalInfoToneGenerator != null) {
1065 //First stop any ongoing SignalInfo tone
1066 mSignalInfoToneGenerator.stopTone();
1067
1068 //Start playing the new tone if its a valid tone
1069 mSignalInfoToneGenerator.startTone(mToneId);
1070 }
1071 }
1072 }
1073
1074 /**
1075 * Plays a tone when the phone receives a SignalInfo record.
1076 */
1077 private void onSignalInfo(AsyncResult r) {
1078 // Signal Info are totally ignored on non-voice-capable devices.
1079 if (!PhoneGlobals.sVoiceCapable) {
1080 Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring...");
1081 return;
1082 }
1083
1084 if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) {
1085 // Do not start any new SignalInfo tone when Call state is INCOMING
1086 // and stop any previous SignalInfo tone which is being played
1087 stopSignalInfoTone();
1088 } else {
1089 // Extract the SignalInfo String from the message
1090 CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result);
1091 // Only proceed if a Signal info is present.
1092 if (signalInfoRec != null) {
1093 boolean isPresent = signalInfoRec.isPresent;
1094 if (DBG) log("onSignalInfo: isPresent=" + isPresent);
1095 if (isPresent) {// if tone is valid
1096 int uSignalType = signalInfoRec.signalType;
1097 int uAlertPitch = signalInfoRec.alertPitch;
1098 int uSignal = signalInfoRec.signal;
1099
1100 if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" +
1101 uAlertPitch + ", uSignal=" + uSignal);
1102 //Map the Signal to a ToneGenerator ToneID only if Signal info is present
1103 int toneID = SignalToneUtil.getAudioToneFromSignalInfo
1104 (uSignalType, uAlertPitch, uSignal);
1105
1106 //Create the SignalInfo tone player and pass the ToneID
1107 new SignalInfoTonePlayer(toneID).start();
1108 }
1109 }
1110 }
1111 }
1112
1113 /**
1114 * Stops a SignalInfo tone in the following condition
1115 * 1 - On receiving a New Ringing Call
1116 * 2 - On disconnecting a call
1117 * 3 - On answering a Call Waiting Call
1118 */
1119 /* package */ void stopSignalInfoTone() {
1120 if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player");
1121 new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start();
1122 }
1123
1124 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001125 * Return the private variable mPreviousCdmaCallState.
1126 */
1127 /* package */ Call.State getPreviousCdmaCallState() {
1128 return mPreviousCdmaCallState;
1129 }
1130
1131 /**
1132 * Return the private variable mVoicePrivacyState.
1133 */
1134 /* package */ boolean getVoicePrivacyState() {
1135 return mVoicePrivacyState;
1136 }
1137
1138 /**
1139 * Return the private variable mIsCdmaRedialCall.
1140 */
1141 /* package */ boolean getIsCdmaRedialCall() {
1142 return mIsCdmaRedialCall;
1143 }
1144
1145 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001146 * Inner class to handle emergency call tone and vibrator
1147 */
1148 private class EmergencyTonePlayerVibrator {
1149 private final int EMG_VIBRATE_LENGTH = 1000; // ms.
1150 private final int EMG_VIBRATE_PAUSE = 1000; // ms.
1151 private final long[] mVibratePattern =
1152 new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE };
1153
1154 private ToneGenerator mToneGenerator;
1155 // We don't rely on getSystemService(Context.VIBRATOR_SERVICE) to make sure this vibrator
1156 // object will be isolated from others.
1157 private Vibrator mEmgVibrator = new SystemVibrator();
1158 private int mInCallVolume;
1159
1160 /**
1161 * constructor
1162 */
1163 public EmergencyTonePlayerVibrator() {
1164 }
1165
1166 /**
1167 * Start the emergency tone or vibrator.
1168 */
1169 private void start() {
1170 if (VDBG) log("call startEmergencyToneOrVibrate.");
1171 int ringerMode = mAudioManager.getRingerMode();
1172
1173 if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) &&
1174 (ringerMode == AudioManager.RINGER_MODE_NORMAL)) {
1175 log("EmergencyTonePlayerVibrator.start(): emergency tone...");
1176 mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL,
1177 InCallTonePlayer.TONE_RELATIVE_VOLUME_EMERGENCY);
1178 if (mToneGenerator != null) {
1179 mInCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
1180 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1181 mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
1182 0);
1183 mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK);
1184 mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT;
1185 }
1186 } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) {
1187 log("EmergencyTonePlayerVibrator.start(): emergency vibrate...");
1188 if (mEmgVibrator != null) {
John Spurlock6ee06d02014-07-18 20:06:20 -04001189 mEmgVibrator.vibrate(mVibratePattern, 0, VIBRATION_ATTRIBUTES);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001190 mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE;
1191 }
1192 }
1193 }
1194
1195 /**
1196 * If the emergency tone is active, stop the tone or vibrator accordingly.
1197 */
1198 private void stop() {
1199 if (VDBG) log("call stopEmergencyToneOrVibrate.");
1200
1201 if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT)
1202 && (mToneGenerator != null)) {
1203 mToneGenerator.stopTone();
1204 mToneGenerator.release();
1205 mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
1206 mInCallVolume,
1207 0);
1208 } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE)
1209 && (mEmgVibrator != null)) {
1210 mEmgVibrator.cancel();
1211 }
1212 mCurrentEmergencyToneState = EMERGENCY_TONE_OFF;
1213 }
1214 }
1215
1216 private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
1217 new BluetoothProfile.ServiceListener() {
1218 public void onServiceConnected(int profile, BluetoothProfile proxy) {
1219 mBluetoothHeadset = (BluetoothHeadset) proxy;
1220 if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
1221 }
1222
1223 public void onServiceDisconnected(int profile) {
1224 mBluetoothHeadset = null;
1225 }
1226 };
1227
1228 private void onRingbackTone(AsyncResult r) {
1229 boolean playTone = (Boolean)(r.result);
1230
1231 if (playTone == true) {
1232 // Only play when foreground call is in DIALING or ALERTING.
1233 // to prevent a late coming playtone after ALERTING.
1234 // Don't play ringback tone if it is in play, otherwise it will cut
1235 // the current tone and replay it
1236 if (mCM.getActiveFgCallState().isDialing() &&
1237 mInCallRingbackTonePlayer == null) {
1238 mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK);
1239 mInCallRingbackTonePlayer.start();
1240 }
1241 } else {
1242 if (mInCallRingbackTonePlayer != null) {
1243 mInCallRingbackTonePlayer.stopTone();
1244 mInCallRingbackTonePlayer = null;
1245 }
1246 }
1247 }
1248
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001249 private void log(String msg) {
1250 Log.d(LOG_TAG, msg);
1251 }
1252}