DialpadFragment.java revision bddd6fb09fb0bbf7787e600b3b4c044482a94d61
1/* 2 * Copyright (C) 2011 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.dialer.dialpad; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.Dialog; 22import android.app.DialogFragment; 23import android.app.Fragment; 24import android.content.ContentResolver; 25import android.content.Context; 26import android.content.DialogInterface; 27import android.content.Intent; 28import android.content.res.Resources; 29import android.database.Cursor; 30import android.graphics.Bitmap; 31import android.graphics.BitmapFactory; 32import android.media.AudioManager; 33import android.media.ToneGenerator; 34import android.net.Uri; 35import android.os.Bundle; 36import android.os.RemoteException; 37import android.os.ServiceManager; 38import android.os.SystemProperties; 39import android.provider.Contacts.Intents.Insert; 40import android.provider.Contacts.People; 41import android.provider.Contacts.Phones; 42import android.provider.Contacts.PhonesColumns; 43import android.provider.Settings; 44import android.telephony.PhoneNumberUtils; 45import android.telephony.PhoneStateListener; 46import android.telephony.TelephonyManager; 47import android.text.Editable; 48import android.text.SpannableString; 49import android.text.TextUtils; 50import android.text.TextWatcher; 51import android.text.style.RelativeSizeSpan; 52import android.util.AttributeSet; 53import android.util.DisplayMetrics; 54import android.util.Log; 55import android.view.KeyEvent; 56import android.view.LayoutInflater; 57import android.view.Menu; 58import android.view.MenuInflater; 59import android.view.MenuItem; 60import android.view.View; 61import android.view.ViewConfiguration; 62import android.view.ViewGroup; 63import android.view.ViewTreeObserver; 64import android.view.ViewTreeObserver.OnPreDrawListener; 65import android.widget.AdapterView; 66import android.widget.BaseAdapter; 67import android.widget.EditText; 68import android.widget.ImageView; 69import android.widget.LinearLayout; 70import android.widget.ListView; 71import android.widget.PopupMenu; 72import android.widget.TableRow; 73import android.widget.TextView; 74 75import com.android.contacts.common.CallUtil; 76import com.android.contacts.common.GeoUtil; 77import com.android.contacts.common.activity.TransactionSafeActivity; 78import com.android.contacts.common.preference.ContactsPreferences; 79import com.android.contacts.common.util.PhoneNumberFormatter; 80import com.android.contacts.common.util.StopWatch; 81import com.android.dialer.NeededForReflection; 82import com.android.dialer.DialtactsActivity; 83import com.android.dialer.R; 84import com.android.dialer.SpecialCharSequenceMgr; 85import com.android.dialer.database.DialerDatabaseHelper; 86import com.android.dialer.interactions.PhoneNumberInteraction; 87import com.android.dialer.util.OrientationUtil; 88import com.android.internal.telephony.ITelephony; 89import com.android.phone.common.CallLogAsync; 90import com.android.phone.common.HapticFeedback; 91import com.google.common.annotations.VisibleForTesting; 92 93/** 94 * Fragment that displays a twelve-key phone dialpad. 95 */ 96public class DialpadFragment extends Fragment 97 implements View.OnClickListener, 98 View.OnLongClickListener, View.OnKeyListener, 99 AdapterView.OnItemClickListener, TextWatcher, 100 PopupMenu.OnMenuItemClickListener, 101 DialpadKeyButton.OnPressedListener { 102 private static final String TAG = DialpadFragment.class.getSimpleName(); 103 104 public interface OnDialpadFragmentStartedListener { 105 public void onDialpadFragmentStarted(); 106 } 107 108 /** 109 * LinearLayout with getter and setter methods for the translationY property using floats, 110 * for animation purposes. 111 */ 112 public static class DialpadSlidingLinearLayout extends LinearLayout { 113 114 public DialpadSlidingLinearLayout(Context context) { 115 super(context); 116 } 117 118 public DialpadSlidingLinearLayout(Context context, AttributeSet attrs) { 119 super(context, attrs); 120 } 121 122 public DialpadSlidingLinearLayout(Context context, AttributeSet attrs, int defStyle) { 123 super(context, attrs, defStyle); 124 } 125 126 @NeededForReflection 127 public float getYFraction() { 128 final int height = getHeight(); 129 if (height == 0) return 0; 130 return getTranslationY() / height; 131 } 132 133 @NeededForReflection 134 public void setYFraction(float yFraction) { 135 setTranslationY(yFraction * getHeight()); 136 } 137 } 138 139 public interface OnDialpadQueryChangedListener { 140 void onDialpadQueryChanged(String query); 141 } 142 143 private static final boolean DEBUG = DialtactsActivity.DEBUG; 144 145 // This is the amount of screen the dialpad fragment takes up when fully displayed 146 private static final float DIALPAD_SLIDE_FRACTION = 0.67f; 147 148 private static final String EMPTY_NUMBER = ""; 149 private static final char PAUSE = ','; 150 private static final char WAIT = ';'; 151 152 /** The length of DTMF tones in milliseconds */ 153 private static final int TONE_LENGTH_MS = 150; 154 private static final int TONE_LENGTH_INFINITE = -1; 155 156 /** The DTMF tone volume relative to other sounds in the stream */ 157 private static final int TONE_RELATIVE_VOLUME = 80; 158 159 /** Stream type used to play the DTMF tones off call, and mapped to the volume control keys */ 160 private static final int DIAL_TONE_STREAM_TYPE = AudioManager.STREAM_DTMF; 161 162 private ContactsPreferences mContactsPrefs; 163 164 private OnDialpadQueryChangedListener mDialpadQueryListener; 165 166 /** 167 * View (usually FrameLayout) containing mDigits field. This can be null, in which mDigits 168 * isn't enclosed by the container. 169 */ 170 private View mDigitsContainer; 171 private EditText mDigits; 172 173 /** Remembers if we need to clear digits field when the screen is completely gone. */ 174 private boolean mClearDigitsOnStop; 175 176 private View mDelete; 177 private ToneGenerator mToneGenerator; 178 private final Object mToneGeneratorLock = new Object(); 179 private View mDialpad; 180 /** 181 * Remembers the number of dialpad buttons which are pressed at this moment. 182 * If it becomes 0, meaning no buttons are pressed, we'll call 183 * {@link ToneGenerator#stopTone()}; the method shouldn't be called unless the last key is 184 * released. 185 */ 186 private int mDialpadPressCount; 187 188 private View mDialButtonContainer; 189 private View mDialButton; 190 private ListView mDialpadChooser; 191 private DialpadChooserAdapter mDialpadChooserAdapter; 192 193 private DialerDatabaseHelper mDialerDatabaseHelper; 194 195 /** 196 * Regular expression prohibiting manual phone call. Can be empty, which means "no rule". 197 */ 198 private String mProhibitedPhoneNumberRegexp; 199 200 201 // Last number dialed, retrieved asynchronously from the call DB 202 // in onCreate. This number is displayed when the user hits the 203 // send key and cleared in onPause. 204 private final CallLogAsync mCallLog = new CallLogAsync(); 205 private String mLastNumberDialed = EMPTY_NUMBER; 206 207 // determines if we want to playback local DTMF tones. 208 private boolean mDTMFToneEnabled; 209 210 // Vibration (haptic feedback) for dialer key presses. 211 private final HapticFeedback mHaptic = new HapticFeedback(); 212 213 /** Identifier for the "Add Call" intent extra. */ 214 private static final String ADD_CALL_MODE_KEY = "add_call_mode"; 215 216 /** 217 * Identifier for intent extra for sending an empty Flash message for 218 * CDMA networks. This message is used by the network to simulate a 219 * press/depress of the "hookswitch" of a landline phone. Aka "empty flash". 220 * 221 * TODO: Using an intent extra to tell the phone to send this flash is a 222 * temporary measure. To be replaced with an ITelephony call in the future. 223 * TODO: Keep in sync with the string defined in OutgoingCallBroadcaster.java 224 * in Phone app until this is replaced with the ITelephony API. 225 */ 226 private static final String EXTRA_SEND_EMPTY_FLASH 227 = "com.android.phone.extra.SEND_EMPTY_FLASH"; 228 229 private String mCurrentCountryIso; 230 231 private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() { 232 /** 233 * Listen for phone state changes so that we can take down the 234 * "dialpad chooser" if the phone becomes idle while the 235 * chooser UI is visible. 236 */ 237 @Override 238 public void onCallStateChanged(int state, String incomingNumber) { 239 // Log.i(TAG, "PhoneStateListener.onCallStateChanged: " 240 // + state + ", '" + incomingNumber + "'"); 241 if ((state == TelephonyManager.CALL_STATE_IDLE) && dialpadChooserVisible()) { 242 // Log.i(TAG, "Call ended with dialpad chooser visible! Taking it down..."); 243 // Note there's a race condition in the UI here: the 244 // dialpad chooser could conceivably disappear (on its 245 // own) at the exact moment the user was trying to select 246 // one of the choices, which would be confusing. (But at 247 // least that's better than leaving the dialpad chooser 248 // onscreen, but useless...) 249 showDialpadChooser(false); 250 } 251 } 252 }; 253 254 private boolean mWasEmptyBeforeTextChange; 255 256 /** 257 * This field is set to true while processing an incoming DIAL intent, in order to make sure 258 * that SpecialCharSequenceMgr actions can be triggered by user input but *not* by a 259 * tel: URI passed by some other app. It will be set to false when all digits are cleared. 260 */ 261 private boolean mDigitsFilledByIntent; 262 263 private boolean mStartedFromNewIntent = false; 264 private boolean mFirstLaunch = false; 265 266 private static final String PREF_DIGITS_FILLED_BY_INTENT = "pref_digits_filled_by_intent"; 267 268 /** 269 * Return an Intent for launching voicemail screen. 270 */ 271 private static Intent getVoicemailIntent() { 272 final Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, 273 Uri.fromParts("voicemail", "", null)); 274 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 275 return intent; 276 } 277 278 private TelephonyManager getTelephonyManager() { 279 return (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE); 280 } 281 282 @Override 283 public void beforeTextChanged(CharSequence s, int start, int count, int after) { 284 mWasEmptyBeforeTextChange = TextUtils.isEmpty(s); 285 } 286 287 @Override 288 public void onTextChanged(CharSequence input, int start, int before, int changeCount) { 289 if (mWasEmptyBeforeTextChange != TextUtils.isEmpty(input)) { 290 final Activity activity = getActivity(); 291 if (activity != null) { 292 activity.invalidateOptionsMenu(); 293 } 294 } 295 296 // DTMF Tones do not need to be played here any longer - 297 // the DTMF dialer handles that functionality now. 298 } 299 300 @Override 301 public void afterTextChanged(Editable input) { 302 // When DTMF dialpad buttons are being pressed, we delay SpecialCharSequencMgr sequence, 303 // since some of SpecialCharSequenceMgr's behavior is too abrupt for the "touch-down" 304 // behavior. 305 if (!mDigitsFilledByIntent && 306 SpecialCharSequenceMgr.handleChars(getActivity(), input.toString(), mDigits)) { 307 // A special sequence was entered, clear the digits 308 mDigits.getText().clear(); 309 } 310 311 if (isDigitsEmpty()) { 312 mDigitsFilledByIntent = false; 313 mDigits.setCursorVisible(false); 314 } 315 316 if (mDialpadQueryListener != null) { 317 mDialpadQueryListener.onDialpadQueryChanged(mDigits.getText().toString()); 318 } 319 updateDialAndDeleteButtonEnabledState(); 320 } 321 322 @Override 323 public void onCreate(Bundle state) { 324 super.onCreate(state); 325 mFirstLaunch = true; 326 mContactsPrefs = new ContactsPreferences(getActivity()); 327 mCurrentCountryIso = GeoUtil.getCurrentCountryIso(getActivity()); 328 329 mDialerDatabaseHelper = DialerDatabaseHelper.getInstance(getActivity()); 330 SmartDialPrefix.initializeNanpSettings(getActivity()); 331 332 try { 333 mHaptic.init(getActivity(), 334 getResources().getBoolean(R.bool.config_enable_dialer_key_vibration)); 335 } catch (Resources.NotFoundException nfe) { 336 Log.e(TAG, "Vibrate control bool missing.", nfe); 337 } 338 339 mProhibitedPhoneNumberRegexp = getResources().getString( 340 R.string.config_prohibited_phone_number_regexp); 341 342 if (state != null) { 343 mDigitsFilledByIntent = state.getBoolean(PREF_DIGITS_FILLED_BY_INTENT); 344 } 345 } 346 347 @Override 348 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) { 349 final View fragmentView = inflater.inflate(R.layout.dialpad_fragment, container, 350 false); 351 fragmentView.buildLayer(); 352 353 // TODO krelease: Get rid of this ugly hack which is to prevent the first frame of the 354 // animation from drawing the fragment at translationY = 0 355 final ViewTreeObserver vto = fragmentView.getViewTreeObserver(); 356 final OnPreDrawListener preDrawListener = new OnPreDrawListener() { 357 358 @Override 359 public boolean onPreDraw() { 360 if (isHidden()) return true; 361 if (fragmentView.getTranslationY() == 0) { 362 ((DialpadSlidingLinearLayout) fragmentView).setYFraction( 363 DIALPAD_SLIDE_FRACTION); 364 } 365 final ViewTreeObserver vto = fragmentView.getViewTreeObserver(); 366 vto.removeOnPreDrawListener(this); 367 return true; 368 } 369 370 }; 371 372 vto.addOnPreDrawListener(preDrawListener); 373 374 // Load up the resources for the text field. 375 Resources r = getResources(); 376 377 mDigitsContainer = fragmentView.findViewById(R.id.digits_container); 378 mDigits = (EditText) fragmentView.findViewById(R.id.digits); 379 mDigits.setKeyListener(UnicodeDialerKeyListener.INSTANCE); 380 mDigits.setOnClickListener(this); 381 mDigits.setOnKeyListener(this); 382 mDigits.setOnLongClickListener(this); 383 mDigits.addTextChangedListener(this); 384 PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(getActivity(), mDigits); 385 // Check for the presence of the keypad 386 View oneButton = fragmentView.findViewById(R.id.one); 387 if (oneButton != null) { 388 setupKeypad(fragmentView); 389 } 390 391 mDialButton = fragmentView.findViewById(R.id.dialButton); 392 if (r.getBoolean(R.bool.config_show_onscreen_dial_button)) { 393 mDialButton.setOnClickListener(this); 394 mDialButton.setOnLongClickListener(this); 395 } else { 396 mDialButton.setVisibility(View.GONE); // It's VISIBLE by default 397 mDialButton = null; 398 } 399 400 mDelete = fragmentView.findViewById(R.id.deleteButton); 401 if (mDelete != null) { 402 mDelete.setOnClickListener(this); 403 mDelete.setOnLongClickListener(this); 404 } 405 406 mDialpad = fragmentView.findViewById(R.id.dialpad); // This is null in landscape mode. 407 408 // In landscape we put the keyboard in phone mode. 409 if (null == mDialpad) { 410 mDigits.setInputType(android.text.InputType.TYPE_CLASS_PHONE); 411 } else { 412 mDigits.setCursorVisible(false); 413 } 414 415 // Set up the "dialpad chooser" UI; see showDialpadChooser(). 416 mDialpadChooser = (ListView) fragmentView.findViewById(R.id.dialpadChooser); 417 mDialpadChooser.setOnItemClickListener(this); 418 419 return fragmentView; 420 } 421 422 @Override 423 public void onStart() { 424 super.onStart(); 425 426 final Activity activity = getActivity(); 427 428 try { 429 ((OnDialpadFragmentStartedListener) activity).onDialpadFragmentStarted(); 430 } catch (ClassCastException e) { 431 throw new ClassCastException(activity.toString() 432 + " must implement OnDialpadFragmentStartedListener"); 433 } 434 435 final View overflowButton = getView().findViewById(R.id.overflow_menu_on_dialpad); 436 overflowButton.setOnClickListener(this); 437 } 438 439 private boolean isLayoutReady() { 440 return mDigits != null; 441 } 442 443 public EditText getDigitsWidget() { 444 return mDigits; 445 } 446 447 /** 448 * @return true when {@link #mDigits} is actually filled by the Intent. 449 */ 450 private boolean fillDigitsIfNecessary(Intent intent) { 451 // Only fills digits from an intent if it is a new intent. 452 // Otherwise falls back to the previously used number. 453 if (!mFirstLaunch && !mStartedFromNewIntent) { 454 return false; 455 } 456 457 final String action = intent.getAction(); 458 if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action)) { 459 Uri uri = intent.getData(); 460 if (uri != null) { 461 if (CallUtil.SCHEME_TEL.equals(uri.getScheme())) { 462 // Put the requested number into the input area 463 String data = uri.getSchemeSpecificPart(); 464 // Remember it is filled via Intent. 465 mDigitsFilledByIntent = true; 466 final String converted = PhoneNumberUtils.convertKeypadLettersToDigits( 467 PhoneNumberUtils.replaceUnicodeDigits(data)); 468 setFormattedDigits(converted, null); 469 return true; 470 } else { 471 String type = intent.getType(); 472 if (People.CONTENT_ITEM_TYPE.equals(type) 473 || Phones.CONTENT_ITEM_TYPE.equals(type)) { 474 // Query the phone number 475 Cursor c = getActivity().getContentResolver().query(intent.getData(), 476 new String[] {PhonesColumns.NUMBER, PhonesColumns.NUMBER_KEY}, 477 null, null, null); 478 if (c != null) { 479 try { 480 if (c.moveToFirst()) { 481 // Remember it is filled via Intent. 482 mDigitsFilledByIntent = true; 483 // Put the number into the input area 484 setFormattedDigits(c.getString(0), c.getString(1)); 485 return true; 486 } 487 } finally { 488 c.close(); 489 } 490 } 491 } 492 } 493 } 494 } 495 return false; 496 } 497 498 /** 499 * Determines whether an add call operation is requested. 500 * 501 * @param intent The intent. 502 * @return {@literal true} if add call operation was requested. {@literal false} otherwise. 503 */ 504 private static boolean isAddCallMode(Intent intent) { 505 final String action = intent.getAction(); 506 if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action)) { 507 // see if we are "adding a call" from the InCallScreen; false by default. 508 return intent.getBooleanExtra(ADD_CALL_MODE_KEY, false); 509 } else { 510 return false; 511 } 512 } 513 514 /** 515 * Checks the given Intent and changes dialpad's UI state. For example, if the Intent requires 516 * the screen to enter "Add Call" mode, this method will show correct UI for the mode. 517 */ 518 private void configureScreenFromIntent(Activity parent) { 519 // If we were not invoked with a DIAL intent, 520 if (!(parent instanceof DialtactsActivity)) { 521 setStartedFromNewIntent(false); 522 return; 523 } 524 // See if we were invoked with a DIAL intent. If we were, fill in the appropriate 525 // digits in the dialer field. 526 Intent intent = parent.getIntent(); 527 528 if (!isLayoutReady()) { 529 // This happens typically when parent's Activity#onNewIntent() is called while 530 // Fragment#onCreateView() isn't called yet, and thus we cannot configure Views at 531 // this point. onViewCreate() should call this method after preparing layouts, so 532 // just ignore this call now. 533 Log.i(TAG, 534 "Screen configuration is requested before onCreateView() is called. Ignored"); 535 return; 536 } 537 538 boolean needToShowDialpadChooser = false; 539 540 // Be sure *not* to show the dialpad chooser if this is an 541 // explicit "Add call" action, though. 542 final boolean isAddCallMode = isAddCallMode(intent); 543 if (!isAddCallMode) { 544 545 // Don't show the chooser when called via onNewIntent() and phone number is present. 546 // i.e. User clicks a telephone link from gmail for example. 547 // In this case, we want to show the dialpad with the phone number. 548 final boolean digitsFilled = fillDigitsIfNecessary(intent); 549 if (!(mStartedFromNewIntent && digitsFilled)) { 550 551 final String action = intent.getAction(); 552 if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action) 553 || Intent.ACTION_MAIN.equals(action)) { 554 // If there's already an active call, bring up an intermediate UI to 555 // make the user confirm what they really want to do. 556 if (phoneIsInUse()) { 557 needToShowDialpadChooser = true; 558 } 559 } 560 561 } 562 } 563 showDialpadChooser(needToShowDialpadChooser); 564 setStartedFromNewIntent(false); 565 } 566 567 public void setStartedFromNewIntent(boolean value) { 568 mStartedFromNewIntent = value; 569 } 570 571 /** 572 * Sets formatted digits to digits field. 573 */ 574 private void setFormattedDigits(String data, String normalizedNumber) { 575 // strip the non-dialable numbers out of the data string. 576 String dialString = PhoneNumberUtils.extractNetworkPortion(data); 577 dialString = 578 PhoneNumberUtils.formatNumber(dialString, normalizedNumber, mCurrentCountryIso); 579 if (!TextUtils.isEmpty(dialString)) { 580 Editable digits = mDigits.getText(); 581 digits.replace(0, digits.length(), dialString); 582 // for some reason this isn't getting called in the digits.replace call above.. 583 // but in any case, this will make sure the background drawable looks right 584 afterTextChanged(digits); 585 } 586 } 587 588 private void setupKeypad(View fragmentView) { 589 final int[] buttonIds = new int[] {R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four, 590 R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.star, R.id.pound}; 591 592 final int[] numberIds = new int[] {R.string.dialpad_0_number, R.string.dialpad_1_number, 593 R.string.dialpad_2_number, R.string.dialpad_3_number, R.string.dialpad_4_number, 594 R.string.dialpad_5_number, R.string.dialpad_6_number, R.string.dialpad_7_number, 595 R.string.dialpad_8_number, R.string.dialpad_9_number, R.string.dialpad_star_number, 596 R.string.dialpad_pound_number}; 597 598 final int[] letterIds = new int[] {R.string.dialpad_0_letters, R.string.dialpad_1_letters, 599 R.string.dialpad_2_letters, R.string.dialpad_3_letters, R.string.dialpad_4_letters, 600 R.string.dialpad_5_letters, R.string.dialpad_6_letters, R.string.dialpad_7_letters, 601 R.string.dialpad_8_letters, R.string.dialpad_9_letters, 602 R.string.dialpad_star_letters, R.string.dialpad_pound_letters}; 603 604 DialpadKeyButton dialpadKey; 605 TextView numberView; 606 TextView lettersView; 607 final Resources resources = getResources(); 608 for (int i = 0; i < buttonIds.length; i++) { 609 dialpadKey = (DialpadKeyButton) fragmentView.findViewById(buttonIds[i]); 610 dialpadKey.setLayoutParams(new TableRow.LayoutParams( 611 TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); 612 dialpadKey.setOnPressedListener(this); 613 numberView = (TextView) dialpadKey.findViewById(R.id.dialpad_key_number); 614 lettersView = (TextView) dialpadKey.findViewById(R.id.dialpad_key_letters); 615 numberView.setText(resources.getString(numberIds[i])); 616 if (lettersView != null) { 617 lettersView.setText(resources.getString(letterIds[i])); 618 } 619 } 620 621 // Long-pressing one button will initiate Voicemail. 622 fragmentView.findViewById(R.id.one).setOnLongClickListener(this); 623 624 // Long-pressing zero button will enter '+' instead. 625 fragmentView.findViewById(R.id.zero).setOnLongClickListener(this); 626 627 } 628 629 @Override 630 public void onResume() { 631 super.onResume(); 632 633 final DialtactsActivity activity = (DialtactsActivity) getActivity(); 634 mDialpadQueryListener = activity; 635 636 final StopWatch stopWatch = StopWatch.start("Dialpad.onResume"); 637 638 // Query the last dialed number. Do it first because hitting 639 // the DB is 'slow'. This call is asynchronous. 640 queryLastOutgoingCall(); 641 642 stopWatch.lap("qloc"); 643 644 final ContentResolver contentResolver = activity.getContentResolver(); 645 646 // retrieve the DTMF tone play back setting. 647 mDTMFToneEnabled = Settings.System.getInt(contentResolver, 648 Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1; 649 650 stopWatch.lap("dtwd"); 651 652 // Retrieve the haptic feedback setting. 653 mHaptic.checkSystemSetting(); 654 655 stopWatch.lap("hptc"); 656 657 // if the mToneGenerator creation fails, just continue without it. It is 658 // a local audio signal, and is not as important as the dtmf tone itself. 659 synchronized (mToneGeneratorLock) { 660 if (mToneGenerator == null) { 661 try { 662 mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME); 663 } catch (RuntimeException e) { 664 Log.w(TAG, "Exception caught while creating local tone generator: " + e); 665 mToneGenerator = null; 666 } 667 } 668 } 669 stopWatch.lap("tg"); 670 // Prevent unnecessary confusion. Reset the press count anyway. 671 mDialpadPressCount = 0; 672 673 // Initialize smart dialing state. This has to be done before anything is filled in before 674 // the dialpad edittext to prevent entries from being loaded from a null cache. 675 initializeSmartDialingState(); 676 677 configureScreenFromIntent(getActivity()); 678 679 stopWatch.lap("fdin"); 680 681 // While we're in the foreground, listen for phone state changes, 682 // purely so that we can take down the "dialpad chooser" if the 683 // phone becomes idle while the chooser UI is visible. 684 getTelephonyManager().listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); 685 686 stopWatch.lap("tm"); 687 688 // Potentially show hint text in the mDigits field when the user 689 // hasn't typed any digits yet. (If there's already an active call, 690 // this hint text will remind the user that he's about to add a new 691 // call.) 692 // 693 // TODO: consider adding better UI for the case where *both* lines 694 // are currently in use. (Right now we let the user try to add 695 // another call, but that call is guaranteed to fail. Perhaps the 696 // entire dialer UI should be disabled instead.) 697 if (phoneIsInUse()) { 698 final SpannableString hint = new SpannableString( 699 getActivity().getString(R.string.dialerDialpadHintText)); 700 hint.setSpan(new RelativeSizeSpan(0.8f), 0, hint.length(), 0); 701 mDigits.setHint(hint); 702 } else { 703 // Common case; no hint necessary. 704 mDigits.setHint(null); 705 706 // Also, a sanity-check: the "dialpad chooser" UI should NEVER 707 // be visible if the phone is idle! 708 showDialpadChooser(false); 709 } 710 711 mFirstLaunch = false; 712 713 stopWatch.lap("hnt"); 714 715 updateDialAndDeleteButtonEnabledState(); 716 717 stopWatch.lap("bes"); 718 719 stopWatch.stopAndLog(TAG, 50); 720 } 721 722 @Override 723 public void onPause() { 724 super.onPause(); 725 726 // Stop listening for phone state changes. 727 getTelephonyManager().listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); 728 729 // Make sure we don't leave this activity with a tone still playing. 730 stopTone(); 731 // Just in case reset the counter too. 732 mDialpadPressCount = 0; 733 734 synchronized (mToneGeneratorLock) { 735 if (mToneGenerator != null) { 736 mToneGenerator.release(); 737 mToneGenerator = null; 738 } 739 } 740 // TODO: I wonder if we should not check if the AsyncTask that 741 // lookup the last dialed number has completed. 742 mLastNumberDialed = EMPTY_NUMBER; // Since we are going to query again, free stale number. 743 744 SpecialCharSequenceMgr.cleanup(); 745 } 746 747 @Override 748 public void onStop() { 749 super.onStop(); 750 751 if (mClearDigitsOnStop) { 752 mClearDigitsOnStop = false; 753 mDigits.getText().clear(); 754 } 755 } 756 757 @Override 758 public void onSaveInstanceState(Bundle outState) { 759 super.onSaveInstanceState(outState); 760 outState.putBoolean(PREF_DIGITS_FILLED_BY_INTENT, mDigitsFilledByIntent); 761 } 762 763 private void setupMenuItems(Menu menu) { 764 final MenuItem addToContactMenuItem = menu.findItem(R.id.menu_add_contacts); 765 766 // We show "add to contacts" menu only when the user is 767 // seeing usual dialpad and has typed at least one digit. 768 // We never show a menu if the "choose dialpad" UI is up. 769 if (dialpadChooserVisible() || isDigitsEmpty()) { 770 addToContactMenuItem.setVisible(false); 771 } else { 772 final CharSequence digits = mDigits.getText(); 773 // Put the current digits string into an intent 774 addToContactMenuItem.setIntent(getAddToContactIntent(digits)); 775 addToContactMenuItem.setVisible(true); 776 } 777 } 778 779 private static Intent getAddToContactIntent(CharSequence digits) { 780 final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT); 781 intent.putExtra(Insert.PHONE, digits); 782 intent.setType(People.CONTENT_ITEM_TYPE); 783 return intent; 784 } 785 786 private void keyPressed(int keyCode) { 787 switch (keyCode) { 788 case KeyEvent.KEYCODE_1: 789 playTone(ToneGenerator.TONE_DTMF_1, TONE_LENGTH_INFINITE); 790 break; 791 case KeyEvent.KEYCODE_2: 792 playTone(ToneGenerator.TONE_DTMF_2, TONE_LENGTH_INFINITE); 793 break; 794 case KeyEvent.KEYCODE_3: 795 playTone(ToneGenerator.TONE_DTMF_3, TONE_LENGTH_INFINITE); 796 break; 797 case KeyEvent.KEYCODE_4: 798 playTone(ToneGenerator.TONE_DTMF_4, TONE_LENGTH_INFINITE); 799 break; 800 case KeyEvent.KEYCODE_5: 801 playTone(ToneGenerator.TONE_DTMF_5, TONE_LENGTH_INFINITE); 802 break; 803 case KeyEvent.KEYCODE_6: 804 playTone(ToneGenerator.TONE_DTMF_6, TONE_LENGTH_INFINITE); 805 break; 806 case KeyEvent.KEYCODE_7: 807 playTone(ToneGenerator.TONE_DTMF_7, TONE_LENGTH_INFINITE); 808 break; 809 case KeyEvent.KEYCODE_8: 810 playTone(ToneGenerator.TONE_DTMF_8, TONE_LENGTH_INFINITE); 811 break; 812 case KeyEvent.KEYCODE_9: 813 playTone(ToneGenerator.TONE_DTMF_9, TONE_LENGTH_INFINITE); 814 break; 815 case KeyEvent.KEYCODE_0: 816 playTone(ToneGenerator.TONE_DTMF_0, TONE_LENGTH_INFINITE); 817 break; 818 case KeyEvent.KEYCODE_POUND: 819 playTone(ToneGenerator.TONE_DTMF_P, TONE_LENGTH_INFINITE); 820 break; 821 case KeyEvent.KEYCODE_STAR: 822 playTone(ToneGenerator.TONE_DTMF_S, TONE_LENGTH_INFINITE); 823 break; 824 default: 825 break; 826 } 827 828 mHaptic.vibrate(); 829 KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); 830 mDigits.onKeyDown(keyCode, event); 831 832 // If the cursor is at the end of the text we hide it. 833 final int length = mDigits.length(); 834 if (length == mDigits.getSelectionStart() && length == mDigits.getSelectionEnd()) { 835 mDigits.setCursorVisible(false); 836 } 837 } 838 839 @Override 840 public boolean onKey(View view, int keyCode, KeyEvent event) { 841 switch (view.getId()) { 842 case R.id.digits: 843 if (keyCode == KeyEvent.KEYCODE_ENTER) { 844 dialButtonPressed(); 845 return true; 846 } 847 break; 848 } 849 return false; 850 } 851 852 /** 853 * When a key is pressed, we start playing DTMF tone, do vibration, and enter the digit 854 * immediately. When a key is released, we stop the tone. Note that the "key press" event will 855 * be delivered by the system with certain amount of delay, it won't be synced with user's 856 * actual "touch-down" behavior. 857 */ 858 @Override 859 public void onPressed(View view, boolean pressed) { 860 if (DEBUG) Log.d(TAG, "onPressed(). view: " + view + ", pressed: " + pressed); 861 if (pressed) { 862 switch (view.getId()) { 863 case R.id.one: { 864 keyPressed(KeyEvent.KEYCODE_1); 865 break; 866 } 867 case R.id.two: { 868 keyPressed(KeyEvent.KEYCODE_2); 869 break; 870 } 871 case R.id.three: { 872 keyPressed(KeyEvent.KEYCODE_3); 873 break; 874 } 875 case R.id.four: { 876 keyPressed(KeyEvent.KEYCODE_4); 877 break; 878 } 879 case R.id.five: { 880 keyPressed(KeyEvent.KEYCODE_5); 881 break; 882 } 883 case R.id.six: { 884 keyPressed(KeyEvent.KEYCODE_6); 885 break; 886 } 887 case R.id.seven: { 888 keyPressed(KeyEvent.KEYCODE_7); 889 break; 890 } 891 case R.id.eight: { 892 keyPressed(KeyEvent.KEYCODE_8); 893 break; 894 } 895 case R.id.nine: { 896 keyPressed(KeyEvent.KEYCODE_9); 897 break; 898 } 899 case R.id.zero: { 900 keyPressed(KeyEvent.KEYCODE_0); 901 break; 902 } 903 case R.id.pound: { 904 keyPressed(KeyEvent.KEYCODE_POUND); 905 break; 906 } 907 case R.id.star: { 908 keyPressed(KeyEvent.KEYCODE_STAR); 909 break; 910 } 911 default: { 912 Log.wtf(TAG, "Unexpected onTouch(ACTION_DOWN) event from: " + view); 913 break; 914 } 915 } 916 mDialpadPressCount++; 917 } else { 918 view.jumpDrawablesToCurrentState(); 919 mDialpadPressCount--; 920 if (mDialpadPressCount < 0) { 921 // e.g. 922 // - when the user action is detected as horizontal swipe, at which only 923 // "up" event is thrown. 924 // - when the user long-press '0' button, at which dialpad will decrease this count 925 // while it still gets press-up event here. 926 if (DEBUG) Log.d(TAG, "mKeyPressCount become negative."); 927 stopTone(); 928 mDialpadPressCount = 0; 929 } else if (mDialpadPressCount == 0) { 930 stopTone(); 931 } 932 } 933 } 934 935 @Override 936 public void onClick(View view) { 937 switch (view.getId()) { 938 case R.id.overflow_menu_on_dialpad: { 939 final PopupMenu popupMenu = new PopupMenu(getActivity(), view); 940 final Menu menu = popupMenu.getMenu(); 941 popupMenu.inflate(R.menu.dialpad_options); 942 popupMenu.setOnMenuItemClickListener(this); 943 setupMenuItems(menu); 944 popupMenu.show(); 945 break; 946 } 947 case R.id.deleteButton: { 948 keyPressed(KeyEvent.KEYCODE_DEL); 949 return; 950 } 951 case R.id.dialButton: { 952 mHaptic.vibrate(); // Vibrate here too, just like we do for the regular keys 953 dialButtonPressed(); 954 return; 955 } 956 case R.id.digits: { 957 if (!isDigitsEmpty()) { 958 mDigits.setCursorVisible(true); 959 } 960 return; 961 } 962 default: { 963 Log.wtf(TAG, "Unexpected onClick() event from: " + view); 964 return; 965 } 966 } 967 } 968 969 @Override 970 public boolean onLongClick(View view) { 971 final Editable digits = mDigits.getText(); 972 final int id = view.getId(); 973 switch (id) { 974 case R.id.deleteButton: { 975 digits.clear(); 976 // TODO: The framework forgets to clear the pressed 977 // status of disabled button. Until this is fixed, 978 // clear manually the pressed status. b/2133127 979 mDelete.setPressed(false); 980 return true; 981 } 982 case R.id.one: { 983 // '1' may be already entered since we rely on onTouch() event for numeric buttons. 984 // Just for safety we also check if the digits field is empty or not. 985 if (isDigitsEmpty() || TextUtils.equals(mDigits.getText(), "1")) { 986 // We'll try to initiate voicemail and thus we want to remove irrelevant string. 987 removePreviousDigitIfPossible(); 988 989 if (isVoicemailAvailable()) { 990 callVoicemail(); 991 } else if (getActivity() != null) { 992 // Voicemail is unavailable maybe because Airplane mode is turned on. 993 // Check the current status and show the most appropriate error message. 994 final boolean isAirplaneModeOn = 995 Settings.System.getInt(getActivity().getContentResolver(), 996 Settings.System.AIRPLANE_MODE_ON, 0) != 0; 997 if (isAirplaneModeOn) { 998 DialogFragment dialogFragment = ErrorDialogFragment.newInstance( 999 R.string.dialog_voicemail_airplane_mode_message); 1000 dialogFragment.show(getFragmentManager(), 1001 "voicemail_request_during_airplane_mode"); 1002 } else { 1003 DialogFragment dialogFragment = ErrorDialogFragment.newInstance( 1004 R.string.dialog_voicemail_not_ready_message); 1005 dialogFragment.show(getFragmentManager(), "voicemail_not_ready"); 1006 } 1007 } 1008 return true; 1009 } 1010 return false; 1011 } 1012 case R.id.zero: { 1013 // Remove tentative input ('0') done by onTouch(). 1014 removePreviousDigitIfPossible(); 1015 keyPressed(KeyEvent.KEYCODE_PLUS); 1016 1017 // Stop tone immediately and decrease the press count, so that possible subsequent 1018 // dial button presses won't honor the 0 click any more. 1019 // Note: this *will* make mDialpadPressCount negative when the 0 key is released, 1020 // which should be handled appropriately. 1021 stopTone(); 1022 if (mDialpadPressCount > 0) mDialpadPressCount--; 1023 1024 return true; 1025 } 1026 case R.id.digits: { 1027 // Right now EditText does not show the "paste" option when cursor is not visible. 1028 // To show that, make the cursor visible, and return false, letting the EditText 1029 // show the option by itself. 1030 mDigits.setCursorVisible(true); 1031 return false; 1032 } 1033 case R.id.dialButton: { 1034 if (isDigitsEmpty()) { 1035 handleDialButtonClickWithEmptyDigits(); 1036 // This event should be consumed so that onClick() won't do the exactly same 1037 // thing. 1038 return true; 1039 } else { 1040 return false; 1041 } 1042 } 1043 } 1044 return false; 1045 } 1046 1047 /** 1048 * Remove the digit just before the current position. This can be used if we want to replace 1049 * the previous digit or cancel previously entered character. 1050 */ 1051 private void removePreviousDigitIfPossible() { 1052 final Editable editable = mDigits.getText(); 1053 final int currentPosition = mDigits.getSelectionStart(); 1054 if (currentPosition > 0) { 1055 mDigits.setSelection(currentPosition); 1056 mDigits.getText().delete(currentPosition - 1, currentPosition); 1057 } 1058 } 1059 1060 public void callVoicemail() { 1061 startActivity(getVoicemailIntent()); 1062 mClearDigitsOnStop = true; 1063 getActivity().finish(); 1064 } 1065 1066 public static class ErrorDialogFragment extends DialogFragment { 1067 private int mTitleResId; 1068 private int mMessageResId; 1069 1070 private static final String ARG_TITLE_RES_ID = "argTitleResId"; 1071 private static final String ARG_MESSAGE_RES_ID = "argMessageResId"; 1072 1073 public static ErrorDialogFragment newInstance(int messageResId) { 1074 return newInstance(0, messageResId); 1075 } 1076 1077 public static ErrorDialogFragment newInstance(int titleResId, int messageResId) { 1078 final ErrorDialogFragment fragment = new ErrorDialogFragment(); 1079 final Bundle args = new Bundle(); 1080 args.putInt(ARG_TITLE_RES_ID, titleResId); 1081 args.putInt(ARG_MESSAGE_RES_ID, messageResId); 1082 fragment.setArguments(args); 1083 return fragment; 1084 } 1085 1086 @Override 1087 public void onCreate(Bundle savedInstanceState) { 1088 super.onCreate(savedInstanceState); 1089 mTitleResId = getArguments().getInt(ARG_TITLE_RES_ID); 1090 mMessageResId = getArguments().getInt(ARG_MESSAGE_RES_ID); 1091 } 1092 1093 @Override 1094 public Dialog onCreateDialog(Bundle savedInstanceState) { 1095 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 1096 if (mTitleResId != 0) { 1097 builder.setTitle(mTitleResId); 1098 } 1099 if (mMessageResId != 0) { 1100 builder.setMessage(mMessageResId); 1101 } 1102 builder.setPositiveButton(android.R.string.ok, 1103 new DialogInterface.OnClickListener() { 1104 @Override 1105 public void onClick(DialogInterface dialog, int which) { 1106 dismiss(); 1107 } 1108 }); 1109 return builder.create(); 1110 } 1111 } 1112 1113 /** 1114 * In most cases, when the dial button is pressed, there is a 1115 * number in digits area. Pack it in the intent, start the 1116 * outgoing call broadcast as a separate task and finish this 1117 * activity. 1118 * 1119 * When there is no digit and the phone is CDMA and off hook, 1120 * we're sending a blank flash for CDMA. CDMA networks use Flash 1121 * messages when special processing needs to be done, mainly for 1122 * 3-way or call waiting scenarios. Presumably, here we're in a 1123 * special 3-way scenario where the network needs a blank flash 1124 * before being able to add the new participant. (This is not the 1125 * case with all 3-way calls, just certain CDMA infrastructures.) 1126 * 1127 * Otherwise, there is no digit, display the last dialed 1128 * number. Don't finish since the user may want to edit it. The 1129 * user needs to press the dial button again, to dial it (general 1130 * case described above). 1131 */ 1132 public void dialButtonPressed() { 1133 if (isDigitsEmpty()) { // No number entered. 1134 handleDialButtonClickWithEmptyDigits(); 1135 } else { 1136 final String number = mDigits.getText().toString(); 1137 1138 // "persist.radio.otaspdial" is a temporary hack needed for one carrier's automated 1139 // test equipment. 1140 // TODO: clean it up. 1141 if (number != null 1142 && !TextUtils.isEmpty(mProhibitedPhoneNumberRegexp) 1143 && number.matches(mProhibitedPhoneNumberRegexp) 1144 && (SystemProperties.getInt("persist.radio.otaspdial", 0) != 1)) { 1145 Log.i(TAG, "The phone number is prohibited explicitly by a rule."); 1146 if (getActivity() != null) { 1147 DialogFragment dialogFragment = ErrorDialogFragment.newInstance( 1148 R.string.dialog_phone_call_prohibited_message); 1149 dialogFragment.show(getFragmentManager(), "phone_prohibited_dialog"); 1150 } 1151 1152 // Clear the digits just in case. 1153 mDigits.getText().clear(); 1154 } else { 1155 final Intent intent = CallUtil.getCallIntent(number, 1156 (getActivity() instanceof DialtactsActivity ? 1157 ((DialtactsActivity) getActivity()).getCallOrigin() : null)); 1158 startActivity(intent); 1159 mClearDigitsOnStop = true; 1160 getActivity().finish(); 1161 } 1162 } 1163 } 1164 1165 private String getCallOrigin() { 1166 return (getActivity() instanceof DialtactsActivity) ? 1167 ((DialtactsActivity) getActivity()).getCallOrigin() : null; 1168 } 1169 1170 private void handleDialButtonClickWithEmptyDigits() { 1171 if (phoneIsCdma() && phoneIsOffhook()) { 1172 // This is really CDMA specific. On GSM is it possible 1173 // to be off hook and wanted to add a 3rd party using 1174 // the redial feature. 1175 startActivity(newFlashIntent()); 1176 } else { 1177 if (!TextUtils.isEmpty(mLastNumberDialed)) { 1178 // Recall the last number dialed. 1179 mDigits.setText(mLastNumberDialed); 1180 1181 // ...and move the cursor to the end of the digits string, 1182 // so you'll be able to delete digits using the Delete 1183 // button (just as if you had typed the number manually.) 1184 // 1185 // Note we use mDigits.getText().length() here, not 1186 // mLastNumberDialed.length(), since the EditText widget now 1187 // contains a *formatted* version of mLastNumberDialed (due to 1188 // mTextWatcher) and its length may have changed. 1189 mDigits.setSelection(mDigits.getText().length()); 1190 } else { 1191 // There's no "last number dialed" or the 1192 // background query is still running. There's 1193 // nothing useful for the Dial button to do in 1194 // this case. Note: with a soft dial button, this 1195 // can never happens since the dial button is 1196 // disabled under these conditons. 1197 playTone(ToneGenerator.TONE_PROP_NACK); 1198 } 1199 } 1200 } 1201 1202 /** 1203 * Plays the specified tone for TONE_LENGTH_MS milliseconds. 1204 */ 1205 private void playTone(int tone) { 1206 playTone(tone, TONE_LENGTH_MS); 1207 } 1208 1209 /** 1210 * Play the specified tone for the specified milliseconds 1211 * 1212 * The tone is played locally, using the audio stream for phone calls. 1213 * Tones are played only if the "Audible touch tones" user preference 1214 * is checked, and are NOT played if the device is in silent mode. 1215 * 1216 * The tone length can be -1, meaning "keep playing the tone." If the caller does so, it should 1217 * call stopTone() afterward. 1218 * 1219 * @param tone a tone code from {@link ToneGenerator} 1220 * @param durationMs tone length. 1221 */ 1222 private void playTone(int tone, int durationMs) { 1223 // if local tone playback is disabled, just return. 1224 if (!mDTMFToneEnabled) { 1225 return; 1226 } 1227 1228 // Also do nothing if the phone is in silent mode. 1229 // We need to re-check the ringer mode for *every* playTone() 1230 // call, rather than keeping a local flag that's updated in 1231 // onResume(), since it's possible to toggle silent mode without 1232 // leaving the current activity (via the ENDCALL-longpress menu.) 1233 AudioManager audioManager = 1234 (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); 1235 int ringerMode = audioManager.getRingerMode(); 1236 if ((ringerMode == AudioManager.RINGER_MODE_SILENT) 1237 || (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) { 1238 return; 1239 } 1240 1241 synchronized (mToneGeneratorLock) { 1242 if (mToneGenerator == null) { 1243 Log.w(TAG, "playTone: mToneGenerator == null, tone: " + tone); 1244 return; 1245 } 1246 1247 // Start the new tone (will stop any playing tone) 1248 mToneGenerator.startTone(tone, durationMs); 1249 } 1250 } 1251 1252 /** 1253 * Stop the tone if it is played. 1254 */ 1255 private void stopTone() { 1256 // if local tone playback is disabled, just return. 1257 if (!mDTMFToneEnabled) { 1258 return; 1259 } 1260 synchronized (mToneGeneratorLock) { 1261 if (mToneGenerator == null) { 1262 Log.w(TAG, "stopTone: mToneGenerator == null"); 1263 return; 1264 } 1265 mToneGenerator.stopTone(); 1266 } 1267 } 1268 1269 /** 1270 * Brings up the "dialpad chooser" UI in place of the usual Dialer 1271 * elements (the textfield/button and the dialpad underneath). 1272 * 1273 * We show this UI if the user brings up the Dialer while a call is 1274 * already in progress, since there's a good chance we got here 1275 * accidentally (and the user really wanted the in-call dialpad instead). 1276 * So in this situation we display an intermediate UI that lets the user 1277 * explicitly choose between the in-call dialpad ("Use touch tone 1278 * keypad") and the regular Dialer ("Add call"). (Or, the option "Return 1279 * to call in progress" just goes back to the in-call UI with no dialpad 1280 * at all.) 1281 * 1282 * @param enabled If true, show the "dialpad chooser" instead 1283 * of the regular Dialer UI 1284 */ 1285 private void showDialpadChooser(boolean enabled) { 1286 // Check if onCreateView() is already called by checking one of View objects. 1287 if (!isLayoutReady()) { 1288 return; 1289 } 1290 1291 if (enabled) { 1292 // Log.i(TAG, "Showing dialpad chooser!"); 1293 if (mDigitsContainer != null) { 1294 mDigitsContainer.setVisibility(View.GONE); 1295 } else { 1296 // mDigits is not enclosed by the container. Make the digits field itself gone. 1297 mDigits.setVisibility(View.GONE); 1298 } 1299 if (mDialpad != null) mDialpad.setVisibility(View.GONE); 1300 if (mDialButtonContainer != null) mDialButtonContainer.setVisibility(View.GONE); 1301 1302 mDialpadChooser.setVisibility(View.VISIBLE); 1303 1304 // Instantiate the DialpadChooserAdapter and hook it up to the 1305 // ListView. We do this only once. 1306 if (mDialpadChooserAdapter == null) { 1307 mDialpadChooserAdapter = new DialpadChooserAdapter(getActivity()); 1308 } 1309 mDialpadChooser.setAdapter(mDialpadChooserAdapter); 1310 } else { 1311 // Log.i(TAG, "Displaying normal Dialer UI."); 1312 if (mDigitsContainer != null) { 1313 mDigitsContainer.setVisibility(View.VISIBLE); 1314 } else { 1315 mDigits.setVisibility(View.VISIBLE); 1316 } 1317 if (mDialpad != null) mDialpad.setVisibility(View.VISIBLE); 1318 if (mDialButtonContainer != null) mDialButtonContainer.setVisibility(View.VISIBLE); 1319 mDialpadChooser.setVisibility(View.GONE); 1320 } 1321 } 1322 1323 /** 1324 * @return true if we're currently showing the "dialpad chooser" UI. 1325 */ 1326 private boolean dialpadChooserVisible() { 1327 return mDialpadChooser.getVisibility() == View.VISIBLE; 1328 } 1329 1330 /** 1331 * Simple list adapter, binding to an icon + text label 1332 * for each item in the "dialpad chooser" list. 1333 */ 1334 private static class DialpadChooserAdapter extends BaseAdapter { 1335 private LayoutInflater mInflater; 1336 1337 // Simple struct for a single "choice" item. 1338 static class ChoiceItem { 1339 String text; 1340 Bitmap icon; 1341 int id; 1342 1343 public ChoiceItem(String s, Bitmap b, int i) { 1344 text = s; 1345 icon = b; 1346 id = i; 1347 } 1348 } 1349 1350 // IDs for the possible "choices": 1351 static final int DIALPAD_CHOICE_USE_DTMF_DIALPAD = 101; 1352 static final int DIALPAD_CHOICE_RETURN_TO_CALL = 102; 1353 static final int DIALPAD_CHOICE_ADD_NEW_CALL = 103; 1354 1355 private static final int NUM_ITEMS = 3; 1356 private ChoiceItem mChoiceItems[] = new ChoiceItem[NUM_ITEMS]; 1357 1358 public DialpadChooserAdapter(Context context) { 1359 // Cache the LayoutInflate to avoid asking for a new one each time. 1360 mInflater = LayoutInflater.from(context); 1361 1362 // Initialize the possible choices. 1363 // TODO: could this be specified entirely in XML? 1364 1365 // - "Use touch tone keypad" 1366 mChoiceItems[0] = new ChoiceItem( 1367 context.getString(R.string.dialer_useDtmfDialpad), 1368 BitmapFactory.decodeResource(context.getResources(), 1369 R.drawable.ic_dialer_fork_tt_keypad), 1370 DIALPAD_CHOICE_USE_DTMF_DIALPAD); 1371 1372 // - "Return to call in progress" 1373 mChoiceItems[1] = new ChoiceItem( 1374 context.getString(R.string.dialer_returnToInCallScreen), 1375 BitmapFactory.decodeResource(context.getResources(), 1376 R.drawable.ic_dialer_fork_current_call), 1377 DIALPAD_CHOICE_RETURN_TO_CALL); 1378 1379 // - "Add call" 1380 mChoiceItems[2] = new ChoiceItem( 1381 context.getString(R.string.dialer_addAnotherCall), 1382 BitmapFactory.decodeResource(context.getResources(), 1383 R.drawable.ic_dialer_fork_add_call), 1384 DIALPAD_CHOICE_ADD_NEW_CALL); 1385 } 1386 1387 @Override 1388 public int getCount() { 1389 return NUM_ITEMS; 1390 } 1391 1392 /** 1393 * Return the ChoiceItem for a given position. 1394 */ 1395 @Override 1396 public Object getItem(int position) { 1397 return mChoiceItems[position]; 1398 } 1399 1400 /** 1401 * Return a unique ID for each possible choice. 1402 */ 1403 @Override 1404 public long getItemId(int position) { 1405 return position; 1406 } 1407 1408 /** 1409 * Make a view for each row. 1410 */ 1411 @Override 1412 public View getView(int position, View convertView, ViewGroup parent) { 1413 // When convertView is non-null, we can reuse it (there's no need 1414 // to reinflate it.) 1415 if (convertView == null) { 1416 convertView = mInflater.inflate(R.layout.dialpad_chooser_list_item, null); 1417 } 1418 1419 TextView text = (TextView) convertView.findViewById(R.id.text); 1420 text.setText(mChoiceItems[position].text); 1421 1422 ImageView icon = (ImageView) convertView.findViewById(R.id.icon); 1423 icon.setImageBitmap(mChoiceItems[position].icon); 1424 1425 return convertView; 1426 } 1427 } 1428 1429 /** 1430 * Handle clicks from the dialpad chooser. 1431 */ 1432 @Override 1433 public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 1434 DialpadChooserAdapter.ChoiceItem item = 1435 (DialpadChooserAdapter.ChoiceItem) parent.getItemAtPosition(position); 1436 int itemId = item.id; 1437 switch (itemId) { 1438 case DialpadChooserAdapter.DIALPAD_CHOICE_USE_DTMF_DIALPAD: 1439 // Log.i(TAG, "DIALPAD_CHOICE_USE_DTMF_DIALPAD"); 1440 // Fire off an intent to go back to the in-call UI 1441 // with the dialpad visible. 1442 returnToInCallScreen(true); 1443 break; 1444 1445 case DialpadChooserAdapter.DIALPAD_CHOICE_RETURN_TO_CALL: 1446 // Log.i(TAG, "DIALPAD_CHOICE_RETURN_TO_CALL"); 1447 // Fire off an intent to go back to the in-call UI 1448 // (with the dialpad hidden). 1449 returnToInCallScreen(false); 1450 break; 1451 1452 case DialpadChooserAdapter.DIALPAD_CHOICE_ADD_NEW_CALL: 1453 // Log.i(TAG, "DIALPAD_CHOICE_ADD_NEW_CALL"); 1454 // Ok, guess the user really did want to be here (in the 1455 // regular Dialer) after all. Bring back the normal Dialer UI. 1456 showDialpadChooser(false); 1457 break; 1458 1459 default: 1460 Log.w(TAG, "onItemClick: unexpected itemId: " + itemId); 1461 break; 1462 } 1463 } 1464 1465 /** 1466 * Returns to the in-call UI (where there's presumably a call in 1467 * progress) in response to the user selecting "use touch tone keypad" 1468 * or "return to call" from the dialpad chooser. 1469 */ 1470 private void returnToInCallScreen(boolean showDialpad) { 1471 try { 1472 ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone")); 1473 if (phone != null) phone.showCallScreenWithDialpad(showDialpad); 1474 } catch (RemoteException e) { 1475 Log.w(TAG, "phone.showCallScreenWithDialpad() failed", e); 1476 } 1477 1478 // Finally, finish() ourselves so that we don't stay on the 1479 // activity stack. 1480 // Note that we do this whether or not the showCallScreenWithDialpad() 1481 // call above had any effect or not! (That call is a no-op if the 1482 // phone is idle, which can happen if the current call ends while 1483 // the dialpad chooser is up. In this case we can't show the 1484 // InCallScreen, and there's no point staying here in the Dialer, 1485 // so we just take the user back where he came from...) 1486 getActivity().finish(); 1487 } 1488 1489 /** 1490 * @return true if the phone is "in use", meaning that at least one line 1491 * is active (ie. off hook or ringing or dialing). 1492 */ 1493 public boolean phoneIsInUse() { 1494 return getTelephonyManager().getCallState() != TelephonyManager.CALL_STATE_IDLE; 1495 } 1496 1497 /** 1498 * @return true if the phone is a CDMA phone type 1499 */ 1500 private boolean phoneIsCdma() { 1501 return getTelephonyManager().getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA; 1502 } 1503 1504 /** 1505 * @return true if the phone state is OFFHOOK 1506 */ 1507 private boolean phoneIsOffhook() { 1508 return getTelephonyManager().getCallState() == TelephonyManager.CALL_STATE_OFFHOOK; 1509 } 1510 1511 @Override 1512 public boolean onMenuItemClick(MenuItem item) { 1513 // R.id.menu_add_contacts already has an add to contact intent populated by setupMenuItems 1514 switch (item.getItemId()) { 1515 case R.id.menu_2s_pause: 1516 updateDialString(PAUSE); 1517 return true; 1518 case R.id.menu_add_wait: 1519 updateDialString(WAIT); 1520 return true; 1521 default: 1522 return false; 1523 } 1524 } 1525 1526 /** 1527 * Updates the dial string (mDigits) after inserting a Pause character (,) 1528 * or Wait character (;). 1529 */ 1530 private void updateDialString(char newDigit) { 1531 if(newDigit != WAIT && newDigit != PAUSE) { 1532 Log.wtf(TAG, "Not expected for anything other than PAUSE & WAIT"); 1533 return; 1534 } 1535 1536 int selectionStart; 1537 int selectionEnd; 1538 1539 // SpannableStringBuilder editable_text = new SpannableStringBuilder(mDigits.getText()); 1540 int anchor = mDigits.getSelectionStart(); 1541 int point = mDigits.getSelectionEnd(); 1542 1543 selectionStart = Math.min(anchor, point); 1544 selectionEnd = Math.max(anchor, point); 1545 1546 if (selectionStart == -1) { 1547 selectionStart = selectionEnd = mDigits.length(); 1548 } 1549 1550 Editable digits = mDigits.getText(); 1551 1552 if (canAddDigit(digits, selectionStart, selectionEnd, newDigit)) { 1553 digits.replace(selectionStart, selectionEnd, Character.toString(newDigit)); 1554 1555 if (selectionStart != selectionEnd) { 1556 // Unselect: back to a regular cursor, just pass the character inserted. 1557 mDigits.setSelection(selectionStart + 1); 1558 } 1559 } 1560 } 1561 1562 /** 1563 * Update the enabledness of the "Dial" and "Backspace" buttons if applicable. 1564 */ 1565 private void updateDialAndDeleteButtonEnabledState() { 1566 final boolean digitsNotEmpty = !isDigitsEmpty(); 1567 1568 if (mDialButton != null) { 1569 // On CDMA phones, if we're already on a call, we *always* 1570 // enable the Dial button (since you can press it without 1571 // entering any digits to send an empty flash.) 1572 if (phoneIsCdma() && phoneIsOffhook()) { 1573 mDialButton.setEnabled(true); 1574 } else { 1575 // Common case: GSM, or CDMA but not on a call. 1576 // Enable the Dial button if some digits have 1577 // been entered, or if there is a last dialed number 1578 // that could be redialed. 1579 mDialButton.setEnabled(digitsNotEmpty || 1580 !TextUtils.isEmpty(mLastNumberDialed)); 1581 } 1582 } 1583 mDelete.setEnabled(digitsNotEmpty); 1584 } 1585 1586 /** 1587 * Check if voicemail is enabled/accessible. 1588 * 1589 * @return true if voicemail is enabled and accessibly. Note that this can be false 1590 * "temporarily" after the app boot. 1591 * @see TelephonyManager#getVoiceMailNumber() 1592 */ 1593 private boolean isVoicemailAvailable() { 1594 try { 1595 return getTelephonyManager().getVoiceMailNumber() != null; 1596 } catch (SecurityException se) { 1597 // Possibly no READ_PHONE_STATE privilege. 1598 Log.w(TAG, "SecurityException is thrown. Maybe privilege isn't sufficient."); 1599 } 1600 return false; 1601 } 1602 1603 /** 1604 * Returns true of the newDigit parameter can be added at the current selection 1605 * point, otherwise returns false. 1606 * Only prevents input of WAIT and PAUSE digits at an unsupported position. 1607 * Fails early if start == -1 or start is larger than end. 1608 */ 1609 @VisibleForTesting 1610 /* package */ static boolean canAddDigit(CharSequence digits, int start, int end, 1611 char newDigit) { 1612 if(newDigit != WAIT && newDigit != PAUSE) { 1613 Log.wtf(TAG, "Should not be called for anything other than PAUSE & WAIT"); 1614 return false; 1615 } 1616 1617 // False if no selection, or selection is reversed (end < start) 1618 if (start == -1 || end < start) { 1619 return false; 1620 } 1621 1622 // unsupported selection-out-of-bounds state 1623 if (start > digits.length() || end > digits.length()) return false; 1624 1625 // Special digit cannot be the first digit 1626 if (start == 0) return false; 1627 1628 if (newDigit == WAIT) { 1629 // preceding char is ';' (WAIT) 1630 if (digits.charAt(start - 1) == WAIT) return false; 1631 1632 // next char is ';' (WAIT) 1633 if ((digits.length() > end) && (digits.charAt(end) == WAIT)) return false; 1634 } 1635 1636 return true; 1637 } 1638 1639 /** 1640 * @return true if the widget with the phone number digits is empty. 1641 */ 1642 private boolean isDigitsEmpty() { 1643 return mDigits.length() == 0; 1644 } 1645 1646 /** 1647 * Starts the asyn query to get the last dialed/outgoing 1648 * number. When the background query finishes, mLastNumberDialed 1649 * is set to the last dialed number or an empty string if none 1650 * exists yet. 1651 */ 1652 private void queryLastOutgoingCall() { 1653 mLastNumberDialed = EMPTY_NUMBER; 1654 CallLogAsync.GetLastOutgoingCallArgs lastCallArgs = 1655 new CallLogAsync.GetLastOutgoingCallArgs( 1656 getActivity(), 1657 new CallLogAsync.OnLastOutgoingCallComplete() { 1658 @Override 1659 public void lastOutgoingCall(String number) { 1660 // TODO: Filter out emergency numbers if 1661 // the carrier does not want redial for 1662 // these. 1663 // If the fragment has already been detached since the last time 1664 // we called queryLastOutgoingCall in onResume there is no point 1665 // doing anything here. 1666 if (getActivity() == null) return; 1667 mLastNumberDialed = number; 1668 updateDialAndDeleteButtonEnabledState(); 1669 } 1670 }); 1671 mCallLog.getLastOutgoingCall(lastCallArgs); 1672 } 1673 1674 private Intent newFlashIntent() { 1675 final Intent intent = CallUtil.getCallIntent(EMPTY_NUMBER); 1676 intent.putExtra(EXTRA_SEND_EMPTY_FLASH, true); 1677 return intent; 1678 } 1679 1680 private void initializeSmartDialingState() { 1681 // Handle smart dialing related state 1682 // TODO krelease: This should probably be moved to somewhere more appropriate, maybe 1683 // into DialtactsActivity 1684 mDialerDatabaseHelper.startSmartDialUpdateThread(); 1685 } 1686 1687 @Override 1688 public void onHiddenChanged(boolean hidden) { 1689 super.onHiddenChanged(hidden); 1690 final DialtactsActivity activity = (DialtactsActivity) getActivity(); 1691 if (activity == null) return; 1692 if (hidden) { 1693 activity.showSearchBar(); 1694 } else { 1695 activity.hideSearchBar(); 1696 } 1697 } 1698} 1699