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