blob: b9135c8872974cd1f37ce74ca36d1d93ae4e4113 [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 android.app.AlertDialog;
20import android.app.Dialog;
21import android.app.ProgressDialog;
22import android.bluetooth.IBluetoothHeadsetPhone;
23import android.content.ActivityNotFoundException;
Sailesh Nepalbfb68322013-11-07 14:07:41 -080024import android.content.ComponentName;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070025import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070028import android.content.res.Configuration;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070029import android.media.AudioManager;
30import android.net.Uri;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070031import android.os.Handler;
32import android.os.Message;
33import android.os.RemoteException;
34import android.os.SystemProperties;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070035import android.telecom.PhoneAccount;
Andrew Leed5165b02014-12-05 15:53:58 -080036import android.telecom.PhoneAccountHandle;
Tyler Gunn4d45d1c2014-09-12 22:17:53 -070037import android.telecom.VideoProfile;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070038import android.telephony.PhoneNumberUtils;
Nancy Chene53a0642015-03-12 11:20:12 -070039import android.telephony.SubscriptionInfo;
Santos Cordonf69df962015-02-03 11:15:19 -080040import android.telephony.SubscriptionManager;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070041import android.text.TextUtils;
42import android.util.Log;
Andrew Leeb3ee4dc2015-01-23 17:35:00 -080043import android.view.ContextThemeWrapper;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070044import android.view.KeyEvent;
45import android.view.LayoutInflater;
46import android.view.View;
47import android.view.WindowManager;
48import android.widget.EditText;
49import android.widget.Toast;
50
51import com.android.internal.telephony.Call;
52import com.android.internal.telephony.CallManager;
53import com.android.internal.telephony.CallStateException;
54import com.android.internal.telephony.CallerInfo;
55import com.android.internal.telephony.CallerInfoAsyncQuery;
56import com.android.internal.telephony.Connection;
Stuart Scottdcf40a92014-12-09 10:45:01 -080057import com.android.internal.telephony.IccCard;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070058import com.android.internal.telephony.MmiCode;
59import com.android.internal.telephony.Phone;
60import com.android.internal.telephony.PhoneConstants;
Stuart Scottdcf40a92014-12-09 10:45:01 -080061import com.android.internal.telephony.PhoneFactory;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070062import com.android.internal.telephony.TelephonyCapabilities;
63import com.android.internal.telephony.TelephonyProperties;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070064import com.android.internal.telephony.sip.SipPhone;
Santos Cordon80855d52015-02-10 04:33:36 -080065import com.android.internal.telephony.uicc.UiccCard;
Santos Cordon69a69192013-08-22 14:25:42 -070066import com.android.phone.CallGatewayManager.RawGatewayInfo;
Andrew Leed5165b02014-12-05 15:53:58 -080067import com.android.services.telephony.TelephonyConnectionService;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070068
Santos Cordon7d4ddf62013-07-10 11:58:08 -070069import java.util.Arrays;
Santos Cordon7d4ddf62013-07-10 11:58:08 -070070import java.util.List;
71
72/**
73 * Misc utilities for the Phone app.
74 */
75public class PhoneUtils {
76 private static final String LOG_TAG = "PhoneUtils";
77 private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
78
79 // Do not check in with VDBG = true, since that may write PII to the system log.
80 private static final boolean VDBG = false;
81
82 /** Control stack trace for Audio Mode settings */
83 private static final boolean DBG_SETAUDIOMODE_STACK = false;
84
85 /** Identifier for the "Add Call" intent extra. */
86 static final String ADD_CALL_MODE_KEY = "add_call_mode";
87
88 // Return codes from placeCall()
89 static final int CALL_STATUS_DIALED = 0; // The number was successfully dialed
90 static final int CALL_STATUS_DIALED_MMI = 1; // The specified number was an MMI code
91 static final int CALL_STATUS_FAILED = 2; // The call failed
92
93 // State of the Phone's audio modes
94 // Each state can move to the other states, but within the state only certain
95 // transitions for AudioManager.setMode() are allowed.
96 static final int AUDIO_IDLE = 0; /** audio behaviour at phone idle */
97 static final int AUDIO_RINGING = 1; /** audio behaviour while ringing */
98 static final int AUDIO_OFFHOOK = 2; /** audio behaviour while in call. */
99
100 // USSD string length for MMI operations
101 static final int MIN_USSD_LEN = 1;
102 static final int MAX_USSD_LEN = 160;
103
104 /** Speaker state, persisting between wired headset connection events */
105 private static boolean sIsSpeakerEnabled = false;
106
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700107 /** Static handler for the connection/mute tracking */
108 private static ConnectionHandler mConnectionHandler;
109
110 /** Phone state changed event*/
111 private static final int PHONE_STATE_CHANGED = -1;
112
Zhihai Xua4915c72013-10-18 17:01:16 -0700113 /** check status then decide whether answerCall */
114 private static final int MSG_CHECK_STATUS_ANSWERCALL = 100;
115
116 /** poll phone DISCONNECTING status interval */
117 private static final int DISCONNECTING_POLLING_INTERVAL_MS = 200;
118
119 /** poll phone DISCONNECTING status times limit */
120 private static final int DISCONNECTING_POLLING_TIMES_LIMIT = 8;
121
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700122 /** Define for not a special CNAP string */
123 private static final int CNAP_SPECIAL_CASE_NO = -1;
124
125 /** Noise suppression status as selected by user */
126 private static boolean sIsNoiseSuppressionEnabled = true;
127
Yorke Leee0f2b792014-10-15 12:30:44 -0700128 /**
129 * Theme to use for dialogs displayed by utility methods in this class. This is needed
130 * because these dialogs are displayed using the application context, which does not resolve
131 * the dialog theme correctly.
132 */
133 private static final int THEME = AlertDialog.THEME_DEVICE_DEFAULT_LIGHT;
134
Zhihai Xua4915c72013-10-18 17:01:16 -0700135 private static class FgRingCalls {
136 private Call fgCall;
137 private Call ringing;
138 public FgRingCalls(Call fg, Call ring) {
139 fgCall = fg;
140 ringing = ring;
141 }
142 }
143
Etan Cohen37abbab2014-03-07 16:57:03 -0800144 /** USSD information used to aggregate all USSD messages */
145 private static AlertDialog sUssdDialog = null;
146 private static StringBuilder sUssdMsg = new StringBuilder();
147
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700148 /**
149 * Handler that tracks the connections and updates the value of the
150 * Mute settings for each connection as needed.
151 */
152 private static class ConnectionHandler extends Handler {
153 @Override
154 public void handleMessage(Message msg) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700155 switch (msg.what) {
Zhihai Xua4915c72013-10-18 17:01:16 -0700156 case MSG_CHECK_STATUS_ANSWERCALL:
157 FgRingCalls frC = (FgRingCalls) msg.obj;
158 // wait for finishing disconnecting
159 // before check the ringing call state
160 if ((frC.fgCall != null) &&
161 (frC.fgCall.getState() == Call.State.DISCONNECTING) &&
162 (msg.arg1 < DISCONNECTING_POLLING_TIMES_LIMIT)) {
163 Message retryMsg =
164 mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
165 retryMsg.arg1 = 1 + msg.arg1;
166 retryMsg.obj = msg.obj;
167 mConnectionHandler.sendMessageDelayed(retryMsg,
168 DISCONNECTING_POLLING_INTERVAL_MS);
169 // since hangupActiveCall() also accepts the ringing call
170 // check if the ringing call was already answered or not
171 // only answer it when the call still is ringing
172 } else if (frC.ringing.isRinging()) {
173 if (msg.arg1 == DISCONNECTING_POLLING_TIMES_LIMIT) {
174 Log.e(LOG_TAG, "DISCONNECTING time out");
175 }
176 answerCall(frC.ringing);
177 }
178 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700179 }
180 }
181 }
182
183 /**
184 * Register the ConnectionHandler with the phone, to receive connection events
185 */
186 public static void initializeConnectionHandler(CallManager cm) {
187 if (mConnectionHandler == null) {
188 mConnectionHandler = new ConnectionHandler();
189 }
190
191 // pass over cm as user.obj
192 cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
193
194 }
195
196 /** This class is never instantiated. */
197 private PhoneUtils() {
198 }
199
200 /**
201 * Answer the currently-ringing call.
202 *
203 * @return true if we answered the call, or false if there wasn't
204 * actually a ringing incoming call, or some other error occurred.
205 *
206 * @see #answerAndEndHolding(CallManager, Call)
207 * @see #answerAndEndActive(CallManager, Call)
208 */
209 /* package */ static boolean answerCall(Call ringingCall) {
210 log("answerCall(" + ringingCall + ")...");
211 final PhoneGlobals app = PhoneGlobals.getInstance();
212 final CallNotifier notifier = app.notifier;
213
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700214 final Phone phone = ringingCall.getPhone();
215 final boolean phoneIsCdma = (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA);
216 boolean answered = false;
217 IBluetoothHeadsetPhone btPhone = null;
218
219 if (phoneIsCdma) {
220 // Stop any signalInfo tone being played when a Call waiting gets answered
221 if (ringingCall.getState() == Call.State.WAITING) {
222 notifier.stopSignalInfoTone();
223 }
224 }
225
226 if (ringingCall != null && ringingCall.isRinging()) {
227 if (DBG) log("answerCall: call state = " + ringingCall.getState());
228 try {
229 if (phoneIsCdma) {
230 if (app.cdmaPhoneCallState.getCurrentCallState()
231 == CdmaPhoneCallState.PhoneCallState.IDLE) {
232 // This is the FIRST incoming call being answered.
233 // Set the Phone Call State to SINGLE_ACTIVE
234 app.cdmaPhoneCallState.setCurrentCallState(
235 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
236 } else {
237 // This is the CALL WAITING call being answered.
238 // Set the Phone Call State to CONF_CALL
239 app.cdmaPhoneCallState.setCurrentCallState(
240 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
241 // Enable "Add Call" option after answering a Call Waiting as the user
242 // should be allowed to add another call in case one of the parties
243 // drops off
244 app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
Santos Cordon13fed9f2014-09-24 13:10:34 -0700245 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700246 }
247
248 final boolean isRealIncomingCall = isRealIncomingCall(ringingCall.getState());
249
250 //if (DBG) log("sPhone.acceptCall");
251 app.mCM.acceptCall(ringingCall);
252 answered = true;
253
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700254 setAudioMode();
255
256 // Check is phone in any dock, and turn on speaker accordingly
257 final boolean speakerActivated = activateSpeakerIfDocked(phone);
258
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700259 final BluetoothManager btManager = app.getBluetoothManager();
260
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700261 // When answering a phone call, the user will move the phone near to her/his ear
262 // and start conversation, without checking its speaker status. If some other
263 // application turned on the speaker mode before the call and didn't turn it off,
264 // Phone app would need to be responsible for the speaker phone.
265 // Here, we turn off the speaker if
266 // - the phone call is the first in-coming call,
267 // - we did not activate speaker by ourselves during the process above, and
268 // - Bluetooth headset is not in use.
269 if (isRealIncomingCall && !speakerActivated && isSpeakerOn(app)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700270 && !btManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700271 // This is not an error but might cause users' confusion. Add log just in case.
272 Log.i(LOG_TAG, "Forcing speaker off due to new incoming call...");
273 turnOnSpeaker(app, false, true);
274 }
275 } catch (CallStateException ex) {
276 Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
277
278 if (phoneIsCdma) {
279 // restore the cdmaPhoneCallState and btPhone.cdmaSetSecondCallState:
280 app.cdmaPhoneCallState.setCurrentCallState(
281 app.cdmaPhoneCallState.getPreviousCallState());
282 if (btPhone != null) {
283 try {
284 btPhone.cdmaSetSecondCallState(false);
285 } catch (RemoteException e) {
286 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
287 }
288 }
289 }
290 }
291 }
292 return answered;
293 }
294
295 /**
Santos Cordonde10b752013-09-19 04:11:33 -0700296 * Hangs up all active calls.
297 */
298 static void hangupAllCalls(CallManager cm) {
299 final Call ringing = cm.getFirstActiveRingingCall();
300 final Call fg = cm.getActiveFgCall();
301 final Call bg = cm.getFirstActiveBgCall();
302
303 // We go in reverse order, BG->FG->RINGING because hanging up a ringing call or an active
304 // call can move a bg call to a fg call which would force us to loop over each call
305 // several times. This ordering works best to ensure we dont have any more calls.
306 if (bg != null && !bg.isIdle()) {
307 hangup(bg);
308 }
309 if (fg != null && !fg.isIdle()) {
310 hangup(fg);
311 }
312 if (ringing != null && !ringing.isIdle()) {
313 hangupRingingCall(fg);
314 }
315 }
316
317 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700318 * Smart "hang up" helper method which hangs up exactly one connection,
319 * based on the current Phone state, as follows:
320 * <ul>
321 * <li>If there's a ringing call, hang that up.
322 * <li>Else if there's a foreground call, hang that up.
323 * <li>Else if there's a background call, hang that up.
324 * <li>Otherwise do nothing.
325 * </ul>
326 * @return true if we successfully hung up, or false
327 * if there were no active calls at all.
328 */
329 static boolean hangup(CallManager cm) {
330 boolean hungup = false;
331 Call ringing = cm.getFirstActiveRingingCall();
332 Call fg = cm.getActiveFgCall();
333 Call bg = cm.getFirstActiveBgCall();
334
335 if (!ringing.isIdle()) {
336 log("hangup(): hanging up ringing call");
337 hungup = hangupRingingCall(ringing);
338 } else if (!fg.isIdle()) {
339 log("hangup(): hanging up foreground call");
340 hungup = hangup(fg);
341 } else if (!bg.isIdle()) {
342 log("hangup(): hanging up background call");
343 hungup = hangup(bg);
344 } else {
345 // No call to hang up! This is unlikely in normal usage,
346 // since the UI shouldn't be providing an "End call" button in
347 // the first place. (But it *can* happen, rarely, if an
348 // active call happens to disconnect on its own right when the
349 // user is trying to hang up..)
350 log("hangup(): no active call to hang up");
351 }
352 if (DBG) log("==> hungup = " + hungup);
353
354 return hungup;
355 }
356
357 static boolean hangupRingingCall(Call ringing) {
358 if (DBG) log("hangup ringing call");
359 int phoneType = ringing.getPhone().getPhoneType();
360 Call.State state = ringing.getState();
361
362 if (state == Call.State.INCOMING) {
363 // Regular incoming call (with no other active calls)
364 log("hangupRingingCall(): regular incoming call: hangup()");
365 return hangup(ringing);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700366 } else {
367 // Unexpected state: the ringing call isn't INCOMING or
368 // WAITING, so there's no reason to have called
369 // hangupRingingCall() in the first place.
370 // (Presumably the incoming call went away at the exact moment
371 // we got here, so just do nothing.)
372 Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
373 return false;
374 }
375 }
376
377 static boolean hangupActiveCall(Call foreground) {
378 if (DBG) log("hangup active call");
379 return hangup(foreground);
380 }
381
382 static boolean hangupHoldingCall(Call background) {
383 if (DBG) log("hangup holding call");
384 return hangup(background);
385 }
386
387 /**
388 * Used in CDMA phones to end the complete Call session
389 * @param phone the Phone object.
390 * @return true if *any* call was successfully hung up
391 */
392 static boolean hangupRingingAndActive(Phone phone) {
393 boolean hungUpRingingCall = false;
394 boolean hungUpFgCall = false;
395 Call ringingCall = phone.getRingingCall();
396 Call fgCall = phone.getForegroundCall();
397
398 // Hang up any Ringing Call
399 if (!ringingCall.isIdle()) {
400 log("hangupRingingAndActive: Hang up Ringing Call");
401 hungUpRingingCall = hangupRingingCall(ringingCall);
402 }
403
404 // Hang up any Active Call
405 if (!fgCall.isIdle()) {
406 log("hangupRingingAndActive: Hang up Foreground Call");
407 hungUpFgCall = hangupActiveCall(fgCall);
408 }
409
410 return hungUpRingingCall || hungUpFgCall;
411 }
412
413 /**
414 * Trivial wrapper around Call.hangup(), except that we return a
415 * boolean success code rather than throwing CallStateException on
416 * failure.
417 *
418 * @return true if the call was successfully hung up, or false
419 * if the call wasn't actually active.
420 */
421 static boolean hangup(Call call) {
422 try {
423 CallManager cm = PhoneGlobals.getInstance().mCM;
424
425 if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
426 // handle foreground call hangup while there is background call
427 log("- hangup(Call): hangupForegroundResumeBackground...");
428 cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
429 } else {
430 log("- hangup(Call): regular hangup()...");
431 call.hangup();
432 }
433 return true;
434 } catch (CallStateException ex) {
435 Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
436 }
437
438 return false;
439 }
440
441 /**
442 * Trivial wrapper around Connection.hangup(), except that we silently
443 * do nothing (rather than throwing CallStateException) if the
444 * connection wasn't actually active.
445 */
446 static void hangup(Connection c) {
447 try {
448 if (c != null) {
449 c.hangup();
450 }
451 } catch (CallStateException ex) {
452 Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
453 }
454 }
455
456 static boolean answerAndEndHolding(CallManager cm, Call ringing) {
457 if (DBG) log("end holding & answer waiting: 1");
458 if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
459 Log.e(LOG_TAG, "end holding failed!");
460 return false;
461 }
462
463 if (DBG) log("end holding & answer waiting: 2");
464 return answerCall(ringing);
465
466 }
467
468 /**
469 * Answers the incoming call specified by "ringing", and ends the currently active phone call.
470 *
471 * This method is useful when's there's an incoming call which we cannot manage with the
472 * current call. e.g. when you are having a phone call with CDMA network and has received
473 * a SIP call, then we won't expect our telephony can manage those phone calls simultaneously.
474 * Note that some types of network may allow multiple phone calls at once; GSM allows to hold
475 * an ongoing phone call, so we don't need to end the active call. The caller of this method
476 * needs to check if the network allows multiple phone calls or not.
477 *
478 * @see #answerCall(Call)
479 * @see InCallScreen#internalAnswerCall()
480 */
481 /* package */ static boolean answerAndEndActive(CallManager cm, Call ringing) {
482 if (DBG) log("answerAndEndActive()...");
483
484 // Unlike the answerCall() method, we *don't* need to stop the
485 // ringer or change audio modes here since the user is already
486 // in-call, which means that the audio mode is already set
487 // correctly, and that we wouldn't have started the ringer in the
488 // first place.
489
490 // hanging up the active call also accepts the waiting call
491 // while active call and waiting call are from the same phone
492 // i.e. both from GSM phone
Zhihai Xua4915c72013-10-18 17:01:16 -0700493 Call fgCall = cm.getActiveFgCall();
494 if (!hangupActiveCall(fgCall)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700495 Log.w(LOG_TAG, "end active call failed!");
496 return false;
497 }
498
Zhihai Xua4915c72013-10-18 17:01:16 -0700499 mConnectionHandler.removeMessages(MSG_CHECK_STATUS_ANSWERCALL);
500 Message msg = mConnectionHandler.obtainMessage(MSG_CHECK_STATUS_ANSWERCALL);
501 msg.arg1 = 1;
502 msg.obj = new FgRingCalls(fgCall, ringing);
503 mConnectionHandler.sendMessage(msg);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700504
505 return true;
506 }
507
508 /**
509 * For a CDMA phone, advance the call state upon making a new
510 * outgoing call.
511 *
512 * <pre>
513 * IDLE -> SINGLE_ACTIVE
514 * or
515 * SINGLE_ACTIVE -> THRWAY_ACTIVE
516 * </pre>
517 * @param app The phone instance.
518 */
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700519 private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
520 Connection connection) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700521 if (app.cdmaPhoneCallState.getCurrentCallState() ==
522 CdmaPhoneCallState.PhoneCallState.IDLE) {
523 // This is the first outgoing call. Set the Phone Call State to ACTIVE
524 app.cdmaPhoneCallState.setCurrentCallState(
525 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
526 } else {
527 // This is the second outgoing call. Set the Phone Call State to 3WAY
528 app.cdmaPhoneCallState.setCurrentCallState(
529 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700530
Santos Cordonda120f42014-08-06 04:44:34 -0700531 // TODO: Remove this code.
Sailesh Nepal23d9ed72014-07-03 09:40:26 -0700532 //app.getCallModeler().setCdmaOutgoing3WayCall(connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700533 }
534 }
535
536 /**
Santos Cordon69a69192013-08-22 14:25:42 -0700537 * @see placeCall below
538 */
539 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
540 boolean isEmergencyCall) {
541 return placeCall(context, phone, number, contactRef, isEmergencyCall,
542 CallGatewayManager.EMPTY_INFO, null);
543 }
544
545 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700546 * Dial the number using the phone passed in.
547 *
548 * If the connection is establised, this method issues a sync call
549 * that may block to query the caller info.
550 * TODO: Change the logic to use the async query.
551 *
552 * @param context To perform the CallerInfo query.
553 * @param phone the Phone object.
554 * @param number to be dialed as requested by the user. This is
555 * NOT the phone number to connect to. It is used only to build the
556 * call card and to update the call log. See above for restrictions.
557 * @param contactRef that triggered the call. Typically a 'tel:'
558 * uri but can also be a 'content://contacts' one.
559 * @param isEmergencyCall indicates that whether or not this is an
560 * emergency call
561 * @param gatewayUri Is the address used to setup the connection, null
562 * if not using a gateway
Santos Cordon69a69192013-08-22 14:25:42 -0700563 * @param callGateway Class for setting gateway data on a successful call.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700564 *
565 * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
566 */
Santos Cordon69a69192013-08-22 14:25:42 -0700567 public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
568 boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
569 final Uri gatewayUri = gatewayInfo.gatewayUri;
570
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700571 if (VDBG) {
572 log("placeCall()... number: '" + number + "'"
573 + ", GW:'" + gatewayUri + "'"
574 + ", contactRef:" + contactRef
575 + ", isEmergencyCall: " + isEmergencyCall);
576 } else {
577 log("placeCall()... number: " + toLogSafePhoneNumber(number)
578 + ", GW: " + (gatewayUri != null ? "non-null" : "null")
579 + ", emergency? " + isEmergencyCall);
580 }
581 final PhoneGlobals app = PhoneGlobals.getInstance();
582
583 boolean useGateway = false;
584 if (null != gatewayUri &&
585 !isEmergencyCall &&
586 PhoneUtils.isRoutableViaGateway(number)) { // Filter out MMI, OTA and other codes.
587 useGateway = true;
588 }
589
590 int status = CALL_STATUS_DIALED;
591 Connection connection;
592 String numberToDial;
593 if (useGateway) {
594 // TODO: 'tel' should be a constant defined in framework base
595 // somewhere (it is in webkit.)
Jay Shrauner137458b2014-09-05 14:27:25 -0700596 if (null == gatewayUri || !PhoneAccount.SCHEME_TEL.equals(gatewayUri.getScheme())) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700597 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
598 return CALL_STATUS_FAILED;
599 }
600
601 // We can use getSchemeSpecificPart because we don't allow #
602 // in the gateway numbers (treated a fragment delim.) However
603 // if we allow more complex gateway numbers sequence (with
604 // passwords or whatnot) that use #, this may break.
605 // TODO: Need to support MMI codes.
606 numberToDial = gatewayUri.getSchemeSpecificPart();
607 } else {
608 numberToDial = number;
609 }
610
611 // Remember if the phone state was in IDLE state before this call.
612 // After calling CallManager#dial(), getState() will return different state.
613 final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
614
615 try {
Ihab Awad76f3b4e2014-08-07 19:49:18 -0700616 connection = app.mCM.dial(phone, numberToDial, VideoProfile.VideoState.AUDIO_ONLY);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700617 } catch (CallStateException ex) {
618 // CallStateException means a new outgoing call is not currently
619 // possible: either no more call slots exist, or there's another
620 // call already in the process of dialing or ringing.
621 Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
622 return CALL_STATUS_FAILED;
623
624 // Note that it's possible for CallManager.dial() to return
625 // null *without* throwing an exception; that indicates that
626 // we dialed an MMI (see below).
627 }
628
629 int phoneType = phone.getPhoneType();
630
631 // On GSM phones, null is returned for MMI codes
632 if (null == connection) {
Santos Cordonf77a3392014-07-21 19:48:10 -0700633 status = CALL_STATUS_FAILED;
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700634 } else {
Tyler Gunn10f1c6a2014-01-17 12:01:11 -0800635 // Now that the call is successful, we can save the gateway info for the call
636 if (callGateway != null) {
637 callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
638 }
639
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700640 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
Santos Cordonad1ed6d2013-09-16 03:04:23 -0700641 updateCdmaCallStateOnNewOutgoingCall(app, connection);
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700642 }
643
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700644 if (gatewayUri == null) {
645 // phone.dial() succeeded: we're now in a normal phone call.
646 // attach the URI to the CallerInfo Object if it is there,
647 // otherwise just attach the Uri Reference.
648 // if the uri does not have a "content" scheme, then we treat
649 // it as if it does NOT have a unique reference.
650 String content = context.getContentResolver().SCHEME_CONTENT;
651 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
652 Object userDataObject = connection.getUserData();
653 if (userDataObject == null) {
654 connection.setUserData(contactRef);
655 } else {
656 // TODO: This branch is dead code, we have
657 // just created the connection which has
658 // no user data (null) by default.
659 if (userDataObject instanceof CallerInfo) {
660 ((CallerInfo) userDataObject).contactRefUri = contactRef;
661 } else {
662 ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
663 contactRef;
664 }
665 }
666 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700667 }
Santos Cordonc264cba2013-09-19 04:55:40 -0700668
Chiao Chenge365ba72013-09-26 14:18:12 -0700669 startGetCallerInfo(context, connection, null, null, gatewayInfo);
670
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700671 setAudioMode();
672
673 if (DBG) log("about to activate speaker");
674 // Check is phone in any dock, and turn on speaker accordingly
675 final boolean speakerActivated = activateSpeakerIfDocked(phone);
676
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700677 final BluetoothManager btManager = app.getBluetoothManager();
678
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700679 // See also similar logic in answerCall().
680 if (initiallyIdle && !speakerActivated && isSpeakerOn(app)
Santos Cordon27a3c1f2013-08-06 07:49:27 -0700681 && !btManager.isBluetoothHeadsetAudioOn()) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700682 // This is not an error but might cause users' confusion. Add log just in case.
683 Log.i(LOG_TAG, "Forcing speaker off when initiating a new outgoing call...");
684 PhoneUtils.turnOnSpeaker(app, false, true);
685 }
686 }
687
688 return status;
689 }
690
691 /* package */ static String toLogSafePhoneNumber(String number) {
692 // For unknown number, log empty string.
693 if (number == null) {
694 return "";
695 }
696
697 if (VDBG) {
698 // When VDBG is true we emit PII.
699 return number;
700 }
701
702 // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
703 // sanitized phone numbers.
704 StringBuilder builder = new StringBuilder();
705 for (int i = 0; i < number.length(); i++) {
706 char c = number.charAt(i);
707 if (c == '-' || c == '@' || c == '.') {
708 builder.append(c);
709 } else {
710 builder.append('x');
711 }
712 }
713 return builder.toString();
714 }
715
716 /**
717 * Wrapper function to control when to send an empty Flash command to the network.
718 * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
719 * to the network prior to placing a 3-way call for it to be successful.
720 */
721 static void sendEmptyFlash(Phone phone) {
722 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
723 Call fgCall = phone.getForegroundCall();
724 if (fgCall.getState() == Call.State.ACTIVE) {
725 // Send the empty flash
726 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
727 switchHoldingAndActive(phone.getBackgroundCall());
728 }
729 }
730 }
731
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700732 static void swap() {
733 final PhoneGlobals mApp = PhoneGlobals.getInstance();
734 if (!okToSwapCalls(mApp.mCM)) {
735 // TODO: throw an error instead?
736 return;
737 }
738
739 // Swap the fg and bg calls.
740 // In the future we may provide some way for user to choose among
741 // multiple background calls, for now, always act on the first background call.
742 PhoneUtils.switchHoldingAndActive(mApp.mCM.getFirstActiveBgCall());
Gabriel Peal36ebb0d2014-03-20 09:20:43 -0700743 }
744
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700745 /**
746 * @param heldCall is the background call want to be swapped
747 */
748 static void switchHoldingAndActive(Call heldCall) {
749 log("switchHoldingAndActive()...");
750 try {
751 CallManager cm = PhoneGlobals.getInstance().mCM;
752 if (heldCall.isIdle()) {
753 // no heldCall, so it is to hold active call
754 cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
755 } else {
756 // has particular heldCall, so to switch
757 cm.switchHoldingAndActive(heldCall);
758 }
759 setAudioMode(cm);
760 } catch (CallStateException ex) {
761 Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
762 }
763 }
764
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700765 static void mergeCalls() {
766 mergeCalls(PhoneGlobals.getInstance().mCM);
767 }
768
769 static void mergeCalls(CallManager cm) {
770 int phoneType = cm.getFgPhone().getPhoneType();
771 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
772 log("mergeCalls(): CDMA...");
773 PhoneGlobals app = PhoneGlobals.getInstance();
774 if (app.cdmaPhoneCallState.getCurrentCallState()
775 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
776 // Set the Phone Call State to conference
777 app.cdmaPhoneCallState.setCurrentCallState(
778 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
779
780 // Send flash cmd
781 // TODO: Need to change the call from switchHoldingAndActive to
782 // something meaningful as we are not actually trying to swap calls but
783 // instead are merging two calls by sending a Flash command.
784 log("- sending flash...");
785 switchHoldingAndActive(cm.getFirstActiveBgCall());
786 }
787 } else {
788 try {
789 log("mergeCalls(): calling cm.conference()...");
790 cm.conference(cm.getFirstActiveBgCall());
791 } catch (CallStateException ex) {
792 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
793 }
794 }
795 }
796
797 static void separateCall(Connection c) {
798 try {
799 if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
800 c.separate();
801 } catch (CallStateException ex) {
802 Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
803 }
804 }
805
806 /**
807 * Handle the MMIInitiate message and put up an alert that lets
808 * the user cancel the operation, if applicable.
809 *
810 * @param context context to get strings.
811 * @param mmiCode the MmiCode object being started.
812 * @param buttonCallbackMessage message to post when button is clicked.
813 * @param previousAlert a previous alert used in this activity.
814 * @return the dialog handle
815 */
816 static Dialog displayMMIInitiate(Context context,
817 MmiCode mmiCode,
818 Message buttonCallbackMessage,
819 Dialog previousAlert) {
820 if (DBG) log("displayMMIInitiate: " + mmiCode);
821 if (previousAlert != null) {
822 previousAlert.dismiss();
823 }
824
825 // The UI paradigm we are using now requests that all dialogs have
826 // user interaction, and that any other messages to the user should
827 // be by way of Toasts.
828 //
829 // In adhering to this request, all MMI initiating "OK" dialogs
830 // (non-cancelable MMIs) that end up being closed when the MMI
831 // completes (thereby showing a completion dialog) are being
832 // replaced with Toasts.
833 //
834 // As a side effect, moving to Toasts for the non-cancelable MMIs
835 // also means that buttonCallbackMessage (which was tied into "OK")
836 // is no longer invokable for these dialogs. This is not a problem
837 // since the only callback messages we supported were for cancelable
838 // MMIs anyway.
839 //
840 // A cancelable MMI is really just a USSD request. The term
841 // "cancelable" here means that we can cancel the request when the
842 // system prompts us for a response, NOT while the network is
843 // processing the MMI request. Any request to cancel a USSD while
844 // the network is NOT ready for a response may be ignored.
845 //
846 // With this in mind, we replace the cancelable alert dialog with
847 // a progress dialog, displayed until we receive a request from
848 // the the network. For more information, please see the comments
849 // in the displayMMIComplete() method below.
850 //
851 // Anything that is NOT a USSD request is a normal MMI request,
852 // which will bring up a toast (desribed above).
853
854 boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
855
856 if (!isCancelable) {
857 if (DBG) log("not a USSD code, displaying status toast.");
858 CharSequence text = context.getText(R.string.mmiStarted);
859 Toast.makeText(context, text, Toast.LENGTH_SHORT)
860 .show();
861 return null;
862 } else {
863 if (DBG) log("running USSD code, displaying indeterminate progress.");
864
865 // create the indeterminate progress dialog and display it.
866 ProgressDialog pd = new ProgressDialog(context);
867 pd.setMessage(context.getText(R.string.ussdRunning));
868 pd.setCancelable(false);
869 pd.setIndeterminate(true);
870 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
871
872 pd.show();
873
874 return pd;
875 }
876
877 }
878
879 /**
880 * Handle the MMIComplete message and fire off an intent to display
881 * the message.
882 *
883 * @param context context to get strings.
884 * @param mmiCode MMI result.
885 * @param previousAlert a previous alert used in this activity.
886 */
887 static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
888 Message dismissCallbackMessage,
889 AlertDialog previousAlert) {
890 final PhoneGlobals app = PhoneGlobals.getInstance();
891 CharSequence text;
892 int title = 0; // title for the progress dialog, if needed.
893 MmiCode.State state = mmiCode.getState();
894
895 if (DBG) log("displayMMIComplete: state=" + state);
896
897 switch (state) {
898 case PENDING:
899 // USSD code asking for feedback from user.
900 text = mmiCode.getMessage();
901 if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
902 break;
903 case CANCELLED:
904 text = null;
905 break;
906 case COMPLETE:
907 if (app.getPUKEntryActivity() != null) {
908 // if an attempt to unPUK the device was made, we specify
909 // the title and the message here.
910 title = com.android.internal.R.string.PinMmi;
911 text = context.getText(R.string.puk_unlocked);
912 break;
913 }
914 // All other conditions for the COMPLETE mmi state will cause
915 // the case to fall through to message logic in common with
916 // the FAILED case.
917
918 case FAILED:
919 text = mmiCode.getMessage();
920 if (DBG) log("- using text from MMI message: '" + text + "'");
921 break;
922 default:
923 throw new IllegalStateException("Unexpected MmiCode state: " + state);
924 }
925
926 if (previousAlert != null) {
927 previousAlert.dismiss();
928 }
929
930 // Check to see if a UI exists for the PUK activation. If it does
931 // exist, then it indicates that we're trying to unblock the PUK.
932 if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
933 if (DBG) log("displaying PUK unblocking progress dialog.");
934
935 // create the progress dialog, make sure the flags and type are
936 // set correctly.
937 ProgressDialog pd = new ProgressDialog(app);
938 pd.setTitle(title);
939 pd.setMessage(text);
940 pd.setCancelable(false);
941 pd.setIndeterminate(true);
942 pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
943 pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
944
945 // display the dialog
946 pd.show();
947
948 // indicate to the Phone app that the progress dialog has
949 // been assigned for the PUK unlock / SIM READY process.
950 app.setPukEntryProgressDialog(pd);
951
952 } else {
953 // In case of failure to unlock, we'll need to reset the
954 // PUK unlock activity, so that the user may try again.
955 if (app.getPUKEntryActivity() != null) {
956 app.setPukEntryActivity(null);
957 }
958
959 // A USSD in a pending state means that it is still
960 // interacting with the user.
961 if (state != MmiCode.State.PENDING) {
962 if (DBG) log("MMI code has finished running.");
963
964 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
965 if (text == null || text.length() == 0)
966 return;
967
968 // displaying system alert dialog on the screen instead of
969 // using another activity to display the message. This
970 // places the message at the forefront of the UI.
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700971
Etan Cohen37abbab2014-03-07 16:57:03 -0800972 if (sUssdDialog == null) {
Yorke Leee0f2b792014-10-15 12:30:44 -0700973 sUssdDialog = new AlertDialog.Builder(context, THEME)
Etan Cohen37abbab2014-03-07 16:57:03 -0800974 .setPositiveButton(R.string.ok, null)
975 .setCancelable(true)
976 .setOnDismissListener(new DialogInterface.OnDismissListener() {
977 @Override
978 public void onDismiss(DialogInterface dialog) {
979 sUssdMsg.setLength(0);
980 }
981 })
982 .create();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700983
Etan Cohen37abbab2014-03-07 16:57:03 -0800984 sUssdDialog.getWindow().setType(
Wenlu Wue8e05712015-03-06 14:20:18 +0100985 WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
Etan Cohen37abbab2014-03-07 16:57:03 -0800986 sUssdDialog.getWindow().addFlags(
987 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
988 }
989 if (sUssdMsg.length() != 0) {
990 sUssdMsg
991 .insert(0, "\n")
992 .insert(0, app.getResources().getString(R.string.ussd_dialog_sep))
993 .insert(0, "\n");
994 }
995 sUssdMsg.insert(0, text);
996 sUssdDialog.setMessage(sUssdMsg.toString());
997 sUssdDialog.show();
Santos Cordon7d4ddf62013-07-10 11:58:08 -0700998 } else {
999 if (DBG) log("USSD code has requested user input. Constructing input dialog.");
1000
1001 // USSD MMI code that is interacting with the user. The
1002 // basic set of steps is this:
1003 // 1. User enters a USSD request
1004 // 2. We recognize the request and displayMMIInitiate
1005 // (above) creates a progress dialog.
1006 // 3. Request returns and we get a PENDING or COMPLETE
1007 // message.
1008 // 4. These MMI messages are caught in the PhoneApp
1009 // (onMMIComplete) and the InCallScreen
1010 // (mHandler.handleMessage) which bring up this dialog
1011 // and closes the original progress dialog,
1012 // respectively.
1013 // 5. If the message is anything other than PENDING,
1014 // we are done, and the alert dialog (directly above)
1015 // displays the outcome.
1016 // 6. If the network is requesting more information from
1017 // the user, the MMI will be in a PENDING state, and
1018 // we display this dialog with the message.
1019 // 7. User input, or cancel requests result in a return
1020 // to step 1. Keep in mind that this is the only
1021 // time that a USSD should be canceled.
1022
1023 // inflate the layout with the scrolling text area for the dialog.
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001024 ContextThemeWrapper contextThemeWrapper =
1025 new ContextThemeWrapper(context, R.style.DialerAlertDialogTheme);
1026 LayoutInflater inflater = (LayoutInflater) contextThemeWrapper.getSystemService(
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001027 Context.LAYOUT_INFLATER_SERVICE);
1028 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
1029
1030 // get the input field.
1031 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
1032
1033 // specify the dialog's click listener, with SEND and CANCEL logic.
1034 final DialogInterface.OnClickListener mUSSDDialogListener =
1035 new DialogInterface.OnClickListener() {
1036 public void onClick(DialogInterface dialog, int whichButton) {
1037 switch (whichButton) {
1038 case DialogInterface.BUTTON_POSITIVE:
1039 // As per spec 24.080, valid length of ussd string
1040 // is 1 - 160. If length is out of the range then
1041 // display toast message & Cancel MMI operation.
1042 if (inputText.length() < MIN_USSD_LEN
1043 || inputText.length() > MAX_USSD_LEN) {
1044 Toast.makeText(app,
1045 app.getResources().getString(R.string.enter_input,
1046 MIN_USSD_LEN, MAX_USSD_LEN),
1047 Toast.LENGTH_LONG).show();
1048 if (mmiCode.isCancelable()) {
1049 mmiCode.cancel();
1050 }
1051 } else {
1052 phone.sendUssdResponse(inputText.getText().toString());
1053 }
1054 break;
1055 case DialogInterface.BUTTON_NEGATIVE:
1056 if (mmiCode.isCancelable()) {
1057 mmiCode.cancel();
1058 }
1059 break;
1060 }
1061 }
1062 };
1063
1064 // build the dialog
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001065 final AlertDialog newDialog = new AlertDialog.Builder(contextThemeWrapper)
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001066 .setMessage(text)
1067 .setView(dialogView)
1068 .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1069 .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1070 .setCancelable(false)
1071 .create();
1072
1073 // attach the key listener to the dialog's input field and make
1074 // sure focus is set.
1075 final View.OnKeyListener mUSSDDialogInputListener =
1076 new View.OnKeyListener() {
1077 public boolean onKey(View v, int keyCode, KeyEvent event) {
1078 switch (keyCode) {
1079 case KeyEvent.KEYCODE_CALL:
1080 case KeyEvent.KEYCODE_ENTER:
1081 if(event.getAction() == KeyEvent.ACTION_DOWN) {
1082 phone.sendUssdResponse(inputText.getText().toString());
1083 newDialog.dismiss();
1084 }
1085 return true;
1086 }
1087 return false;
1088 }
1089 };
1090 inputText.setOnKeyListener(mUSSDDialogInputListener);
1091 inputText.requestFocus();
1092
1093 // set the window properties of the dialog
1094 newDialog.getWindow().setType(
1095 WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1096 newDialog.getWindow().addFlags(
1097 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1098
1099 // now show the dialog!
1100 newDialog.show();
Andrew Leeb3ee4dc2015-01-23 17:35:00 -08001101
1102 newDialog.getButton(DialogInterface.BUTTON_POSITIVE)
1103 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
1104 newDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
1105 .setTextColor(context.getResources().getColor(R.color.dialer_theme_color));
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001106 }
1107 }
1108 }
1109
1110 /**
1111 * Cancels the current pending MMI operation, if applicable.
1112 * @return true if we canceled an MMI operation, or false
1113 * if the current pending MMI wasn't cancelable
1114 * or if there was no current pending MMI at all.
1115 *
1116 * @see displayMMIInitiate
1117 */
1118 static boolean cancelMmiCode(Phone phone) {
1119 List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1120 int count = pendingMmis.size();
1121 if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1122
1123 boolean canceled = false;
1124 if (count > 0) {
1125 // assume that we only have one pending MMI operation active at a time.
1126 // I don't think it's possible to enter multiple MMI codes concurrently
1127 // in the phone UI, because during the MMI operation, an Alert panel
1128 // is displayed, which prevents more MMI code from being entered.
1129 MmiCode mmiCode = pendingMmis.get(0);
1130 if (mmiCode.isCancelable()) {
1131 mmiCode.cancel();
1132 canceled = true;
1133 }
1134 }
1135 return canceled;
1136 }
1137
1138 public static class VoiceMailNumberMissingException extends Exception {
1139 VoiceMailNumberMissingException() {
1140 super();
1141 }
1142
1143 VoiceMailNumberMissingException(String msg) {
1144 super(msg);
1145 }
1146 }
1147
1148 /**
1149 * Given an Intent (which is presumably the ACTION_CALL intent that
1150 * initiated this outgoing call), figure out the actual phone number we
1151 * should dial.
1152 *
1153 * Note that the returned "number" may actually be a SIP address,
1154 * if the specified intent contains a sip: URI.
1155 *
1156 * This method is basically a wrapper around PhoneUtils.getNumberFromIntent(),
1157 * except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra.
1158 * (That extra, if present, tells us the exact string to pass down to the
1159 * telephony layer. It's guaranteed to be safe to dial: it's either a PSTN
1160 * phone number with separators and keypad letters stripped out, or a raw
1161 * unencoded SIP address.)
1162 *
1163 * @return the phone number corresponding to the specified Intent, or null
1164 * if the Intent has no action or if the intent's data is malformed or
1165 * missing.
1166 *
1167 * @throws VoiceMailNumberMissingException if the intent
1168 * contains a "voicemail" URI, but there's no voicemail
1169 * number configured on the device.
1170 */
1171 public static String getInitialNumber(Intent intent)
1172 throws PhoneUtils.VoiceMailNumberMissingException {
1173 if (DBG) log("getInitialNumber(): " + intent);
1174
1175 String action = intent.getAction();
1176 if (TextUtils.isEmpty(action)) {
1177 return null;
1178 }
1179
1180 // If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone
1181 // number from there. (That extra takes precedence over the actual data
1182 // included in the intent.)
1183 if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) {
1184 String actualNumberToDial =
1185 intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL);
1186 if (DBG) {
1187 log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '"
1188 + toLogSafePhoneNumber(actualNumberToDial) + "'");
1189 }
1190 return actualNumberToDial;
1191 }
1192
1193 return getNumberFromIntent(PhoneGlobals.getInstance(), intent);
1194 }
1195
1196 /**
1197 * Gets the phone number to be called from an intent. Requires a Context
1198 * to access the contacts database, and a Phone to access the voicemail
1199 * number.
1200 *
1201 * <p>If <code>phone</code> is <code>null</code>, the function will return
1202 * <code>null</code> for <code>voicemail:</code> URIs;
1203 * if <code>context</code> is <code>null</code>, the function will return
1204 * <code>null</code> for person/phone URIs.</p>
1205 *
1206 * <p>If the intent contains a <code>sip:</code> URI, the returned
1207 * "number" is actually the SIP address.
1208 *
1209 * @param context a context to use (or
1210 * @param intent the intent
1211 *
1212 * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1213 * a <code>voicemail:</code> URI, but <code>phone</code> does not
1214 * have a voicemail number set.
1215 *
1216 * @return the phone number (or SIP address) that would be called by the intent,
1217 * or <code>null</code> if the number cannot be found.
1218 */
1219 private static String getNumberFromIntent(Context context, Intent intent)
1220 throws VoiceMailNumberMissingException {
1221 Uri uri = intent.getData();
1222 String scheme = uri.getScheme();
1223
1224 // The sip: scheme is simple: just treat the rest of the URI as a
1225 // SIP address.
Jay Shrauner137458b2014-09-05 14:27:25 -07001226 if (PhoneAccount.SCHEME_SIP.equals(scheme)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001227 return uri.getSchemeSpecificPart();
1228 }
1229
1230 // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1231 // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1232
1233 final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1234
1235 // Check for a voicemail-dialing request. If the voicemail number is
1236 // empty, throw a VoiceMailNumberMissingException.
Jay Shrauner137458b2014-09-05 14:27:25 -07001237 if (PhoneAccount.SCHEME_VOICEMAIL.equals(scheme) &&
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001238 (number == null || TextUtils.isEmpty(number)))
1239 throw new VoiceMailNumberMissingException();
1240
1241 return number;
1242 }
1243
1244 /**
1245 * Returns the caller-id info corresponding to the specified Connection.
1246 * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1247 * extract a phone number from the specified Connection, and feed that
1248 * number into CallerInfo.getCallerInfo().)
1249 *
1250 * The returned CallerInfo may be null in certain error cases, like if the
1251 * specified Connection was null, or if we weren't able to get a valid
1252 * phone number from the Connection.
1253 *
1254 * Finally, if the getCallerInfo() call did succeed, we save the resulting
1255 * CallerInfo object in the "userData" field of the Connection.
1256 *
1257 * NOTE: This API should be avoided, with preference given to the
1258 * asynchronous startGetCallerInfo API.
1259 */
1260 static CallerInfo getCallerInfo(Context context, Connection c) {
1261 CallerInfo info = null;
1262
1263 if (c != null) {
1264 //See if there is a URI attached. If there is, this means
1265 //that there is no CallerInfo queried yet, so we'll need to
1266 //replace the URI with a full CallerInfo object.
1267 Object userDataObject = c.getUserData();
1268 if (userDataObject instanceof Uri) {
1269 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1270 if (info != null) {
1271 c.setUserData(info);
1272 }
1273 } else {
1274 if (userDataObject instanceof CallerInfoToken) {
1275 //temporary result, while query is running
1276 info = ((CallerInfoToken) userDataObject).currentInfo;
1277 } else {
1278 //final query result
1279 info = (CallerInfo) userDataObject;
1280 }
1281 if (info == null) {
1282 // No URI, or Existing CallerInfo, so we'll have to make do with
1283 // querying a new CallerInfo using the connection's phone number.
1284 String number = c.getAddress();
1285
1286 if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
1287
1288 if (!TextUtils.isEmpty(number)) {
1289 info = CallerInfo.getCallerInfo(context, number);
1290 if (info != null) {
1291 c.setUserData(info);
1292 }
1293 }
1294 }
1295 }
1296 }
1297 return info;
1298 }
1299
1300 /**
1301 * Class returned by the startGetCallerInfo call to package a temporary
1302 * CallerInfo Object, to be superceded by the CallerInfo Object passed
1303 * into the listener when the query with token mAsyncQueryToken is complete.
1304 */
1305 public static class CallerInfoToken {
1306 /**indicates that there will no longer be updates to this request.*/
1307 public boolean isFinal;
1308
1309 public CallerInfo currentInfo;
1310 public CallerInfoAsyncQuery asyncQuery;
1311 }
1312
1313 /**
1314 * Start a CallerInfo Query based on the earliest connection in the call.
1315 */
1316 static CallerInfoToken startGetCallerInfo(Context context, Call call,
1317 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1318 Connection conn = null;
1319 int phoneType = call.getPhone().getPhoneType();
1320 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1321 conn = call.getLatestConnection();
1322 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001323 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07001324 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001325 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001326 conn = call.getEarliestConnection();
1327 } else {
1328 throw new IllegalStateException("Unexpected phone type: " + phoneType);
1329 }
1330
1331 return startGetCallerInfo(context, conn, listener, cookie);
1332 }
1333
Chiao Chenge365ba72013-09-26 14:18:12 -07001334 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1335 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1336 return startGetCallerInfo(context, c, listener, cookie, null);
1337 }
1338
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001339 /**
1340 * place a temporary callerinfo object in the hands of the caller and notify
1341 * caller when the actual query is done.
1342 */
1343 static CallerInfoToken startGetCallerInfo(Context context, Connection c,
Chiao Chenge365ba72013-09-26 14:18:12 -07001344 CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
1345 RawGatewayInfo info) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001346 CallerInfoToken cit;
1347
1348 if (c == null) {
1349 //TODO: perhaps throw an exception here.
1350 cit = new CallerInfoToken();
1351 cit.asyncQuery = null;
1352 return cit;
1353 }
1354
1355 Object userDataObject = c.getUserData();
1356
1357 // There are now 3 states for the Connection's userData object:
1358 //
1359 // (1) Uri - query has not been executed yet
1360 //
1361 // (2) CallerInfoToken - query is executing, but has not completed.
1362 //
1363 // (3) CallerInfo - query has executed.
1364 //
1365 // In each case we have slightly different behaviour:
1366 // 1. If the query has not been executed yet (Uri or null), we start
1367 // query execution asynchronously, and note it by attaching a
1368 // CallerInfoToken as the userData.
1369 // 2. If the query is executing (CallerInfoToken), we've essentially
1370 // reached a state where we've received multiple requests for the
1371 // same callerInfo. That means that once the query is complete,
1372 // we'll need to execute the additional listener requested.
1373 // 3. If the query has already been executed (CallerInfo), we just
1374 // return the CallerInfo object as expected.
1375 // 4. Regarding isFinal - there are cases where the CallerInfo object
1376 // will not be attached, like when the number is empty (caller id
1377 // blocking). This flag is used to indicate that the
1378 // CallerInfoToken object is going to be permanent since no
1379 // query results will be returned. In the case where a query
1380 // has been completed, this flag is used to indicate to the caller
1381 // that the data will not be updated since it is valid.
1382 //
1383 // Note: For the case where a number is NOT retrievable, we leave
1384 // the CallerInfo as null in the CallerInfoToken. This is
1385 // something of a departure from the original code, since the old
1386 // code manufactured a CallerInfo object regardless of the query
1387 // outcome. From now on, we will append an empty CallerInfo
1388 // object, to mirror previous behaviour, and to avoid Null Pointer
1389 // Exceptions.
1390
1391 if (userDataObject instanceof Uri) {
1392 // State (1): query has not been executed yet
1393
1394 //create a dummy callerinfo, populate with what we know from URI.
1395 cit = new CallerInfoToken();
1396 cit.currentInfo = new CallerInfo();
1397 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1398 (Uri) userDataObject, sCallerInfoQueryListener, c);
1399 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1400 cit.isFinal = false;
1401
1402 c.setUserData(cit);
1403
1404 if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1405
1406 } else if (userDataObject == null) {
1407 // No URI, or Existing CallerInfo, so we'll have to make do with
1408 // querying a new CallerInfo using the connection's phone number.
1409 String number = c.getAddress();
1410
Chiao Cheng685dcb62013-10-02 11:51:06 -07001411 if (info != null && info != CallGatewayManager.EMPTY_INFO) {
Chiao Chenge365ba72013-09-26 14:18:12 -07001412 // Gateway number, the connection number is actually the gateway number.
1413 // need to lookup via dialed number.
1414 number = info.trueNumber;
1415 }
1416
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001417 if (DBG) {
1418 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
1419 log("- number (address): " + toLogSafePhoneNumber(number));
1420 log("- c: " + c);
1421 log("- phone: " + c.getCall().getPhone());
1422 int phoneType = c.getCall().getPhone().getPhoneType();
1423 log("- phoneType: " + phoneType);
1424 switch (phoneType) {
1425 case PhoneConstants.PHONE_TYPE_NONE: log(" ==> PHONE_TYPE_NONE"); break;
1426 case PhoneConstants.PHONE_TYPE_GSM: log(" ==> PHONE_TYPE_GSM"); break;
Etan Cohen0ca1c802014-07-07 15:35:48 -07001427 case PhoneConstants.PHONE_TYPE_IMS: log(" ==> PHONE_TYPE_IMS"); break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001428 case PhoneConstants.PHONE_TYPE_CDMA: log(" ==> PHONE_TYPE_CDMA"); break;
1429 case PhoneConstants.PHONE_TYPE_SIP: log(" ==> PHONE_TYPE_SIP"); break;
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07001430 case PhoneConstants.PHONE_TYPE_THIRD_PARTY:
1431 log(" ==> PHONE_TYPE_THIRD_PARTY");
1432 break;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001433 default: log(" ==> Unknown phone type"); break;
1434 }
1435 }
1436
1437 cit = new CallerInfoToken();
1438 cit.currentInfo = new CallerInfo();
1439
1440 // Store CNAP information retrieved from the Connection (we want to do this
1441 // here regardless of whether the number is empty or not).
1442 cit.currentInfo.cnapName = c.getCnapName();
1443 cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1444 // by ContactInfo later
1445 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1446 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1447
1448 if (VDBG) {
1449 log("startGetCallerInfo: number = " + number);
1450 log("startGetCallerInfo: CNAP Info from FW(1): name="
1451 + cit.currentInfo.cnapName
1452 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1453 }
1454
1455 // handling case where number is null (caller id hidden) as well.
1456 if (!TextUtils.isEmpty(number)) {
1457 // Check for special CNAP cases and modify the CallerInfo accordingly
1458 // to be sure we keep the right information to display/log later
1459 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1460 cit.currentInfo.numberPresentation);
1461
1462 cit.currentInfo.phoneNumber = number;
1463 // For scenarios where we may receive a valid number from the network but a
1464 // restricted/unavailable presentation, we do not want to perform a contact query
1465 // (see note on isFinal above). So we set isFinal to true here as well.
1466 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1467 cit.isFinal = true;
1468 } else {
1469 if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
1470 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1471 number, sCallerInfoQueryListener, c);
1472 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1473 cit.isFinal = false;
1474 }
1475 } else {
1476 // This is the case where we are querying on a number that
1477 // is null or empty, like a caller whose caller id is
1478 // blocked or empty (CLIR). The previous behaviour was to
1479 // throw a null CallerInfo object back to the user, but
1480 // this departure is somewhat cleaner.
1481 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1482 cit.isFinal = true; // please see note on isFinal, above.
1483 }
1484
1485 c.setUserData(cit);
1486
1487 if (DBG) {
1488 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
1489 }
1490
1491 } else if (userDataObject instanceof CallerInfoToken) {
1492 // State (2): query is executing, but has not completed.
1493
1494 // just tack on this listener to the queue.
1495 cit = (CallerInfoToken) userDataObject;
1496
1497 // handling case where number is null (caller id hidden) as well.
1498 if (cit.asyncQuery != null) {
1499 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1500
1501 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1502 listener.getClass().toString());
1503 } else {
1504 // handling case where number/name gets updated later on by the network
1505 String updatedNumber = c.getAddress();
Chiao Chenge365ba72013-09-26 14:18:12 -07001506
1507 if (info != null) {
1508 // Gateway number, the connection number is actually the gateway number.
1509 // need to lookup via dialed number.
1510 updatedNumber = info.trueNumber;
1511 }
1512
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001513 if (DBG) {
1514 log("startGetCallerInfo: updatedNumber initially = "
1515 + toLogSafePhoneNumber(updatedNumber));
1516 }
1517 if (!TextUtils.isEmpty(updatedNumber)) {
1518 // Store CNAP information retrieved from the Connection
1519 cit.currentInfo.cnapName = c.getCnapName();
1520 // This can still get overwritten by ContactInfo
1521 cit.currentInfo.name = cit.currentInfo.cnapName;
1522 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1523 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1524
1525 updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1526 updatedNumber, cit.currentInfo.numberPresentation);
1527
1528 cit.currentInfo.phoneNumber = updatedNumber;
1529 if (DBG) {
1530 log("startGetCallerInfo: updatedNumber="
1531 + toLogSafePhoneNumber(updatedNumber));
1532 }
1533 if (VDBG) {
1534 log("startGetCallerInfo: CNAP Info from FW(2): name="
1535 + cit.currentInfo.cnapName
1536 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1537 } else if (DBG) {
1538 log("startGetCallerInfo: CNAP Info from FW(2)");
1539 }
1540 // For scenarios where we may receive a valid number from the network but a
1541 // restricted/unavailable presentation, we do not want to perform a contact query
1542 // (see note on isFinal above). So we set isFinal to true here as well.
1543 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
1544 cit.isFinal = true;
1545 } else {
1546 cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1547 updatedNumber, sCallerInfoQueryListener, c);
1548 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1549 cit.isFinal = false;
1550 }
1551 } else {
1552 if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1553 if (cit.currentInfo == null) {
1554 cit.currentInfo = new CallerInfo();
1555 }
1556 // Store CNAP information retrieved from the Connection
1557 cit.currentInfo.cnapName = c.getCnapName(); // This can still get
1558 // overwritten by ContactInfo
1559 cit.currentInfo.name = cit.currentInfo.cnapName;
1560 cit.currentInfo.numberPresentation = c.getNumberPresentation();
1561 cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1562
1563 if (VDBG) {
1564 log("startGetCallerInfo: CNAP Info from FW(3): name="
1565 + cit.currentInfo.cnapName
1566 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1567 } else if (DBG) {
1568 log("startGetCallerInfo: CNAP Info from FW(3)");
1569 }
1570 cit.isFinal = true; // please see note on isFinal, above.
1571 }
1572 }
1573 } else {
1574 // State (3): query is complete.
1575
1576 // The connection's userDataObject is a full-fledged
1577 // CallerInfo instance. Wrap it in a CallerInfoToken and
1578 // return it to the user.
1579
1580 cit = new CallerInfoToken();
1581 cit.currentInfo = (CallerInfo) userDataObject;
1582 cit.asyncQuery = null;
1583 cit.isFinal = true;
1584 // since the query is already done, call the listener.
1585 if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1586 if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1587 }
1588 return cit;
1589 }
1590
1591 /**
1592 * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1593 * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1594 */
1595 private static final int QUERY_TOKEN = -1;
1596 static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1597 new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1598 /**
1599 * When the query completes, we stash the resulting CallerInfo
1600 * object away in the Connection's "userData" (where it will
1601 * later be retrieved by the in-call UI.)
1602 */
1603 public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1604 if (DBG) log("query complete, updating connection.userdata");
1605 Connection conn = (Connection) cookie;
1606
1607 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1608 // If no ContactInfo, then we want to use CNAP information coming from network
1609 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1610 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1611 // If the number presentation has not been set by
1612 // the ContactInfo, use the one from the
1613 // connection.
1614
1615 // TODO: Need a new util method to merge the info
1616 // from the Connection in a CallerInfo object.
1617 // Here 'ci' is a new CallerInfo instance read
1618 // from the DB. It has lost all the connection
1619 // info preset before the query (see PhoneUtils
1620 // line 1334). We should have a method to merge
1621 // back into this new instance the info from the
1622 // connection object not set by the DB. If the
1623 // Connection already has a CallerInfo instance in
1624 // userData, then we could use this instance to
1625 // fill 'ci' in. The same routine could be used in
1626 // PhoneUtils.
1627 if (0 == ci.numberPresentation) {
1628 ci.numberPresentation = conn.getNumberPresentation();
1629 }
1630 } else {
1631 // No matching contact was found for this number.
1632 // Return a new CallerInfo based solely on the CNAP
1633 // information from the network.
1634
1635 CallerInfo newCi = getCallerInfo(null, conn);
1636
1637 // ...but copy over the (few) things we care about
1638 // from the original CallerInfo object:
1639 if (newCi != null) {
1640 newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1641 newCi.geoDescription = ci.geoDescription; // To get geo description string
1642 ci = newCi;
1643 }
1644 }
1645
1646 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1647 conn.setUserData(ci);
1648 }
1649 };
1650
1651
1652 /**
1653 * Returns a single "name" for the specified given a CallerInfo object.
1654 * If the name is null, return defaultString as the default value, usually
1655 * context.getString(R.string.unknown).
1656 */
1657 static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1658 if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1659
1660 String compactName = null;
1661 if (ci != null) {
1662 if (TextUtils.isEmpty(ci.name)) {
1663 // Perform any modifications for special CNAP cases to
1664 // the phone number being displayed, if applicable.
1665 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1666 ci.numberPresentation);
1667 } else {
1668 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1669 compactName = ci.name;
1670 }
1671 }
1672
1673 if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1674 // If we're still null/empty here, then check if we have a presentation
1675 // string that takes precedence that we could return, otherwise display
1676 // "unknown" string.
1677 if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
1678 compactName = context.getString(R.string.private_num);
1679 } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
1680 compactName = context.getString(R.string.payphone);
1681 } else {
1682 compactName = context.getString(R.string.unknown);
1683 }
1684 }
1685 if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1686 return compactName;
1687 }
1688
1689 /**
1690 * Returns true if the specified Call is a "conference call", meaning
1691 * that it owns more than one Connection object. This information is
1692 * used to trigger certain UI changes that appear when a conference
1693 * call is active (like displaying the label "Conference call", and
1694 * enabling the "Manage conference" UI.)
1695 *
1696 * Watch out: This method simply checks the number of Connections,
1697 * *not* their states. So if a Call has (for example) one ACTIVE
1698 * connection and one DISCONNECTED connection, this method will return
1699 * true (which is unintuitive, since the Call isn't *really* a
1700 * conference call any more.)
1701 *
1702 * @return true if the specified call has more than one connection (in any state.)
1703 */
1704 static boolean isConferenceCall(Call call) {
1705 // CDMA phones don't have the same concept of "conference call" as
1706 // GSM phones do; there's no special "conference call" state of
1707 // the UI or a "manage conference" function. (Instead, when
1708 // you're in a 3-way call, all we can do is display the "generic"
1709 // state of the UI.) So as far as the in-call UI is concerned,
1710 // Conference corresponds to generic display.
1711 final PhoneGlobals app = PhoneGlobals.getInstance();
1712 int phoneType = call.getPhone().getPhoneType();
1713 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1714 CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1715 if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1716 || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1717 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1718 return true;
1719 }
1720 } else {
1721 List<Connection> connections = call.getConnections();
1722 if (connections != null && connections.size() > 1) {
1723 return true;
1724 }
1725 }
1726 return false;
1727
1728 // TODO: We may still want to change the semantics of this method
1729 // to say that a given call is only really a conference call if
1730 // the number of ACTIVE connections, not the total number of
1731 // connections, is greater than one. (See warning comment in the
1732 // javadoc above.)
1733 // Here's an implementation of that:
1734 // if (connections == null) {
1735 // return false;
1736 // }
1737 // int numActiveConnections = 0;
1738 // for (Connection conn : connections) {
1739 // if (DBG) log(" - CONN: " + conn + ", state = " + conn.getState());
1740 // if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1741 // if (numActiveConnections > 1) {
1742 // return true;
1743 // }
1744 // }
1745 // return false;
1746 }
1747
1748 /**
1749 * Launch the Dialer to start a new call.
1750 * This is just a wrapper around the ACTION_DIAL intent.
1751 */
1752 /* package */ static boolean startNewCall(final CallManager cm) {
1753 final PhoneGlobals app = PhoneGlobals.getInstance();
1754
1755 // Sanity-check that this is OK given the current state of the phone.
1756 if (!okToAddCall(cm)) {
1757 Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1758 dumpCallManager();
1759 return false;
1760 }
1761
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001762 Intent intent = new Intent(Intent.ACTION_DIAL);
1763 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1764
1765 // when we request the dialer come up, we also want to inform
1766 // it that we're going through the "add call" option from the
1767 // InCallScreen / PhoneUtils.
1768 intent.putExtra(ADD_CALL_MODE_KEY, true);
1769 try {
1770 app.startActivity(intent);
1771 } catch (ActivityNotFoundException e) {
1772 // This is rather rare but possible.
1773 // Note: this method is used even when the phone is encrypted. At that moment
1774 // the system may not find any Activity which can accept this Intent.
1775 Log.e(LOG_TAG, "Activity for adding calls isn't found.");
1776 return false;
1777 }
1778
1779 return true;
1780 }
1781
1782 /**
1783 * Turns on/off speaker.
1784 *
1785 * @param context Context
1786 * @param flag True when speaker should be on. False otherwise.
1787 * @param store True when the settings should be stored in the device.
1788 */
1789 /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1790 if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1791 final PhoneGlobals app = PhoneGlobals.getInstance();
1792
1793 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1794 audioManager.setSpeakerphoneOn(flag);
1795
1796 // record the speaker-enable value
1797 if (store) {
1798 sIsSpeakerEnabled = flag;
1799 }
1800
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001801 // We also need to make a fresh call to PhoneApp.updateWakeState()
1802 // any time the speaker state changes, since the screen timeout is
1803 // sometimes different depending on whether or not the speaker is
1804 // in use.
1805 app.updateWakeState();
1806
Hariprasad Jayakumareee6a9e2014-04-25 15:33:13 -07001807 app.mCM.setEchoSuppressionEnabled();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001808 }
1809
1810 /**
1811 * Restore the speaker mode, called after a wired headset disconnect
1812 * event.
1813 */
1814 static void restoreSpeakerMode(Context context) {
1815 if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1816
1817 // change the mode if needed.
1818 if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1819 turnOnSpeaker(context, sIsSpeakerEnabled, false);
1820 }
1821 }
1822
1823 static boolean isSpeakerOn(Context context) {
1824 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1825 return audioManager.isSpeakerphoneOn();
1826 }
1827
1828
1829 static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
1830 if (DBG) log("turnOnNoiseSuppression: " + flag);
1831 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1832
1833 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1834 return;
1835 }
1836
1837 if (flag) {
1838 audioManager.setParameters("noise_suppression=auto");
1839 } else {
1840 audioManager.setParameters("noise_suppression=off");
1841 }
1842
1843 // record the speaker-enable value
1844 if (store) {
1845 sIsNoiseSuppressionEnabled = flag;
1846 }
1847
1848 // TODO: implement and manage ICON
1849
1850 }
1851
1852 static void restoreNoiseSuppression(Context context) {
1853 if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
1854
1855 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1856 return;
1857 }
1858
1859 // change the mode if needed.
1860 if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
1861 turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
1862 }
1863 }
1864
1865 static boolean isNoiseSuppressionOn(Context context) {
1866
1867 if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1868 return false;
1869 }
1870
1871 AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1872 String noiseSuppression = audioManager.getParameters("noise_suppression");
1873 if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
1874 if (noiseSuppression.contains("off")) {
1875 return false;
1876 } else {
1877 return true;
1878 }
1879 }
1880
Santos Cordonc264cba2013-09-19 04:55:40 -07001881 static boolean isInEmergencyCall(CallManager cm) {
1882 for (Connection cn : cm.getActiveFgCall().getConnections()) {
Yorke Lee36bb2542014-06-05 08:09:52 -07001883 if (PhoneNumberUtils.isLocalEmergencyNumber(PhoneGlobals.getInstance(),
1884 cn.getAddress())) {
Santos Cordonc264cba2013-09-19 04:55:40 -07001885 return true;
1886 }
1887 }
1888 return false;
1889 }
1890
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001891 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001892 * Get the mute state of foreground phone, which has the current
1893 * foreground call
1894 */
1895 static boolean getMute() {
Santos Cordonbb2bcef2014-08-05 19:08:10 -07001896 return false;
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001897 }
1898
1899 /* package */ static void setAudioMode() {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001900 }
1901
1902 /**
1903 * Sets the audio mode per current phone state.
1904 */
1905 /* package */ static void setAudioMode(CallManager cm) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001906 }
1907
1908 /**
1909 * Look for ANY connections on the phone that qualify as being
1910 * disconnected.
1911 *
1912 * @return true if we find a connection that is disconnected over
1913 * all the phone's call objects.
1914 */
1915 /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1916 return hasDisconnectedConnections(phone.getForegroundCall()) ||
1917 hasDisconnectedConnections(phone.getBackgroundCall()) ||
1918 hasDisconnectedConnections(phone.getRingingCall());
1919 }
1920
1921 /**
1922 * Iterate over all connections in a call to see if there are any
1923 * that are not alive (disconnected or idle).
1924 *
1925 * @return true if we find a connection that is disconnected, and
1926 * pending removal via
1927 * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1928 */
1929 private static final boolean hasDisconnectedConnections(Call call) {
1930 // look through all connections for non-active ones.
1931 for (Connection c : call.getConnections()) {
1932 if (!c.isAlive()) {
1933 return true;
1934 }
1935 }
1936 return false;
1937 }
1938
1939 //
1940 // Misc UI policy helper functions
1941 //
1942
1943 /**
Christine Chenaf2fd0a2013-09-13 16:27:40 -07001944 * @return true if we're allowed to hold calls, given the current
1945 * state of the Phone.
1946 */
1947 /* package */ static boolean okToHoldCall(CallManager cm) {
1948 final Call fgCall = cm.getActiveFgCall();
1949 final boolean hasHoldingCall = cm.hasActiveBgCall();
1950 final Call.State fgCallState = fgCall.getState();
1951
1952 // The "Hold" control is disabled entirely if there's
1953 // no way to either hold or unhold in the current state.
1954 final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
1955 final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
1956 final boolean canHold = okToHold || okToUnhold;
1957
1958 return canHold;
1959 }
1960
1961 /**
1962 * @return true if we support holding calls, given the current
1963 * state of the Phone.
1964 */
1965 /* package */ static boolean okToSupportHold(CallManager cm) {
1966 boolean supportsHold = false;
1967
1968 final Call fgCall = cm.getActiveFgCall();
1969 final boolean hasHoldingCall = cm.hasActiveBgCall();
1970 final Call.State fgCallState = fgCall.getState();
1971
1972 if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
1973 // This phone has the concept of explicit "Hold" and "Unhold" actions.
1974 supportsHold = true;
1975 } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
1976 // Even when foreground phone device doesn't support hold/unhold, phone devices
1977 // for background holding calls may do.
1978 final Call bgCall = cm.getFirstActiveBgCall();
1979 if (bgCall != null &&
1980 TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
1981 supportsHold = true;
1982 }
1983 }
1984 return supportsHold;
1985 }
1986
1987 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07001988 * @return true if we're allowed to swap calls, given the current
1989 * state of the Phone.
1990 */
1991 /* package */ static boolean okToSwapCalls(CallManager cm) {
1992 int phoneType = cm.getDefaultPhone().getPhoneType();
1993 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
1994 // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1995 // state by either accepting a Call Waiting or by merging two calls
1996 PhoneGlobals app = PhoneGlobals.getInstance();
1997 return (app.cdmaPhoneCallState.getCurrentCallState()
1998 == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1999 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002000 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07002001 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002002 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002003 // GSM: "Swap" is available if both lines are in use and there's no
2004 // incoming call. (Actually we need to verify that the active
2005 // call really is in the ACTIVE state and the holding call really
2006 // is in the HOLDING state, since you *can't* actually swap calls
2007 // when the foreground call is DIALING or ALERTING.)
2008 return !cm.hasActiveRingingCall()
2009 && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
2010 && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
2011 } else {
2012 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2013 }
2014 }
2015
2016 /**
2017 * @return true if we're allowed to merge calls, given the current
2018 * state of the Phone.
2019 */
2020 /* package */ static boolean okToMergeCalls(CallManager cm) {
2021 int phoneType = cm.getFgPhone().getPhoneType();
2022 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2023 // CDMA: "Merge" is enabled only when the user is in a 3Way call.
2024 PhoneGlobals app = PhoneGlobals.getInstance();
2025 return ((app.cdmaPhoneCallState.getCurrentCallState()
2026 == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
2027 && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
2028 } else {
2029 // GSM: "Merge" is available if both lines are in use and there's no
2030 // incoming call, *and* the current conference isn't already
2031 // "full".
2032 // TODO: shall move all okToMerge logic to CallManager
2033 return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
2034 && cm.hasActiveBgCall()
2035 && cm.canConference(cm.getFirstActiveBgCall());
2036 }
2037 }
2038
2039 /**
2040 * @return true if the UI should let you add a new call, given the current
2041 * state of the Phone.
2042 */
2043 /* package */ static boolean okToAddCall(CallManager cm) {
2044 Phone phone = cm.getActiveFgCall().getPhone();
2045
2046 // "Add call" is never allowed in emergency callback mode (ECM).
2047 if (isPhoneInEcm(phone)) {
2048 return false;
2049 }
2050
2051 int phoneType = phone.getPhoneType();
2052 final Call.State fgCallState = cm.getActiveFgCall().getState();
2053 if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
2054 // CDMA: "Add call" button is only enabled when:
2055 // - ForegroundCall is in ACTIVE state
2056 // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
2057 PhoneGlobals app = PhoneGlobals.getInstance();
2058 return ((fgCallState == Call.State.ACTIVE)
2059 && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
2060 } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002061 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)
Etan Cohen0ca1c802014-07-07 15:35:48 -07002062 || (phoneType == PhoneConstants.PHONE_TYPE_IMS)
Sailesh Nepalbd76e4e2013-10-27 13:59:44 -07002063 || (phoneType == PhoneConstants.PHONE_TYPE_THIRD_PARTY)) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002064 // GSM: "Add call" is available only if ALL of the following are true:
2065 // - There's no incoming ringing call
2066 // - There's < 2 lines in use
2067 // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
2068 // (We mainly need to make sure it *isn't* DIALING or ALERTING.)
2069 final boolean hasRingingCall = cm.hasActiveRingingCall();
2070 final boolean hasActiveCall = cm.hasActiveFgCall();
2071 final boolean hasHoldingCall = cm.hasActiveBgCall();
2072 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2073
2074 return !hasRingingCall
2075 && !allLinesTaken
2076 && ((fgCallState == Call.State.ACTIVE)
2077 || (fgCallState == Call.State.IDLE)
2078 || (fgCallState == Call.State.DISCONNECTED));
2079 } else {
2080 throw new IllegalStateException("Unexpected phone type: " + phoneType);
2081 }
2082 }
2083
2084 /**
2085 * Based on the input CNAP number string,
2086 * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
2087 * Otherwise, return CNAP_SPECIAL_CASE_NO.
2088 */
2089 private static int checkCnapSpecialCases(String n) {
2090 if (n.equals("PRIVATE") ||
2091 n.equals("P") ||
2092 n.equals("RES")) {
2093 if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
2094 return PhoneConstants.PRESENTATION_RESTRICTED;
2095 } else if (n.equals("UNAVAILABLE") ||
2096 n.equals("UNKNOWN") ||
2097 n.equals("UNA") ||
2098 n.equals("U")) {
2099 if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
2100 return PhoneConstants.PRESENTATION_UNKNOWN;
2101 } else {
2102 if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
2103 return CNAP_SPECIAL_CASE_NO;
2104 }
2105 }
2106
2107 /**
2108 * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
2109 * from the network to indicate different number presentations, convert them to
2110 * expected number and presentation values within the CallerInfo object.
2111 * @param number number we use to verify if we are in a corner case
2112 * @param presentation presentation value used to verify if we are in a corner case
2113 * @return the new String that should be used for the phone number
2114 */
2115 /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2116 String number, int presentation) {
2117 // Obviously we return number if ci == null, but still return number if
2118 // number == null, because in these cases the correct string will still be
2119 // displayed/logged after this function returns based on the presentation value.
2120 if (ci == null || number == null) return number;
2121
2122 if (DBG) {
2123 log("modifyForSpecialCnapCases: initially, number="
2124 + toLogSafePhoneNumber(number)
2125 + ", presentation=" + presentation + " ci " + ci);
2126 }
2127
2128 // "ABSENT NUMBER" is a possible value we could get from the network as the
2129 // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2130 // and fix the presentation to be the same.
2131 final String[] absentNumberValues =
2132 context.getResources().getStringArray(R.array.absent_num);
2133 if (Arrays.asList(absentNumberValues).contains(number)
2134 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
2135 number = context.getString(R.string.unknown);
2136 ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
2137 }
2138
2139 // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2140 // cases only apply if we received an allowed presentation from the network, so check
2141 // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2142 // match the presentation passed in for verification (meaning we changed it previously
2143 // because it's a corner case and we're being called from a different entry point).
2144 if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
2145 || (ci.numberPresentation != presentation
2146 && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
2147 int cnapSpecialCase = checkCnapSpecialCases(number);
2148 if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2149 // For all special strings, change number & numberPresentation.
2150 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
2151 number = context.getString(R.string.private_num);
2152 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
2153 number = context.getString(R.string.unknown);
2154 }
2155 if (DBG) {
2156 log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
2157 + "; presentation now=" + cnapSpecialCase);
2158 }
2159 ci.numberPresentation = cnapSpecialCase;
2160 }
2161 }
2162 if (DBG) {
2163 log("modifyForSpecialCnapCases: returning number string="
2164 + toLogSafePhoneNumber(number));
2165 }
2166 return number;
2167 }
2168
2169 //
2170 // Support for 3rd party phone service providers.
2171 //
2172
2173 /**
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002174 * Check if a phone number can be route through a 3rd party
2175 * gateway. The number must be a global phone number in numerical
2176 * form (1-800-666-SEXY won't work).
2177 *
2178 * MMI codes and the like cannot be used as a dial number for the
2179 * gateway either.
2180 *
2181 * @param number To be dialed via a 3rd party gateway.
2182 * @return true If the number can be routed through the 3rd party network.
2183 */
Santos Cordon69a69192013-08-22 14:25:42 -07002184 private static boolean isRoutableViaGateway(String number) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002185 if (TextUtils.isEmpty(number)) {
2186 return false;
2187 }
2188 number = PhoneNumberUtils.stripSeparators(number);
2189 if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2190 return false;
2191 }
2192 number = PhoneNumberUtils.extractNetworkPortion(number);
2193 return PhoneNumberUtils.isGlobalPhoneNumber(number);
2194 }
2195
2196 /**
2197 * This function is called when phone answers or places a call.
2198 * Check if the phone is in a car dock or desk dock.
2199 * If yes, turn on the speaker, when no wired or BT headsets are connected.
2200 * Otherwise do nothing.
2201 * @return true if activated
2202 */
2203 private static boolean activateSpeakerIfDocked(Phone phone) {
2204 if (DBG) log("activateSpeakerIfDocked()...");
2205
2206 boolean activated = false;
2207 if (PhoneGlobals.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
2208 if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
Santos Cordon593ab382013-08-06 21:58:23 -07002209 final PhoneGlobals app = PhoneGlobals.getInstance();
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002210
Christine Chen3e0f0412013-09-18 20:33:49 -07002211 // TODO: This function should move to AudioRouter
Santos Cordon593ab382013-08-06 21:58:23 -07002212 final BluetoothManager btManager = app.getBluetoothManager();
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002213 //final WiredHeadsetManager wiredHeadset = app.getWiredHeadsetManager();
2214 //final AudioRouter audioRouter = app.getAudioRouter();
Santos Cordon593ab382013-08-06 21:58:23 -07002215
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002216 /*if (!wiredHeadset.isHeadsetPlugged() && !btManager.isBluetoothHeadsetAudioOn()) {
2217 //audioRouter.setSpeaker(true);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002218 activated = true;
Santos Cordonbb2bcef2014-08-05 19:08:10 -07002219 }*/
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002220 }
2221 return activated;
2222 }
2223
2224
2225 /**
2226 * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2227 */
2228 /* package */ static boolean isPhoneInEcm(Phone phone) {
2229 if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
2230 // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
2231 // TODO: There ought to be a better API for this than just
2232 // exposing a system property all the way up to the app layer,
2233 // probably a method like "inEcm()" provided by the telephony
2234 // layer.
2235 String ecmMode =
2236 SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
2237 if (ecmMode != null) {
2238 return ecmMode.equals("true");
2239 }
2240 }
2241 return false;
2242 }
2243
2244 /**
2245 * Returns the most appropriate Phone object to handle a call
2246 * to the specified number.
2247 *
2248 * @param cm the CallManager.
2249 * @param scheme the scheme from the data URI that the number originally came from.
2250 * @param number the phone number, or SIP address.
2251 */
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002252 public static Phone pickPhoneBasedOnNumber(CallManager cm, String scheme, String number,
2253 String primarySipUri, ComponentName thirdPartyCallComponent) {
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002254 if (DBG) {
2255 log("pickPhoneBasedOnNumber: scheme " + scheme
2256 + ", number " + toLogSafePhoneNumber(number)
2257 + ", sipUri "
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002258 + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null")
2259 + ", thirdPartyCallComponent: " + thirdPartyCallComponent);
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002260 }
2261
2262 if (primarySipUri != null) {
2263 Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2264 if (phone != null) return phone;
2265 }
Sailesh Nepalbfb68322013-11-07 14:07:41 -08002266
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002267 return cm.getDefaultPhone();
2268 }
2269
2270 public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2271 for (Phone phone : cm.getAllPhones()) {
2272 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
2273 String sipUri = ((SipPhone) phone).getSipUri();
2274 if (target.equals(sipUri)) {
2275 if (DBG) log("- pickPhoneBasedOnNumber:" +
2276 "found SipPhone! obj = " + phone + ", "
2277 + phone.getClass());
2278 return phone;
2279 }
2280 }
2281 }
2282 return null;
2283 }
2284
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002285 /**
2286 * Returns true when the given call is in INCOMING state and there's no foreground phone call,
2287 * meaning the call is the first real incoming call the phone is having.
2288 */
2289 public static boolean isRealIncomingCall(Call.State state) {
2290 return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
2291 }
2292
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002293 public static String getPresentationString(Context context, int presentation) {
2294 String name = context.getString(R.string.unknown);
2295 if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
2296 name = context.getString(R.string.private_num);
2297 } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
2298 name = context.getString(R.string.payphone);
2299 }
2300 return name;
2301 }
2302
2303 public static void sendViewNotificationAsync(Context context, Uri contactUri) {
2304 if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
2305 Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
2306 intent.setClassName("com.android.contacts",
2307 "com.android.contacts.ViewNotificationService");
2308 context.startService(intent);
2309 }
2310
2311 //
2312 // General phone and call state debugging/testing code
2313 //
2314
2315 /* package */ static void dumpCallState(Phone phone) {
2316 PhoneGlobals app = PhoneGlobals.getInstance();
2317 Log.d(LOG_TAG, "dumpCallState():");
2318 Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2319 + ", state = " + phone.getState());
2320
2321 StringBuilder b = new StringBuilder(128);
2322
2323 Call call = phone.getForegroundCall();
2324 b.setLength(0);
2325 b.append(" - FG call: ").append(call.getState());
2326 b.append(" isAlive ").append(call.getState().isAlive());
2327 b.append(" isRinging ").append(call.getState().isRinging());
2328 b.append(" isDialing ").append(call.getState().isDialing());
2329 b.append(" isIdle ").append(call.isIdle());
2330 b.append(" hasConnections ").append(call.hasConnections());
2331 Log.d(LOG_TAG, b.toString());
2332
2333 call = phone.getBackgroundCall();
2334 b.setLength(0);
2335 b.append(" - BG call: ").append(call.getState());
2336 b.append(" isAlive ").append(call.getState().isAlive());
2337 b.append(" isRinging ").append(call.getState().isRinging());
2338 b.append(" isDialing ").append(call.getState().isDialing());
2339 b.append(" isIdle ").append(call.isIdle());
2340 b.append(" hasConnections ").append(call.hasConnections());
2341 Log.d(LOG_TAG, b.toString());
2342
2343 call = phone.getRingingCall();
2344 b.setLength(0);
2345 b.append(" - RINGING call: ").append(call.getState());
2346 b.append(" isAlive ").append(call.getState().isAlive());
2347 b.append(" isRinging ").append(call.getState().isRinging());
2348 b.append(" isDialing ").append(call.getState().isDialing());
2349 b.append(" isIdle ").append(call.isIdle());
2350 b.append(" hasConnections ").append(call.hasConnections());
2351 Log.d(LOG_TAG, b.toString());
2352
2353
2354 final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2355 final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2356 final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2357 final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2358 b.setLength(0);
2359 b.append(" - hasRingingCall ").append(hasRingingCall);
2360 b.append(" hasActiveCall ").append(hasActiveCall);
2361 b.append(" hasHoldingCall ").append(hasHoldingCall);
2362 b.append(" allLinesTaken ").append(allLinesTaken);
2363 Log.d(LOG_TAG, b.toString());
2364
2365 // On CDMA phones, dump out the CdmaPhoneCallState too:
2366 if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
2367 if (app.cdmaPhoneCallState != null) {
2368 Log.d(LOG_TAG, " - CDMA call state: "
2369 + app.cdmaPhoneCallState.getCurrentCallState());
2370 } else {
2371 Log.d(LOG_TAG, " - CDMA device, but null cdmaPhoneCallState!");
2372 }
2373 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002374 }
2375
2376 private static void log(String msg) {
2377 Log.d(LOG_TAG, msg);
2378 }
2379
2380 static void dumpCallManager() {
2381 Call call;
2382 CallManager cm = PhoneGlobals.getInstance().mCM;
2383 StringBuilder b = new StringBuilder(128);
2384
2385
2386
2387 Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2388 // TODO: Don't log "cm" itself, since CallManager.toString()
2389 // already spews out almost all this same information.
2390 // We should fix CallManager.toString() to be more minimal, and
2391 // use an explicit dumpState() method for the verbose dump.
2392 // Log.d(LOG_TAG, "CallManager: " + cm
2393 // + ", state = " + cm.getState());
2394 Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
2395 b.setLength(0);
2396 call = cm.getActiveFgCall();
2397 b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2398 b.append(call);
2399 b.append( " State: ").append(cm.getActiveFgCallState());
2400 b.append( " Conn: ").append(cm.getFgCallConnections());
2401 Log.d(LOG_TAG, b.toString());
2402 b.setLength(0);
2403 call = cm.getFirstActiveBgCall();
2404 b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2405 b.append(call);
2406 b.append( " State: ").append(cm.getFirstActiveBgCall().getState());
2407 b.append( " Conn: ").append(cm.getBgCallConnections());
2408 Log.d(LOG_TAG, b.toString());
2409 b.setLength(0);
2410 call = cm.getFirstActiveRingingCall();
2411 b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2412 b.append(call);
2413 b.append( " State: ").append(cm.getFirstActiveRingingCall().getState());
2414 Log.d(LOG_TAG, b.toString());
2415
2416
2417
2418 for (Phone phone : CallManager.getInstance().getAllPhones()) {
2419 if (phone != null) {
2420 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2421 + ", state = " + phone.getState());
2422 b.setLength(0);
2423 call = phone.getForegroundCall();
2424 b.append(" - FG call: ").append(call);
2425 b.append( " State: ").append(call.getState());
2426 b.append( " Conn: ").append(call.hasConnections());
2427 Log.d(LOG_TAG, b.toString());
2428 b.setLength(0);
2429 call = phone.getBackgroundCall();
2430 b.append(" - BG call: ").append(call);
2431 b.append( " State: ").append(call.getState());
2432 b.append( " Conn: ").append(call.hasConnections());
2433 Log.d(LOG_TAG, b.toString());b.setLength(0);
2434 call = phone.getRingingCall();
2435 b.append(" - RINGING call: ").append(call);
2436 b.append( " State: ").append(call.getState());
2437 b.append( " Conn: ").append(call.hasConnections());
2438 Log.d(LOG_TAG, b.toString());
2439 }
2440 }
2441
2442 Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2443 }
2444
2445 /**
2446 * @return if the context is in landscape orientation.
2447 */
2448 public static boolean isLandscape(Context context) {
2449 return context.getResources().getConfiguration().orientation
2450 == Configuration.ORIENTATION_LANDSCAPE;
2451 }
Andrew Leed5165b02014-12-05 15:53:58 -08002452
Nancy Chene53a0642015-03-12 11:20:12 -07002453 public static PhoneAccountHandle makePstnPhoneAccountHandle(String id) {
2454 return makePstnPhoneAccountHandleWithPrefix(id, "", false);
2455 }
2456
Nancy Chen32031f42015-03-04 21:00:07 -08002457 public static PhoneAccountHandle makePstnPhoneAccountHandle(int phoneId) {
2458 return makePstnPhoneAccountHandle(PhoneFactory.getPhone(phoneId));
2459 }
2460
Andrew Leed5165b02014-12-05 15:53:58 -08002461 public static PhoneAccountHandle makePstnPhoneAccountHandle(Phone phone) {
2462 return makePstnPhoneAccountHandleWithPrefix(phone, "", false);
2463 }
2464
2465 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2466 Phone phone, String prefix, boolean isEmergency) {
Andrew Leed5165b02014-12-05 15:53:58 -08002467 // TODO: Should use some sort of special hidden flag to decorate this account as
2468 // an emergency-only account
Santos Cordon80855d52015-02-10 04:33:36 -08002469 String id = isEmergency ? "E" : prefix + String.valueOf(phone.getIccSerialNumber());
Nancy Chene53a0642015-03-12 11:20:12 -07002470 return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
2471 }
2472
2473 public static PhoneAccountHandle makePstnPhoneAccountHandleWithPrefix(
2474 String id, String prefix, boolean isEmergency) {
2475 ComponentName pstnConnectionServiceName = getPstnConnectionServiceName();
Andrew Leed5165b02014-12-05 15:53:58 -08002476 return new PhoneAccountHandle(pstnConnectionServiceName, id);
2477 }
Stuart Scottdcf40a92014-12-09 10:45:01 -08002478
Santos Cordonf69df962015-02-03 11:15:19 -08002479 public static int getSubIdForPhoneAccount(PhoneAccount phoneAccount) {
Santos Cordon21e78ac2015-02-06 05:19:29 -08002480 if (phoneAccount != null
2481 && phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)) {
2482 return getSubIdForPhoneAccountHandle(phoneAccount.getAccountHandle());
2483 }
2484 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2485 }
2486
2487 public static int getSubIdForPhoneAccountHandle(PhoneAccountHandle handle) {
2488 if (handle != null && handle.getComponentName().equals(getPstnConnectionServiceName())) {
Santos Cordon80855d52015-02-10 04:33:36 -08002489 Phone phone = getPhoneFromIccId(handle.getId());
2490 if (phone != null) {
2491 return phone.getSubId();
Santos Cordonf69df962015-02-03 11:15:19 -08002492 }
2493 }
2494 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
2495 }
2496
Nancy Chene53a0642015-03-12 11:20:12 -07002497 /**
2498 * Determine if a given phone account corresponds to an active SIM
2499 *
2500 * @param sm An instance of the subscription manager so it is not recreated for each calling of
2501 * this method.
2502 * @param handle The handle for the phone account to check
2503 * @return {@code true} If there is an active SIM for this phone account,
2504 * {@code false} otherwise.
2505 */
2506 public static boolean isPhoneAccountActive(SubscriptionManager sm, PhoneAccountHandle handle) {
2507 return sm.getActiveSubscriptionInfoForIccIndex(handle.getId()) != null;
2508 }
2509
Santos Cordonf69df962015-02-03 11:15:19 -08002510 private static ComponentName getPstnConnectionServiceName() {
2511 return new ComponentName(PhoneGlobals.getInstance(), TelephonyConnectionService.class);
2512 }
2513
Santos Cordon80855d52015-02-10 04:33:36 -08002514 private static Phone getPhoneFromIccId(String iccId) {
2515 if (!TextUtils.isEmpty(iccId)) {
2516 for (Phone phone : PhoneFactory.getPhones()) {
2517 String phoneIccId = phone.getIccSerialNumber();
2518 if (iccId.equals(phoneIccId)) {
2519 return phone;
2520 }
2521 }
2522 }
Santos Cordon80855d52015-02-10 04:33:36 -08002523 return null;
2524 }
2525
Stuart Scottdcf40a92014-12-09 10:45:01 -08002526 /**
2527 * Register ICC status for all phones.
2528 */
2529 static final void registerIccStatus(Handler handler, int event) {
2530 for (Phone phone : PhoneFactory.getPhones()) {
2531 IccCard sim = phone.getIccCard();
2532 if (sim != null) {
2533 if (VDBG) Log.v(LOG_TAG, "register for ICC status, phone " + phone.getPhoneId());
2534 sim.registerForNetworkLocked(handler, event, phone);
2535 }
2536 }
2537 }
2538
2539 /**
2540 * Set the radio power on/off state for all phones.
2541 *
2542 * @param enabled true means on, false means off.
2543 */
2544 static final void setRadioPower(boolean enabled) {
2545 for (Phone phone : PhoneFactory.getPhones()) {
2546 phone.setRadioPower(enabled);
2547 }
2548 }
Santos Cordon7d4ddf62013-07-10 11:58:08 -07002549}