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