From 183cb71663320f16149d83eeebaff7795a4b55f2 Mon Sep 17 00:00:00 2001 From: linyuh Date: Wed, 27 Dec 2017 17:02:37 -0800 Subject: Remove field prefixes. Test: Existing tests PiperOrigin-RevId: 180230450 Change-Id: I0b2589cfeeaef81e42a04efa48af24b4e4d0e95f --- java/com/android/dialer/app/DialtactsActivity.java | 660 ++++++++++----------- .../app/calllog/BlockReportSpamListener.java | 52 +- .../dialer/app/calllog/CallLogActivity.java | 72 +-- .../android/dialer/app/calllog/CallLogAdapter.java | 353 ++++++----- .../android/dialer/app/calllog/CallLogAsync.java | 6 +- .../dialer/app/calllog/CallLogAsyncTaskUtil.java | 16 +- .../dialer/app/calllog/CallLogFragment.java | 290 ++++----- .../dialer/app/calllog/CallLogGroupBuilder.java | 20 +- .../dialer/app/calllog/CallLogListItemHelper.java | 44 +- .../app/calllog/CallLogListItemViewHolder.java | 257 ++++---- .../calllog/CallLogNotificationsQueryHelper.java | 48 +- .../app/calllog/DialerQuickContactBadge.java | 8 +- .../dialer/app/calllog/GroupingListAdapter.java | 56 +- .../dialer/app/calllog/PhoneCallDetailsHelper.java | 107 ++-- .../calllog/VisualVoicemailCallLogFragment.java | 44 +- .../app/calllog/calllogcache/CallLogCache.java | 58 +- .../dialer/app/contactinfo/ContactInfoCache.java | 98 +-- .../dialer/app/contactinfo/ContactPhotoLoader.java | 26 +- .../app/filterednumber/BlockedNumbersFragment.java | 52 +- .../dialer/app/filterednumber/NumbersAdapter.java | 36 +- .../ViewNumbersToImportFragment.java | 12 +- .../dialer/app/list/AllContactsFragment.java | 32 +- .../dialer/app/list/BlockedListSearchAdapter.java | 16 +- .../dialer/app/list/BlockedListSearchFragment.java | 24 +- .../dialer/app/list/ContentChangedFilter.java | 8 +- .../app/list/DialerPhoneNumberListAdapter.java | 34 +- .../dialer/app/list/DragDropController.java | 49 +- .../com/android/dialer/app/list/ListsFragment.java | 183 +++--- .../dialer/app/list/OldSpeedDialFragment.java | 180 +++--- .../dialer/app/list/PhoneFavoriteListView.java | 162 ++--- .../app/list/PhoneFavoriteSquareTileView.java | 18 +- .../dialer/app/list/PhoneFavoriteTileView.java | 19 +- .../dialer/app/list/PhoneFavoritesTileAdapter.java | 196 +++--- .../dialer/app/list/RegularSearchFragment.java | 18 +- .../dialer/app/list/RegularSearchListAdapter.java | 8 +- java/com/android/dialer/app/list/RemoveView.java | 40 +- .../android/dialer/app/list/SearchFragment.java | 106 ++-- .../app/list/SmartDialNumberListAdapter.java | 22 +- .../dialer/app/list/SmartDialSearchFragment.java | 24 +- .../app/settings/AppCompatPreferenceActivity.java | 20 +- .../app/settings/DialerSettingsActivity.java | 4 +- .../dialer/app/settings/SoundSettingsFragment.java | 60 +- .../app/voicemail/VoicemailAudioManager.java | 88 +-- .../app/voicemail/VoicemailPlaybackLayout.java | 252 ++++---- .../app/voicemail/VoicemailPlaybackPresenter.java | 460 +++++++------- .../dialer/app/voicemail/WiredHeadsetManager.java | 40 +- .../dialer/app/widget/ActionBarController.java | 107 ++-- .../dialer/app/widget/SearchEditTextLayout.java | 188 +++--- .../dialer/blocking/BlockNumberDialogFragment.java | 72 +-- .../dialer/blocking/BlockReportSpamDialogs.java | 74 +-- .../dialer/blocking/FilteredNumberProvider.java | 26 +- .../MigrateBlockedNumbersDialogFragment.java | 16 +- .../dialer/callcomposer/camera/CameraManager.java | 328 +++++----- .../dialer/callcomposer/camera/CameraPreview.java | 48 +- .../callcomposer/camera/HardwareCameraPreview.java | 26 +- .../callcomposer/camera/ImagePersistWorker.java | 52 +- .../callcomposer/camera/SoftwareCameraPreview.java | 24 +- .../camera/camerafocus/FocusOverlayManager.java | 230 ++++--- .../camera/camerafocus/OverlayRenderer.java | 40 +- .../callcomposer/camera/camerafocus/PieItem.java | 66 +-- .../camera/camerafocus/PieRenderer.java | 539 +++++++++-------- .../camera/camerafocus/RenderOverlay.java | 42 +- .../camera/exif/CountedDataInputStream.java | 34 +- .../dialer/callcomposer/camera/exif/ExifData.java | 12 +- .../callcomposer/camera/exif/ExifInterface.java | 48 +- .../callcomposer/camera/exif/ExifParser.java | 210 +++---- .../dialer/callcomposer/camera/exif/ExifTag.java | 200 +++---- .../dialer/callcomposer/camera/exif/IfdData.java | 30 +- .../dialer/callcomposer/camera/exif/Rational.java | 18 +- .../cameraui/CameraMediaChooserView.java | 6 +- .../dialer/calllogutils/CallTypeHelper.java | 102 ++-- .../dialer/calllogutils/CallTypeIconsView.java | 78 +-- .../common/concurrent/AsyncTaskExecutors.java | 18 +- .../dialer/compat/PathInterpolatorCompat.java | 26 +- .../dialer/contactphoto/ContactPhotoManager.java | 14 +- .../contactphoto/ContactPhotoManagerImpl.java | 362 +++++------ .../dialer/database/CallLogQueryHandler.java | 46 +- .../dialer/database/DialerDatabaseHelper.java | 38 +- .../dialer/dialpadview/DialpadFragment.java | 405 +++++++------ .../dialer/dialpadview/DialpadKeyButton.java | 80 +-- .../dialer/dialpadview/DialpadTextView.java | 14 +- .../android/dialer/dialpadview/DialpadView.java | 120 ++-- .../dialpadview/PseudoEmergencyAnimator.java | 40 +- .../dialer/dialpadview/SpecialCharSequenceMgr.java | 58 +- .../interactions/PhoneNumberInteraction.java | 102 ++-- .../dialer/lettertile/LetterTileDrawable.java | 178 +++--- .../android/dialer/location/CountryDetector.java | 8 +- .../dialer/phonenumbercache/ContactInfoHelper.java | 56 +- .../dialer/smartdial/SmartDialCursorLoader.java | 48 +- .../smartdial/util/SmartDialNameMatcher.java | 26 +- .../dialer/smartdial/util/SmartDialPrefix.java | 42 +- java/com/android/dialer/telecom/TelecomUtil.java | 8 +- java/com/android/dialer/util/ExpirableCache.java | 32 +- .../com/android/dialer/util/TouchPointManager.java | 12 +- .../dialer/util/TransactionSafeActivity.java | 12 +- .../settings/VoicemailChangePinActivity.java | 175 +++--- .../VisualVoicemailEnabledChecker.java | 36 +- .../android/dialer/widget/EmptyContentView.java | 52 +- .../widget/FloatingActionButtonController.java | 69 ++- .../dialer/widget/ResizingTextEditText.java | 14 +- .../dialer/widget/ResizingTextTextView.java | 14 +- 101 files changed, 4535 insertions(+), 4564 deletions(-) (limited to 'java/com/android/dialer') diff --git a/java/com/android/dialer/app/DialtactsActivity.java b/java/com/android/dialer/app/DialtactsActivity.java index bbb45943a..66e02b4d8 100644 --- a/java/com/android/dialer/app/DialtactsActivity.java +++ b/java/com/android/dialer/app/DialtactsActivity.java @@ -204,74 +204,74 @@ public class DialtactsActivity extends TransactionSafeActivity */ private static final long HISTORY_TAB_SEEN_TIMEOUT = TimeUnit.SECONDS.toMillis(3); - private static Optional sVoiceSearchEnabledForTest = Optional.absent(); + private static Optional voiceSearchEnabledForTest = Optional.absent(); /** Fragment containing the dialpad that slides into view */ - protected DialpadFragment mDialpadFragment; + protected DialpadFragment dialpadFragment; /** Root layout of DialtactsActivity */ - private CoordinatorLayout mParentLayout; + private CoordinatorLayout parentLayout; /** Fragment for searching phone numbers using the alphanumeric keyboard. */ - private RegularSearchFragment mRegularSearchFragment; + private RegularSearchFragment regularSearchFragment; /** Fragment for searching phone numbers using the dialpad. */ - private SmartDialSearchFragment mSmartDialSearchFragment; + private SmartDialSearchFragment smartDialSearchFragment; /** new Fragment for search phone numbers using the keyboard and the dialpad. */ - private NewSearchFragment mNewSearchFragment; + private NewSearchFragment newSearchFragment; /** Animation that slides in. */ - private Animation mSlideIn; + private Animation slideIn; /** Animation that slides out. */ - private Animation mSlideOut; + private Animation slideOut; /** Fragment containing the speed dial list, call history list, and all contacts list. */ - private ListsFragment mListsFragment; + private ListsFragment listsFragment; /** * Tracks whether onSaveInstanceState has been called. If true, no fragment transactions can be * commited. */ - private boolean mStateSaved; - - private boolean mIsKeyboardOpen; - private boolean mInNewSearch; - private boolean mIsRestarting; - private boolean mInDialpadSearch; - private boolean mInRegularSearch; - private boolean mClearSearchOnPause; - private boolean mIsDialpadShown; + private boolean stateSaved; + + private boolean isKeyboardOpen; + private boolean inNewSearch; + private boolean isRestarting; + private boolean inDialpadSearch; + private boolean inRegularSearch; + private boolean clearSearchOnPause; + private boolean isDialpadShown; /** Whether or not the device is in landscape orientation. */ - private boolean mIsLandscape; + private boolean isLandscape; /** True if the dialpad is only temporarily showing due to being in call */ - private boolean mInCallDialpadUp; + private boolean inCallDialpadUp; /** True when this activity has been launched for the first time. */ - private boolean mFirstLaunch; + private boolean firstLaunch; /** * Search query to be applied to the SearchView in the ActionBar once onCreateOptionsMenu has been * called. */ - private String mPendingSearchViewQuery; - - private PopupMenu mOverflowMenu; - private EditText mSearchView; - private SearchEditTextLayout mSearchEditTextLayout; - private View mVoiceSearchButton; - private String mSearchQuery; - private String mDialpadQuery; - private DialerDatabaseHelper mDialerDatabaseHelper; - private DragDropController mDragDropController; - private ActionBarController mActionBarController; - private FloatingActionButtonController mFloatingActionButtonController; - private boolean mWasConfigurationChange; + private String pendingSearchViewQuery; + + private PopupMenu overflowMenu; + private EditText searchView; + private SearchEditTextLayout searchEditTextLayout; + private View voiceSearchButton; + private String searchQuery; + private String dialpadQuery; + private DialerDatabaseHelper dialerDatabaseHelper; + private DragDropController dragDropController; + private ActionBarController actionBarController; + private FloatingActionButtonController floatingActionButtonController; + private boolean wasConfigurationChange; private long timeTabSelected; - private P13nLogger mP13nLogger; - private P13nRanker mP13nRanker; + private P13nLogger p13nLogger; + private P13nRanker p13nRanker; public boolean isMultiSelectModeEnabled; private boolean isLastTabEnabled; - AnimationListenerAdapter mSlideInListener = + AnimationListenerAdapter slideInListener = new AnimationListenerAdapter() { @Override public void onAnimationEnd(Animation animation) { @@ -279,7 +279,7 @@ public class DialtactsActivity extends TransactionSafeActivity } }; /** Listener for after slide out animation completes on dialer fragment. */ - AnimationListenerAdapter mSlideOutListener = + AnimationListenerAdapter slideOutListener = new AnimationListenerAdapter() { @Override public void onAnimationEnd(Animation animation) { @@ -287,7 +287,7 @@ public class DialtactsActivity extends TransactionSafeActivity } }; /** Listener used to send search queries to the phone search fragment. */ - private final TextWatcher mPhoneSearchQueryTextListener = + private final TextWatcher phoneSearchQueryTextListener = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @@ -295,7 +295,7 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public void onTextChanged(CharSequence s, int start, int before, int count) { final String newText = s.toString(); - if (newText.equals(mSearchQuery)) { + if (newText.equals(searchQuery)) { // If the query hasn't changed (perhaps due to activity being destroyed // and restored, or user launching the same DIAL intent twice), then there is // no need to do anything here. @@ -307,8 +307,8 @@ public class DialtactsActivity extends TransactionSafeActivity } LogUtil.v("DialtactsActivity.onTextChanged", "called with new query: " + newText); - LogUtil.v("DialtactsActivity.onTextChanged", "previous query: " + mSearchQuery); - mSearchQuery = newText; + LogUtil.v("DialtactsActivity.onTextChanged", "previous query: " + searchQuery); + searchQuery = newText; // TODO(calderwoodra): show p13n when newText is empty. // Show search fragment only when the query string is changed to non-empty text. @@ -316,18 +316,18 @@ public class DialtactsActivity extends TransactionSafeActivity // Call enterSearchUi only if we are switching search modes, or showing a search // fragment for the first time. final boolean sameSearchMode = - (mIsDialpadShown && mInDialpadSearch) || (!mIsDialpadShown && mInRegularSearch); + (isDialpadShown && inDialpadSearch) || (!isDialpadShown && inRegularSearch); if (!sameSearchMode) { - enterSearchUi(mIsDialpadShown, mSearchQuery, true /* animate */); + enterSearchUi(isDialpadShown, searchQuery, true /* animate */); } } - if (mSmartDialSearchFragment != null && mSmartDialSearchFragment.isVisible()) { - mSmartDialSearchFragment.setQueryString(mSearchQuery); - } else if (mRegularSearchFragment != null && mRegularSearchFragment.isVisible()) { - mRegularSearchFragment.setQueryString(mSearchQuery); - } else if (mNewSearchFragment != null && mNewSearchFragment.isVisible()) { - mNewSearchFragment.setQuery(mSearchQuery, getCallInitiationType()); + if (smartDialSearchFragment != null && smartDialSearchFragment.isVisible()) { + smartDialSearchFragment.setQueryString(searchQuery); + } else if (regularSearchFragment != null && regularSearchFragment.isVisible()) { + regularSearchFragment.setQueryString(searchQuery); + } else if (newSearchFragment != null && newSearchFragment.isVisible()) { + newSearchFragment.setQuery(searchQuery, getCallInitiationType()); } } @@ -335,27 +335,27 @@ public class DialtactsActivity extends TransactionSafeActivity public void afterTextChanged(Editable s) {} }; /** Open the search UI when the user clicks on the search box. */ - private final View.OnClickListener mSearchViewOnClickListener = + private final View.OnClickListener searchViewOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (!isInSearchUi()) { PerformanceReport.recordClick(UiAction.Type.OPEN_SEARCH); - mActionBarController.onSearchBoxTapped(); + actionBarController.onSearchBoxTapped(); enterSearchUi( - false /* smartDialSearch */, mSearchView.getText().toString(), true /* animate */); + false /* smartDialSearch */, searchView.getText().toString(), true /* animate */); } } }; - private int mActionBarHeight; - private int mPreviouslySelectedTabIndex; + private int actionBarHeight; + private int previouslySelectedTabIndex; /** * The text returned from a voice search query. Set in {@link #onActivityResult} and used in * {@link #onResume()} to populate the search box. */ - private String mVoiceSearchQuery; + private String voiceSearchQuery; /** * @param tab the TAB_INDEX_* constant in {@link ListsFragment} @@ -391,11 +391,11 @@ public class DialtactsActivity extends TransactionSafeActivity LogUtil.enterBlock("DialtactsActivity.onCreate"); super.onCreate(savedInstanceState); - mFirstLaunch = true; + firstLaunch = true; isLastTabEnabled = ConfigProviderBindings.get(this).getBoolean("last_tab_enabled", false); final Resources resources = getResources(); - mActionBarHeight = resources.getDimensionPixelSize(R.dimen.action_bar_height_large); + actionBarHeight = resources.getDimensionPixelSize(R.dimen.action_bar_height_large); Trace.beginSection(TAG + " setContentView"); setContentView(R.layout.dialtacts_activity); @@ -408,35 +408,34 @@ public class DialtactsActivity extends TransactionSafeActivity actionBar.setDisplayShowCustomEnabled(true); actionBar.setBackgroundDrawable(null); - mSearchEditTextLayout = actionBar.getCustomView().findViewById(R.id.search_view_container); + searchEditTextLayout = actionBar.getCustomView().findViewById(R.id.search_view_container); - mActionBarController = new ActionBarController(this, mSearchEditTextLayout); + actionBarController = new ActionBarController(this, searchEditTextLayout); - mSearchView = mSearchEditTextLayout.findViewById(R.id.search_view); - mSearchView.addTextChangedListener(mPhoneSearchQueryTextListener); - mSearchView.setHint(getSearchBoxHint()); + searchView = searchEditTextLayout.findViewById(R.id.search_view); + searchView.addTextChangedListener(phoneSearchQueryTextListener); + searchView.setHint(getSearchBoxHint()); - mVoiceSearchButton = mSearchEditTextLayout.findViewById(R.id.voice_search_button); - mSearchEditTextLayout + voiceSearchButton = searchEditTextLayout.findViewById(R.id.voice_search_button); + searchEditTextLayout .findViewById(R.id.search_box_collapsed) - .setOnClickListener(mSearchViewOnClickListener); - mSearchEditTextLayout + .setOnClickListener(searchViewOnClickListener); + searchEditTextLayout .findViewById(R.id.search_back_button) .setOnClickListener(v -> exitSearchUi()); - mIsLandscape = + isLandscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; - mPreviouslySelectedTabIndex = DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL; + previouslySelectedTabIndex = DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL; FloatingActionButton floatingActionButton = findViewById(R.id.floating_action_button); floatingActionButton.setOnClickListener(this); - mFloatingActionButtonController = - new FloatingActionButtonController(this, floatingActionButton); + floatingActionButtonController = new FloatingActionButtonController(this, floatingActionButton); ImageButton optionsMenuButton = - mSearchEditTextLayout.findViewById(R.id.dialtacts_options_menu_button); + searchEditTextLayout.findViewById(R.id.dialtacts_options_menu_button); optionsMenuButton.setOnClickListener(this); - mOverflowMenu = buildOptionsMenu(optionsMenuButton); - optionsMenuButton.setOnTouchListener(mOverflowMenu.getDragToOpenListener()); + overflowMenu = buildOptionsMenu(optionsMenuButton); + optionsMenuButton.setOnTouchListener(overflowMenu.getDragToOpenListener()); // Add the favorites fragment but only if savedInstanceState is null. Otherwise the // fragment manager is responsible for recreating it. @@ -446,56 +445,56 @@ public class DialtactsActivity extends TransactionSafeActivity .add(R.id.dialtacts_frame, new ListsFragment(), TAG_FAVORITES_FRAGMENT) .commit(); } else { - mSearchQuery = savedInstanceState.getString(KEY_SEARCH_QUERY); - mDialpadQuery = savedInstanceState.getString(KEY_DIALPAD_QUERY); - mInRegularSearch = savedInstanceState.getBoolean(KEY_IN_REGULAR_SEARCH_UI); - mInDialpadSearch = savedInstanceState.getBoolean(KEY_IN_DIALPAD_SEARCH_UI); - mInNewSearch = savedInstanceState.getBoolean(KEY_IN_NEW_SEARCH_UI); - mFirstLaunch = savedInstanceState.getBoolean(KEY_FIRST_LAUNCH); - mWasConfigurationChange = savedInstanceState.getBoolean(KEY_WAS_CONFIGURATION_CHANGE); - mIsDialpadShown = savedInstanceState.getBoolean(KEY_IS_DIALPAD_SHOWN); - mFloatingActionButtonController.setVisible(savedInstanceState.getBoolean(KEY_FAB_VISIBLE)); - mActionBarController.restoreInstanceState(savedInstanceState); + searchQuery = savedInstanceState.getString(KEY_SEARCH_QUERY); + dialpadQuery = savedInstanceState.getString(KEY_DIALPAD_QUERY); + inRegularSearch = savedInstanceState.getBoolean(KEY_IN_REGULAR_SEARCH_UI); + inDialpadSearch = savedInstanceState.getBoolean(KEY_IN_DIALPAD_SEARCH_UI); + inNewSearch = savedInstanceState.getBoolean(KEY_IN_NEW_SEARCH_UI); + firstLaunch = savedInstanceState.getBoolean(KEY_FIRST_LAUNCH); + wasConfigurationChange = savedInstanceState.getBoolean(KEY_WAS_CONFIGURATION_CHANGE); + isDialpadShown = savedInstanceState.getBoolean(KEY_IS_DIALPAD_SHOWN); + floatingActionButtonController.setVisible(savedInstanceState.getBoolean(KEY_FAB_VISIBLE)); + actionBarController.restoreInstanceState(savedInstanceState); } final boolean isLayoutRtl = ViewUtil.isRtl(); - if (mIsLandscape) { - mSlideIn = + if (isLandscape) { + slideIn = AnimationUtils.loadAnimation( this, isLayoutRtl ? R.anim.dialpad_slide_in_left : R.anim.dialpad_slide_in_right); - mSlideOut = + slideOut = AnimationUtils.loadAnimation( this, isLayoutRtl ? R.anim.dialpad_slide_out_left : R.anim.dialpad_slide_out_right); } else { - mSlideIn = AnimationUtils.loadAnimation(this, R.anim.dialpad_slide_in_bottom); - mSlideOut = AnimationUtils.loadAnimation(this, R.anim.dialpad_slide_out_bottom); + slideIn = AnimationUtils.loadAnimation(this, R.anim.dialpad_slide_in_bottom); + slideOut = AnimationUtils.loadAnimation(this, R.anim.dialpad_slide_out_bottom); } - mSlideIn.setInterpolator(AnimUtils.EASE_IN); - mSlideOut.setInterpolator(AnimUtils.EASE_OUT); + slideIn.setInterpolator(AnimUtils.EASE_IN); + slideOut.setInterpolator(AnimUtils.EASE_OUT); - mSlideIn.setAnimationListener(mSlideInListener); - mSlideOut.setAnimationListener(mSlideOutListener); + slideIn.setAnimationListener(slideInListener); + slideOut.setAnimationListener(slideOutListener); - mParentLayout = (CoordinatorLayout) findViewById(R.id.dialtacts_mainlayout); - mParentLayout.setOnDragListener(new LayoutOnDragListener()); + parentLayout = (CoordinatorLayout) findViewById(R.id.dialtacts_mainlayout); + parentLayout.setOnDragListener(new LayoutOnDragListener()); ViewUtil.doOnGlobalLayout( floatingActionButton, view -> { - int screenWidth = mParentLayout.getWidth(); - mFloatingActionButtonController.setScreenWidth(screenWidth); - mFloatingActionButtonController.align(getFabAlignment(), false /* animate */); + int screenWidth = parentLayout.getWidth(); + floatingActionButtonController.setScreenWidth(screenWidth); + floatingActionButtonController.align(getFabAlignment(), false /* animate */); }); Trace.endSection(); Trace.beginSection(TAG + " initialize smart dialing"); - mDialerDatabaseHelper = Database.get(this).getDatabaseHelper(this); + dialerDatabaseHelper = Database.get(this).getDatabaseHelper(this); SmartDialPrefix.initializeNanpSettings(this); Trace.endSection(); - mP13nLogger = P13nLogging.get(getApplicationContext()); - mP13nRanker = P13nRanking.get(getApplicationContext()); + p13nLogger = P13nLogging.get(getApplicationContext()); + p13nRanker = P13nRanking.get(getApplicationContext()); Trace.endSection(); // Update the new search fragment to the correct position and the ActionBar's visibility. @@ -522,78 +521,78 @@ public class DialtactsActivity extends TransactionSafeActivity PerformanceReport.startRecording(); } - mStateSaved = false; - if (mFirstLaunch) { + stateSaved = false; + if (firstLaunch) { LogUtil.i("DialtactsActivity.onResume", "mFirstLaunch true, displaying fragment"); displayFragment(getIntent()); - } else if (!phoneIsInUse() && mInCallDialpadUp) { + } else if (!phoneIsInUse() && inCallDialpadUp) { LogUtil.i("DialtactsActivity.onResume", "phone not in use, hiding dialpad fragment"); hideDialpadFragment(false, true); - mInCallDialpadUp = false; - } else if (mIsDialpadShown) { + inCallDialpadUp = false; + } else if (isDialpadShown) { LogUtil.i("DialtactsActivity.onResume", "showing dialpad on resume"); showDialpadFragment(false); } else { - PostCall.promptUserForMessageIfNecessary(this, mParentLayout); + PostCall.promptUserForMessageIfNecessary(this, parentLayout); } // On M the fragment manager does not restore the hidden state of a fragment from // savedInstanceState so it must be hidden again. - if (!mIsDialpadShown && mDialpadFragment != null && !mDialpadFragment.isHidden()) { + if (!isDialpadShown && dialpadFragment != null && !dialpadFragment.isHidden()) { LogUtil.i( "DialtactsActivity.onResume", "mDialpadFragment attached but not hidden, forcing hide"); - getFragmentManager().beginTransaction().hide(mDialpadFragment).commit(); + getFragmentManager().beginTransaction().hide(dialpadFragment).commit(); } // If there was a voice query result returned in the {@link #onActivityResult} callback, it // will have been stashed in mVoiceSearchQuery since the search results fragment cannot be // shown until onResume has completed. Active the search UI and set the search term now. - if (!TextUtils.isEmpty(mVoiceSearchQuery)) { - mActionBarController.onSearchBoxTapped(); - mSearchView.setText(mVoiceSearchQuery); - mVoiceSearchQuery = null; + if (!TextUtils.isEmpty(voiceSearchQuery)) { + actionBarController.onSearchBoxTapped(); + searchView.setText(voiceSearchQuery); + voiceSearchQuery = null; } - if (mIsRestarting) { + if (isRestarting) { // This is only called when the activity goes from resumed -> paused -> resumed, so it // will not cause an extra view to be sent out on rotation - if (mIsDialpadShown) { + if (isDialpadShown) { Logger.get(this).logScreenView(ScreenEvent.Type.DIALPAD, this); } - mIsRestarting = false; + isRestarting = false; } prepareVoiceSearchButton(); - if (!mWasConfigurationChange) { - mDialerDatabaseHelper.startSmartDialUpdateThread(); + if (!wasConfigurationChange) { + dialerDatabaseHelper.startSmartDialUpdateThread(); } - if (mIsDialpadShown) { - mFloatingActionButtonController.scaleOut(); + if (isDialpadShown) { + floatingActionButtonController.scaleOut(); } else { - mFloatingActionButtonController.align(getFabAlignment(), false /* animate */); + floatingActionButtonController.align(getFabAlignment(), false /* animate */); } - if (mFirstLaunch) { + if (firstLaunch) { // Only process the Intent the first time onResume() is called after receiving it if (Calls.CONTENT_TYPE.equals(getIntent().getType())) { // Externally specified extras take precedence to EXTRA_SHOW_TAB, which is only // used internally. final Bundle extras = getIntent().getExtras(); if (extras != null && extras.getInt(Calls.EXTRA_CALL_TYPE_FILTER) == Calls.VOICEMAIL_TYPE) { - mListsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); + listsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); Logger.get(this).logImpression(DialerImpression.Type.VVM_NOTIFICATION_CLICKED); } else { - mListsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_HISTORY); + listsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_HISTORY); } } else if (getIntent().hasExtra(EXTRA_SHOW_TAB)) { int index = getIntent().getIntExtra(EXTRA_SHOW_TAB, DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL); - if (index < mListsFragment.getTabCount()) { + if (index < listsFragment.getTabCount()) { // Hide dialpad since this is an explicit intent to show a specific tab, which is coming // from missed call or voicemail notification. hideDialpadFragment(false, false); exitSearchUi(); - mListsFragment.showTab(index); + listsFragment.showTab(index); } } @@ -609,13 +608,13 @@ public class DialtactsActivity extends TransactionSafeActivity 1000); } - mFirstLaunch = false; + firstLaunch = false; setSearchBoxHint(); timeTabSelected = SystemClock.elapsedRealtime(); - mP13nLogger.reset(); - mP13nRanker.refresh( + p13nLogger.reset(); + p13nRanker.refresh( new P13nRefreshCompleteListener() { @Override public void onP13nRefreshComplete() { @@ -628,16 +627,16 @@ public class DialtactsActivity extends TransactionSafeActivity @Override protected void onRestart() { super.onRestart(); - mIsRestarting = true; + isRestarting = true; } @Override protected void onPause() { - if (mClearSearchOnPause) { + if (clearSearchOnPause) { hideDialpadAndSearchUi(); - mClearSearchOnPause = false; + clearSearchOnPause = false; } - if (mSlideOut.hasStarted() && !mSlideOut.hasEnded()) { + if (slideOut.hasStarted() && !slideOut.hasEnded()) { commitDialpadFragmentHide(); } super.onPause(); @@ -649,17 +648,17 @@ public class DialtactsActivity extends TransactionSafeActivity boolean timeoutElapsed = SystemClock.elapsedRealtime() - timeTabSelected >= HISTORY_TAB_SEEN_TIMEOUT; boolean isOnHistoryTab = - mListsFragment.getCurrentTabIndex() == DialtactsPagerAdapter.TAB_INDEX_HISTORY; + listsFragment.getCurrentTabIndex() == DialtactsPagerAdapter.TAB_INDEX_HISTORY; if (isOnHistoryTab && timeoutElapsed && !isChangingConfigurations() && !getSystemService(KeyguardManager.class).isKeyguardLocked()) { - mListsFragment.markMissedCallsAsReadAndRemoveNotifications(); + listsFragment.markMissedCallsAsReadAndRemoveNotifications(); } StorageComponent.get(this) .unencryptedSharedPrefs() .edit() - .putInt(KEY_LAST_TAB, mListsFragment.getCurrentTabIndex()) + .putInt(KEY_LAST_TAB, listsFragment.getCurrentTabIndex()) .apply(); } @@ -667,38 +666,38 @@ public class DialtactsActivity extends TransactionSafeActivity protected void onSaveInstanceState(Bundle outState) { LogUtil.enterBlock("DialtactsActivity.onSaveInstanceState"); super.onSaveInstanceState(outState); - outState.putString(KEY_SEARCH_QUERY, mSearchQuery); - outState.putString(KEY_DIALPAD_QUERY, mDialpadQuery); - outState.putBoolean(KEY_IN_REGULAR_SEARCH_UI, mInRegularSearch); - outState.putBoolean(KEY_IN_DIALPAD_SEARCH_UI, mInDialpadSearch); - outState.putBoolean(KEY_IN_NEW_SEARCH_UI, mInNewSearch); - outState.putBoolean(KEY_FIRST_LAUNCH, mFirstLaunch); - outState.putBoolean(KEY_IS_DIALPAD_SHOWN, mIsDialpadShown); - outState.putBoolean(KEY_FAB_VISIBLE, mFloatingActionButtonController.isVisible()); + outState.putString(KEY_SEARCH_QUERY, searchQuery); + outState.putString(KEY_DIALPAD_QUERY, dialpadQuery); + outState.putBoolean(KEY_IN_REGULAR_SEARCH_UI, inRegularSearch); + outState.putBoolean(KEY_IN_DIALPAD_SEARCH_UI, inDialpadSearch); + outState.putBoolean(KEY_IN_NEW_SEARCH_UI, inNewSearch); + outState.putBoolean(KEY_FIRST_LAUNCH, firstLaunch); + outState.putBoolean(KEY_IS_DIALPAD_SHOWN, isDialpadShown); + outState.putBoolean(KEY_FAB_VISIBLE, floatingActionButtonController.isVisible()); outState.putBoolean(KEY_WAS_CONFIGURATION_CHANGE, isChangingConfigurations()); - mActionBarController.saveInstanceState(outState); - mStateSaved = true; + actionBarController.saveInstanceState(outState); + stateSaved = true; } @Override public void onAttachFragment(final Fragment fragment) { LogUtil.i("DialtactsActivity.onAttachFragment", "fragment: %s", fragment); if (fragment instanceof DialpadFragment) { - mDialpadFragment = (DialpadFragment) fragment; + dialpadFragment = (DialpadFragment) fragment; } else if (fragment instanceof SmartDialSearchFragment) { - mSmartDialSearchFragment = (SmartDialSearchFragment) fragment; - mSmartDialSearchFragment.setOnPhoneNumberPickerActionListener(this); - if (!TextUtils.isEmpty(mDialpadQuery)) { - mSmartDialSearchFragment.setAddToContactNumber(mDialpadQuery); + smartDialSearchFragment = (SmartDialSearchFragment) fragment; + smartDialSearchFragment.setOnPhoneNumberPickerActionListener(this); + if (!TextUtils.isEmpty(dialpadQuery)) { + smartDialSearchFragment.setAddToContactNumber(dialpadQuery); } } else if (fragment instanceof SearchFragment) { - mRegularSearchFragment = (RegularSearchFragment) fragment; - mRegularSearchFragment.setOnPhoneNumberPickerActionListener(this); + regularSearchFragment = (RegularSearchFragment) fragment; + regularSearchFragment.setOnPhoneNumberPickerActionListener(this); } else if (fragment instanceof ListsFragment) { - mListsFragment = (ListsFragment) fragment; - mListsFragment.addOnPageChangeListener(this); + listsFragment = (ListsFragment) fragment; + listsFragment.addOnPageChangeListener(this); } else if (fragment instanceof NewSearchFragment) { - mNewSearchFragment = (NewSearchFragment) fragment; + newSearchFragment = (NewSearchFragment) fragment; updateSearchFragmentPosition(); } if (fragment instanceof SearchFragment) { @@ -710,14 +709,14 @@ public class DialtactsActivity extends TransactionSafeActivity public Cursor rerankCursor(Cursor data) { Assert.isMainThread(); String queryString = searchFragment.getQueryString(); - return mP13nRanker.rankCursor(data, queryString == null ? 0 : queryString.length()); + return p13nRanker.rankCursor(data, queryString == null ? 0 : queryString.length()); } }); searchFragment.addOnLoadFinishedListener( new OnLoadFinishedListener() { @Override public void onLoadFinished() { - mP13nLogger.onSearchQuery( + p13nLogger.onSearchQuery( searchFragment.getQueryString(), (PhoneNumberListAdapter) searchFragment.getAdapter()); } @@ -731,18 +730,18 @@ public class DialtactsActivity extends TransactionSafeActivity } public boolean isListsFragmentVisible() { - return mListsFragment.getUserVisibleHint(); + return listsFragment.getUserVisibleHint(); } @Override public void onClick(View view) { int resId = view.getId(); if (resId == R.id.floating_action_button) { - if (!mIsDialpadShown) { + if (!isDialpadShown) { LogUtil.i( "DialtactsActivity.onClick", "floating action button clicked, going to show dialpad"); PerformanceReport.recordClick(UiAction.Type.OPEN_DIALPAD); - mInCallDialpadUp = false; + inCallDialpadUp = false; showDialpadFragment(true); PostCall.closePrompt(); } else { @@ -761,7 +760,7 @@ public class DialtactsActivity extends TransactionSafeActivity .show(); } } else if (resId == R.id.dialtacts_options_menu_button) { - mOverflowMenu.show(); + overflowMenu.show(); } else { Assert.fail("Unexpected onClick event from " + view); } @@ -805,7 +804,7 @@ public class DialtactsActivity extends TransactionSafeActivity final ArrayList matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches.size() > 0) { - mVoiceSearchQuery = matches.get(0); + voiceSearchQuery = matches.get(0); } else { LogUtil.i("DialtactsActivity.onActivityResult", "voice search - nothing heard"); } @@ -820,7 +819,7 @@ public class DialtactsActivity extends TransactionSafeActivity getString( R.string.call_composer_connection_failed, data.getStringExtra(CallComposerActivity.KEY_CONTACT_NAME)); - Snackbar.make(mParentLayout, message, Snackbar.LENGTH_LONG).show(); + Snackbar.make(parentLayout, message, Snackbar.LENGTH_LONG).show(); } else { LogUtil.i("DialtactsActivity.onActivityResult", "returned from call composer, no error"); } @@ -830,7 +829,7 @@ public class DialtactsActivity extends TransactionSafeActivity && data.getBooleanExtra(CallDetailsActivity.EXTRA_HAS_ENRICHED_CALL_DATA, false)) { String number = data.getStringExtra(CallDetailsActivity.EXTRA_PHONE_NUMBER); int snackbarDurationMillis = 5_000; - Snackbar.make(mParentLayout, getString(R.string.ec_data_deleted), snackbarDurationMillis) + Snackbar.make(parentLayout, getString(R.string.ec_data_deleted), snackbarDurationMillis) .setAction( R.string.view_conversation, v -> startActivity(IntentProvider.getSendSmsIntentProvider(number).getIntent(this))) @@ -849,7 +848,7 @@ public class DialtactsActivity extends TransactionSafeActivity * Update the number of unread voicemails (potentially other tabs) displayed next to the tab icon. */ public void updateTabUnreadCounts() { - mListsFragment.updateTabUnreadCounts(); + listsFragment.updateTabUnreadCounts(); } /** @@ -860,40 +859,40 @@ public class DialtactsActivity extends TransactionSafeActivity */ private void showDialpadFragment(boolean animate) { LogUtil.i("DialtactActivity.showDialpadFragment", "animate: %b", animate); - if (mIsDialpadShown) { + if (isDialpadShown) { LogUtil.i("DialtactsActivity.showDialpadFragment", "dialpad already shown"); return; } - if (mStateSaved) { + if (stateSaved) { LogUtil.i("DialtactsActivity.showDialpadFragment", "state already saved"); return; } - mIsDialpadShown = true; + isDialpadShown = true; - mListsFragment.setUserVisibleHint(false); + listsFragment.setUserVisibleHint(false); final FragmentTransaction ft = getFragmentManager().beginTransaction(); - if (mDialpadFragment == null) { - mDialpadFragment = new DialpadFragment(); - ft.add(R.id.dialtacts_container, mDialpadFragment, TAG_DIALPAD_FRAGMENT); + if (dialpadFragment == null) { + dialpadFragment = new DialpadFragment(); + ft.add(R.id.dialtacts_container, dialpadFragment, TAG_DIALPAD_FRAGMENT); } else { - ft.show(mDialpadFragment); + ft.show(dialpadFragment); } - mDialpadFragment.setAnimate(animate); + dialpadFragment.setAnimate(animate); Logger.get(this).logScreenView(ScreenEvent.Type.DIALPAD, this); ft.commit(); if (animate) { - mFloatingActionButtonController.scaleOut(); + floatingActionButtonController.scaleOut(); maybeEnterSearchUi(); } else { - mFloatingActionButtonController.scaleOut(); + floatingActionButtonController.scaleOut(); maybeEnterSearchUi(); } - mActionBarController.onDialpadUp(); + actionBarController.onDialpadUp(); - Assert.isNotNull(mListsFragment.getView()).animate().alpha(0).withLayer(); + Assert.isNotNull(listsFragment.getView()).animate().alpha(0).withLayer(); // adjust the title, so the user will know where we're at when the activity start/resumes. setTitle(R.string.launcherDialpadActivityLabel); @@ -910,11 +909,11 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public void onDialpadShown() { LogUtil.enterBlock("DialtactsActivity.onDialpadShown"); - Assert.isNotNull(mDialpadFragment); - if (mDialpadFragment.getAnimate()) { - Assert.isNotNull(mDialpadFragment.getView()).startAnimation(mSlideIn); + Assert.isNotNull(dialpadFragment); + if (dialpadFragment.getAnimate()) { + Assert.isNotNull(dialpadFragment.getView()).startAnimation(slideIn); } else { - mDialpadFragment.setYFraction(0); + dialpadFragment.setYFraction(0); } updateSearchFragmentPosition(); @@ -922,7 +921,7 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public void onCallPlacedFromDialpad() { - mClearSearchOnPause = true; + clearSearchOnPause = true; } @Override @@ -938,38 +937,38 @@ public class DialtactsActivity extends TransactionSafeActivity */ private void hideDialpadFragment(boolean animate, boolean clearDialpad) { LogUtil.enterBlock("DialtactsActivity.hideDialpadFragment"); - if (mDialpadFragment == null || mDialpadFragment.getView() == null) { + if (dialpadFragment == null || dialpadFragment.getView() == null) { return; } if (clearDialpad) { // Temporarily disable accessibility when we clear the dialpad, since it should be // invisible and should not announce anything. - mDialpadFragment + dialpadFragment .getDigitsWidget() .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); - mDialpadFragment.clearDialpad(); - mDialpadFragment + dialpadFragment.clearDialpad(); + dialpadFragment .getDigitsWidget() .setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO); } - if (!mIsDialpadShown) { + if (!isDialpadShown) { return; } - mIsDialpadShown = false; - mDialpadFragment.setAnimate(animate); - mListsFragment.setUserVisibleHint(true); - mListsFragment.sendScreenViewForCurrentPosition(); + isDialpadShown = false; + dialpadFragment.setAnimate(animate); + listsFragment.setUserVisibleHint(true); + listsFragment.sendScreenViewForCurrentPosition(); updateSearchFragmentPosition(); - mFloatingActionButtonController.align(getFabAlignment(), animate); + floatingActionButtonController.align(getFabAlignment(), animate); if (animate) { - mDialpadFragment.getView().startAnimation(mSlideOut); + dialpadFragment.getView().startAnimation(slideOut); } else { commitDialpadFragmentHide(); } - mActionBarController.onDialpadDown(); + actionBarController.onDialpadDown(); // reset the title to normal. setTitle(R.string.launcherActivityLabel); @@ -977,23 +976,20 @@ public class DialtactsActivity extends TransactionSafeActivity /** Finishes hiding the dialpad fragment after any animations are completed. */ private void commitDialpadFragmentHide() { - if (!mStateSaved - && mDialpadFragment != null - && !mDialpadFragment.isHidden() - && !isDestroyed()) { + if (!stateSaved && dialpadFragment != null && !dialpadFragment.isHidden() && !isDestroyed()) { final FragmentTransaction ft = getFragmentManager().beginTransaction(); - ft.hide(mDialpadFragment); + ft.hide(dialpadFragment); ft.commit(); } - mFloatingActionButtonController.scaleIn(); + floatingActionButtonController.scaleIn(); } private void updateSearchFragmentPosition() { SearchFragment fragment = null; - if (mSmartDialSearchFragment != null) { - fragment = mSmartDialSearchFragment; - } else if (mRegularSearchFragment != null) { - fragment = mRegularSearchFragment; + if (smartDialSearchFragment != null) { + fragment = smartDialSearchFragment; + } else if (regularSearchFragment != null) { + fragment = regularSearchFragment; } LogUtil.d( "DialtactsActivity.updateSearchFragmentPosition", @@ -1006,47 +1002,47 @@ public class DialtactsActivity extends TransactionSafeActivity // available immediately which is required to update position. By forcing an animation, // position will be updated after a delay by when the dialpad height would be available. fragment.updatePosition(true /* animate */); - } else if (mNewSearchFragment != null) { + } else if (newSearchFragment != null) { int animationDuration = getResources().getInteger(R.integer.dialpad_slide_in_duration); int actionbarHeight = getResources().getDimensionPixelSize(R.dimen.action_bar_height_large); int shadowHeight = getResources().getDrawable(R.drawable.search_shadow).getIntrinsicHeight(); int start = isDialpadShown() ? actionbarHeight - shadowHeight : 0; int end = isDialpadShown() ? 0 : actionbarHeight - shadowHeight; - mNewSearchFragment.animatePosition(start, end, animationDuration); + newSearchFragment.animatePosition(start, end, animationDuration); } } @Override public boolean isInSearchUi() { - return mInDialpadSearch || mInRegularSearch || mInNewSearch; + return inDialpadSearch || inRegularSearch || inNewSearch; } @Override public boolean hasSearchQuery() { - return !TextUtils.isEmpty(mSearchQuery); + return !TextUtils.isEmpty(searchQuery); } private void setNotInSearchUi() { - mInDialpadSearch = false; - mInRegularSearch = false; - mInNewSearch = false; + inDialpadSearch = false; + inRegularSearch = false; + inNewSearch = false; } private void hideDialpadAndSearchUi() { - if (mIsDialpadShown) { + if (isDialpadShown) { hideDialpadFragment(false, true); } exitSearchUi(); } private void prepareVoiceSearchButton() { - mSearchEditTextLayout.setVoiceSearchEnabled(isVoiceSearchEnabled()); - mVoiceSearchButton.setOnClickListener(this); + searchEditTextLayout.setVoiceSearchEnabled(isVoiceSearchEnabled()); + voiceSearchButton.setOnClickListener(this); } private boolean isVoiceSearchEnabled() { - if (sVoiceSearchEnabledForTest.isPresent()) { - return sVoiceSearchEnabledForTest.get(); + if (voiceSearchEnabledForTest.isPresent()) { + return voiceSearchEnabledForTest.get(); } return canIntentBeHandled(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)); } @@ -1061,7 +1057,7 @@ public class DialtactsActivity extends TransactionSafeActivity /** Sets the hint text for the contacts search box */ private void setSearchBoxHint() { - ((TextView) mSearchEditTextLayout.findViewById(R.id.search_box_start_search)) + ((TextView) searchEditTextLayout.findViewById(R.id.search_box_start_search)) .setHint(getSearchBoxHint()); } @@ -1074,12 +1070,12 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public boolean onCreateOptionsMenu(Menu menu) { - if (mPendingSearchViewQuery != null) { - mSearchView.setText(mPendingSearchViewQuery); - mPendingSearchViewQuery = null; + if (pendingSearchViewQuery != null) { + searchView.setText(pendingSearchViewQuery); + pendingSearchViewQuery = null; } - if (mActionBarController != null) { - mActionBarController.restoreActionBarOffset(); + if (actionBarController != null) { + actionBarController.restoreActionBarOffset(); } return false; } @@ -1133,9 +1129,9 @@ public class DialtactsActivity extends TransactionSafeActivity isDialIntent, isAddCallIntent); showDialpadFragment(false); - mDialpadFragment.setStartedFromNewIntent(true); - if (showDialpadChooser && !mDialpadFragment.isVisible()) { - mInCallDialpadUp = true; + dialpadFragment.setStartedFromNewIntent(true); + if (showDialpadChooser && !dialpadFragment.isVisible()) { + inCallDialpadUp = true; } } else if (isLastTabEnabled) { @TabIndex @@ -1145,8 +1141,8 @@ public class DialtactsActivity extends TransactionSafeActivity .getInt(KEY_LAST_TAB, DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL); // If voicemail tab is saved and its availability changes, we still move to the voicemail tab // but it is quickly removed and shown the contacts tab. - if (mListsFragment != null) { - mListsFragment.showTab(tabIndex); + if (listsFragment != null) { + listsFragment.showTab(tabIndex); PerformanceReport.setStartingTabIndex(tabIndex); } else { PerformanceReport.setStartingTabIndex(DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL); @@ -1158,9 +1154,9 @@ public class DialtactsActivity extends TransactionSafeActivity public void onNewIntent(Intent newIntent) { LogUtil.enterBlock("DialtactsActivity.onNewIntent"); setIntent(newIntent); - mFirstLaunch = true; + firstLaunch = true; - mStateSaved = false; + stateSaved = false; displayFragment(newIntent); invalidateOptionsMenu(); @@ -1184,43 +1180,43 @@ public class DialtactsActivity extends TransactionSafeActivity /** Shows the search fragment */ private void enterSearchUi(boolean smartDialSearch, String query, boolean animate) { LogUtil.i("DialtactsActivity.enterSearchUi", "smart dial: %b", smartDialSearch); - if (mStateSaved || getFragmentManager().isDestroyed()) { + if (stateSaved || getFragmentManager().isDestroyed()) { // Weird race condition where fragment is doing work after the activity is destroyed // due to talkback being on (a bug). Just return since we can't do any // constructive here. LogUtil.i( "DialtactsActivity.enterSearchUi", "not entering search UI (mStateSaved: %b, isDestroyed: %b)", - mStateSaved, + stateSaved, getFragmentManager().isDestroyed()); return; } final FragmentTransaction transaction = getFragmentManager().beginTransaction(); - if (mInDialpadSearch && mSmartDialSearchFragment != null) { - transaction.remove(mSmartDialSearchFragment); - } else if (mInRegularSearch && mRegularSearchFragment != null) { - transaction.remove(mRegularSearchFragment); + if (inDialpadSearch && smartDialSearchFragment != null) { + transaction.remove(smartDialSearchFragment); + } else if (inRegularSearch && regularSearchFragment != null) { + transaction.remove(regularSearchFragment); } final String tag; - mInDialpadSearch = false; - mInRegularSearch = false; - mInNewSearch = false; + inDialpadSearch = false; + inRegularSearch = false; + inNewSearch = false; boolean useNewSearch = ConfigProviderBindings.get(this).getBoolean("enable_new_search_fragment", false); if (useNewSearch) { tag = TAG_NEW_SEARCH_FRAGMENT; - mInNewSearch = true; + inNewSearch = true; } else if (smartDialSearch) { tag = TAG_SMARTDIAL_SEARCH_FRAGMENT; - mInDialpadSearch = true; + inDialpadSearch = true; } else { tag = TAG_REGULAR_SEARCH_FRAGMENT; - mInRegularSearch = true; + inRegularSearch = true; } - mFloatingActionButtonController.scaleOut(); + floatingActionButtonController.scaleOut(); if (animate) { transaction.setCustomAnimations(android.R.animator.fade_in, 0); @@ -1259,7 +1255,7 @@ public class DialtactsActivity extends TransactionSafeActivity // Will show empty list if P13nRanker is not enabled. Else, re-ranked list by the ranker. if (!useNewSearch) { ((SearchFragment) fragment) - .setShowEmptyListForNullQuery(mP13nRanker.shouldShowEmptyListForNullQuery()); + .setShowEmptyListForNullQuery(p13nRanker.shouldShowEmptyListForNullQuery()); } else { // TODO(calderwoodra): add p13n ranker to new search. } @@ -1272,9 +1268,9 @@ public class DialtactsActivity extends TransactionSafeActivity transaction.commit(); if (animate) { - Assert.isNotNull(mListsFragment.getView()).animate().alpha(0).withLayer(); + Assert.isNotNull(listsFragment.getView()).animate().alpha(0).withLayer(); } - mListsFragment.setUserVisibleHint(false); + listsFragment.setUserVisibleHint(false); if (smartDialSearch) { Logger.get(this).logScreenView(ScreenEvent.Type.SMART_DIAL_SEARCH, this); @@ -1288,14 +1284,14 @@ public class DialtactsActivity extends TransactionSafeActivity LogUtil.enterBlock("DialtactsActivity.exitSearchUi"); // See related bug in enterSearchUI(); - if (getFragmentManager().isDestroyed() || mStateSaved) { + if (getFragmentManager().isDestroyed() || stateSaved) { return; } - mSearchView.setText(null); + searchView.setText(null); - if (mDialpadFragment != null) { - mDialpadFragment.clearDialpad(); + if (dialpadFragment != null) { + dialpadFragment.clearDialpad(); } setNotInSearchUi(); @@ -1305,65 +1301,65 @@ public class DialtactsActivity extends TransactionSafeActivity // - Not visible (move then show the fab) // - Visible, in the correct position (do nothing) // - Visible, in the wrong position (hide, move, then show the fab) - if (mFloatingActionButtonController.isVisible() + if (floatingActionButtonController.isVisible() && getFabAlignment() != FloatingActionButtonController.ALIGN_END) { - mFloatingActionButtonController.scaleOut( + floatingActionButtonController.scaleOut( new OnVisibilityChangedListener() { @Override public void onHidden(FloatingActionButton floatingActionButton) { super.onHidden(floatingActionButton); onPageScrolled( - mListsFragment.getCurrentTabIndex(), 0 /* offset */, 0 /* pixelOffset */); - mFloatingActionButtonController.scaleIn(); + listsFragment.getCurrentTabIndex(), 0 /* offset */, 0 /* pixelOffset */); + floatingActionButtonController.scaleIn(); } }); - } else if (!mFloatingActionButtonController.isVisible() && mListsFragment.shouldShowFab()) { - onPageScrolled(mListsFragment.getCurrentTabIndex(), 0 /* offset */, 0 /* pixelOffset */); + } else if (!floatingActionButtonController.isVisible() && listsFragment.shouldShowFab()) { + onPageScrolled(listsFragment.getCurrentTabIndex(), 0 /* offset */, 0 /* pixelOffset */); ThreadUtil.getUiThreadHandler() - .postDelayed(() -> mFloatingActionButtonController.scaleIn(), FAB_SCALE_IN_DELAY_MS); + .postDelayed(() -> floatingActionButtonController.scaleIn(), FAB_SCALE_IN_DELAY_MS); } final FragmentTransaction transaction = getFragmentManager().beginTransaction(); - if (mSmartDialSearchFragment != null) { - transaction.remove(mSmartDialSearchFragment); + if (smartDialSearchFragment != null) { + transaction.remove(smartDialSearchFragment); } - if (mRegularSearchFragment != null) { - transaction.remove(mRegularSearchFragment); + if (regularSearchFragment != null) { + transaction.remove(regularSearchFragment); } - if (mNewSearchFragment != null) { - transaction.remove(mNewSearchFragment); + if (newSearchFragment != null) { + transaction.remove(newSearchFragment); } transaction.commit(); - Assert.isNotNull(mListsFragment.getView()).animate().alpha(1).withLayer(); + Assert.isNotNull(listsFragment.getView()).animate().alpha(1).withLayer(); - if (mDialpadFragment == null || !mDialpadFragment.isVisible()) { + if (dialpadFragment == null || !dialpadFragment.isVisible()) { // If the dialpad fragment wasn't previously visible, then send a screen view because // we are exiting regular search. Otherwise, the screen view will be sent by // {@link #hideDialpadFragment}. - mListsFragment.sendScreenViewForCurrentPosition(); - mListsFragment.setUserVisibleHint(true); + listsFragment.sendScreenViewForCurrentPosition(); + listsFragment.setUserVisibleHint(true); } - onPageSelected(mListsFragment.getCurrentTabIndex()); + onPageSelected(listsFragment.getCurrentTabIndex()); - mActionBarController.onSearchUiExited(); + actionBarController.onSearchUiExited(); } @Override public void onBackPressed() { PerformanceReport.recordClick(UiAction.Type.PRESS_ANDROID_BACK_BUTTON); - if (mStateSaved) { + if (stateSaved) { return; } - if (mIsDialpadShown) { + if (isDialpadShown) { hideDialpadFragment(true, false); - if (TextUtils.isEmpty(mDialpadQuery)) { + if (TextUtils.isEmpty(dialpadQuery)) { exitSearchUi(); } } else if (isInSearchUi()) { - if (mIsKeyboardOpen) { - DialerUtils.hideInputMethod(mParentLayout); + if (isKeyboardOpen) { + DialerUtils.hideInputMethod(parentLayout); PerformanceReport.recordClick(UiAction.Type.HIDE_KEYBOARD_IN_SEARCH); } else { exitSearchUi(); @@ -1378,51 +1374,51 @@ public class DialtactsActivity extends TransactionSafeActivity super.onConfigurationChanged(configuration); // Checks whether a hardware keyboard is available if (configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) { - mIsKeyboardOpen = true; + isKeyboardOpen = true; } else if (configuration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) { - mIsKeyboardOpen = false; + isKeyboardOpen = false; } } private void maybeEnterSearchUi() { if (!isInSearchUi()) { - enterSearchUi(true /* isSmartDial */, mSearchQuery, false); + enterSearchUi(true /* isSmartDial */, searchQuery, false); } } @Override public void onDialpadQueryChanged(String query) { - mDialpadQuery = query; - if (mSmartDialSearchFragment != null) { - mSmartDialSearchFragment.setAddToContactNumber(query); + dialpadQuery = query; + if (smartDialSearchFragment != null) { + smartDialSearchFragment.setAddToContactNumber(query); } - if (mNewSearchFragment != null) { - mNewSearchFragment.setRawNumber(query); + if (newSearchFragment != null) { + newSearchFragment.setRawNumber(query); } final String normalizedQuery = SmartDialNameMatcher.normalizeNumber(/* context = */ this, query); - if (!TextUtils.equals(mSearchView.getText(), normalizedQuery)) { + if (!TextUtils.equals(searchView.getText(), normalizedQuery)) { if (DEBUG) { LogUtil.v("DialtactsActivity.onDialpadQueryChanged", "new query: " + query); } - if (mDialpadFragment == null || !mDialpadFragment.isVisible()) { + if (dialpadFragment == null || !dialpadFragment.isVisible()) { // This callback can happen if the dialpad fragment is recreated because of // activity destruction. In that case, don't update the search view because // that would bring the user back to the search fragment regardless of the // previous state of the application. Instead, just return here and let the // fragment manager correctly figure out whatever fragment was last displayed. if (!TextUtils.isEmpty(normalizedQuery)) { - mPendingSearchViewQuery = normalizedQuery; + pendingSearchViewQuery = normalizedQuery; } return; } - mSearchView.setText(normalizedQuery); + searchView.setText(normalizedQuery); } try { - if (mDialpadFragment != null && mDialpadFragment.isVisible()) { - mDialpadFragment.process_quote_emergency_unquote(normalizedQuery); + if (dialpadFragment != null && dialpadFragment.isVisible()) { + dialpadFragment.process_quote_emergency_unquote(normalizedQuery); } } catch (Exception ignored) { // Skip any exceptions for this piece of code @@ -1431,9 +1427,9 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public boolean onDialpadSpacerTouchWithEmptyQuery() { - if (mInDialpadSearch - && mSmartDialSearchFragment != null - && !mSmartDialSearchFragment.isShowingPermissionRequest()) { + if (inDialpadSearch + && smartDialSearchFragment != null + && !smartDialSearchFragment.isShowingPermissionRequest()) { PerformanceReport.recordClick(UiAction.Type.CLOSE_DIALPAD); hideDialpadFragment(true /* animate */, true /* clearDialpad */); return true; @@ -1443,15 +1439,15 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public boolean onSearchListTouch(MotionEvent event) { - if (mIsDialpadShown) { + if (isDialpadShown) { PerformanceReport.recordClick(UiAction.Type.CLOSE_DIALPAD); hideDialpadFragment(true, false); - if (TextUtils.isEmpty(mDialpadQuery)) { + if (TextUtils.isEmpty(dialpadQuery)) { exitSearchUi(); } return true; } else { - UiUtil.hideKeyboardFrom(this, mSearchEditTextLayout); + UiUtil.hideKeyboardFrom(this, searchEditTextLayout); } return false; } @@ -1461,7 +1457,7 @@ public class DialtactsActivity extends TransactionSafeActivity PerformanceReport.recordScrollStateChange(scrollState); if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { hideDialpadFragment(true, false); - DialerUtils.hideInputMethod(mParentLayout); + DialerUtils.hideInputMethod(parentLayout); } } @@ -1485,7 +1481,7 @@ public class DialtactsActivity extends TransactionSafeActivity /** Called when the user has long-pressed a contact tile to start a drag operation. */ @Override public void onDragStarted(int x, int y, PhoneFavoriteSquareTileView view) { - mListsFragment.showRemoveView(true); + listsFragment.showRemoveView(true); } @Override @@ -1494,7 +1490,7 @@ public class DialtactsActivity extends TransactionSafeActivity /** Called when the user has released a contact tile after long-pressing it. */ @Override public void onDragFinished(int x, int y) { - mListsFragment.showRemoveView(false); + listsFragment.showRemoveView(false); } @Override @@ -1506,15 +1502,15 @@ public class DialtactsActivity extends TransactionSafeActivity */ @Override public void setDragDropController(DragDropController dragController) { - mDragDropController = dragController; - mListsFragment.getRemoveView().setDragDropController(dragController); + dragDropController = dragController; + listsFragment.getRemoveView().setDragDropController(dragController); } /** Implemented to satisfy {@link OldSpeedDialFragment.HostInterface} */ @Override public void showAllContactsTab() { - if (mListsFragment != null) { - mListsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_ALL_CONTACTS); + if (listsFragment != null) { + listsFragment.showTab(DialtactsPagerAdapter.TAB_INDEX_ALL_CONTACTS); } } @@ -1529,14 +1525,14 @@ public class DialtactsActivity extends TransactionSafeActivity LogUtil.d("DialtactsActivity.enableFloatingButton", "enable: %b", enabled); // Floating button shouldn't be enabled when dialpad is shown. if (!isDialpadShown() || !enabled) { - mFloatingActionButtonController.setVisible(enabled); + floatingActionButtonController.setVisible(enabled); } } @Override public void onPickDataUri( Uri dataUri, boolean isVideoCall, CallSpecificAppData callSpecificAppData) { - mClearSearchOnPause = true; + clearSearchOnPause = true; PhoneNumberInteraction.startInteractionForPhoneCall( DialtactsActivity.this, dataUri, isVideoCall, callSpecificAppData); } @@ -1555,7 +1551,7 @@ public class DialtactsActivity extends TransactionSafeActivity .setIsVideoCall(isVideoCall) .setAllowAssistedDial(callSpecificAppData.getAllowAssistedDialing())); - mClearSearchOnPause = true; + clearSearchOnPause = true; } @Override @@ -1569,30 +1565,30 @@ public class DialtactsActivity extends TransactionSafeActivity if (newFavoritesIsEnabled()) { return; } - int tabIndex = mListsFragment.getCurrentTabIndex(); + int tabIndex = listsFragment.getCurrentTabIndex(); // Scroll the button from center to end when moving from the Speed Dial to Call History tab. // In RTL, scroll when the current tab is Call History instead, since the order of the tabs // is reversed and the ViewPager returns the left tab position during scroll. boolean isRtl = ViewUtil.isRtl(); - if (!isRtl && tabIndex == DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL && !mIsLandscape) { - mFloatingActionButtonController.onPageScrolled(positionOffset); - } else if (isRtl && tabIndex == DialtactsPagerAdapter.TAB_INDEX_HISTORY && !mIsLandscape) { - mFloatingActionButtonController.onPageScrolled(1 - positionOffset); + if (!isRtl && tabIndex == DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL && !isLandscape) { + floatingActionButtonController.onPageScrolled(positionOffset); + } else if (isRtl && tabIndex == DialtactsPagerAdapter.TAB_INDEX_HISTORY && !isLandscape) { + floatingActionButtonController.onPageScrolled(1 - positionOffset); } else if (tabIndex != DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL) { - mFloatingActionButtonController.onPageScrolled(1); + floatingActionButtonController.onPageScrolled(1); } } @Override public void onPageSelected(int position) { updateMissedCalls(); - int tabIndex = mListsFragment.getCurrentTabIndex(); - if (tabIndex != mPreviouslySelectedTabIndex) { - mFloatingActionButtonController.scaleIn(); + int tabIndex = listsFragment.getCurrentTabIndex(); + if (tabIndex != previouslySelectedTabIndex) { + floatingActionButtonController.scaleIn(); } LogUtil.i("DialtactsActivity.onPageSelected", "tabIndex: %d", tabIndex); - mPreviouslySelectedTabIndex = tabIndex; + previouslySelectedTabIndex = tabIndex; timeTabSelected = SystemClock.elapsedRealtime(); } @@ -1601,18 +1597,18 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public boolean isActionBarShowing() { - return mActionBarController.isActionBarShowing(); + return actionBarController.isActionBarShowing(); } @Override public boolean isDialpadShown() { - return mIsDialpadShown; + return isDialpadShown; } @Override public int getDialpadHeight() { - if (mDialpadFragment != null) { - return mDialpadFragment.getDialpadHeight(); + if (dialpadFragment != null) { + return dialpadFragment.getDialpadHeight(); } return 0; } @@ -1624,23 +1620,23 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public int getActionBarHeight() { - return mActionBarHeight; + return actionBarHeight; } @VisibleForTesting public int getFabAlignment() { if (!newFavoritesIsEnabled() - && !mIsLandscape + && !isLandscape && !isInSearchUi() - && mListsFragment.getCurrentTabIndex() == DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL) { + && listsFragment.getCurrentTabIndex() == DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL) { return FloatingActionButtonController.ALIGN_MIDDLE; } return FloatingActionButtonController.ALIGN_END; } private void updateMissedCalls() { - if (mPreviouslySelectedTabIndex == DialtactsPagerAdapter.TAB_INDEX_HISTORY) { - mListsFragment.markMissedCallsAsReadAndRemoveNotifications(); + if (previouslySelectedTabIndex == DialtactsPagerAdapter.TAB_INDEX_HISTORY) { + listsFragment.markMissedCallsAsReadAndRemoveNotifications(); } } @@ -1690,19 +1686,19 @@ public class DialtactsActivity extends TransactionSafeActivity } private CallInitiationType.Type getCallInitiationType() { - return mIsDialpadShown + return isDialpadShown ? CallInitiationType.Type.DIALPAD : CallInitiationType.Type.REGULAR_SEARCH; } @Override public void onCallPlacedFromSearch() { - DialerUtils.hideInputMethod(mParentLayout); - mClearSearchOnPause = true; + DialerUtils.hideInputMethod(parentLayout); + clearSearchOnPause = true; } protected int getPreviouslySelectedTabIndex() { - return mPreviouslySelectedTabIndex; + return previouslySelectedTabIndex; } @Override @@ -1726,8 +1722,8 @@ public class DialtactsActivity extends TransactionSafeActivity MenuItem clearFrequents = menu.findItem(R.id.menu_clear_frequents); clearFrequents.setVisible( PermissionsUtil.hasContactsReadPermissions(DialtactsActivity.this) - && mListsFragment != null - && mListsFragment.hasFrequents()); + && listsFragment != null + && listsFragment.hasFrequents()); menu.findItem(R.id.menu_history) .setVisible(PermissionsUtil.hasPhonePermissions(DialtactsActivity.this)); @@ -1759,7 +1755,7 @@ public class DialtactsActivity extends TransactionSafeActivity @Override public boolean onDrag(View v, DragEvent event) { if (event.getAction() == DragEvent.ACTION_DRAG_LOCATION) { - mDragDropController.handleDragHovered(v, (int) event.getX(), (int) event.getY()); + dragDropController.handleDragHovered(v, (int) event.getX(), (int) event.getY()); } return true; } @@ -1767,7 +1763,7 @@ public class DialtactsActivity extends TransactionSafeActivity @VisibleForTesting static void setVoiceSearchEnabledForTest(Optional enabled) { - sVoiceSearchEnabledForTest = enabled; + voiceSearchEnabledForTest = enabled; } private boolean newFavoritesIsEnabled() { diff --git a/java/com/android/dialer/app/calllog/BlockReportSpamListener.java b/java/com/android/dialer/app/calllog/BlockReportSpamListener.java index 05fb2b345..092c0982e 100644 --- a/java/com/android/dialer/app/calllog/BlockReportSpamListener.java +++ b/java/com/android/dialer/app/calllog/BlockReportSpamListener.java @@ -33,10 +33,10 @@ import com.android.dialer.spam.SpamComponent; /** Listener to show dialogs for block and report spam actions. */ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClickListener { - private final Context mContext; - private final FragmentManager mFragmentManager; - private final RecyclerView.Adapter mAdapter; - private final FilteredNumberAsyncQueryHandler mFilteredNumberAsyncQueryHandler; + private final Context context; + private final FragmentManager fragmentManager; + private final RecyclerView.Adapter adapter; + private final FilteredNumberAsyncQueryHandler filteredNumberAsyncQueryHandler; private final Spam spam; public BlockReportSpamListener( @@ -44,10 +44,10 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic FragmentManager fragmentManager, RecyclerView.Adapter adapter, FilteredNumberAsyncQueryHandler filteredNumberAsyncQueryHandler) { - mContext = context; - mFragmentManager = fragmentManager; - mAdapter = adapter; - mFilteredNumberAsyncQueryHandler = filteredNumberAsyncQueryHandler; + this.context = context; + this.fragmentManager = fragmentManager; + this.adapter = adapter; + this.filteredNumberAsyncQueryHandler = filteredNumberAsyncQueryHandler; spam = SpamComponent.get(context).spam(); } @@ -64,7 +64,7 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic isSpamChecked -> { LogUtil.i("BlockReportSpamListener.onBlockReportSpam", "onClick"); if (isSpamChecked && spam.isSpamEnabled()) { - Logger.get(mContext) + Logger.get(context) .logImpression( DialerImpression.Type .REPORT_CALL_AS_SPAM_VIA_CALL_LOG_BLOCK_REPORT_SPAM_SENT_VIA_BLOCK_NUMBER_DIALOG); @@ -75,17 +75,17 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic ReportingLocation.Type.CALL_LOG_HISTORY, contactSourceType); } - mFilteredNumberAsyncQueryHandler.blockNumber( + filteredNumberAsyncQueryHandler.blockNumber( uri -> { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.USER_ACTION_BLOCKED_NUMBER); - mAdapter.notifyDataSetChanged(); + adapter.notifyDataSetChanged(); }, number, countryIso); }, null) - .show(mFragmentManager, BlockReportSpamDialogs.BLOCK_REPORT_SPAM_DIALOG_TAG); + .show(fragmentManager, BlockReportSpamDialogs.BLOCK_REPORT_SPAM_DIALOG_TAG); } @Override @@ -101,7 +101,7 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic () -> { LogUtil.i("BlockReportSpamListener.onBlock", "onClick"); if (spam.isSpamEnabled()) { - Logger.get(mContext) + Logger.get(context) .logImpression( DialerImpression.Type .DIALOG_ACTION_CONFIRM_NUMBER_SPAM_INDIRECTLY_VIA_BLOCK_NUMBER); @@ -112,17 +112,17 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic ReportingLocation.Type.CALL_LOG_HISTORY, contactSourceType); } - mFilteredNumberAsyncQueryHandler.blockNumber( + filteredNumberAsyncQueryHandler.blockNumber( uri -> { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.USER_ACTION_BLOCKED_NUMBER); - mAdapter.notifyDataSetChanged(); + adapter.notifyDataSetChanged(); }, number, countryIso); }, null) - .show(mFragmentManager, BlockReportSpamDialogs.BLOCK_DIALOG_TAG); + .show(fragmentManager, BlockReportSpamDialogs.BLOCK_DIALOG_TAG); } @Override @@ -140,7 +140,7 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic () -> { LogUtil.i("BlockReportSpamListener.onUnblock", "onClick"); if (isSpam && spam.isSpamEnabled()) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.REPORT_AS_NOT_SPAM_VIA_UNBLOCK_NUMBER); spam.reportNotSpamFromCallHistory( number, @@ -149,16 +149,16 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic ReportingLocation.Type.CALL_LOG_HISTORY, contactSourceType); } - mFilteredNumberAsyncQueryHandler.unblock( + filteredNumberAsyncQueryHandler.unblock( (rows, values) -> { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.USER_ACTION_UNBLOCKED_NUMBER); - mAdapter.notifyDataSetChanged(); + adapter.notifyDataSetChanged(); }, blockId); }, null) - .show(mFragmentManager, BlockReportSpamDialogs.UNBLOCK_DIALOG_TAG); + .show(fragmentManager, BlockReportSpamDialogs.UNBLOCK_DIALOG_TAG); } @Override @@ -173,7 +173,7 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic () -> { LogUtil.i("BlockReportSpamListener.onReportNotSpam", "onClick"); if (spam.isSpamEnabled()) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.DIALOG_ACTION_CONFIRM_NUMBER_NOT_SPAM); spam.reportNotSpamFromCallHistory( number, @@ -182,9 +182,9 @@ public class BlockReportSpamListener implements CallLogListItemViewHolder.OnClic ReportingLocation.Type.CALL_LOG_HISTORY, contactSourceType); } - mAdapter.notifyDataSetChanged(); + adapter.notifyDataSetChanged(); }, null) - .show(mFragmentManager, BlockReportSpamDialogs.NOT_SPAM_DIALOG_TAG); + .show(fragmentManager, BlockReportSpamDialogs.NOT_SPAM_DIALOG_TAG); } } diff --git a/java/com/android/dialer/app/calllog/CallLogActivity.java b/java/com/android/dialer/app/calllog/CallLogActivity.java index 4b65ed934..99e11b06c 100644 --- a/java/com/android/dialer/app/calllog/CallLogActivity.java +++ b/java/com/android/dialer/app/calllog/CallLogActivity.java @@ -52,13 +52,13 @@ public class CallLogActivity extends TransactionSafeActivity @VisibleForTesting static final int TAB_INDEX_ALL = 0; @VisibleForTesting static final int TAB_INDEX_MISSED = 1; private static final int TAB_INDEX_COUNT = 2; - private ViewPager mViewPager; - private ViewPagerTabs mViewPagerTabs; - private ViewPagerAdapter mViewPagerAdapter; - private CallLogFragment mAllCallsFragment; - private CallLogFragment mMissedCallsFragment; - private String[] mTabTitles; - private boolean mIsResumed; + private ViewPager viewPager; + private ViewPagerTabs viewPagerTabs; + private ViewPagerAdapter viewPagerAdapter; + private CallLogFragment allCallsFragment; + private CallLogFragment missedCallsFragment; + private String[] tabTitles; + private boolean isResumed; private int selectedPageIndex; @Override @@ -84,21 +84,21 @@ public class CallLogActivity extends TransactionSafeActivity } selectedPageIndex = startingTab; - mTabTitles = new String[TAB_INDEX_COUNT]; - mTabTitles[0] = getString(R.string.call_log_all_title); - mTabTitles[1] = getString(R.string.call_log_missed_title); + tabTitles = new String[TAB_INDEX_COUNT]; + tabTitles[0] = getString(R.string.call_log_all_title); + tabTitles[1] = getString(R.string.call_log_missed_title); - mViewPager = (ViewPager) findViewById(R.id.call_log_pager); + viewPager = (ViewPager) findViewById(R.id.call_log_pager); - mViewPagerAdapter = new ViewPagerAdapter(getFragmentManager()); - mViewPager.setAdapter(mViewPagerAdapter); - mViewPager.setOffscreenPageLimit(1); - mViewPager.setOnPageChangeListener(this); + viewPagerAdapter = new ViewPagerAdapter(getFragmentManager()); + viewPager.setAdapter(viewPagerAdapter); + viewPager.setOffscreenPageLimit(1); + viewPager.setOnPageChangeListener(this); - mViewPagerTabs = (ViewPagerTabs) findViewById(R.id.viewpager_header); + viewPagerTabs = (ViewPagerTabs) findViewById(R.id.viewpager_header); - mViewPagerTabs.setViewPager(mViewPager); - mViewPager.setCurrentItem(startingTab); + viewPagerTabs.setViewPager(viewPager); + viewPager.setCurrentItem(startingTab); } @Override @@ -110,23 +110,23 @@ public class CallLogActivity extends TransactionSafeActivity PerformanceReport.startRecording(); } - mIsResumed = true; + isResumed = true; super.onResume(); sendScreenViewForChildFragment(); } @Override protected void onPause() { - mIsResumed = false; + isResumed = false; super.onPause(); } @Override protected void onStop() { - if (!isChangingConfigurations() && mViewPager != null) { + if (!isChangingConfigurations() && viewPager != null) { // Make sure current index != selectedPageIndex selectedPageIndex = -1; - updateMissedCalls(mViewPager.getCurrentItem()); + updateMissedCalls(viewPager.getCurrentItem()); } super.onStop(); } @@ -141,9 +141,9 @@ public class CallLogActivity extends TransactionSafeActivity @Override public boolean onPrepareOptionsMenu(Menu menu) { final MenuItem itemDeleteAll = menu.findItem(R.id.delete_all); - if (mAllCallsFragment != null && itemDeleteAll != null) { + if (allCallsFragment != null && itemDeleteAll != null) { // If onPrepareOptionsMenu is called before fragments are loaded, don't do anything. - final CallLogAdapter adapter = mAllCallsFragment.getAdapter(); + final CallLogAdapter adapter = allCallsFragment.getAdapter(); itemDeleteAll.setVisible(adapter != null && !adapter.isEmpty()); } return true; @@ -170,22 +170,22 @@ public class CallLogActivity extends TransactionSafeActivity @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { - mViewPagerTabs.onPageScrolled(position, positionOffset, positionOffsetPixels); + viewPagerTabs.onPageScrolled(position, positionOffset, positionOffsetPixels); } @Override public void onPageSelected(int position) { updateMissedCalls(position); selectedPageIndex = position; - if (mIsResumed) { + if (isResumed) { sendScreenViewForChildFragment(); } - mViewPagerTabs.onPageSelected(position); + viewPagerTabs.onPageSelected(position); } @Override public void onPageScrollStateChanged(int state) { - mViewPagerTabs.onPageScrollStateChanged(state); + viewPagerTabs.onPageScrollStateChanged(state); } private void sendScreenViewForChildFragment() { @@ -194,7 +194,7 @@ public class CallLogActivity extends TransactionSafeActivity private int getRtlPosition(int position) { if (ViewUtil.isRtl()) { - return mViewPagerAdapter.getCount() - 1 - position; + return viewPagerAdapter.getCount() - 1 - position; } return position; } @@ -205,13 +205,13 @@ public class CallLogActivity extends TransactionSafeActivity } switch (getRtlPosition(position)) { case TAB_INDEX_ALL: - if (mAllCallsFragment != null) { - mAllCallsFragment.markMissedCallsAsReadAndRemoveNotifications(); + if (allCallsFragment != null) { + allCallsFragment.markMissedCallsAsReadAndRemoveNotifications(); } break; case TAB_INDEX_MISSED: - if (mMissedCallsFragment != null) { - mMissedCallsFragment.markMissedCallsAsReadAndRemoveNotifications(); + if (missedCallsFragment != null) { + missedCallsFragment.markMissedCallsAsReadAndRemoveNotifications(); } break; default: @@ -255,10 +255,10 @@ public class CallLogActivity extends TransactionSafeActivity final CallLogFragment fragment = (CallLogFragment) super.instantiateItem(container, position); switch (getRtlPosition(position)) { case TAB_INDEX_ALL: - mAllCallsFragment = fragment; + allCallsFragment = fragment; break; case TAB_INDEX_MISSED: - mMissedCallsFragment = fragment; + missedCallsFragment = fragment; break; default: throw Assert.createIllegalStateFailException("Invalid position: " + position); @@ -268,7 +268,7 @@ public class CallLogActivity extends TransactionSafeActivity @Override public CharSequence getPageTitle(int position) { - return mTabTitles[position]; + return tabTitles[position]; } @Override diff --git a/java/com/android/dialer/app/calllog/CallLogAdapter.java b/java/com/android/dialer/app/calllog/CallLogAdapter.java index f3d04d935..261b0ec94 100644 --- a/java/com/android/dialer/app/calllog/CallLogAdapter.java +++ b/java/com/android/dialer/app/calllog/CallLogAdapter.java @@ -116,54 +116,54 @@ public class CallLogAdapter extends GroupingListAdapter public static final String ENABLE_CALL_LOG_MULTI_SELECT = "enable_call_log_multiselect"; public static final boolean ENABLE_CALL_LOG_MULTI_SELECT_FLAG = true; - protected final Activity mActivity; - protected final VoicemailPlaybackPresenter mVoicemailPlaybackPresenter; + protected final Activity activity; + protected final VoicemailPlaybackPresenter voicemailPlaybackPresenter; /** Cache for repeated requests to Telecom/Telephony. */ - protected final CallLogCache mCallLogCache; + protected final CallLogCache callLogCache; - private final CallFetcher mCallFetcher; - private final OnActionModeStateChangedListener mActionModeStateChangedListener; - private final MultiSelectRemoveView mMultiSelectRemoveView; - @NonNull private final FilteredNumberAsyncQueryHandler mFilteredNumberAsyncQueryHandler; - private final int mActivityType; + private final CallFetcher callFetcher; + private final OnActionModeStateChangedListener actionModeStateChangedListener; + private final MultiSelectRemoveView multiSelectRemoveView; + @NonNull private final FilteredNumberAsyncQueryHandler filteredNumberAsyncQueryHandler; + private final int activityType; /** Instance of helper class for managing views. */ - private final CallLogListItemHelper mCallLogListItemHelper; + private final CallLogListItemHelper callLogListItemHelper; /** Helper to group call log entries. */ - private final CallLogGroupBuilder mCallLogGroupBuilder; + private final CallLogGroupBuilder callLogGroupBuilder; - private final AsyncTaskExecutor mAsyncTaskExecutor = AsyncTaskExecutors.createAsyncTaskExecutor(); - private ContactInfoCache mContactInfoCache; + private final AsyncTaskExecutor asyncTaskExecutor = AsyncTaskExecutors.createAsyncTaskExecutor(); + private ContactInfoCache contactInfoCache; // Tracks the position of the currently expanded list item. - private int mCurrentlyExpandedPosition = RecyclerView.NO_POSITION; + private int currentlyExpandedPosition = RecyclerView.NO_POSITION; // Tracks the rowId of the currently expanded list item, so the position can be updated if there // are any changes to the call log entries, such as additions or removals. - private long mCurrentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; + private long currentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; - private final CallLogAlertManager mCallLogAlertManager; + private final CallLogAlertManager callLogAlertManager; - public ActionMode mActionMode = null; + public ActionMode actionMode = null; public boolean selectAllMode = false; public boolean deselectAllMode = false; private final SparseArray selectedItems = new SparseArray<>(); - private final ActionMode.Callback mActionModeCallback = + private final ActionMode.Callback actionModeCallback = new ActionMode.Callback() { // Called when the action mode is created; startActionMode() was called @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { - if (mActivity != null) { + if (activity != null) { announceforAccessibility( - mActivity.getCurrentFocus(), - mActivity.getString(R.string.description_entering_bulk_action_mode)); + activity.getCurrentFocus(), + activity.getString(R.string.description_entering_bulk_action_mode)); } - mActionMode = mode; + actionMode = mode; // Inflate a menu resource providing context menu items MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.actionbar_delete, menu); - mMultiSelectRemoveView.showMultiSelectRemoveView(true); - mActionModeStateChangedListener.onActionModeStateChanged(true); + multiSelectRemoveView.showMultiSelectRemoveView(true); + actionModeStateChangedListener.onActionModeStateChanged(true); return true; } @@ -178,7 +178,7 @@ public class CallLogAdapter extends GroupingListAdapter @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { if (item.getItemId() == R.id.action_bar_delete_menu_item) { - Logger.get(mActivity).logImpression(DialerImpression.Type.MULTISELECT_TAP_DELETE_ICON); + Logger.get(activity).logImpression(DialerImpression.Type.MULTISELECT_TAP_DELETE_ICON); if (selectedItems.size() > 0) { showDeleteSelectedItemsDialog(); } @@ -191,27 +191,27 @@ public class CallLogAdapter extends GroupingListAdapter // Called when the user exits the action mode @Override public void onDestroyActionMode(ActionMode mode) { - if (mActivity != null) { + if (activity != null) { announceforAccessibility( - mActivity.getCurrentFocus(), - mActivity.getString(R.string.description_leaving_bulk_action_mode)); + activity.getCurrentFocus(), + activity.getString(R.string.description_leaving_bulk_action_mode)); } selectedItems.clear(); - mActionMode = null; + actionMode = null; selectAllMode = false; deselectAllMode = false; - mMultiSelectRemoveView.showMultiSelectRemoveView(false); - mActionModeStateChangedListener.onActionModeStateChanged(false); + multiSelectRemoveView.showMultiSelectRemoveView(false); + actionModeStateChangedListener.onActionModeStateChanged(false); notifyDataSetChanged(); } }; private void showDeleteSelectedItemsDialog() { SparseArray voicemailsToDeleteOnConfirmation = selectedItems.clone(); - new AlertDialog.Builder(mActivity, R.style.AlertDialogCustom) + new AlertDialog.Builder(activity, R.style.AlertDialogCustom) .setCancelable(true) .setTitle( - mActivity + activity .getResources() .getQuantityString( R.plurals.delete_voicemails_confirmation_dialog_title, selectedItems.size())) @@ -224,9 +224,9 @@ public class CallLogAdapter extends GroupingListAdapter "CallLogAdapter.showDeleteSelectedItemsDialog", "onClick, these items to delete " + voicemailsToDeleteOnConfirmation); deleteSelectedItems(voicemailsToDeleteOnConfirmation); - mActionMode.finish(); + actionMode.finish(); dialog.cancel(); - Logger.get(mActivity) + Logger.get(activity) .logImpression( DialerImpression.Type.MULTISELECT_DELETE_ENTRY_VIA_CONFIRMATION_DIALOG); } @@ -235,7 +235,7 @@ public class CallLogAdapter extends GroupingListAdapter new OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { - Logger.get(mActivity) + Logger.get(activity) .logImpression( DialerImpression.Type .MULTISELECT_CANCEL_CONFIRMATION_DIALOG_VIA_CANCEL_TOUCH); @@ -247,7 +247,7 @@ public class CallLogAdapter extends GroupingListAdapter new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int button) { - Logger.get(mActivity) + Logger.get(activity) .logImpression( DialerImpression.Type .MULTISELECT_CANCEL_CONFIRMATION_DIALOG_VIA_CANCEL_BUTTON); @@ -255,7 +255,7 @@ public class CallLogAdapter extends GroupingListAdapter } }) .show(); - Logger.get(mActivity) + Logger.get(activity) .logImpression(DialerImpression.Type.MULTISELECT_DISPLAY_DELETE_CONFIRMATION_DIALOG); } @@ -263,30 +263,30 @@ public class CallLogAdapter extends GroupingListAdapter for (int i = 0; i < voicemailsToDelete.size(); i++) { String voicemailUri = voicemailsToDelete.get(voicemailsToDelete.keyAt(i)); LogUtil.i("CallLogAdapter.deleteSelectedItems", "deleting uri:" + voicemailUri); - CallLogAsyncTaskUtil.deleteVoicemail(mActivity, Uri.parse(voicemailUri), null); + CallLogAsyncTaskUtil.deleteVoicemail(activity, Uri.parse(voicemailUri), null); } } - private final View.OnLongClickListener mLongPressListener = + private final View.OnLongClickListener longPressListener = new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (ConfigProviderBindings.get(v.getContext()) .getBoolean(ENABLE_CALL_LOG_MULTI_SELECT, ENABLE_CALL_LOG_MULTI_SELECT_FLAG) - && mVoicemailPlaybackPresenter != null) { + && voicemailPlaybackPresenter != null) { if (v.getId() == R.id.primary_action_view || v.getId() == R.id.quick_contact_photo) { - if (mActionMode == null) { - Logger.get(mActivity) + if (actionMode == null) { + Logger.get(activity) .logImpression( DialerImpression.Type.MULTISELECT_LONG_PRESS_ENTER_MULTI_SELECT_MODE); - mActionMode = v.startActionMode(mActionModeCallback); + actionMode = v.startActionMode(actionModeCallback); } - Logger.get(mActivity) + Logger.get(activity) .logImpression(DialerImpression.Type.MULTISELECT_LONG_PRESS_TAP_ENTRY); CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder) v.getTag(); viewHolder.quickContactView.setVisibility(View.GONE); viewHolder.checkBoxView.setVisibility(View.VISIBLE); - mExpandCollapseListener.onClick(v); + expandCollapseListener.onClick(v); return true; } } @@ -296,11 +296,11 @@ public class CallLogAdapter extends GroupingListAdapter @VisibleForTesting public View.OnClickListener getExpandCollapseListener() { - return mExpandCollapseListener; + return expandCollapseListener; } /** The OnClickListener used to expand or collapse the action buttons of a call log entry. */ - private final View.OnClickListener mExpandCollapseListener = + private final View.OnClickListener expandCollapseListener = new View.OnClickListener() { @Override public void onClick(View v) { @@ -310,17 +310,17 @@ public class CallLogAdapter extends GroupingListAdapter if (viewHolder == null) { return; } - if (mActionMode != null && viewHolder.voicemailUri != null) { + if (actionMode != null && viewHolder.voicemailUri != null) { selectAllMode = false; deselectAllMode = false; - mMultiSelectRemoveView.setSelectAllModeToFalse(); + multiSelectRemoveView.setSelectAllModeToFalse(); int id = getVoicemailId(viewHolder.voicemailUri); if (selectedItems.get(id) != null) { - Logger.get(mActivity) + Logger.get(activity) .logImpression(DialerImpression.Type.MULTISELECT_SINGLE_PRESS_UNSELECT_ENTRY); uncheckMarkCallLogEntry(viewHolder, id); } else { - Logger.get(mActivity) + Logger.get(activity) .logImpression(DialerImpression.Type.MULTISELECT_SINGLE_PRESS_SELECT_ENTRY); checkMarkCallLogEntry(viewHolder); // select all check box logic @@ -330,15 +330,15 @@ public class CallLogAdapter extends GroupingListAdapter "getitem count %d is equal to items select count %d, check select all box", getItemCount(), selectedItems.size()); - mMultiSelectRemoveView.tapSelectAll(); + multiSelectRemoveView.tapSelectAll(); } } return; } - if (mVoicemailPlaybackPresenter != null) { + if (voicemailPlaybackPresenter != null) { // Always reset the voicemail playback state on expand or collapse. - mVoicemailPlaybackPresenter.resetAll(); + voicemailPlaybackPresenter.resetAll(); } // If enriched call capabilities were unknown on the initial load, @@ -368,16 +368,16 @@ public class CallLogAdapter extends GroupingListAdapter getEnrichedCallManager().requestCapabilities(viewHolder.number); } - if (viewHolder.rowId == mCurrentlyExpandedRowId) { + if (viewHolder.rowId == currentlyExpandedRowId) { // Hide actions, if the clicked item is the expanded item. viewHolder.showActions(false); - mCurrentlyExpandedPosition = RecyclerView.NO_POSITION; - mCurrentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; + currentlyExpandedPosition = RecyclerView.NO_POSITION; + currentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; } else { if (viewHolder.callType == CallLog.Calls.MISSED_TYPE) { - CallLogAsyncTaskUtil.markCallAsRead(mActivity, viewHolder.callIds); - if (mActivityType == ACTIVITY_TYPE_DIALTACTS) { + CallLogAsyncTaskUtil.markCallAsRead(activity, viewHolder.callIds); + if (activityType == ACTIVITY_TYPE_DIALTACTS) { ((DialtactsActivity) v.getContext()).updateTabUnreadCounts(); } } @@ -400,7 +400,7 @@ public class CallLogAdapter extends GroupingListAdapter if (intentProvider == null) { return false; } - return DuoConstants.PACKAGE_NAME.equals(intentProvider.getIntent(mActivity).getPackage()); + return DuoConstants.PACKAGE_NAME.equals(intentProvider.getIntent(activity).getPackage()); } }; @@ -411,8 +411,8 @@ public class CallLogAdapter extends GroupingListAdapter private void checkMarkCallLogEntry(CallLogListItemViewHolder viewHolder) { announceforAccessibility( - mActivity.getCurrentFocus(), - mActivity.getString( + activity.getCurrentFocus(), + activity.getString( R.string.description_selecting_bulk_action_mode, viewHolder.nameOrNumber)); viewHolder.quickContactView.setVisibility(View.GONE); viewHolder.checkBoxView.setVisibility(View.VISIBLE); @@ -427,14 +427,14 @@ public class CallLogAdapter extends GroupingListAdapter } private void updateActionBar() { - if (mActionMode == null && selectedItems.size() > 0) { - Logger.get(mActivity) + if (actionMode == null && selectedItems.size() > 0) { + Logger.get(activity) .logImpression(DialerImpression.Type.MULTISELECT_ROTATE_AND_SHOW_ACTION_MODE); - mActivity.startActionMode(mActionModeCallback); + activity.startActionMode(actionModeCallback); } - if (mActionMode != null) { - mActionMode.setTitle( - mActivity + if (actionMode != null) { + actionMode.setTitle( + activity .getResources() .getString( R.string.voicemailMultiSelectActionBarTitle, @@ -444,8 +444,8 @@ public class CallLogAdapter extends GroupingListAdapter private void uncheckMarkCallLogEntry(CallLogListItemViewHolder viewHolder, int id) { announceforAccessibility( - mActivity.getCurrentFocus(), - mActivity.getString( + activity.getCurrentFocus(), + activity.getString( R.string.description_unselecting_bulk_action_mode, viewHolder.nameOrNumber)); selectedItems.delete(id); viewHolder.checkBoxView.setVisibility(View.GONE); @@ -464,7 +464,7 @@ public class CallLogAdapter extends GroupingListAdapter * if removing an item, it will be shown as an invisible view. This simplifies the calculation of * item position. */ - @NonNull private Set mHiddenRowIds = new ArraySet<>(); + @NonNull private Set hiddenRowIds = new ArraySet<>(); /** * Holds a list of URIs that are pending deletion or undo. If the activity ends before the undo * timeout, all of the pending URIs will be deleted. @@ -473,9 +473,9 @@ public class CallLogAdapter extends GroupingListAdapter * VisualVoicemailCallLogFragment}. The CallLogAdapter does not need to know about what to do with * hidden item or what to hide. */ - @NonNull private final Set mHiddenItemUris = new ArraySet<>(); + @NonNull private final Set hiddenItemUris = new ArraySet<>(); - private CallLogListItemViewHolder.OnClickListener mBlockReportSpamListener; + private CallLogListItemViewHolder.OnClickListener blockReportSpamListener; /** * Map, keyed by call ID, used to track the callback action for a call. Calls associated with the @@ -483,7 +483,7 @@ public class CallLogAdapter extends GroupingListAdapter * com.android.dialer.app.calllog.CallLogGroupBuilder}. This information is used to set the * callback icon and trigger the corresponding action. */ - private final Map mCallbackActions = new ArrayMap<>(); + private final Map callbackActions = new ArrayMap<>(); /** * Map, keyed by call ID, used to track the day group for a call. As call log entries are put into @@ -497,12 +497,12 @@ public class CallLogAdapter extends GroupingListAdapter * previous day group without having to reverse the cursor to the start of the previous day call * log entry. */ - private final Map mDayGroups = new ArrayMap<>(); + private final Map dayGroups = new ArrayMap<>(); - private boolean mLoading = true; - private ContactsPreferences mContactsPreferences; + private boolean loading = true; + private ContactsPreferences contactsPreferences; - private boolean mIsSpamEnabled; + private boolean isSpamEnabled; public CallLogAdapter( Activity activity, @@ -517,58 +517,58 @@ public class CallLogAdapter extends GroupingListAdapter int activityType) { super(); - mActivity = activity; - mCallFetcher = callFetcher; - mActionModeStateChangedListener = actionModeStateChangedListener; - mMultiSelectRemoveView = multiSelectRemoveView; - mVoicemailPlaybackPresenter = voicemailPlaybackPresenter; - if (mVoicemailPlaybackPresenter != null) { - mVoicemailPlaybackPresenter.setOnVoicemailDeletedListener(this); + this.activity = activity; + this.callFetcher = callFetcher; + this.actionModeStateChangedListener = actionModeStateChangedListener; + this.multiSelectRemoveView = multiSelectRemoveView; + this.voicemailPlaybackPresenter = voicemailPlaybackPresenter; + if (this.voicemailPlaybackPresenter != null) { + this.voicemailPlaybackPresenter.setOnVoicemailDeletedListener(this); } - mActivityType = activityType; + this.activityType = activityType; - mContactInfoCache = contactInfoCache; + this.contactInfoCache = contactInfoCache; if (!PermissionsUtil.hasContactsReadPermissions(activity)) { - mContactInfoCache.disableRequestProcessing(); + this.contactInfoCache.disableRequestProcessing(); } - Resources resources = mActivity.getResources(); + Resources resources = this.activity.getResources(); - mCallLogCache = callLogCache; + this.callLogCache = callLogCache; PhoneCallDetailsHelper phoneCallDetailsHelper = - new PhoneCallDetailsHelper(mActivity, resources, mCallLogCache); - mCallLogListItemHelper = - new CallLogListItemHelper(phoneCallDetailsHelper, resources, mCallLogCache); - mCallLogGroupBuilder = new CallLogGroupBuilder(this); - mFilteredNumberAsyncQueryHandler = Assert.isNotNull(filteredNumberAsyncQueryHandler); + new PhoneCallDetailsHelper(this.activity, resources, this.callLogCache); + callLogListItemHelper = + new CallLogListItemHelper(phoneCallDetailsHelper, resources, this.callLogCache); + callLogGroupBuilder = new CallLogGroupBuilder(this); + this.filteredNumberAsyncQueryHandler = Assert.isNotNull(filteredNumberAsyncQueryHandler); - mContactsPreferences = new ContactsPreferences(mActivity); + contactsPreferences = new ContactsPreferences(this.activity); - mBlockReportSpamListener = + blockReportSpamListener = new BlockReportSpamListener( - mActivity, - ((Activity) mActivity).getFragmentManager(), + this.activity, + ((Activity) this.activity).getFragmentManager(), this, - mFilteredNumberAsyncQueryHandler); + this.filteredNumberAsyncQueryHandler); setHasStableIds(true); - mCallLogAlertManager = - new CallLogAlertManager(this, LayoutInflater.from(mActivity), alertContainer); + callLogAlertManager = + new CallLogAlertManager(this, LayoutInflater.from(this.activity), alertContainer); } private void expandViewHolderActions(CallLogListItemViewHolder viewHolder) { if (!TextUtils.isEmpty(viewHolder.voicemailUri)) { - Logger.get(mActivity).logImpression(DialerImpression.Type.VOICEMAIL_EXPAND_ENTRY); + Logger.get(activity).logImpression(DialerImpression.Type.VOICEMAIL_EXPAND_ENTRY); } - int lastExpandedPosition = mCurrentlyExpandedPosition; + int lastExpandedPosition = currentlyExpandedPosition; // Show the actions for the clicked list item. viewHolder.showActions(true); - mCurrentlyExpandedPosition = viewHolder.getAdapterPosition(); - mCurrentlyExpandedRowId = viewHolder.rowId; + currentlyExpandedPosition = viewHolder.getAdapterPosition(); + currentlyExpandedRowId = viewHolder.rowId; // If another item is expanded, notify it that it has changed. Its actions will be // hidden when it is re-binded because we change mCurrentlyExpandedRowId above. @@ -578,8 +578,8 @@ public class CallLogAdapter extends GroupingListAdapter } public void onSaveInstanceState(Bundle outState) { - outState.putInt(KEY_EXPANDED_POSITION, mCurrentlyExpandedPosition); - outState.putLong(KEY_EXPANDED_ROW_ID, mCurrentlyExpandedRowId); + outState.putInt(KEY_EXPANDED_POSITION, currentlyExpandedPosition); + outState.putLong(KEY_EXPANDED_ROW_ID, currentlyExpandedRowId); ArrayList listOfSelectedItems = new ArrayList<>(); @@ -603,9 +603,9 @@ public class CallLogAdapter extends GroupingListAdapter public void onRestoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { - mCurrentlyExpandedPosition = + currentlyExpandedPosition = savedInstanceState.getInt(KEY_EXPANDED_POSITION, RecyclerView.NO_POSITION); - mCurrentlyExpandedRowId = + currentlyExpandedRowId = savedInstanceState.getLong(KEY_EXPANDED_ROW_ID, NO_EXPANDED_LIST_ITEM); // Restoring multi selected entries ArrayList listOfSelectedItems = @@ -642,15 +642,15 @@ public class CallLogAdapter extends GroupingListAdapter /** Requery on background thread when {@link Cursor} changes. */ @Override protected void onContentChanged() { - mCallFetcher.fetchCalls(); + callFetcher.fetchCalls(); } public void setLoading(boolean loading) { - mLoading = loading; + this.loading = loading; } public boolean isEmpty() { - if (mLoading) { + if (loading) { // We don't want the empty state to show when loading. return false; } else { @@ -659,15 +659,15 @@ public class CallLogAdapter extends GroupingListAdapter } public void clearFilteredNumbersCache() { - mFilteredNumberAsyncQueryHandler.clearCache(); + filteredNumberAsyncQueryHandler.clearCache(); } public void onResume() { - if (PermissionsUtil.hasPermission(mActivity, android.Manifest.permission.READ_CONTACTS)) { - mContactInfoCache.start(); + if (PermissionsUtil.hasPermission(activity, android.Manifest.permission.READ_CONTACTS)) { + contactInfoCache.start(); } - mContactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); - mIsSpamEnabled = SpamComponent.get(mActivity).spam().isSpamEnabled(); + contactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); + isSpamEnabled = SpamComponent.get(activity).spam().isSpamEnabled(); getDuo().registerListener(this); notifyDataSetChanged(); } @@ -675,8 +675,8 @@ public class CallLogAdapter extends GroupingListAdapter public void onPause() { getDuo().unregisterListener(this); pauseCache(); - for (Uri uri : mHiddenItemUris) { - CallLogAsyncTaskUtil.deleteVoicemail(mActivity, uri, null); + for (Uri uri : hiddenItemUris) { + CallLogAsyncTaskUtil.deleteVoicemail(activity, uri, null); } } @@ -685,24 +685,24 @@ public class CallLogAdapter extends GroupingListAdapter } public CallLogAlertManager getAlertManager() { - return mCallLogAlertManager; + return callLogAlertManager; } @VisibleForTesting /* package */ void pauseCache() { - mContactInfoCache.stop(); - mCallLogCache.reset(); + contactInfoCache.stop(); + callLogCache.reset(); } @Override protected void addGroups(Cursor cursor) { - mCallLogGroupBuilder.addGroups(cursor); + callLogGroupBuilder.addGroups(cursor); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_ALERT) { - return mCallLogAlertManager.createViewHolder(parent); + return callLogAlertManager.createViewHolder(parent); } return createCallLogEntryViewHolder(parent); } @@ -714,19 +714,19 @@ public class CallLogAdapter extends GroupingListAdapter * @return The {@link ViewHolder}. */ private ViewHolder createCallLogEntryViewHolder(ViewGroup parent) { - LayoutInflater inflater = LayoutInflater.from(mActivity); + LayoutInflater inflater = LayoutInflater.from(activity); View view = inflater.inflate(R.layout.call_log_list_item, parent, false); CallLogListItemViewHolder viewHolder = CallLogListItemViewHolder.create( view, - mActivity, - mBlockReportSpamListener, - mExpandCollapseListener, - mLongPressListener, - mActionModeStateChangedListener, - mCallLogCache, - mCallLogListItemHelper, - mVoicemailPlaybackPresenter); + activity, + blockReportSpamListener, + expandCollapseListener, + longPressListener, + actionModeStateChangedListener, + callLogCache, + callLogListItemHelper, + voicemailPlaybackPresenter); viewHolder.callLogEntryView.setTag(viewHolder); @@ -802,7 +802,7 @@ public class CallLogAdapter extends GroupingListAdapter int groupSize = getGroupSize(position); CallDetailsEntries callDetailsEntries = createCallDetailsEntries(c, groupSize); PhoneCallDetails details = createPhoneCallDetails(c, groupSize, views); - if (mHiddenRowIds.contains(c.getLong(CallLogQuery.ID))) { + if (hiddenRowIds.contains(c.getLong(CallLogQuery.ID))) { views.callLogEntryView.setVisibility(View.GONE); views.dayGroupHeader.setVisibility(View.GONE); return; @@ -810,7 +810,7 @@ public class CallLogAdapter extends GroupingListAdapter views.callLogEntryView.setVisibility(View.VISIBLE); // dayGroupHeader will be restored after loadAndRender() if it is needed. } - if (mCurrentlyExpandedRowId == views.rowId) { + if (currentlyExpandedRowId == views.rowId) { views.inflateActionViewStub(); } loadAndRender(views, views.rowId, details, callDetailsEntries); @@ -849,19 +849,19 @@ public class CallLogAdapter extends GroupingListAdapter @Override protected Boolean doInBackground(Void... params) { viewHolder.blockId = - mFilteredNumberAsyncQueryHandler.getBlockedIdSynchronous( + filteredNumberAsyncQueryHandler.getBlockedIdSynchronous( viewHolder.number, viewHolder.countryIso); details.isBlocked = viewHolder.blockId != null; if (isCancelled()) { return false; } - if (mIsSpamEnabled) { + if (isSpamEnabled) { viewHolder.isSpamFeatureEnabled = true; // Only display the call as a spam call if there are incoming calls in the list. // Call log cards with only outgoing calls should never be displayed as spam. viewHolder.isSpam = details.hasIncomingCalls() - && SpamComponent.get(mActivity) + && SpamComponent.get(activity) .spam() .checkSpamStatusSynchronous(viewHolder.number, viewHolder.countryIso); details.isSpam = viewHolder.isSpam; @@ -887,7 +887,7 @@ public class CallLogAdapter extends GroupingListAdapter }; viewHolder.asyncTask = loadDataTask; - mAsyncTaskExecutor.submit(LOAD_DATA_TASK_IDENTIFIER, loadDataTask); + asyncTaskExecutor.submit(LOAD_DATA_TASK_IDENTIFIER, loadDataTask); } @MainThread @@ -1011,8 +1011,7 @@ public class CallLogAdapter extends GroupingListAdapter final PhoneAccountHandle accountHandle = PhoneAccountUtils.getAccount(details.accountComponentName, details.accountId); - final boolean isVoicemailNumber = - mCallLogCache.isVoicemailNumber(accountHandle, details.number); + final boolean isVoicemailNumber = callLogCache.isVoicemailNumber(accountHandle, details.number); // Note: Binding of the action buttons is done as required in configureActionViews when the // user expands the actions ViewStub. @@ -1024,19 +1023,19 @@ public class CallLogAdapter extends GroupingListAdapter // Only do remote lookup in first 5 rows. int position = views.getAdapterPosition(); info = - mContactInfoCache.getValue( + contactInfoCache.getValue( details.number + details.postDialDigits, details.countryIso, details.cachedContactInfo, position - < ConfigProviderBindings.get(mActivity) + < ConfigProviderBindings.get(activity) .getLong("number_of_call_to_do_remote_lookup", 5L)); } CharSequence formattedNumber = info.formattedNumber == null ? null : PhoneNumberUtilsCompat.createTtsSpannable(info.formattedNumber); - details.updateDisplayNumber(mActivity, formattedNumber, isVoicemailNumber); + details.updateDisplayNumber(activity, formattedNumber, isVoicemailNumber); views.displayNumber = details.displayNumber; views.accountHandle = accountHandle; @@ -1046,7 +1045,7 @@ public class CallLogAdapter extends GroupingListAdapter details.contactUri = info.lookupUri; details.namePrimary = info.name; details.nameAlternative = info.nameAlternative; - details.nameDisplayOrder = mContactsPreferences.getDisplayOrder(); + details.nameDisplayOrder = contactsPreferences.getDisplayOrder(); details.numberType = info.type; details.numberLabel = info.label; details.photoUri = info.photoUri; @@ -1067,9 +1066,9 @@ public class CallLogAdapter extends GroupingListAdapter } views.info = info; - views.numberType = getNumberType(mActivity.getResources(), details); + views.numberType = getNumberType(activity.getResources(), details); - mCallLogListItemHelper.updatePhoneCallDetails(details); + callLogListItemHelper.updatePhoneCallDetails(details); return true; } @@ -1119,11 +1118,11 @@ public class CallLogAdapter extends GroupingListAdapter views.checkBoxView.setVisibility(View.GONE); views.quickContactView.setVisibility(View.VISIBLE); } - mCallLogListItemHelper.setPhoneCallDetails(views, details); - if (mCurrentlyExpandedRowId == views.rowId) { + callLogListItemHelper.setPhoneCallDetails(views, details); + if (currentlyExpandedRowId == views.rowId) { // In case ViewHolders were added/removed, update the expanded position if the rowIds // match so that we can restore the correct expanded state on rebind. - mCurrentlyExpandedPosition = views.getAdapterPosition(); + currentlyExpandedPosition = views.getAdapterPosition(); views.showActions(true); } else { views.showActions(false); @@ -1134,12 +1133,12 @@ public class CallLogAdapter extends GroupingListAdapter @Override public int getItemCount() { - return super.getItemCount() + (mCallLogAlertManager.isEmpty() ? 0 : 1); + return super.getItemCount() + (callLogAlertManager.isEmpty() ? 0 : 1); } @Override public int getItemViewType(int position) { - if (position == ALERT_POSITION && !mCallLogAlertManager.isEmpty()) { + if (position == ALERT_POSITION && !callLogAlertManager.isEmpty()) { return VIEW_TYPE_ALERT; } return VIEW_TYPE_CALLLOG; @@ -1153,7 +1152,7 @@ public class CallLogAdapter extends GroupingListAdapter */ @Override public Object getItem(int position) { - return super.getItem(position - (mCallLogAlertManager.isEmpty() ? 0 : 1)); + return super.getItem(position - (callLogAlertManager.isEmpty() ? 0 : 1)); } @Override @@ -1168,11 +1167,11 @@ public class CallLogAdapter extends GroupingListAdapter @Override public int getGroupSize(int position) { - return super.getGroupSize(position - (mCallLogAlertManager.isEmpty() ? 0 : 1)); + return super.getGroupSize(position - (callLogAlertManager.isEmpty() ? 0 : 1)); } protected boolean isCallLogActivity() { - return mActivityType == ACTIVITY_TYPE_CALL_LOG; + return activityType == ACTIVITY_TYPE_CALL_LOG; } /** @@ -1183,9 +1182,9 @@ public class CallLogAdapter extends GroupingListAdapter */ @Override public void onVoicemailDeleted(CallLogListItemViewHolder viewHolder, Uri uri) { - mHiddenRowIds.add(viewHolder.rowId); + hiddenRowIds.add(viewHolder.rowId); // Save the new hidden item uri in case the activity is suspend before the undo has timed out. - mHiddenItemUris.add(uri); + hiddenItemUris.add(uri); collapseExpandedCard(); notifyItemChanged(viewHolder.getAdapterPosition()); @@ -1194,20 +1193,20 @@ public class CallLogAdapter extends GroupingListAdapter } private void collapseExpandedCard() { - mCurrentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; - mCurrentlyExpandedPosition = RecyclerView.NO_POSITION; + currentlyExpandedRowId = NO_EXPANDED_LIST_ITEM; + currentlyExpandedPosition = RecyclerView.NO_POSITION; } /** When the list is changing all stored position is no longer valid. */ public void invalidatePositions() { - mCurrentlyExpandedPosition = RecyclerView.NO_POSITION; + currentlyExpandedPosition = RecyclerView.NO_POSITION; } /** When the user clicks "undo", the hidden item is unhidden. */ @Override public void onVoicemailDeleteUndo(long rowId, int adapterPosition, Uri uri) { - mHiddenItemUris.remove(uri); - mHiddenRowIds.remove(rowId); + hiddenItemUris.remove(uri); + hiddenRowIds.remove(rowId); notifyItemChanged(adapterPosition); // The next item might have to update its day group label notifyItemChanged(adapterPosition + 1); @@ -1216,7 +1215,7 @@ public class CallLogAdapter extends GroupingListAdapter /** This callback signifies that a database deletion has completed. */ @Override public void onVoicemailDeletedInDatabase(long rowId, Uri uri) { - mHiddenItemUris.remove(uri); + hiddenItemUris.remove(uri); } /** @@ -1240,7 +1239,7 @@ public class CallLogAdapter extends GroupingListAdapter } private void moveToPreviousNonHiddenRow(Cursor cursor) { - while (cursor.moveToPrevious() && mHiddenRowIds.contains(cursor.getLong(CallLogQuery.ID))) {} + while (cursor.moveToPrevious() && hiddenRowIds.contains(cursor.getLong(CallLogQuery.ID))) {} } /** @@ -1252,7 +1251,7 @@ public class CallLogAdapter extends GroupingListAdapter */ @MainThread private int getCallbackAction(long callId) { - Integer result = mCallbackActions.get(callId); + Integer result = callbackActions.get(callId); if (result != null) { return result; } @@ -1268,7 +1267,7 @@ public class CallLogAdapter extends GroupingListAdapter */ @MainThread private int getDayGroup(long callId) { - Integer result = mDayGroups.get(callId); + Integer result = dayGroups.get(callId); if (result != null) { return result; } @@ -1320,13 +1319,13 @@ public class CallLogAdapter extends GroupingListAdapter @VisibleForTesting void disableRequestProcessingForTest() { // TODO: Remove this and test the cache directly. - mContactInfoCache.disableRequestProcessing(); + contactInfoCache.disableRequestProcessing(); } @VisibleForTesting void injectContactInfoForTest(String number, String countryIso, ContactInfo contactInfo) { // TODO: Remove this and test the cache directly. - mContactInfoCache.injectContactInfoForTest(number, countryIso, contactInfo); + contactInfoCache.injectContactInfoForTest(number, countryIso, contactInfo); } /** @@ -1338,7 +1337,7 @@ public class CallLogAdapter extends GroupingListAdapter @Override @MainThread public void setCallbackAction(long rowId, @CallbackAction int callbackAction) { - mCallbackActions.put(rowId, callbackAction); + callbackActions.put(rowId, callbackAction); } /** @@ -1350,14 +1349,14 @@ public class CallLogAdapter extends GroupingListAdapter @Override @MainThread public void setDayGroup(long rowId, int dayGroup) { - mDayGroups.put(rowId, dayGroup); + dayGroups.put(rowId, dayGroup); } /** Clears the day group associations on re-bind of the call log. */ @Override @MainThread public void clearDayGroups() { - mDayGroups.clear(); + dayGroups.clear(); } /** @@ -1388,22 +1387,22 @@ public class CallLogAdapter extends GroupingListAdapter */ private CharSequence getGroupDescription(int group) { if (group == CallLogGroupBuilder.DAY_GROUP_TODAY) { - return mActivity.getResources().getString(R.string.call_log_header_today); + return activity.getResources().getString(R.string.call_log_header_today); } else if (group == CallLogGroupBuilder.DAY_GROUP_YESTERDAY) { - return mActivity.getResources().getString(R.string.call_log_header_yesterday); + return activity.getResources().getString(R.string.call_log_header_yesterday); } else { - return mActivity.getResources().getString(R.string.call_log_header_other); + return activity.getResources().getString(R.string.call_log_header_other); } } @NonNull private EnrichedCallManager getEnrichedCallManager() { - return EnrichedCallComponent.get(mActivity).getEnrichedCallManager(); + return EnrichedCallComponent.get(activity).getEnrichedCallManager(); } @NonNull private Duo getDuo() { - return DuoComponent.get(mActivity).getDuo(); + return DuoComponent.get(activity).getDuo(); } @Override diff --git a/java/com/android/dialer/app/calllog/CallLogAsync.java b/java/com/android/dialer/app/calllog/CallLogAsync.java index f62deca89..26435f311 100644 --- a/java/com/android/dialer/app/calllog/CallLogAsync.java +++ b/java/com/android/dialer/app/calllog/CallLogAsync.java @@ -65,10 +65,10 @@ public class CallLogAsync { /** AsyncTask to get the last outgoing call from the DB. */ private class GetLastOutgoingCallTask extends AsyncTask { - private final OnLastOutgoingCallComplete mCallback; + private final OnLastOutgoingCallComplete callback; public GetLastOutgoingCallTask(OnLastOutgoingCallComplete callback) { - mCallback = callback; + this.callback = callback; } // Happens on a background thread. We cannot run the callback @@ -90,7 +90,7 @@ public class CallLogAsync { @Override protected void onPostExecute(String number) { Assert.isMainThread(); - mCallback.lastOutgoingCall(number); + callback.lastOutgoingCall(number); } } } diff --git a/java/com/android/dialer/app/calllog/CallLogAsyncTaskUtil.java b/java/com/android/dialer/app/calllog/CallLogAsyncTaskUtil.java index c0d30f53a..08f5585b0 100644 --- a/java/com/android/dialer/app/calllog/CallLogAsyncTaskUtil.java +++ b/java/com/android/dialer/app/calllog/CallLogAsyncTaskUtil.java @@ -38,20 +38,20 @@ import com.android.voicemail.VoicemailClient; public class CallLogAsyncTaskUtil { private static final String TAG = "CallLogAsyncTaskUtil"; - private static AsyncTaskExecutor sAsyncTaskExecutor; + private static AsyncTaskExecutor asyncTaskExecutor; private static void initTaskExecutor() { - sAsyncTaskExecutor = AsyncTaskExecutors.createThreadPoolExecutor(); + asyncTaskExecutor = AsyncTaskExecutors.createThreadPoolExecutor(); } public static void markVoicemailAsRead( @NonNull final Context context, @NonNull final Uri voicemailUri) { LogUtil.enterBlock("CallLogAsyncTaskUtil.markVoicemailAsRead, voicemailUri: " + voicemailUri); - if (sAsyncTaskExecutor == null) { + if (asyncTaskExecutor == null) { initTaskExecutor(); } - sAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.MARK_VOICEMAIL_READ, new AsyncTask() { @Override @@ -77,11 +77,11 @@ public class CallLogAsyncTaskUtil { @NonNull final Context context, final Uri voicemailUri, @Nullable final CallLogAsyncTaskListener callLogAsyncTaskListener) { - if (sAsyncTaskExecutor == null) { + if (asyncTaskExecutor == null) { initTaskExecutor(); } - sAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.DELETE_VOICEMAIL, new AsyncTask() { @Override @@ -113,11 +113,11 @@ public class CallLogAsyncTaskUtil { || !PermissionsUtil.hasCallLogWritePermissions(context)) { return; } - if (sAsyncTaskExecutor == null) { + if (asyncTaskExecutor == null) { initTaskExecutor(); } - sAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.MARK_CALL_READ, new AsyncTask() { @Override diff --git a/java/com/android/dialer/app/calllog/CallLogFragment.java b/java/com/android/dialer/app/calllog/CallLogFragment.java index 6910f1918..4f5035fc6 100644 --- a/java/com/android/dialer/app/calllog/CallLogFragment.java +++ b/java/com/android/dialer/app/calllog/CallLogFragment.java @@ -101,47 +101,47 @@ public class CallLogFragment extends Fragment private static final int EVENT_UPDATE_DISPLAY = 1; private static final long MILLIS_IN_MINUTE = 60 * 1000; - private final Handler mHandler = new Handler(); + private final Handler handler = new Handler(); // See issue 6363009 - private final ContentObserver mCallLogObserver = new CustomContentObserver(); - private final ContentObserver mContactsObserver = new CustomContentObserver(); - private View mMultiSelectUnSelectAllViewContent; - private TextView mSelectUnselectAllViewText; - private ImageView mSelectUnselectAllIcon; - private RecyclerView mRecyclerView; - private LinearLayoutManager mLayoutManager; - private CallLogAdapter mAdapter; - private CallLogQueryHandler mCallLogQueryHandler; - private boolean mScrollToTop; - private EmptyContentView mEmptyListView; - private ContactInfoCache mContactInfoCache; - private final OnContactInfoChangedListener mOnContactInfoChangedListener = + private final ContentObserver callLogObserver = new CustomContentObserver(); + private final ContentObserver contactsObserver = new CustomContentObserver(); + private View multiSelectUnSelectAllViewContent; + private TextView selectUnselectAllViewText; + private ImageView selectUnselectAllIcon; + private RecyclerView recyclerView; + private LinearLayoutManager layoutManager; + private CallLogAdapter adapter; + private CallLogQueryHandler callLogQueryHandler; + private boolean scrollToTop; + private EmptyContentView emptyListView; + private ContactInfoCache contactInfoCache; + private final OnContactInfoChangedListener onContactInfoChangedListener = new OnContactInfoChangedListener() { @Override public void onContactInfoChanged() { - if (mAdapter != null) { - mAdapter.notifyDataSetChanged(); + if (adapter != null) { + adapter.notifyDataSetChanged(); } } }; - private boolean mRefreshDataRequired; - private boolean mHasReadCallLogPermission; + private boolean refreshDataRequired; + private boolean hasReadCallLogPermission; // Exactly same variable is in Fragment as a package private. - private boolean mMenuVisible = true; + private boolean menuVisible = true; // Default to all calls. - private int mCallTypeFilter = CallLogQueryHandler.CALL_TYPE_ALL; + private int callTypeFilter = CallLogQueryHandler.CALL_TYPE_ALL; // Log limit - if no limit is specified, then the default in {@link CallLogQueryHandler} // will be used. - private int mLogLimit = NO_LOG_LIMIT; + private int logLimit = NO_LOG_LIMIT; // Date limit (in millis since epoch) - when non-zero, only calls which occurred on or after // the date filter are included. If zero, no date-based filtering occurs. - private long mDateLimit = NO_DATE_LIMIT; + private long dateLimit = NO_DATE_LIMIT; /* * True if this instance of the CallLogFragment shown in the CallLogActivity. */ - private boolean mIsCallLogActivity = false; + private boolean isCallLogActivity = false; private boolean selectAllMode; - private final Handler mDisplayUpdateHandler = + private final Handler displayUpdateHandler = new Handler() { @Override public void handleMessage(Message msg) { @@ -155,8 +155,8 @@ public class CallLogFragment extends Fragment } } }; - protected CallLogModalAlertManager mModalAlertManager; - private ViewGroup mModalAlertView; + protected CallLogModalAlertManager modalAlertManager; + private ViewGroup modalAlertView; public CallLogFragment() { this(CallLogQueryHandler.CALL_TYPE_ALL, NO_LOG_LIMIT); @@ -168,7 +168,7 @@ public class CallLogFragment extends Fragment public CallLogFragment(int filterType, boolean isCallLogActivity) { this(filterType, NO_LOG_LIMIT); - mIsCallLogActivity = isCallLogActivity; + this.isCallLogActivity = isCallLogActivity; } public CallLogFragment(int filterType, int logLimit) { @@ -195,38 +195,38 @@ public class CallLogFragment extends Fragment * @param dateLimit limits results to calls occurring on or after the specified date. */ public CallLogFragment(int filterType, int logLimit, long dateLimit) { - mCallTypeFilter = filterType; - mLogLimit = logLimit; - mDateLimit = dateLimit; + callTypeFilter = filterType; + this.logLimit = logLimit; + this.dateLimit = dateLimit; } @Override public void onCreate(Bundle state) { LogUtil.enterBlock("CallLogFragment.onCreate"); super.onCreate(state); - mRefreshDataRequired = true; + refreshDataRequired = true; if (state != null) { - mCallTypeFilter = state.getInt(KEY_FILTER_TYPE, mCallTypeFilter); - mLogLimit = state.getInt(KEY_LOG_LIMIT, mLogLimit); - mDateLimit = state.getLong(KEY_DATE_LIMIT, mDateLimit); - mIsCallLogActivity = state.getBoolean(KEY_IS_CALL_LOG_ACTIVITY, mIsCallLogActivity); - mHasReadCallLogPermission = state.getBoolean(KEY_HAS_READ_CALL_LOG_PERMISSION, false); - mRefreshDataRequired = state.getBoolean(KEY_REFRESH_DATA_REQUIRED, mRefreshDataRequired); + callTypeFilter = state.getInt(KEY_FILTER_TYPE, callTypeFilter); + logLimit = state.getInt(KEY_LOG_LIMIT, logLimit); + dateLimit = state.getLong(KEY_DATE_LIMIT, dateLimit); + isCallLogActivity = state.getBoolean(KEY_IS_CALL_LOG_ACTIVITY, isCallLogActivity); + hasReadCallLogPermission = state.getBoolean(KEY_HAS_READ_CALL_LOG_PERMISSION, false); + refreshDataRequired = state.getBoolean(KEY_REFRESH_DATA_REQUIRED, refreshDataRequired); selectAllMode = state.getBoolean(KEY_SELECT_ALL_MODE, false); } final Activity activity = getActivity(); final ContentResolver resolver = activity.getContentResolver(); - mCallLogQueryHandler = new CallLogQueryHandler(activity, resolver, this, mLogLimit); + callLogQueryHandler = new CallLogQueryHandler(activity, resolver, this, logLimit); if (PermissionsUtil.hasCallLogReadPermissions(getContext())) { - resolver.registerContentObserver(CallLog.CONTENT_URI, true, mCallLogObserver); + resolver.registerContentObserver(CallLog.CONTENT_URI, true, callLogObserver); } else { LogUtil.w("CallLogFragment.onCreate", "call log permission not available"); } if (PermissionsUtil.hasContactsReadPermissions(getContext())) { resolver.registerContentObserver( - ContactsContract.Contacts.CONTENT_URI, true, mContactsObserver); + ContactsContract.Contacts.CONTENT_URI, true, contactsObserver); } else { LogUtil.w("CallLogFragment.onCreate", "contacts permission not available."); } @@ -240,49 +240,49 @@ public class CallLogFragment extends Fragment // Return false; we did not take ownership of the cursor return false; } - mAdapter.invalidatePositions(); - mAdapter.setLoading(false); - mAdapter.changeCursor(cursor); + adapter.invalidatePositions(); + adapter.setLoading(false); + adapter.changeCursor(cursor); // This will update the state of the "Clear call log" menu item. getActivity().invalidateOptionsMenu(); if (cursor != null && cursor.getCount() > 0) { - mRecyclerView.setPaddingRelative( - mRecyclerView.getPaddingStart(), + recyclerView.setPaddingRelative( + recyclerView.getPaddingStart(), 0, - mRecyclerView.getPaddingEnd(), + recyclerView.getPaddingEnd(), getResources().getDimensionPixelSize(R.dimen.floating_action_button_list_bottom_padding)); - mEmptyListView.setVisibility(View.GONE); + emptyListView.setVisibility(View.GONE); } else { - mRecyclerView.setPaddingRelative( - mRecyclerView.getPaddingStart(), 0, mRecyclerView.getPaddingEnd(), 0); - mEmptyListView.setVisibility(View.VISIBLE); + recyclerView.setPaddingRelative( + recyclerView.getPaddingStart(), 0, recyclerView.getPaddingEnd(), 0); + emptyListView.setVisibility(View.VISIBLE); } - if (mScrollToTop) { + if (scrollToTop) { // The smooth-scroll animation happens over a fixed time period. // As a result, if it scrolls through a large portion of the list, // each frame will jump so far from the previous one that the user // will not experience the illusion of downward motion. Instead, // if we're not already near the top of the list, we instantly jump // near the top, and animate from there. - if (mLayoutManager.findFirstVisibleItemPosition() > 5) { + if (layoutManager.findFirstVisibleItemPosition() > 5) { // TODO: Jump to near the top, then begin smooth scroll. - mRecyclerView.smoothScrollToPosition(0); + recyclerView.smoothScrollToPosition(0); } // Workaround for framework issue: the smooth-scroll doesn't // occur if setSelection() is called immediately before. - mHandler.post( + handler.post( new Runnable() { @Override public void run() { if (getActivity() == null || getActivity().isFinishing()) { return; } - mRecyclerView.smoothScrollToPosition(0); + recyclerView.smoothScrollToPosition(0); } }); - mScrollToTop = false; + scrollToTop = false; } return true; } @@ -304,57 +304,57 @@ public class CallLogFragment extends Fragment } protected void setupView(View view) { - mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); - mRecyclerView.setHasFixedSize(true); - mLayoutManager = new LinearLayoutManager(getActivity()); - mRecyclerView.setLayoutManager(mLayoutManager); - PerformanceReport.logOnScrollStateChange(mRecyclerView); - mEmptyListView = (EmptyContentView) view.findViewById(R.id.empty_list_view); - mEmptyListView.setImage(R.drawable.empty_call_log); - mEmptyListView.setActionClickedListener(this); - mModalAlertView = (ViewGroup) view.findViewById(R.id.modal_message_container); - mModalAlertManager = - new CallLogModalAlertManager(LayoutInflater.from(getContext()), mModalAlertView, this); - mMultiSelectUnSelectAllViewContent = + recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); + recyclerView.setHasFixedSize(true); + layoutManager = new LinearLayoutManager(getActivity()); + recyclerView.setLayoutManager(layoutManager); + PerformanceReport.logOnScrollStateChange(recyclerView); + emptyListView = (EmptyContentView) view.findViewById(R.id.empty_list_view); + emptyListView.setImage(R.drawable.empty_call_log); + emptyListView.setActionClickedListener(this); + modalAlertView = (ViewGroup) view.findViewById(R.id.modal_message_container); + modalAlertManager = + new CallLogModalAlertManager(LayoutInflater.from(getContext()), modalAlertView, this); + multiSelectUnSelectAllViewContent = view.findViewById(R.id.multi_select_select_all_view_content); - mSelectUnselectAllViewText = (TextView) view.findViewById(R.id.select_all_view_text); - mSelectUnselectAllIcon = (ImageView) view.findViewById(R.id.select_all_view_icon); - mMultiSelectUnSelectAllViewContent.setOnClickListener(null); - mSelectUnselectAllIcon.setOnClickListener(this); - mSelectUnselectAllViewText.setOnClickListener(this); + selectUnselectAllViewText = (TextView) view.findViewById(R.id.select_all_view_text); + selectUnselectAllIcon = (ImageView) view.findViewById(R.id.select_all_view_icon); + multiSelectUnSelectAllViewContent.setOnClickListener(null); + selectUnselectAllIcon.setOnClickListener(this); + selectUnselectAllViewText.setOnClickListener(this); } protected void setupData() { int activityType = - mIsCallLogActivity + isCallLogActivity ? CallLogAdapter.ACTIVITY_TYPE_CALL_LOG : CallLogAdapter.ACTIVITY_TYPE_DIALTACTS; String currentCountryIso = GeoUtil.getCurrentCountryIso(getActivity()); - mContactInfoCache = + contactInfoCache = new ContactInfoCache( ExpirableCacheHeadlessFragment.attach((AppCompatActivity) getActivity()) .getRetainedCache(), new ContactInfoHelper(getActivity(), currentCountryIso), - mOnContactInfoChangedListener); - mAdapter = + onContactInfoChangedListener); + adapter = Bindings.getLegacy(getActivity()) .newCallLogAdapter( getActivity(), - mRecyclerView, + recyclerView, this, this, activityType == CallLogAdapter.ACTIVITY_TYPE_DIALTACTS ? (CallLogAdapter.OnActionModeStateChangedListener) getActivity() : null, new CallLogCache(getActivity()), - mContactInfoCache, + contactInfoCache, getVoicemailPlaybackPresenter(), new FilteredNumberAsyncQueryHandler(getActivity()), activityType); - mRecyclerView.setAdapter(mAdapter); - if (mAdapter.getOnScrollListener() != null) { - mRecyclerView.addOnScrollListener(mAdapter.getOnScrollListener()); + recyclerView.setAdapter(adapter); + if (adapter.getOnScrollListener() != null) { + recyclerView.addOnScrollListener(adapter.getOnScrollListener()); } fetchCalls(); } @@ -370,7 +370,7 @@ public class CallLogFragment extends Fragment super.onActivityCreated(savedInstanceState); setupData(); updateSelectAllState(savedInstanceState); - mAdapter.onRestoreInstanceState(savedInstanceState); + adapter.onRestoreInstanceState(savedInstanceState); } private void updateSelectAllState(Bundle savedInstanceState) { @@ -384,7 +384,7 @@ public class CallLogFragment extends Fragment @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); - updateEmptyMessage(mCallTypeFilter); + updateEmptyMessage(callTypeFilter); } @Override @@ -393,23 +393,23 @@ public class CallLogFragment extends Fragment super.onResume(); final boolean hasReadCallLogPermission = PermissionsUtil.hasPermission(getActivity(), READ_CALL_LOG); - if (!mHasReadCallLogPermission && hasReadCallLogPermission) { + if (!this.hasReadCallLogPermission && hasReadCallLogPermission) { // We didn't have the permission before, and now we do. Force a refresh of the call log. // Note that this code path always happens on a fresh start, but mRefreshDataRequired // is already true in that case anyway. - mRefreshDataRequired = true; - updateEmptyMessage(mCallTypeFilter); + refreshDataRequired = true; + updateEmptyMessage(callTypeFilter); } - mHasReadCallLogPermission = hasReadCallLogPermission; + this.hasReadCallLogPermission = hasReadCallLogPermission; /* * Always clear the filtered numbers cache since users could have blocked/unblocked numbers * from the settings page */ - mAdapter.clearFilteredNumbersCache(); + adapter.clearFilteredNumbersCache(); refreshData(); - mAdapter.onResume(); + adapter.onResume(); rescheduleDisplayUpdate(); // onResume() may also be called as a "side" page on the ViewPager, which is not visible. @@ -425,7 +425,7 @@ public class CallLogFragment extends Fragment onNotVisible(); } cancelDisplayUpdate(); - mAdapter.onPause(); + adapter.onPause(); super.onPause(); } @@ -437,48 +437,48 @@ public class CallLogFragment extends Fragment if (CequintCallerIdManager.isCequintCallerIdEnabled(getContext())) { cequintCallerIdManager = CequintCallerIdManager.createInstanceForCallLog(); } - mContactInfoCache.setCequintCallerIdManager(cequintCallerIdManager); + contactInfoCache.setCequintCallerIdManager(cequintCallerIdManager); } @Override public void onStop() { LogUtil.enterBlock("CallLogFragment.onStop"); super.onStop(); - mAdapter.onStop(); - mContactInfoCache.stop(); + adapter.onStop(); + contactInfoCache.stop(); } @Override public void onDestroy() { LogUtil.enterBlock("CallLogFragment.onDestroy"); - if (mAdapter != null) { - mAdapter.changeCursor(null); + if (adapter != null) { + adapter.changeCursor(null); } - getActivity().getContentResolver().unregisterContentObserver(mCallLogObserver); - getActivity().getContentResolver().unregisterContentObserver(mContactsObserver); + getActivity().getContentResolver().unregisterContentObserver(callLogObserver); + getActivity().getContentResolver().unregisterContentObserver(contactsObserver); super.onDestroy(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - outState.putInt(KEY_FILTER_TYPE, mCallTypeFilter); - outState.putInt(KEY_LOG_LIMIT, mLogLimit); - outState.putLong(KEY_DATE_LIMIT, mDateLimit); - outState.putBoolean(KEY_IS_CALL_LOG_ACTIVITY, mIsCallLogActivity); - outState.putBoolean(KEY_HAS_READ_CALL_LOG_PERMISSION, mHasReadCallLogPermission); - outState.putBoolean(KEY_REFRESH_DATA_REQUIRED, mRefreshDataRequired); + outState.putInt(KEY_FILTER_TYPE, callTypeFilter); + outState.putInt(KEY_LOG_LIMIT, logLimit); + outState.putLong(KEY_DATE_LIMIT, dateLimit); + outState.putBoolean(KEY_IS_CALL_LOG_ACTIVITY, isCallLogActivity); + outState.putBoolean(KEY_HAS_READ_CALL_LOG_PERMISSION, hasReadCallLogPermission); + outState.putBoolean(KEY_REFRESH_DATA_REQUIRED, refreshDataRequired); outState.putBoolean(KEY_SELECT_ALL_MODE, selectAllMode); - if (mAdapter != null) { - mAdapter.onSaveInstanceState(outState); + if (adapter != null) { + adapter.onSaveInstanceState(outState); } } @Override public void fetchCalls() { - mCallLogQueryHandler.fetchCalls(mCallTypeFilter, mDateLimit); - if (!mIsCallLogActivity) { + callLogQueryHandler.fetchCalls(callTypeFilter, dateLimit); + if (!isCallLogActivity) { ((ListsFragment) getParentFragment()).updateTabUnreadCounts(); } } @@ -490,8 +490,8 @@ public class CallLogFragment extends Fragment } if (!PermissionsUtil.hasPermission(context, READ_CALL_LOG)) { - mEmptyListView.setDescription(R.string.permission_no_calllog); - mEmptyListView.setActionLabel(R.string.permission_single_turn_on); + emptyListView.setDescription(R.string.permission_no_calllog); + emptyListView.setActionLabel(R.string.permission_single_turn_on); return; } @@ -510,25 +510,25 @@ public class CallLogFragment extends Fragment throw new IllegalArgumentException( "Unexpected filter type in CallLogFragment: " + filterType); } - mEmptyListView.setDescription(messageId); - if (mIsCallLogActivity) { - mEmptyListView.setActionLabel(EmptyContentView.NO_LABEL); + emptyListView.setDescription(messageId); + if (isCallLogActivity) { + emptyListView.setActionLabel(EmptyContentView.NO_LABEL); } else if (filterType == CallLogQueryHandler.CALL_TYPE_ALL) { - mEmptyListView.setActionLabel(R.string.call_log_all_empty_action); + emptyListView.setActionLabel(R.string.call_log_all_empty_action); } else { - mEmptyListView.setActionLabel(EmptyContentView.NO_LABEL); + emptyListView.setActionLabel(EmptyContentView.NO_LABEL); } } public CallLogAdapter getAdapter() { - return mAdapter; + return adapter; } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); - if (mMenuVisible != menuVisible) { - mMenuVisible = menuVisible; + if (this.menuVisible != menuVisible) { + this.menuVisible = menuVisible; if (menuVisible && isResumed()) { refreshData(); } @@ -538,19 +538,19 @@ public class CallLogFragment extends Fragment /** Requests updates to the data to be shown. */ private void refreshData() { // Prevent unnecessary refresh. - if (mRefreshDataRequired) { + if (refreshDataRequired) { // Mark all entries in the contact info cache as out of date, so they will be looked up // again once being shown. - mContactInfoCache.invalidate(); - mAdapter.setLoading(true); + contactInfoCache.invalidate(); + adapter.setLoading(true); fetchCalls(); - mCallLogQueryHandler.fetchVoicemailStatus(); - mCallLogQueryHandler.fetchMissedCallsUnreadCount(); - mRefreshDataRequired = false; + callLogQueryHandler.fetchVoicemailStatus(); + callLogQueryHandler.fetchMissedCallsUnreadCount(); + refreshDataRequired = false; } else { // Refresh the display of the existing data to update the timestamp text descriptions. - mAdapter.notifyDataSetChanged(); + adapter.notifyDataSetChanged(); } } @@ -569,7 +569,7 @@ public class CallLogFragment extends Fragment "CallLogFragment.onEmptyViewActionButtonClicked", "Requesting permissions: " + Arrays.toString(deniedPermissions)); FragmentCompat.requestPermissions(this, deniedPermissions, PHONE_PERMISSIONS_REQUEST_CODE); - } else if (!mIsCallLogActivity) { + } else if (!isCallLogActivity) { LogUtil.i("CallLogFragment.onEmptyViewActionButtonClicked", "showing dialpad"); // Show dialpad if we are not in the call log activity. ((HostInterface) activity).showDialpad(); @@ -582,32 +582,32 @@ public class CallLogFragment extends Fragment if (requestCode == PHONE_PERMISSIONS_REQUEST_CODE) { if (grantResults.length >= 1 && PackageManager.PERMISSION_GRANTED == grantResults[0]) { // Force a refresh of the data since we were missing the permission before this. - mRefreshDataRequired = true; + refreshDataRequired = true; } } } /** Schedules an update to the relative call times (X mins ago). */ private void rescheduleDisplayUpdate() { - if (!mDisplayUpdateHandler.hasMessages(EVENT_UPDATE_DISPLAY)) { + if (!displayUpdateHandler.hasMessages(EVENT_UPDATE_DISPLAY)) { long time = System.currentTimeMillis(); // This value allows us to change the display relatively close to when the time changes // from one minute to the next. long millisUtilNextMinute = MILLIS_IN_MINUTE - (time % MILLIS_IN_MINUTE); - mDisplayUpdateHandler.sendEmptyMessageDelayed(EVENT_UPDATE_DISPLAY, millisUtilNextMinute); + displayUpdateHandler.sendEmptyMessageDelayed(EVENT_UPDATE_DISPLAY, millisUtilNextMinute); } } /** Cancels any pending update requests to update the relative call times (X mins ago). */ private void cancelDisplayUpdate() { - mDisplayUpdateHandler.removeMessages(EVENT_UPDATE_DISPLAY); + displayUpdateHandler.removeMessages(EVENT_UPDATE_DISPLAY); } /** Mark all missed calls as read if Keyguard not locked and possible. */ void markMissedCallsAsReadAndRemoveNotifications() { - if (mCallLogQueryHandler != null + if (callLogQueryHandler != null && !getContext().getSystemService(KeyguardManager.class).isKeyguardLocked()) { - mCallLogQueryHandler.markMissedCallsAsRead(); + callLogQueryHandler.markMissedCallsAsRead(); CallLogNotificationsService.cancelAllMissedCalls(getContext()); } } @@ -621,7 +621,7 @@ public class CallLogFragment extends Fragment } public boolean isModalAlertVisible() { - return mModalAlertManager != null && !mModalAlertManager.isEmpty(); + return modalAlertManager != null && !modalAlertManager.isEmpty(); } @CallSuper @@ -640,14 +640,14 @@ public class CallLogFragment extends Fragment getAdapter().notifyDataSetChanged(); HostInterface hostInterface = (HostInterface) getActivity(); if (show) { - mRecyclerView.setVisibility(View.GONE); - mModalAlertView.setVisibility(View.VISIBLE); + recyclerView.setVisibility(View.GONE); + modalAlertView.setVisibility(View.VISIBLE); if (hostInterface != null && getUserVisibleHint()) { hostInterface.enableFloatingButton(false); } } else { - mRecyclerView.setVisibility(View.VISIBLE); - mModalAlertView.setVisibility(View.GONE); + recyclerView.setVisibility(View.VISIBLE); + modalAlertView.setVisibility(View.GONE); if (hostInterface != null && getUserVisibleHint()) { hostInterface.enableFloatingButton(true); } @@ -656,16 +656,16 @@ public class CallLogFragment extends Fragment @Override public void showMultiSelectRemoveView(boolean show) { - mMultiSelectUnSelectAllViewContent.setVisibility(show ? View.VISIBLE : View.GONE); - mMultiSelectUnSelectAllViewContent.setAlpha(show ? 0 : 1); - mMultiSelectUnSelectAllViewContent.animate().alpha(show ? 1 : 0).start(); + multiSelectUnSelectAllViewContent.setVisibility(show ? View.VISIBLE : View.GONE); + multiSelectUnSelectAllViewContent.setAlpha(show ? 0 : 1); + multiSelectUnSelectAllViewContent.animate().alpha(show ? 1 : 0).start(); ((ListsFragment) getParentFragment()).showMultiSelectRemoveView(show); } @Override public void setSelectAllModeToFalse() { selectAllMode = false; - mSelectUnselectAllIcon.setImageDrawable( + selectUnselectAllIcon.setImageDrawable( getContext().getDrawable(R.drawable.ic_empty_check_mark_white_24dp)); } @@ -689,11 +689,11 @@ public class CallLogFragment extends Fragment private void updateSelectAllIcon() { if (selectAllMode) { - mSelectUnselectAllIcon.setImageDrawable( + selectUnselectAllIcon.setImageDrawable( getContext().getDrawable(R.drawable.ic_check_mark_blue_24dp)); getAdapter().onAllSelected(); } else { - mSelectUnselectAllIcon.setImageDrawable( + selectUnselectAllIcon.setImageDrawable( getContext().getDrawable(R.drawable.ic_empty_check_mark_white_24dp)); getAdapter().onAllDeselected(); } @@ -709,12 +709,12 @@ public class CallLogFragment extends Fragment protected class CustomContentObserver extends ContentObserver { public CustomContentObserver() { - super(mHandler); + super(handler); } @Override public void onChange(boolean selfChange) { - mRefreshDataRequired = true; + refreshDataRequired = true; } } } diff --git a/java/com/android/dialer/app/calllog/CallLogGroupBuilder.java b/java/com/android/dialer/app/calllog/CallLogGroupBuilder.java index a48de0f51..4c0c63408 100644 --- a/java/com/android/dialer/app/calllog/CallLogGroupBuilder.java +++ b/java/com/android/dialer/app/calllog/CallLogGroupBuilder.java @@ -57,15 +57,15 @@ public class CallLogGroupBuilder { /** Instance of the time object used for time calculations. */ private static final Time TIME = new Time(); /** The object on which the groups are created. */ - private final GroupCreator mGroupCreator; + private final GroupCreator groupCreator; public CallLogGroupBuilder(GroupCreator groupCreator) { - mGroupCreator = groupCreator; + this.groupCreator = groupCreator; } /** * Finds all groups of adjacent entries in the call log which should be grouped together and calls - * {@link GroupCreator#addGroup(int, int)} on {@link #mGroupCreator} for each of them. + * {@link GroupCreator#addGroup(int, int)} on {@link #groupCreator} for each of them. * *

For entries that are not grouped with others, we do not need to create a group of size one. * @@ -80,7 +80,7 @@ public class CallLogGroupBuilder { } // Clear any previous day grouping information. - mGroupCreator.clearDayGroups(); + groupCreator.clearDayGroups(); // Get current system time, used for calculating which day group calls belong to. long currentTime = System.currentTimeMillis(); @@ -90,7 +90,7 @@ public class CallLogGroupBuilder { final long firstDate = cursor.getLong(CallLogQuery.DATE); final long firstRowId = cursor.getLong(CallLogQuery.ID); int groupDayGroup = getDayGroup(firstDate, currentTime); - mGroupCreator.setDayGroup(firstRowId, groupDayGroup); + groupCreator.setDayGroup(firstRowId, groupDayGroup); // Determine the callback action for the first call in the cursor. String groupNumber = cursor.getString(CallLogQuery.NUMBER); @@ -99,7 +99,7 @@ public class CallLogGroupBuilder { int groupCallbackAction = CallbackActionHelper.getCallbackAction( groupNumber, groupFeatures, groupAccountComponentName); - mGroupCreator.setCallbackAction(firstRowId, groupCallbackAction); + groupCreator.setCallbackAction(firstRowId, groupCallbackAction); // Instantiate other group values to those of the first call in the cursor. String groupAccountId = cursor.getString(CallLogQuery.ACCOUNT_ID); @@ -164,7 +164,7 @@ public class CallLogGroupBuilder { // Create a group for the previous group of calls, which does not include the // current call. - mGroupCreator.addGroup(cursor.getPosition() - groupSize, groupSize); + groupCreator.addGroup(cursor.getPosition() - groupSize, groupSize); // Start a new group; it will include at least the current call. groupSize = 1; @@ -181,12 +181,12 @@ public class CallLogGroupBuilder { // Save the callback action and the day group associated with the current call. final long currentCallId = cursor.getLong(CallLogQuery.ID); - mGroupCreator.setCallbackAction(currentCallId, groupCallbackAction); - mGroupCreator.setDayGroup(currentCallId, groupDayGroup); + groupCreator.setCallbackAction(currentCallId, groupCallbackAction); + groupCreator.setDayGroup(currentCallId, groupDayGroup); } // Create a group for the last set of calls. - mGroupCreator.addGroup(count - groupSize, groupSize); + groupCreator.addGroup(count - groupSize, groupSize); } /** diff --git a/java/com/android/dialer/app/calllog/CallLogListItemHelper.java b/java/com/android/dialer/app/calllog/CallLogListItemHelper.java index ac43b9ea7..13ee9a41f 100644 --- a/java/com/android/dialer/app/calllog/CallLogListItemHelper.java +++ b/java/com/android/dialer/app/calllog/CallLogListItemHelper.java @@ -32,11 +32,11 @@ import com.android.dialer.compat.AppCompatConstants; /* package */ class CallLogListItemHelper { /** Helper for populating the details of a phone call. */ - private final PhoneCallDetailsHelper mPhoneCallDetailsHelper; + private final PhoneCallDetailsHelper phoneCallDetailsHelper; /** Resources to look up strings. */ - private final Resources mResources; + private final Resources resources; - private final CallLogCache mCallLogCache; + private final CallLogCache callLogCache; /** * Creates a new helper instance. @@ -49,9 +49,9 @@ import com.android.dialer.compat.AppCompatConstants; PhoneCallDetailsHelper phoneCallDetailsHelper, Resources resources, CallLogCache callLogCache) { - mPhoneCallDetailsHelper = phoneCallDetailsHelper; - mResources = resources; - mCallLogCache = callLogCache; + this.phoneCallDetailsHelper = phoneCallDetailsHelper; + this.resources = resources; + this.callLogCache = callLogCache; } /** @@ -63,7 +63,7 @@ import com.android.dialer.compat.AppCompatConstants; @WorkerThread public void updatePhoneCallDetails(PhoneCallDetails details) { Assert.isWorkerThread(); - details.callLocationAndDate = mPhoneCallDetailsHelper.getCallLocationAndDate(details); + details.callLocationAndDate = phoneCallDetailsHelper.getCallLocationAndDate(details); details.callDescription = getCallDescription(details); } @@ -74,7 +74,7 @@ import com.android.dialer.compat.AppCompatConstants; * @param details the details of a phone call needed to fill in the data */ public void setPhoneCallDetails(CallLogListItemViewHolder views, PhoneCallDetails details) { - mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); + phoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); // Set the accessibility text for the contact badge views.quickContactView.setContentDescription(getContactBadgeDescription(details)); @@ -88,7 +88,7 @@ import com.android.dialer.compat.AppCompatConstants; // The call type or Location associated with the call. Use when setting text for a // voicemail log's call button - views.callTypeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); + views.callTypeOrLocation = phoneCallDetailsHelper.getCallTypeOrLocation(details); // Cache country iso. Used for number filtering. views.countryIso = details.countryIso; @@ -114,20 +114,20 @@ import com.android.dialer.compat.AppCompatConstants; views.videoCallButtonView.setContentDescription( TextUtils.expandTemplate( - mResources.getString(R.string.description_video_call_action), nameOrNumber)); + resources.getString(R.string.description_video_call_action), nameOrNumber)); views.createNewContactButtonView.setContentDescription( TextUtils.expandTemplate( - mResources.getString(R.string.description_create_new_contact_action), nameOrNumber)); + resources.getString(R.string.description_create_new_contact_action), nameOrNumber)); views.addToExistingContactButtonView.setContentDescription( TextUtils.expandTemplate( - mResources.getString(R.string.description_add_to_existing_contact_action), + resources.getString(R.string.description_add_to_existing_contact_action), nameOrNumber)); views.detailsButtonView.setContentDescription( TextUtils.expandTemplate( - mResources.getString(R.string.description_details_action), nameOrNumber)); + resources.getString(R.string.description_details_action), nameOrNumber)); } /** @@ -138,10 +138,10 @@ import com.android.dialer.compat.AppCompatConstants; */ private CharSequence getContactBadgeDescription(PhoneCallDetails details) { if (details.isSpam) { - return mResources.getString( + return resources.getString( R.string.description_spam_contact_details, getNameOrNumber(details)); } - return mResources.getString(R.string.description_contact_details, getNameOrNumber(details)); + return resources.getString(R.string.description_contact_details, getNameOrNumber(details)); } /** @@ -178,32 +178,32 @@ import com.android.dialer.compat.AppCompatConstants; final CharSequence nameOrNumber = getNameOrNumber(details); // Get the call type or location of the caller; null if not applicable - final CharSequence typeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); + final CharSequence typeOrLocation = phoneCallDetailsHelper.getCallTypeOrLocation(details); // Get the time/date of the call - final CharSequence timeOfCall = mPhoneCallDetailsHelper.getCallDate(details); + final CharSequence timeOfCall = phoneCallDetailsHelper.getCallDate(details); SpannableStringBuilder callDescription = new SpannableStringBuilder(); // Add number of calls if more than one. if (details.callTypes.length > 1) { callDescription.append( - mResources.getString(R.string.description_num_calls, details.callTypes.length)); + resources.getString(R.string.description_num_calls, details.callTypes.length)); } // If call had video capabilities, add the "Video Call" string. if ((details.features & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO) { - callDescription.append(mResources.getString(R.string.description_video_call)); + callDescription.append(resources.getString(R.string.description_video_call)); } - String accountLabel = mCallLogCache.getAccountLabel(details.accountHandle); + String accountLabel = callLogCache.getAccountLabel(details.accountHandle); CharSequence onAccountLabel = - PhoneCallDetails.createAccountLabelDescription(mResources, details.viaNumber, accountLabel); + PhoneCallDetails.createAccountLabelDescription(resources, details.viaNumber, accountLabel); int stringID = getCallDescriptionStringID(details.callTypes, details.isRead); callDescription.append( TextUtils.expandTemplate( - mResources.getString(stringID), + resources.getString(stringID), nameOrNumber, typeOrLocation == null ? "" : typeOrLocation, timeOfCall, diff --git a/java/com/android/dialer/app/calllog/CallLogListItemViewHolder.java b/java/com/android/dialer/app/calllog/CallLogListItemViewHolder.java index 15c4b5850..f8d3a4cd8 100644 --- a/java/com/android/dialer/app/calllog/CallLogListItemViewHolder.java +++ b/java/com/android/dialer/app/calllog/CallLogListItemViewHolder.java @@ -132,13 +132,13 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder /** The actionable view which places a call to the number corresponding to the call log row. */ public final ImageView primaryActionButtonView; - private final Context mContext; - @Nullable private final PhoneAccountHandle mDefaultPhoneAccountHandle; - private final CallLogCache mCallLogCache; - private final CallLogListItemHelper mCallLogListItemHelper; - private final CachedNumberLookupService mCachedNumberLookupService; - private final VoicemailPlaybackPresenter mVoicemailPlaybackPresenter; - private final OnClickListener mBlockReportListener; + private final Context context; + @Nullable private final PhoneAccountHandle defaultPhoneAccountHandle; + private final CallLogCache callLogCache; + private final CallLogListItemHelper callLogListItemHelper; + private final CachedNumberLookupService cachedNumberLookupService; + private final VoicemailPlaybackPresenter voicemailPlaybackPresenter; + private final OnClickListener blockReportListener; @HostUi private final int hostUi; /** Whether the data fields are populated by the worker thread, ready to be shown. */ public boolean isLoaded; @@ -233,10 +233,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder public boolean isCallComposerCapable; - private View.OnClickListener mExpandCollapseListener; + private View.OnClickListener expandCollapseListener; private final OnActionModeStateChangedListener onActionModeStateChangedListener; private final View.OnLongClickListener longPressListener; - private boolean mVoicemailPrimaryActionButtonClicked; + private boolean voicemailPrimaryActionButtonClicked; public int callbackAction; public int dayGroupHeaderVisibility; @@ -264,18 +264,18 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder ImageView primaryActionButtonView) { super(rootView); - mContext = context; - mExpandCollapseListener = expandCollapseListener; + this.context = context; + this.expandCollapseListener = expandCollapseListener; onActionModeStateChangedListener = actionModeStateChangedListener; longPressListener = longClickListener; - mCallLogCache = callLogCache; - mCallLogListItemHelper = callLogListItemHelper; - mVoicemailPlaybackPresenter = voicemailPlaybackPresenter; - mBlockReportListener = blockReportListener; - mCachedNumberLookupService = PhoneNumberCache.get(mContext).getCachedNumberLookupService(); + this.callLogCache = callLogCache; + this.callLogListItemHelper = callLogListItemHelper; + this.voicemailPlaybackPresenter = voicemailPlaybackPresenter; + this.blockReportListener = blockReportListener; + cachedNumberLookupService = PhoneNumberCache.get(this.context).getCachedNumberLookupService(); // Cache this to avoid having to look it up each time we bind to a call log entry - mDefaultPhoneAccountHandle = + defaultPhoneAccountHandle = TelecomUtil.getDefaultOutgoingPhoneAccount(context, PhoneAccount.SCHEME_TEL); this.rootView = rootView; @@ -292,19 +292,19 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder phoneCallDetailsViews.nameView.setElegantTextHeight(false); phoneCallDetailsViews.callLocationAndDate.setElegantTextHeight(false); - if (mContext instanceof CallLogActivity) { + if (this.context instanceof CallLogActivity) { hostUi = HostUi.CALL_HISTORY; - Logger.get(mContext) + Logger.get(this.context) .logQuickContactOnTouch( quickContactView, InteractionEvent.Type.OPEN_QUICK_CONTACT_FROM_CALL_HISTORY, true); - } else if (mVoicemailPlaybackPresenter == null) { + } else if (this.voicemailPlaybackPresenter == null) { hostUi = HostUi.CALL_LOG; - Logger.get(mContext) + Logger.get(this.context) .logQuickContactOnTouch( quickContactView, InteractionEvent.Type.OPEN_QUICK_CONTACT_FROM_CALL_LOG, true); } else { hostUi = HostUi.VOICEMAIL; - Logger.get(mContext) + Logger.get(this.context) .logQuickContactOnTouch( quickContactView, InteractionEvent.Type.OPEN_QUICK_CONTACT_FROM_VOICEMAIL, false); } @@ -314,16 +314,16 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder quickContactView.setPrioritizedMimeType(Phone.CONTENT_ITEM_TYPE); } primaryActionButtonView.setOnClickListener(this); - primaryActionView.setOnClickListener(mExpandCollapseListener); - if (mVoicemailPlaybackPresenter != null - && ConfigProviderBindings.get(mContext) + primaryActionView.setOnClickListener(this.expandCollapseListener); + if (this.voicemailPlaybackPresenter != null + && ConfigProviderBindings.get(this.context) .getBoolean( CallLogAdapter.ENABLE_CALL_LOG_MULTI_SELECT, CallLogAdapter.ENABLE_CALL_LOG_MULTI_SELECT_FLAG)) { primaryActionView.setOnLongClickListener(longPressListener); quickContactView.setOnLongClickListener(longPressListener); quickContactView.setMulitSelectListeners( - mExpandCollapseListener, onActionModeStateChangedListener); + this.expandCollapseListener, onActionModeStateChangedListener); } else { primaryActionView.setOnCreateContextMenuListener(this); } @@ -400,51 +400,50 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder public boolean onMenuItemClick(MenuItem item) { int resId = item.getItemId(); if (resId == R.id.context_menu_copy_to_clipboard) { - ClipboardUtils.copyText(mContext, null, number, true); + ClipboardUtils.copyText(context, null, number, true); return true; } else if (resId == R.id.context_menu_copy_transcript_to_clipboard) { ClipboardUtils.copyText( - mContext, null, phoneCallDetailsViews.voicemailTranscriptionView.getText(), true); + context, null, phoneCallDetailsViews.voicemailTranscriptionView.getText(), true); return true; } else if (resId == R.id.context_menu_edit_before_call) { final Intent intent = new Intent(Intent.ACTION_DIAL, CallUtil.getCallUri(number)); - intent.setClass(mContext, DialtactsActivity.class); - DialerUtils.startActivityWithErrorToast(mContext, intent); + intent.setClass(context, DialtactsActivity.class); + DialerUtils.startActivityWithErrorToast(context, intent); return true; } else if (resId == R.id.context_menu_block_report_spam) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_BLOCK_REPORT_SPAM); maybeShowBlockNumberMigrationDialog( new BlockedNumbersMigrator.Listener() { @Override public void onComplete() { - mBlockReportListener.onBlockReportSpam( + blockReportListener.onBlockReportSpam( displayNumber, number, countryIso, callType, info.sourceType); } }); } else if (resId == R.id.context_menu_block) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_BLOCK_NUMBER); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_BLOCK_NUMBER); maybeShowBlockNumberMigrationDialog( new BlockedNumbersMigrator.Listener() { @Override public void onComplete() { - mBlockReportListener.onBlock( + blockReportListener.onBlock( displayNumber, number, countryIso, callType, info.sourceType); } }); } else if (resId == R.id.context_menu_unblock) { - Logger.get(mContext) - .logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_UNBLOCK_NUMBER); - mBlockReportListener.onUnblock( + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_UNBLOCK_NUMBER); + blockReportListener.onUnblock( displayNumber, number, countryIso, callType, info.sourceType, isSpam, blockId); } else if (resId == R.id.context_menu_report_not_spam) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.CALL_LOG_CONTEXT_MENU_REPORT_AS_NOT_SPAM); - mBlockReportListener.onReportNotSpam( + blockReportListener.onReportNotSpam( displayNumber, number, countryIso, callType, info.sourceType); } else if (resId == R.id.context_menu_delete) { AsyncTaskExecutors.createAsyncTaskExecutor() - .submit(TASK_DELETE, new DeleteCallTask(mContext, callIds)); + .submit(TASK_DELETE, new DeleteCallTask(context, callIds)); } return false; } @@ -526,7 +525,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder primaryActionButtonView.setImageResource(R.drawable.quantum_ic_play_arrow_white_24); primaryActionButtonView.setContentDescription( TextUtils.expandTemplate( - mContext.getString(R.string.description_voicemail_action), validNameOrNumber)); + context.getString(R.string.description_voicemail_action), validNameOrNumber)); primaryActionButtonView.setVisibility(View.VISIBLE); } else { primaryActionButtonView.setVisibility(View.GONE); @@ -547,7 +546,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder IntentProvider.getReturnVideoCallIntentProvider(number, accountHandle)); primaryActionButtonView.setContentDescription( TextUtils.expandTemplate( - mContext.getString(R.string.description_video_call_action), validNameOrNumber)); + context.getString(R.string.description_video_call_action), validNameOrNumber)); primaryActionButtonView.setImageResource(R.drawable.quantum_ic_videocam_vd_theme_24); primaryActionButtonView.setVisibility(View.VISIBLE); break; @@ -560,20 +559,20 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } primaryActionButtonView.setContentDescription( TextUtils.expandTemplate( - mContext.getString(R.string.description_video_call_action), validNameOrNumber)); + context.getString(R.string.description_video_call_action), validNameOrNumber)); primaryActionButtonView.setImageResource(R.drawable.quantum_ic_videocam_vd_theme_24); primaryActionButtonView.setVisibility(View.VISIBLE); break; case CallbackAction.VOICE: - if (mCallLogCache.isVoicemailNumber(accountHandle, number)) { + if (callLogCache.isVoicemailNumber(accountHandle, number)) { // Call to generic voicemail number, in case there are multiple accounts primaryActionButtonView.setTag(IntentProvider.getReturnVoicemailCallIntentProvider(null)); } else if (canSupportAssistedDialing()) { primaryActionButtonView.setTag( IntentProvider.getAssistedDialIntentProvider( number + postDialDigits, - mContext, - mContext.getSystemService(TelephonyManager.class))); + context, + context.getSystemService(TelephonyManager.class))); } else { primaryActionButtonView.setTag( IntentProvider.getReturnCallIntentProvider(number + postDialDigits)); @@ -581,7 +580,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder primaryActionButtonView.setContentDescription( TextUtils.expandTemplate( - mContext.getString(R.string.description_call_action), validNameOrNumber)); + context.getString(R.string.description_call_action), validNameOrNumber)); primaryActionButtonView.setImageResource(R.drawable.quantum_ic_call_vd_theme_24); primaryActionButtonView.setVisibility(View.VISIBLE); break; @@ -622,14 +621,14 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder voicemailPlaybackView.setVisibility(View.VISIBLE); Uri uri = Uri.parse(voicemailUri); - mVoicemailPlaybackPresenter.setPlaybackView( + voicemailPlaybackPresenter.setPlaybackView( voicemailPlaybackView, rowId, uri, - mVoicemailPrimaryActionButtonClicked, + voicemailPrimaryActionButtonClicked, sendVoicemailButtonView); - mVoicemailPrimaryActionButtonClicked = false; - CallLogAsyncTaskUtil.markVoicemailAsRead(mContext, uri); + voicemailPrimaryActionButtonClicked = false; + CallLogAsyncTaskUtil.markVoicemailAsRead(context, uri); return; } @@ -640,7 +639,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder if (canSupportAssistedDialing()) { callButtonView.setTag( IntentProvider.getAssistedDialIntentProvider( - number, mContext, mContext.getSystemService(TelephonyManager.class))); + number, context, context.getSystemService(TelephonyManager.class))); } else { callButtonView.setTag(IntentProvider.getReturnCallIntentProvider(number)); } @@ -651,7 +650,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder ((TextView) callButtonView.findViewById(R.id.call_action_text)) .setText( TextUtils.expandTemplate( - mContext.getString(R.string.call_log_action_call), + context.getString(R.string.call_log_action_call), nameOrNumber == null ? "" : nameOrNumber)); if (callType == Calls.VOICEMAIL_TYPE && !TextUtils.isEmpty(callTypeOrLocation)) { @@ -661,7 +660,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder callButtonView.setVisibility(View.VISIBLE); } - boolean isVoicemailNumber = mCallLogCache.isVoicemailNumber(accountHandle, number); + boolean isVoicemailNumber = callLogCache.isVoicemailNumber(accountHandle, number); switch (callbackAction) { case CallbackAction.IMS_VIDEO: @@ -672,10 +671,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder videoCallButtonView.setVisibility(View.GONE); break; case CallbackAction.VOICE: - Duo duo = DuoComponent.get(mContext).getDuo(); + Duo duo = DuoComponent.get(context).getDuo(); // For a voice call, set the secondary callback action to be an IMS video call if it is // available. Otherwise try to set it as a Duo call. - if (CallUtil.isVideoEnabled(mContext) + if (CallUtil.isVideoEnabled(context) && (hasPlacedCarrierVideoCall() || canSupportCarrierVideoCall())) { videoCallButtonView.setTag(IntentProvider.getReturnVideoCallIntentProvider(number)); videoCallButtonView.setVisibility(View.VISIBLE); @@ -687,24 +686,24 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } boolean identifiedSpamCall = isSpamFeatureEnabled && isSpam; - if (duo.isReachable(mContext, number)) { + if (duo.isReachable(context, number)) { videoCallButtonView.setTag(IntentProvider.getDuoVideoIntentProvider(number)); videoCallButtonView.setVisibility(View.VISIBLE); - } else if (duo.isActivated(mContext) && !identifiedSpamCall) { - if (ConfigProviderBindings.get(mContext) + } else if (duo.isActivated(context) && !identifiedSpamCall) { + if (ConfigProviderBindings.get(context) .getBoolean("enable_call_log_duo_invite_button", false)) { inviteVideoButtonView.setTag(IntentProvider.getDuoInviteIntentProvider(number)); inviteVideoButtonView.setVisibility(View.VISIBLE); } - } else if (duo.isEnabled(mContext) && !identifiedSpamCall) { - if (!duo.isInstalled(mContext)) { - if (ConfigProviderBindings.get(mContext) + } else if (duo.isEnabled(context) && !identifiedSpamCall) { + if (!duo.isInstalled(context)) { + if (ConfigProviderBindings.get(context) .getBoolean("enable_call_log_install_duo_button", false)) { setUpVideoButtonView.setTag(IntentProvider.getInstallDuoIntentProvider()); setUpVideoButtonView.setVisibility(View.VISIBLE); } } else { - if (ConfigProviderBindings.get(mContext) + if (ConfigProviderBindings.get(context) .getBoolean("enable_call_log_activate_duo_button", false)) { setUpVideoButtonView.setTag(IntentProvider.getSetUpDuoIntentProvider()); setUpVideoButtonView.setVisibility(View.VISIBLE); @@ -719,19 +718,19 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder // For voicemail calls, show the voicemail playback layout; hide otherwise. if (callType == Calls.VOICEMAIL_TYPE - && mVoicemailPlaybackPresenter != null + && voicemailPlaybackPresenter != null && !TextUtils.isEmpty(voicemailUri)) { voicemailPlaybackView.setVisibility(View.VISIBLE); Uri uri = Uri.parse(voicemailUri); - mVoicemailPlaybackPresenter.setPlaybackView( + voicemailPlaybackPresenter.setPlaybackView( voicemailPlaybackView, rowId, uri, - mVoicemailPrimaryActionButtonClicked, + voicemailPrimaryActionButtonClicked, sendVoicemailButtonView); - mVoicemailPrimaryActionButtonClicked = false; - CallLogAsyncTaskUtil.markVoicemailAsRead(mContext, uri); + voicemailPrimaryActionButtonClicked = false; + CallLogAsyncTaskUtil.markVoicemailAsRead(context, uri); } else { voicemailPlaybackView.setVisibility(View.GONE); sendVoicemailButtonView.setVisibility(View.GONE); @@ -742,8 +741,8 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } else { detailsButtonView.setVisibility(View.VISIBLE); boolean canReportCallerId = - mCachedNumberLookupService != null - && mCachedNumberLookupService.canReportAsInvalid(info.sourceType, info.objectId); + cachedNumberLookupService != null + && cachedNumberLookupService.canReportAsInvalid(info.sourceType, info.objectId); detailsButtonView.setTag( IntentProvider.getCallDetailIntentProvider( callDetailsEntries, buildContact(), canReportCallerId, canSupportAssistedDialing())); @@ -773,9 +772,9 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder sendMessageView.setVisibility(View.GONE); } - mCallLogListItemHelper.setActionContentDescriptions(this); + callLogListItemHelper.setActionContentDescriptions(this); - boolean supportsCallSubject = mCallLogCache.doesAccountSupportCallSubject(accountHandle); + boolean supportsCallSubject = callLogCache.doesAccountSupportCallSubject(accountHandle); callWithNoteButtonView.setVisibility( supportsCallSubject && !isVoicemailNumber && info != null ? View.VISIBLE : View.GONE); @@ -796,7 +795,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder private boolean showDuoPrimaryButton() { return accountHandle != null && accountHandle.getComponentName().equals(DuoConstants.PHONE_ACCOUNT_COMPONENT_NAME) - && DuoComponent.get(mContext).getDuo().isReachable(mContext, number); + && DuoComponent.get(context).getDuo().isReachable(context, number); } private static boolean hasDialableChar(CharSequence number) { @@ -818,10 +817,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder if (accountHandle == null) { return false; } - if (mDefaultPhoneAccountHandle == null) { + if (defaultPhoneAccountHandle == null) { return false; } - return accountHandle.getComponentName().equals(mDefaultPhoneAccountHandle.getComponentName()); + return accountHandle.getComponentName().equals(defaultPhoneAccountHandle.getComponentName()); } private boolean canSupportAssistedDialing() { @@ -829,7 +828,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } private boolean canSupportCarrierVideoCall() { - return mCallLogCache.canRelyOnVideoPresence() + return callLogCache.canRelyOnVideoPresence() && info != null && (info.carrierPresence & Phone.CARRIER_PRESENCE_VT_CAPABLE) != 0; } @@ -907,12 +906,12 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder quickContactView.assignContactUri(info.lookupUri); if (isSpamFeatureEnabled && isSpam) { - quickContactView.setImageDrawable(mContext.getDrawable(R.drawable.blocked_contact)); + quickContactView.setImageDrawable(context.getDrawable(R.drawable.blocked_contact)); return; } final String displayName = TextUtils.isEmpty(info.name) ? displayNumber : info.name; - ContactPhotoManager.getInstance(mContext) + ContactPhotoManager.getInstance(context) .loadDialerThumbnailOrPhoto( quickContactView, info.lookupUri, @@ -924,10 +923,9 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder private @ContactType int getContactType() { return LetterTileDrawable.getContactTypeFromPrimitives( - mCallLogCache.isVoicemailNumber(accountHandle, number), + callLogCache.isVoicemailNumber(accountHandle, number), isSpam, - mCachedNumberLookupService != null - && mCachedNumberLookupService.isBusiness(info.sourceType), + cachedNumberLookupService != null && cachedNumberLookupService.isBusiness(info.sourceType), numberPresentation, false); } @@ -935,19 +933,19 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder @Override public void onClick(View view) { if (view.getId() == R.id.primary_action_button) { - CallLogAsyncTaskUtil.markCallAsRead(mContext, callIds); + CallLogAsyncTaskUtil.markCallAsRead(context, callIds); } if (view.getId() == R.id.primary_action_button && !TextUtils.isEmpty(voicemailUri)) { - Logger.get(mContext).logImpression(DialerImpression.Type.VOICEMAIL_PLAY_AUDIO_DIRECTLY); - mVoicemailPrimaryActionButtonClicked = true; - mExpandCollapseListener.onClick(primaryActionView); + Logger.get(context).logImpression(DialerImpression.Type.VOICEMAIL_PLAY_AUDIO_DIRECTLY); + voicemailPrimaryActionButtonClicked = true; + expandCollapseListener.onClick(primaryActionView); return; } if (view.getId() == R.id.call_with_note_action) { CallSubjectDialog.start( - (Activity) mContext, + (Activity) context, info.photoId, info.photoUri, info.lookupUri, @@ -962,12 +960,12 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } if (view.getId() == R.id.block_report_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_BLOCK_REPORT_SPAM); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_BLOCK_REPORT_SPAM); maybeShowBlockNumberMigrationDialog( new BlockedNumbersMigrator.Listener() { @Override public void onComplete() { - mBlockReportListener.onBlockReportSpam( + blockReportListener.onBlockReportSpam( displayNumber, number, countryIso, callType, info.sourceType); } }); @@ -975,12 +973,12 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } if (view.getId() == R.id.block_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_BLOCK_NUMBER); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_BLOCK_NUMBER); maybeShowBlockNumberMigrationDialog( new BlockedNumbersMigrator.Listener() { @Override public void onComplete() { - mBlockReportListener.onBlock( + blockReportListener.onBlock( displayNumber, number, countryIso, callType, info.sourceType); } }); @@ -988,23 +986,23 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } if (view.getId() == R.id.unblock_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_UNBLOCK_NUMBER); - mBlockReportListener.onUnblock( + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_UNBLOCK_NUMBER); + blockReportListener.onUnblock( displayNumber, number, countryIso, callType, info.sourceType, isSpam, blockId); return; } if (view.getId() == R.id.report_not_spam_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_REPORT_AS_NOT_SPAM); - mBlockReportListener.onReportNotSpam( + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_REPORT_AS_NOT_SPAM); + blockReportListener.onReportNotSpam( displayNumber, number, countryIso, callType, info.sourceType); return; } if (view.getId() == R.id.call_compose_action) { LogUtil.i("CallLogListItemViewHolder.onClick", "share and call pressed"); - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_SHARE_AND_CALL); - Activity activity = (Activity) mContext; + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_SHARE_AND_CALL); + Activity activity = (Activity) context; activity.startActivityForResult( CallComposerActivity.newIntent(activity, buildContact()), ActivityRequestCodes.DIALTACTS_CALL_COMPOSER); @@ -1012,8 +1010,8 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } if (view.getId() == R.id.share_voicemail) { - Logger.get(mContext).logImpression(DialerImpression.Type.VVM_SHARE_PRESSED); - mVoicemailPlaybackPresenter.shareVoicemail(); + Logger.get(context).logImpression(DialerImpression.Type.VVM_SHARE_PRESSED); + voicemailPlaybackPresenter.shareVoicemail(); return; } @@ -1024,7 +1022,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder return; } - final Intent intent = intentProvider.getIntent(mContext); + final Intent intent = intentProvider.getIntent(context); // See IntentProvider.getCallDetailIntentProvider() for why this may be null. if (intent == null) { return; @@ -1037,19 +1035,19 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder startDuoActivity(intent); } else if (CallDetailsActivity.isLaunchIntent(intent)) { PerformanceReport.recordClick(UiAction.Type.OPEN_CALL_DETAIL); - ((Activity) mContext) + ((Activity) context) .startActivityForResult(intent, ActivityRequestCodes.DIALTACTS_CALL_DETAILS); } else { if (Intent.ACTION_CALL.equals(intent.getAction()) && intent.getIntExtra(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, -1) == VideoProfile.STATE_BIDIRECTIONAL) { - Logger.get(mContext).logImpression(DialerImpression.Type.IMS_VIDEO_REQUESTED_FROM_CALL_LOG); + Logger.get(context).logImpression(DialerImpression.Type.IMS_VIDEO_REQUESTED_FROM_CALL_LOG); } else if (intent.getDataString() != null && intent.getDataString().contains(DuoConstants.PACKAGE_NAME)) { - Logger.get(mContext).logImpression(DialerImpression.Type.DUO_CALL_LOG_SET_UP_INSTALL); + Logger.get(context).logImpression(DialerImpression.Type.DUO_CALL_LOG_SET_UP_INSTALL); } - DialerUtils.startActivityWithErrorToast(mContext, intent); + DialerUtils.startActivityWithErrorToast(context, intent); } } @@ -1062,14 +1060,14 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder private void startDuoActivity(Intent intent) { if (DuoConstants.DUO_ACTIVATE_ACTION.equals(intent.getAction())) { - Logger.get(mContext).logImpression(DialerImpression.Type.DUO_CALL_LOG_SET_UP_ACTIVATE); + Logger.get(context).logImpression(DialerImpression.Type.DUO_CALL_LOG_SET_UP_ACTIVATE); } else if (DuoConstants.DUO_INVITE_ACTION.equals(intent.getAction())) { - Logger.get(mContext).logImpression(DialerImpression.Type.DUO_CALL_LOG_INVITE); + Logger.get(context).logImpression(DialerImpression.Type.DUO_CALL_LOG_INVITE); } else if (DuoConstants.DUO_CALL_ACTION.equals(intent.getAction())) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.LIGHTBRINGER_VIDEO_REQUESTED_FROM_CALL_LOG); if (isNonContactEntry(info)) { - Logger.get(mContext) + Logger.get(context) .logImpression( DialerImpression.Type.LIGHTBRINGER_NON_CONTACT_VIDEO_REQUESTED_FROM_CALL_LOG); } @@ -1079,10 +1077,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } try { - Activity activity = (Activity) mContext; + Activity activity = (Activity) context; activity.startActivityForResult(intent, ActivityRequestCodes.DIALTACTS_DUO); } catch (ActivityNotFoundException e) { - Toast.makeText(mContext, R.string.activity_not_available, Toast.LENGTH_SHORT).show(); + Toast.makeText(context, R.string.activity_not_available, Toast.LENGTH_SHORT).show(); } } @@ -1115,10 +1113,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder contact.setNumberLabel(numberType); /* third line of contact view. */ - String accountLabel = mCallLogCache.getAccountLabel(accountHandle); + String accountLabel = callLogCache.getAccountLabel(accountHandle); if (!TextUtils.isEmpty(accountLabel)) { SimDetails.Builder simDetails = SimDetails.newBuilder().setNetwork(accountLabel); - simDetails.setColor(mCallLogCache.getAccountColor(accountHandle)); + simDetails.setColor(callLogCache.getAccountColor(accountHandle)); contact.setSimDetails(simDetails.build()); } return contact.build(); @@ -1126,36 +1124,35 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder private void logCallLogAction(int id) { if (id == R.id.send_message_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_SEND_MESSAGE); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_SEND_MESSAGE); } else if (id == R.id.add_to_existing_contact_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_ADD_TO_CONTACT); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_ADD_TO_CONTACT); switch (hostUi) { case HostUi.CALL_HISTORY: - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_CALL_HISTORY); break; case HostUi.CALL_LOG: - Logger.get(mContext).logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_CALL_LOG); + Logger.get(context).logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_CALL_LOG); break; case HostUi.VOICEMAIL: - Logger.get(mContext).logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_VOICEMAIL); + Logger.get(context).logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_VOICEMAIL); break; default: throw Assert.createIllegalStateFailException(); } } else if (id == R.id.create_new_contact_action) { - Logger.get(mContext).logImpression(DialerImpression.Type.CALL_LOG_CREATE_NEW_CONTACT); + Logger.get(context).logImpression(DialerImpression.Type.CALL_LOG_CREATE_NEW_CONTACT); switch (hostUi) { case HostUi.CALL_HISTORY: - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.CREATE_NEW_CONTACT_FROM_CALL_HISTORY); break; case HostUi.CALL_LOG: - Logger.get(mContext) - .logImpression(DialerImpression.Type.CREATE_NEW_CONTACT_FROM_CALL_LOG); + Logger.get(context).logImpression(DialerImpression.Type.CREATE_NEW_CONTACT_FROM_CALL_LOG); break; case HostUi.VOICEMAIL: - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.CREATE_NEW_CONTACT_FROM_VOICEMAIL); break; default: @@ -1166,7 +1163,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder private void maybeShowBlockNumberMigrationDialog(BlockedNumbersMigrator.Listener listener) { if (!FilteredNumberCompat.maybeShowBlockNumberMigrationDialog( - mContext, ((Activity) mContext).getFragmentManager(), listener)) { + context, ((Activity) context).getFragmentManager(), listener)) { listener.onComplete(); } } @@ -1179,8 +1176,8 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder reportNotSpamView.setVisibility(View.GONE); String e164Number = PhoneNumberUtils.formatNumberToE164(number, countryIso); if (isVoicemailNumber - || !FilteredNumbersUtil.canBlockNumber(mContext, e164Number, number) - || !FilteredNumberCompat.canAttemptBlockOperations(mContext)) { + || !FilteredNumbersUtil.canBlockNumber(context, e164Number, number) + || !FilteredNumberCompat.canAttemptBlockOperations(context)) { return; } boolean isBlocked = blockId != null; @@ -1217,7 +1214,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } if (callType == CallLog.Calls.VOICEMAIL_TYPE) { - menu.setHeaderTitle(mContext.getResources().getText(R.string.voicemail)); + menu.setHeaderTitle(context.getResources().getText(R.string.voicemail)); } else { menu.setHeaderTitle( PhoneNumberUtilsCompat.createTtsSpannable( @@ -1237,7 +1234,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder // 3) Number is a SIP address if (PhoneNumberHelper.canPlaceCallsTo(number, numberPresentation) - && !mCallLogCache.isVoicemailNumber(accountHandle, number) + && !callLogCache.isVoicemailNumber(accountHandle, number) && !PhoneNumberHelper.isSipNumber(number)) { menu.add( ContextMenu.NONE, @@ -1258,10 +1255,10 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder } String e164Number = PhoneNumberUtils.formatNumberToE164(number, countryIso); - boolean isVoicemailNumber = mCallLogCache.isVoicemailNumber(accountHandle, number); + boolean isVoicemailNumber = callLogCache.isVoicemailNumber(accountHandle, number); if (!isVoicemailNumber - && FilteredNumbersUtil.canBlockNumber(mContext, e164Number, number) - && FilteredNumberCompat.canAttemptBlockOperations(mContext)) { + && FilteredNumbersUtil.canBlockNumber(context, e164Number, number) + && FilteredNumberCompat.canAttemptBlockOperations(context)) { boolean isBlocked = blockId != null; if (isBlocked) { menu.add( @@ -1309,7 +1306,7 @@ public final class CallLogListItemViewHolder extends RecyclerView.ViewHolder .setOnMenuItemClickListener(this); } - Logger.get(mContext).logScreenView(ScreenEvent.Type.CALL_LOG_CONTEXT_MENU, (Activity) mContext); + Logger.get(context).logScreenView(ScreenEvent.Type.CALL_LOG_CONTEXT_MENU, (Activity) context); } /** Specifies where the view holder belongs. */ diff --git a/java/com/android/dialer/app/calllog/CallLogNotificationsQueryHelper.java b/java/com/android/dialer/app/calllog/CallLogNotificationsQueryHelper.java index 3a4bf8766..d20ddd0e5 100644 --- a/java/com/android/dialer/app/calllog/CallLogNotificationsQueryHelper.java +++ b/java/com/android/dialer/app/calllog/CallLogNotificationsQueryHelper.java @@ -57,20 +57,20 @@ public class CallLogNotificationsQueryHelper { static final String CONFIG_NEW_VOICEMAIL_NOTIFICATION_THRESHOLD_OFFSET = "new_voicemail_notification_threshold"; - private final Context mContext; - private final NewCallsQuery mNewCallsQuery; - private final ContactInfoHelper mContactInfoHelper; - private final String mCurrentCountryIso; + private final Context context; + private final NewCallsQuery newCallsQuery; + private final ContactInfoHelper contactInfoHelper; + private final String currentCountryIso; CallLogNotificationsQueryHelper( Context context, NewCallsQuery newCallsQuery, ContactInfoHelper contactInfoHelper, String countryIso) { - mContext = context; - mNewCallsQuery = newCallsQuery; - mContactInfoHelper = contactInfoHelper; - mCurrentCountryIso = countryIso; + this.context = context; + this.newCallsQuery = newCallsQuery; + this.contactInfoHelper = contactInfoHelper; + currentCountryIso = countryIso; } /** Returns an instance of {@link CallLogNotificationsQueryHelper}. */ @@ -146,7 +146,7 @@ public class CallLogNotificationsQueryHelper { } NewCallsQuery getNewCallsQuery() { - return mNewCallsQuery; + return newCallsQuery; } /** @@ -156,10 +156,10 @@ public class CallLogNotificationsQueryHelper { */ @Nullable public List getNewVoicemails() { - return mNewCallsQuery.query( + return newCallsQuery.query( Calls.VOICEMAIL_TYPE, System.currentTimeMillis() - - ConfigProviderBindings.get(mContext) + - ConfigProviderBindings.get(context) .getLong( CONFIG_NEW_VOICEMAIL_NOTIFICATION_THRESHOLD_OFFSET, TimeUnit.DAYS.toMillis(7))); } @@ -171,7 +171,7 @@ public class CallLogNotificationsQueryHelper { */ @Nullable public List getNewMissedCalls() { - return mNewCallsQuery.query(Calls.MISSED_TYPE); + return newCallsQuery.query(Calls.MISSED_TYPE); } /** @@ -193,7 +193,7 @@ public class CallLogNotificationsQueryHelper { public ContactInfo getContactInfo( @Nullable String number, int numberPresentation, @Nullable String countryIso) { if (countryIso == null) { - countryIso = mCurrentCountryIso; + countryIso = currentCountryIso; } number = (number == null) ? "" : number; @@ -205,14 +205,14 @@ public class CallLogNotificationsQueryHelper { // 1. Special number representation. contactInfo.name = - PhoneNumberDisplayUtil.getDisplayName(mContext, number, numberPresentation, false) + PhoneNumberDisplayUtil.getDisplayName(context, number, numberPresentation, false) .toString(); if (!TextUtils.isEmpty(contactInfo.name)) { return contactInfo; } // 2. Look it up in the cache. - ContactInfo cachedContactInfo = mContactInfoHelper.lookupNumber(number, countryIso); + ContactInfo cachedContactInfo = contactInfoHelper.lookupNumber(number, countryIso); if (cachedContactInfo != null && !TextUtils.isEmpty(cachedContactInfo.name)) { return cachedContactInfo; @@ -226,7 +226,7 @@ public class CallLogNotificationsQueryHelper { contactInfo.name = number; } else { // 5. Otherwise, it's unknown number. - contactInfo.name = mContext.getResources().getString(R.string.unknown); + contactInfo.name = context.getResources().getString(R.string.unknown); } return contactInfo; } @@ -330,12 +330,12 @@ public class CallLogNotificationsQueryHelper { private static final int DATE_COLUMN_INDEX = 8; private static final int TRANSCRIPTION_STATE_COLUMN_INDEX = 9; - private final ContentResolver mContentResolver; - private final Context mContext; + private final ContentResolver contentResolver; + private final Context context; private DefaultNewCallsQuery(Context context, ContentResolver contentResolver) { - mContext = context; - mContentResolver = contentResolver; + this.context = context; + this.contentResolver = contentResolver; } @Override @@ -350,7 +350,7 @@ public class CallLogNotificationsQueryHelper { @TargetApi(Build.VERSION_CODES.M) @SuppressWarnings("MissingPermission") public List query(int type, long thresholdMillis) { - if (!PermissionsUtil.hasPermission(mContext, Manifest.permission.READ_CALL_LOG)) { + if (!PermissionsUtil.hasPermission(context, Manifest.permission.READ_CALL_LOG)) { LogUtil.w( "CallLogNotificationsQueryHelper.DefaultNewCallsQuery.query", "no READ_CALL_LOG permission, returning null for calls lookup."); @@ -382,7 +382,7 @@ public class CallLogNotificationsQueryHelper { } Selection selection = selectionBuilder.build(); try (Cursor cursor = - mContentResolver.query( + contentResolver.query( Calls.CONTENT_URI_WITH_VOICEMAIL, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ? PROJECTION_O : PROJECTION, selection.getSelection(), @@ -407,7 +407,7 @@ public class CallLogNotificationsQueryHelper { @Nullable @Override public NewCall query(Uri callsUri) { - if (!PermissionsUtil.hasPermission(mContext, Manifest.permission.READ_CALL_LOG)) { + if (!PermissionsUtil.hasPermission(context, Manifest.permission.READ_CALL_LOG)) { LogUtil.w( "CallLogNotificationsQueryHelper.DefaultNewCallsQuery.query", "No READ_CALL_LOG permission, returning null for calls lookup."); @@ -415,7 +415,7 @@ public class CallLogNotificationsQueryHelper { } final String selection = String.format("%s = '%s'", Calls.VOICEMAIL_URI, callsUri.toString()); try (Cursor cursor = - mContentResolver.query( + contentResolver.query( Calls.CONTENT_URI_WITH_VOICEMAIL, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ? PROJECTION_O : PROJECTION, selection, diff --git a/java/com/android/dialer/app/calllog/DialerQuickContactBadge.java b/java/com/android/dialer/app/calllog/DialerQuickContactBadge.java index a3aac41fa..81aed8baa 100644 --- a/java/com/android/dialer/app/calllog/DialerQuickContactBadge.java +++ b/java/com/android/dialer/app/calllog/DialerQuickContactBadge.java @@ -27,7 +27,7 @@ import com.android.dialer.logging.Logger; /** Allows us to click the contact badge for non multi select mode. */ class DialerQuickContactBadge extends QuickContactBadge { - private View.OnClickListener mExtraOnClickListener; + private View.OnClickListener extraOnClickListener; private OnActionModeStateChangedListener onActionModeStateChangeListener; public DialerQuickContactBadge(Context context) { @@ -44,11 +44,11 @@ class DialerQuickContactBadge extends QuickContactBadge { @Override public void onClick(View v) { - if (mExtraOnClickListener != null + if (extraOnClickListener != null && onActionModeStateChangeListener.isActionModeStateEnabled()) { Logger.get(v.getContext()) .logImpression(DialerImpression.Type.MULTISELECT_SINGLE_PRESS_TAP_VIA_CONTACT_BADGE); - mExtraOnClickListener.onClick(v); + extraOnClickListener.onClick(v); } else { super.onClick(v); } @@ -57,7 +57,7 @@ class DialerQuickContactBadge extends QuickContactBadge { public void setMulitSelectListeners( View.OnClickListener extraOnClickListener, OnActionModeStateChangedListener actionModeStateChangeListener) { - mExtraOnClickListener = extraOnClickListener; + this.extraOnClickListener = extraOnClickListener; onActionModeStateChangeListener = actionModeStateChangeListener; } } diff --git a/java/com/android/dialer/app/calllog/GroupingListAdapter.java b/java/com/android/dialer/app/calllog/GroupingListAdapter.java index d1157206f..29a4d4e4a 100644 --- a/java/com/android/dialer/app/calllog/GroupingListAdapter.java +++ b/java/com/android/dialer/app/calllog/GroupingListAdapter.java @@ -32,7 +32,7 @@ import android.util.SparseIntArray; */ abstract class GroupingListAdapter extends RecyclerView.Adapter { - protected ContentObserver mChangeObserver = + protected ContentObserver changeObserver = new ContentObserver(new Handler()) { @Override public boolean deliverSelfNotifications() { @@ -44,21 +44,21 @@ abstract class GroupingListAdapter extends RecyclerView.Adapter { onContentChanged(); } }; - protected DataSetObserver mDataSetObserver = + protected DataSetObserver dataSetObserver = new DataSetObserver() { @Override public void onChanged() { notifyDataSetChanged(); } }; - private Cursor mCursor; + private Cursor cursor; /** * SparseIntArray, which maps the cursor position of the first element of a group to the size of * the group. The index of a key in this map corresponds to the list position of that group. */ - private SparseIntArray mGroupMetadata; + private SparseIntArray groupMetadata; - private int mItemCount; + private int itemCount; public GroupingListAdapter() { reset(); @@ -72,28 +72,28 @@ abstract class GroupingListAdapter extends RecyclerView.Adapter { protected abstract void onContentChanged(); public void changeCursor(Cursor cursor) { - if (cursor == mCursor) { + if (cursor == this.cursor) { return; } - if (mCursor != null) { - mCursor.unregisterContentObserver(mChangeObserver); - mCursor.unregisterDataSetObserver(mDataSetObserver); - mCursor.close(); + if (this.cursor != null) { + this.cursor.unregisterContentObserver(changeObserver); + this.cursor.unregisterDataSetObserver(dataSetObserver); + this.cursor.close(); } // Reset whenever the cursor is changed. reset(); - mCursor = cursor; + this.cursor = cursor; if (cursor != null) { - addGroups(mCursor); + addGroups(this.cursor); // Calculate the item count by subtracting group child counts from the cursor count. - mItemCount = mGroupMetadata.size(); + itemCount = groupMetadata.size(); - cursor.registerContentObserver(mChangeObserver); - cursor.registerDataSetObserver(mDataSetObserver); + cursor.registerContentObserver(changeObserver); + cursor.registerDataSetObserver(dataSetObserver); notifyDataSetChanged(); } } @@ -103,18 +103,18 @@ abstract class GroupingListAdapter extends RecyclerView.Adapter { * #addGroups} method. */ public void addGroup(int cursorPosition, int groupSize) { - int lastIndex = mGroupMetadata.size() - 1; - if (lastIndex < 0 || cursorPosition <= mGroupMetadata.keyAt(lastIndex)) { - mGroupMetadata.put(cursorPosition, groupSize); + int lastIndex = groupMetadata.size() - 1; + if (lastIndex < 0 || cursorPosition <= groupMetadata.keyAt(lastIndex)) { + groupMetadata.put(cursorPosition, groupSize); } else { // Optimization to avoid binary search if adding groups in ascending cursor position. - mGroupMetadata.append(cursorPosition, groupSize); + groupMetadata.append(cursorPosition, groupSize); } } @Override public int getItemCount() { - return mItemCount; + return itemCount; } /** @@ -122,11 +122,11 @@ abstract class GroupingListAdapter extends RecyclerView.Adapter { * position. */ public int getGroupSize(int listPosition) { - if (listPosition < 0 || listPosition >= mGroupMetadata.size()) { + if (listPosition < 0 || listPosition >= groupMetadata.size()) { return 0; } - return mGroupMetadata.valueAt(listPosition); + return groupMetadata.valueAt(listPosition); } /** @@ -134,20 +134,20 @@ abstract class GroupingListAdapter extends RecyclerView.Adapter { * corresponding to that position. */ public Object getItem(int listPosition) { - if (mCursor == null || listPosition < 0 || listPosition >= mGroupMetadata.size()) { + if (cursor == null || listPosition < 0 || listPosition >= groupMetadata.size()) { return null; } - int cursorPosition = mGroupMetadata.keyAt(listPosition); - if (mCursor.moveToPosition(cursorPosition)) { - return mCursor; + int cursorPosition = groupMetadata.keyAt(listPosition); + if (cursor.moveToPosition(cursorPosition)) { + return cursor; } else { return null; } } private void reset() { - mItemCount = 0; - mGroupMetadata = new SparseIntArray(); + itemCount = 0; + groupMetadata = new SparseIntArray(); } } diff --git a/java/com/android/dialer/app/calllog/PhoneCallDetailsHelper.java b/java/com/android/dialer/app/calllog/PhoneCallDetailsHelper.java index 794b759f2..fa1f7ab2c 100644 --- a/java/com/android/dialer/app/calllog/PhoneCallDetailsHelper.java +++ b/java/com/android/dialer/app/calllog/PhoneCallDetailsHelper.java @@ -55,17 +55,17 @@ public class PhoneCallDetailsHelper /** The maximum number of icons will be shown to represent the call types in a group. */ private static final int MAX_CALL_TYPE_ICONS = 3; - private final Context mContext; - private final Resources mResources; - private final CallLogCache mCallLogCache; + private final Context context; + private final Resources resources; + private final CallLogCache callLogCache; /** Calendar used to construct dates */ - private final Calendar mCalendar; + private final Calendar calendar; /** The injected current time in milliseconds since the epoch. Used only by tests. */ - private Long mCurrentTimeMillisForTest; + private Long currentTimeMillisForTest; - private CharSequence mPhoneTypeLabelForTest; + private CharSequence phoneTypeLabelForTest; /** List of items to be concatenated together for accessibility descriptions */ - private ArrayList mDescriptionItems = new ArrayList<>(); + private ArrayList descriptionItems = new ArrayList<>(); /** * Creates a new instance of the helper. @@ -75,10 +75,10 @@ public class PhoneCallDetailsHelper * @param resources used to look up strings */ public PhoneCallDetailsHelper(Context context, Resources resources, CallLogCache callLogCache) { - mContext = context; - mResources = resources; - mCallLogCache = callLogCache; - mCalendar = Calendar.getInstance(); + this.context = context; + this.resources = resources; + this.callLogCache = callLogCache; + calendar = Calendar.getInstance(); } /** Fills the call details views with content. */ @@ -100,7 +100,7 @@ public class PhoneCallDetailsHelper views.callTypeIcons.setShowHd( (details.features & Calls.FEATURES_HD_CALL) == Calls.FEATURES_HD_CALL); views.callTypeIcons.setShowWifi( - MotorolaUtils.shouldShowWifiIconInCallLog(mContext, details.features)); + MotorolaUtils.shouldShowWifiIconInCallLog(context, details.features)); views.callTypeIcons.requestLayout(); views.callTypeIcons.setVisibility(View.VISIBLE); @@ -116,23 +116,23 @@ public class PhoneCallDetailsHelper setDetailText(views, callCount, details); // Set the account label if it exists. - String accountLabel = mCallLogCache.getAccountLabel(details.accountHandle); + String accountLabel = callLogCache.getAccountLabel(details.accountHandle); if (!TextUtils.isEmpty(details.viaNumber)) { if (!TextUtils.isEmpty(accountLabel)) { accountLabel = - mResources.getString( + resources.getString( R.string.call_log_via_number_phone_account, accountLabel, details.viaNumber); } else { - accountLabel = mResources.getString(R.string.call_log_via_number, details.viaNumber); + accountLabel = resources.getString(R.string.call_log_via_number, details.viaNumber); } } if (!TextUtils.isEmpty(accountLabel)) { views.callAccountLabel.setVisibility(View.VISIBLE); views.callAccountLabel.setText(accountLabel); - int color = mCallLogCache.getAccountColor(details.accountHandle); + int color = callLogCache.getAccountColor(details.accountHandle); if (color == PhoneAccount.NO_HIGHLIGHT_COLOR) { int defaultColor = R.color.dialer_secondary_text_color; - views.callAccountLabel.setTextColor(mContext.getResources().getColor(defaultColor)); + views.callAccountLabel.setTextColor(context.getResources().getColor(defaultColor)); } else { views.callAccountLabel.setTextColor(color); } @@ -171,23 +171,22 @@ public class PhoneCallDetailsHelper showRatingPrompt = true; } else if (details.transcriptionState == VoicemailCompat.TRANSCRIPTION_AVAILABLE || details.transcriptionState == VoicemailCompat.TRANSCRIPTION_AVAILABLE_AND_RATED) { - branding = mResources.getString(R.string.voicemail_transcription_branding_text); + branding = resources.getString(R.string.voicemail_transcription_branding_text); } } else { switch (details.transcriptionState) { case VoicemailCompat.TRANSCRIPTION_IN_PROGRESS: - branding = mResources.getString(R.string.voicemail_transcription_in_progress); + branding = resources.getString(R.string.voicemail_transcription_in_progress); break; case VoicemailCompat.TRANSCRIPTION_FAILED_NO_SPEECH_DETECTED: - branding = mResources.getString(R.string.voicemail_transcription_failed_no_speech); + branding = resources.getString(R.string.voicemail_transcription_failed_no_speech); break; case VoicemailCompat.TRANSCRIPTION_FAILED_LANGUAGE_NOT_SUPPORTED: branding = - mResources.getString( - R.string.voicemail_transcription_failed_language_not_supported); + resources.getString(R.string.voicemail_transcription_failed_language_not_supported); break; case VoicemailCompat.TRANSCRIPTION_FAILED: - branding = mResources.getString(R.string.voicemail_transcription_failed); + branding = resources.getString(R.string.voicemail_transcription_failed); break; default: break; // Fall through @@ -228,7 +227,7 @@ public class PhoneCallDetailsHelper views.callLocationAndDate.setTypeface(typeface); views.callLocationAndDate.setTextColor( ContextCompat.getColor( - mContext, + context, details.isRead ? R.color.call_log_detail_color : R.color.call_log_unread_text_color)); } @@ -236,16 +235,16 @@ public class PhoneCallDetailsHelper int transcriptionState, PhoneAccountHandle account) { // TODO(mdooley): add a configurable random element here? return transcriptionState == VoicemailCompat.TRANSCRIPTION_AVAILABLE - && VoicemailComponent.get(mContext) + && VoicemailComponent.get(context) .getVoicemailClient() - .isVoicemailDonationEnabled(mContext, account); + .isVoicemailDonationEnabled(context, account); } private void recordTranscriptionRating( TranscriptionRatingValue ratingValue, PhoneCallDetails details) { LogUtil.enterBlock("PhoneCallDetailsHelper.recordTranscriptionRating"); TranscriptionRatingHelper.sendRating( - mContext, + context, ratingValue, Uri.parse(details.voicemailUri), this::onRatingSuccess, @@ -256,7 +255,7 @@ public class PhoneCallDetailsHelper public void onRatingSuccess(Uri voicemailUri) { LogUtil.enterBlock("PhoneCallDetailsHelper.onRatingSuccess"); Toast toast = - Toast.makeText(mContext, R.string.voicemail_transcription_rating_thanks, Toast.LENGTH_LONG); + Toast.makeText(context, R.string.voicemail_transcription_rating_thanks, Toast.LENGTH_LONG); toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 50); toast.show(); } @@ -274,7 +273,7 @@ public class PhoneCallDetailsHelper * @return The call location and date string. */ public CharSequence getCallLocationAndDate(PhoneCallDetails details) { - mDescriptionItems.clear(); + descriptionItems.clear(); if (details.callTypes[0] != Calls.VOICEMAIL_TYPE) { // Get type of call (ie mobile, home, etc) if known, or the caller's location. @@ -283,15 +282,15 @@ public class PhoneCallDetailsHelper // Only add the call type or location if its not empty. It will be empty for unknown // callers. if (!TextUtils.isEmpty(callTypeOrLocation)) { - mDescriptionItems.add(callTypeOrLocation); + descriptionItems.add(callTypeOrLocation); } } // The date of this call - mDescriptionItems.add(getCallDate(details)); + descriptionItems.add(getCallDate(details)); // Create a comma separated list from the call type or location, and call date. - return DialerUtils.join(mDescriptionItems); + return DialerUtils.join(descriptionItems); } /** @@ -304,16 +303,16 @@ public class PhoneCallDetailsHelper */ public CharSequence getCallTypeOrLocation(PhoneCallDetails details) { if (details.isSpam) { - return mResources.getString(R.string.spam_number_call_log_label); + return resources.getString(R.string.spam_number_call_log_label); } else if (details.isBlocked) { - return mResources.getString(R.string.blocked_number_call_log_label); + return resources.getString(R.string.blocked_number_call_log_label); } CharSequence numberFormattedLabel = null; // Only show a label if the number is shown and it is not a SIP address. if (!TextUtils.isEmpty(details.number) && !PhoneNumberHelper.isUriNumber(details.number.toString()) - && !mCallLogCache.isVoicemailNumber(details.accountHandle, details.number)) { + && !callLogCache.isVoicemailNumber(details.accountHandle, details.number)) { if (shouldShowLocation(details)) { numberFormattedLabel = details.geocode; @@ -321,9 +320,9 @@ public class PhoneCallDetailsHelper && TextUtils.isEmpty(details.numberLabel))) { // Get type label only if it will not be "Custom" because of an empty number label. numberFormattedLabel = - mPhoneTypeLabelForTest != null - ? mPhoneTypeLabelForTest - : Phone.getTypeLabel(mResources, details.numberType, details.numberLabel); + phoneTypeLabelForTest != null + ? phoneTypeLabelForTest + : Phone.getTypeLabel(resources, details.numberType, details.numberLabel); } } @@ -350,7 +349,7 @@ public class PhoneCallDetailsHelper } public void setPhoneTypeLabelForTest(CharSequence phoneTypeLabel) { - this.mPhoneTypeLabelForTest = phoneTypeLabel; + this.phoneTypeLabelForTest = phoneTypeLabel; } /** @@ -385,10 +384,10 @@ public class PhoneCallDetailsHelper * @return String representing when the call occurred */ public CharSequence getGranularDateTime(PhoneCallDetails details) { - return mResources.getString( + return resources.getString( R.string.voicemailCallLogDateTimeFormat, getGranularDate(details.date), - DateUtils.formatDateTime(mContext, details.date, DateUtils.FORMAT_SHOW_TIME)); + DateUtils.formatDateTime(context, details.date, DateUtils.FORMAT_SHOW_TIME)); } /** @@ -396,10 +395,10 @@ public class PhoneCallDetailsHelper */ private String getGranularDate(long date) { if (DateUtils.isToday(date)) { - return mResources.getString(R.string.voicemailCallLogToday); + return resources.getString(R.string.voicemailCallLogToday); } return DateUtils.formatDateTime( - mContext, + context, date, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH @@ -412,10 +411,10 @@ public class PhoneCallDetailsHelper * @return {@code true} if date is within the current year, {@code false} otherwise */ private boolean shouldShowYear(long date) { - mCalendar.setTimeInMillis(getCurrentTimeMillis()); - int currentYear = mCalendar.get(Calendar.YEAR); - mCalendar.setTimeInMillis(date); - return currentYear != mCalendar.get(Calendar.YEAR); + calendar.setTimeInMillis(getCurrentTimeMillis()); + int currentYear = calendar.get(Calendar.YEAR); + calendar.setTimeInMillis(date); + return currentYear != calendar.get(Calendar.YEAR); } /** Sets the text of the header view for the details page of a phone call. */ @@ -426,14 +425,14 @@ public class PhoneCallDetailsHelper } else if (!TextUtils.isEmpty(details.displayNumber)) { nameText = details.displayNumber; } else { - nameText = mResources.getString(R.string.unknown); + nameText = resources.getString(R.string.unknown); } nameView.setText(nameText); } public void setCurrentTimeForTest(long currentTimeMillis) { - mCurrentTimeMillisForTest = currentTimeMillis; + currentTimeMillisForTest = currentTimeMillis; } /** @@ -442,10 +441,10 @@ public class PhoneCallDetailsHelper *

It can be injected in tests using {@link #setCurrentTimeForTest(long)}. */ private long getCurrentTimeMillis() { - if (mCurrentTimeMillisForTest == null) { + if (currentTimeMillisForTest == null) { return System.currentTimeMillis(); } else { - return mCurrentTimeMillisForTest; + return currentTimeMillisForTest; } } @@ -456,14 +455,14 @@ public class PhoneCallDetailsHelper CharSequence dateText = details.callLocationAndDate; final CharSequence text; if (callCount != null) { - text = mResources.getString(R.string.call_log_item_count_and_date, callCount, dateText); + text = resources.getString(R.string.call_log_item_count_and_date, callCount, dateText); } else { text = dateText; } if (details.callTypes[0] == Calls.VOICEMAIL_TYPE && details.duration > 0) { views.callLocationAndDate.setText( - mResources.getString( + resources.getString( R.string.voicemailCallLogDateTimeFormatWithDuration, text, getVoicemailDuration(details))); @@ -478,6 +477,6 @@ public class PhoneCallDetailsHelper if (minutes > 99) { minutes = 99; } - return mResources.getString(R.string.voicemailDurationFormat, minutes, seconds); + return resources.getString(R.string.voicemailDurationFormat, minutes, seconds); } } diff --git a/java/com/android/dialer/app/calllog/VisualVoicemailCallLogFragment.java b/java/com/android/dialer/app/calllog/VisualVoicemailCallLogFragment.java index 33fcba002..d38ec57a4 100644 --- a/java/com/android/dialer/app/calllog/VisualVoicemailCallLogFragment.java +++ b/java/com/android/dialer/app/calllog/VisualVoicemailCallLogFragment.java @@ -46,11 +46,11 @@ import java.util.List; public class VisualVoicemailCallLogFragment extends CallLogFragment { - private final ContentObserver mVoicemailStatusObserver = new CustomContentObserver(); - private VoicemailPlaybackPresenter mVoicemailPlaybackPresenter; - private DialerExecutor mPreSyncVoicemailStatusCheckExecutor; + private final ContentObserver voicemailStatusObserver = new CustomContentObserver(); + private VoicemailPlaybackPresenter voicemailPlaybackPresenter; + private DialerExecutor preSyncVoicemailStatusCheckExecutor; - private VoicemailErrorManager mVoicemailErrorManager; + private VoicemailErrorManager voicemailErrorManager; public VisualVoicemailCallLogFragment() { super(CallLog.Calls.VOICEMAIL_TYPE); @@ -58,19 +58,19 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { @Override protected VoicemailPlaybackPresenter getVoicemailPlaybackPresenter() { - return mVoicemailPlaybackPresenter; + return voicemailPlaybackPresenter; } @Override public void onActivityCreated(Bundle savedInstanceState) { - mVoicemailPlaybackPresenter = + voicemailPlaybackPresenter = VoicemailPlaybackPresenter.getInstance(getActivity(), savedInstanceState); if (PermissionsUtil.hasReadVoicemailPermissions(getContext()) && PermissionsUtil.hasAddVoicemailPermissions(getContext())) { getActivity() .getContentResolver() .registerContentObserver( - VoicemailContract.Status.CONTENT_URI, true, mVoicemailStatusObserver); + VoicemailContract.Status.CONTENT_URI, true, voicemailStatusObserver); } else { LogUtil.w( "VisualVoicemailCallLogFragment.onActivityCreated", @@ -78,7 +78,7 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { } super.onActivityCreated(savedInstanceState); - mPreSyncVoicemailStatusCheckExecutor = + preSyncVoicemailStatusCheckExecutor = DialerExecutorComponent.get(getContext()) .dialerExecutorFactory() .createUiTaskBuilder( @@ -88,8 +88,8 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { .onSuccess(this::onPreSyncVoicemailStatusChecked) .build(); - mVoicemailErrorManager = - new VoicemailErrorManager(getContext(), getAdapter().getAlertManager(), mModalAlertManager); + voicemailErrorManager = + new VoicemailErrorManager(getContext(), getAdapter().getAlertManager(), modalAlertManager); if (PermissionsUtil.hasReadVoicemailPermissions(getContext()) && PermissionsUtil.hasAddVoicemailPermissions(getContext())) { @@ -98,7 +98,7 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { .registerContentObserver( VoicemailContract.Status.CONTENT_URI, true, - mVoicemailErrorManager.getContentObserver()); + voicemailErrorManager.getContentObserver()); } else { LogUtil.w( "VisualVoicemailCallLogFragment.onActivityCreated", @@ -116,14 +116,14 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { @Override public void onResume() { super.onResume(); - mVoicemailPlaybackPresenter.onResume(); - mVoicemailErrorManager.onResume(); + voicemailPlaybackPresenter.onResume(); + voicemailErrorManager.onResume(); } @Override public void onPause() { - mVoicemailPlaybackPresenter.onPause(); - mVoicemailErrorManager.onPause(); + voicemailPlaybackPresenter.onPause(); + voicemailErrorManager.onPause(); super.onPause(); } @@ -132,10 +132,10 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { if (isAdded()) { getActivity() .getContentResolver() - .unregisterContentObserver(mVoicemailErrorManager.getContentObserver()); - mVoicemailPlaybackPresenter.onDestroy(); - mVoicemailErrorManager.onDestroy(); - getActivity().getContentResolver().unregisterContentObserver(mVoicemailStatusObserver); + .unregisterContentObserver(voicemailErrorManager.getContentObserver()); + voicemailPlaybackPresenter.onDestroy(); + voicemailErrorManager.onDestroy(); + getActivity().getContentResolver().unregisterContentObserver(voicemailStatusObserver); } super.onDestroy(); } @@ -143,8 +143,8 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - if (mVoicemailPlaybackPresenter != null) { - mVoicemailPlaybackPresenter.onSaveInstanceState(outState); + if (voicemailPlaybackPresenter != null) { + voicemailPlaybackPresenter.onSaveInstanceState(outState); } } @@ -159,7 +159,7 @@ public class VisualVoicemailCallLogFragment extends CallLogFragment { LogUtil.enterBlock("VisualVoicemailCallLogFragment.onVisible"); super.onVisible(); if (getActivity() != null) { - mPreSyncVoicemailStatusCheckExecutor.executeParallel(getActivity()); + preSyncVoicemailStatusCheckExecutor.executeParallel(getActivity()); Logger.get(getActivity()).logImpression(DialerImpression.Type.VVM_TAB_VIEWED); getActivity().setVolumeControlStream(VoicemailAudioManager.PLAYBACK_STREAM); } diff --git a/java/com/android/dialer/app/calllog/calllogcache/CallLogCache.java b/java/com/android/dialer/app/calllog/calllogcache/CallLogCache.java index 15de14318..f45537ca8 100644 --- a/java/com/android/dialer/app/calllog/calllogcache/CallLogCache.java +++ b/java/com/android/dialer/app/calllog/calllogcache/CallLogCache.java @@ -42,24 +42,24 @@ public class CallLogCache { // TODO: Dialer should be fixed so as not to check isVoicemail() so often but at the time of // this writing, that was a much larger undertaking than creating this cache. - protected final Context mContext; + protected final Context context; - private boolean mHasCheckedForVideoAvailability; - private int mVideoAvailability; - private final Map mPhoneAccountLabelCache = new ArrayMap<>(); - private final Map mPhoneAccountColorCache = new ArrayMap<>(); - private final Map mPhoneAccountCallWithNoteCache = new ArrayMap<>(); + private boolean hasCheckedForVideoAvailability; + private int videoAvailability; + private final Map phoneAccountLabelCache = new ArrayMap<>(); + private final Map phoneAccountColorCache = new ArrayMap<>(); + private final Map phoneAccountCallWithNoteCache = new ArrayMap<>(); public CallLogCache(Context context) { - mContext = context; + this.context = context; } public synchronized void reset() { - mPhoneAccountLabelCache.clear(); - mPhoneAccountColorCache.clear(); - mPhoneAccountCallWithNoteCache.clear(); - mHasCheckedForVideoAvailability = false; - mVideoAvailability = 0; + phoneAccountLabelCache.clear(); + phoneAccountColorCache.clear(); + phoneAccountCallWithNoteCache.clear(); + hasCheckedForVideoAvailability = false; + videoAvailability = 0; } /** @@ -71,7 +71,7 @@ public class CallLogCache { if (TextUtils.isEmpty(number)) { return false; } - return TelecomUtil.isVoicemailNumber(mContext, accountHandle, number.toString()); + return TelecomUtil.isVoicemailNumber(context, accountHandle, number.toString()); } /** @@ -79,31 +79,31 @@ public class CallLogCache { * {@link android.provider.ContactsContract.CommonDataKinds.Phone#CARRIER_PRESENCE} column. */ public boolean canRelyOnVideoPresence() { - if (!mHasCheckedForVideoAvailability) { - mVideoAvailability = CallUtil.getVideoCallingAvailability(mContext); - mHasCheckedForVideoAvailability = true; + if (!hasCheckedForVideoAvailability) { + videoAvailability = CallUtil.getVideoCallingAvailability(context); + hasCheckedForVideoAvailability = true; } - return (mVideoAvailability & CallUtil.VIDEO_CALLING_PRESENCE) != 0; + return (videoAvailability & CallUtil.VIDEO_CALLING_PRESENCE) != 0; } /** Extract account label from PhoneAccount object. */ public synchronized String getAccountLabel(PhoneAccountHandle accountHandle) { - if (mPhoneAccountLabelCache.containsKey(accountHandle)) { - return mPhoneAccountLabelCache.get(accountHandle); + if (phoneAccountLabelCache.containsKey(accountHandle)) { + return phoneAccountLabelCache.get(accountHandle); } else { - String label = PhoneAccountUtils.getAccountLabel(mContext, accountHandle); - mPhoneAccountLabelCache.put(accountHandle, label); + String label = PhoneAccountUtils.getAccountLabel(context, accountHandle); + phoneAccountLabelCache.put(accountHandle, label); return label; } } /** Extract account color from PhoneAccount object. */ public synchronized int getAccountColor(PhoneAccountHandle accountHandle) { - if (mPhoneAccountColorCache.containsKey(accountHandle)) { - return mPhoneAccountColorCache.get(accountHandle); + if (phoneAccountColorCache.containsKey(accountHandle)) { + return phoneAccountColorCache.get(accountHandle); } else { - Integer color = PhoneAccountUtils.getAccountColor(mContext, accountHandle); - mPhoneAccountColorCache.put(accountHandle, color); + Integer color = PhoneAccountUtils.getAccountColor(context, accountHandle); + phoneAccountColorCache.put(accountHandle, color); return color; } } @@ -116,12 +116,12 @@ public class CallLogCache { * @return {@code true} if calling with a note is supported, {@code false} otherwise. */ public synchronized boolean doesAccountSupportCallSubject(PhoneAccountHandle accountHandle) { - if (mPhoneAccountCallWithNoteCache.containsKey(accountHandle)) { - return mPhoneAccountCallWithNoteCache.get(accountHandle); + if (phoneAccountCallWithNoteCache.containsKey(accountHandle)) { + return phoneAccountCallWithNoteCache.get(accountHandle); } else { Boolean supportsCallWithNote = - PhoneAccountUtils.getAccountSupportsCallSubject(mContext, accountHandle); - mPhoneAccountCallWithNoteCache.put(accountHandle, supportsCallWithNote); + PhoneAccountUtils.getAccountSupportsCallSubject(context, accountHandle); + phoneAccountCallWithNoteCache.put(accountHandle, supportsCallWithNote); return supportsCallWithNote; } } diff --git a/java/com/android/dialer/app/contactinfo/ContactInfoCache.java b/java/com/android/dialer/app/contactinfo/ContactInfoCache.java index 155a6a2eb..3fcf40c2a 100644 --- a/java/com/android/dialer/app/contactinfo/ContactInfoCache.java +++ b/java/com/android/dialer/app/contactinfo/ContactInfoCache.java @@ -51,14 +51,14 @@ public class ContactInfoCache { private static final int START_THREAD = 2; private static final int START_PROCESSING_REQUESTS_DELAY_MS = 1000; - private final ExpirableCache mCache; - private final ContactInfoHelper mContactInfoHelper; - private final OnContactInfoChangedListener mOnContactInfoChangedListener; - private final BlockingQueue mUpdateRequests; - private final Handler mHandler; - private CequintCallerIdManager mCequintCallerIdManager; - private QueryThread mContactInfoQueryThread; - private volatile boolean mRequestProcessingDisabled = false; + private final ExpirableCache cache; + private final ContactInfoHelper contactInfoHelper; + private final OnContactInfoChangedListener onContactInfoChangedListener; + private final BlockingQueue updateRequests; + private final Handler handler; + private CequintCallerIdManager cequintCallerIdManager; + private QueryThread contactInfoQueryThread; + private volatile boolean requestProcessingDisabled = false; private static class InnerHandler extends Handler { @@ -76,7 +76,7 @@ public class ContactInfoCache { } switch (msg.what) { case REDRAW: - reference.mOnContactInfoChangedListener.onContactInfoChanged(); + reference.onContactInfoChangedListener.onContactInfoChanged(); break; case START_THREAD: reference.startRequestProcessing(); @@ -90,15 +90,15 @@ public class ContactInfoCache { @NonNull ExpirableCache internalCache, @NonNull ContactInfoHelper contactInfoHelper, @NonNull OnContactInfoChangedListener listener) { - mCache = internalCache; - mContactInfoHelper = contactInfoHelper; - mOnContactInfoChangedListener = listener; - mUpdateRequests = new PriorityBlockingQueue<>(); - mHandler = new InnerHandler(new WeakReference<>(this)); + cache = internalCache; + this.contactInfoHelper = contactInfoHelper; + onContactInfoChangedListener = listener; + updateRequests = new PriorityBlockingQueue<>(); + handler = new InnerHandler(new WeakReference<>(this)); } public void setCequintCallerIdManager(CequintCallerIdManager cequintCallerIdManager) { - mCequintCallerIdManager = cequintCallerIdManager; + this.cequintCallerIdManager = cequintCallerIdManager; } public ContactInfo getValue( @@ -107,14 +107,14 @@ public class ContactInfoCache { ContactInfo callLogContactInfo, boolean remoteLookupIfNotFoundLocally) { NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso); - ExpirableCache.CachedValue cachedInfo = mCache.getCachedValue(numberCountryIso); + ExpirableCache.CachedValue cachedInfo = cache.getCachedValue(numberCountryIso); ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue(); int requestType = remoteLookupIfNotFoundLocally ? ContactInfoRequest.TYPE_LOCAL_AND_REMOTE : ContactInfoRequest.TYPE_LOCAL; if (cachedInfo == null) { - mCache.put(numberCountryIso, ContactInfo.EMPTY); + cache.put(numberCountryIso, ContactInfo.EMPTY); // Use the cached contact info from the call log. info = callLogContactInfo; // The db request should happen on a non-UI thread. @@ -161,18 +161,18 @@ public class ContactInfoCache { request.type); ContactInfo info; if (request.isLocalRequest()) { - info = mContactInfoHelper.lookupNumber(request.number, request.countryIso); + info = contactInfoHelper.lookupNumber(request.number, request.countryIso); if (info != null && !info.contactExists) { // TODO(wangqi): Maybe skip look up if it's already available in cached number lookup // service. long start = SystemClock.elapsedRealtime(); - mContactInfoHelper.updateFromCequintCallerId(mCequintCallerIdManager, info, request.number); + contactInfoHelper.updateFromCequintCallerId(cequintCallerIdManager, info, request.number); long time = SystemClock.elapsedRealtime() - start; LogUtil.d( "ContactInfoCache.queryContactInfo", "Cequint Caller Id look up takes %d ms", time); } if (request.type == ContactInfoRequest.TYPE_LOCAL_AND_REMOTE) { - if (!mContactInfoHelper.hasName(info)) { + if (!contactInfoHelper.hasName(info)) { enqueueRequest( request.number, request.countryIso, @@ -183,7 +183,7 @@ public class ContactInfoCache { } } } else { - info = mContactInfoHelper.lookupNumberInRemoteDirectory(request.number, request.countryIso); + info = contactInfoHelper.lookupNumberInRemoteDirectory(request.number, request.countryIso); } if (info == null) { @@ -195,7 +195,7 @@ public class ContactInfoCache { // view. NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(request.number, request.countryIso); - ContactInfo existingInfo = mCache.getPossiblyExpired(numberCountryIso); + ContactInfo existingInfo = cache.getPossiblyExpired(numberCountryIso); final boolean isRemoteSource = info.sourceType != Type.UNKNOWN_SOURCE_TYPE; @@ -210,14 +210,14 @@ public class ContactInfoCache { // Store the data in the cache so that the UI thread can use to display it. Store it // even if it has not changed so that it is marked as not expired. - mCache.put(numberCountryIso, info); + cache.put(numberCountryIso, info); // Update the call log even if the cache it is up-to-date: it is possible that the cache // contains the value from a different call log entry. - mContactInfoHelper.updateCallLogContactInfo( + contactInfoHelper.updateCallLogContactInfo( request.number, request.countryIso, info, request.callLogInfo); if (!request.isLocalRequest()) { - mContactInfoHelper.updateCachedNumberLookupService(info); + contactInfoHelper.updateCachedNumberLookupService(info); } return updated; } @@ -229,9 +229,9 @@ public class ContactInfoCache { public void start() { // Schedule a thread-creation message if the thread hasn't been created yet, as an // optimization to queue fewer messages. - if (mContactInfoQueryThread == null) { + if (contactInfoQueryThread == null) { // TODO: Check whether this delay before starting to process is necessary. - mHandler.sendEmptyMessageDelayed(START_THREAD, START_PROCESSING_REQUESTS_DELAY_MS); + handler.sendEmptyMessageDelayed(START_THREAD, START_PROCESSING_REQUESTS_DELAY_MS); } } @@ -249,22 +249,22 @@ public class ContactInfoCache { */ private synchronized void startRequestProcessing() { // For unit-testing. - if (mRequestProcessingDisabled) { + if (requestProcessingDisabled) { return; } // If a thread is already started, don't start another. - if (mContactInfoQueryThread != null) { + if (contactInfoQueryThread != null) { return; } - mContactInfoQueryThread = new QueryThread(); - mContactInfoQueryThread.setPriority(Thread.MIN_PRIORITY); - mContactInfoQueryThread.start(); + contactInfoQueryThread = new QueryThread(); + contactInfoQueryThread.setPriority(Thread.MIN_PRIORITY); + contactInfoQueryThread.start(); } public void invalidate() { - mCache.expireAll(); + cache.expireAll(); stopRequestProcessing(); } @@ -274,12 +274,12 @@ public class ContactInfoCache { */ private synchronized void stopRequestProcessing() { // Remove any pending requests to start the processing thread. - mHandler.removeMessages(START_THREAD); - if (mContactInfoQueryThread != null) { + handler.removeMessages(START_THREAD); + if (contactInfoQueryThread != null) { // Stop the thread; we are finished with it. - mContactInfoQueryThread.stopProcessing(); - mContactInfoQueryThread.interrupt(); - mContactInfoQueryThread = null; + contactInfoQueryThread.stopProcessing(); + contactInfoQueryThread.interrupt(); + contactInfoQueryThread = null; } } @@ -299,8 +299,8 @@ public class ContactInfoCache { boolean immediate, @ContactInfoRequest.TYPE int type) { ContactInfoRequest request = new ContactInfoRequest(number, countryIso, callLogInfo, type); - if (!mUpdateRequests.contains(request)) { - mUpdateRequests.offer(request); + if (!updateRequests.contains(request)) { + updateRequests.offer(request); } if (immediate) { @@ -318,13 +318,13 @@ public class ContactInfoCache { /** Sets whether processing of requests for contact details should be enabled. */ public void disableRequestProcessing() { - mRequestProcessingDisabled = true; + requestProcessingDisabled = true; } @VisibleForTesting public void injectContactInfoForTest(String number, String countryIso, ContactInfo contactInfo) { NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso); - mCache.put(numberCountryIso, contactInfo); + cache.put(numberCountryIso, contactInfo); } public interface OnContactInfoChangedListener { @@ -337,14 +337,14 @@ public class ContactInfoCache { */ private class QueryThread extends Thread { - private volatile boolean mDone = false; + private volatile boolean done = false; public QueryThread() { super("ContactInfoCache.QueryThread"); } public void stopProcessing() { - mDone = true; + done = true; } @Override @@ -352,18 +352,18 @@ public class ContactInfoCache { boolean shouldRedraw = false; while (true) { // Check if thread is finished, and if so return immediately. - if (mDone) { + if (done) { return; } try { - ContactInfoRequest request = mUpdateRequests.take(); + ContactInfoRequest request = updateRequests.take(); shouldRedraw |= queryContactInfo(request); if (shouldRedraw - && (mUpdateRequests.isEmpty() - || (request.isLocalRequest() && !mUpdateRequests.peek().isLocalRequest()))) { + && (updateRequests.isEmpty() + || (request.isLocalRequest() && !updateRequests.peek().isLocalRequest()))) { shouldRedraw = false; - mHandler.sendEmptyMessage(REDRAW); + handler.sendEmptyMessage(REDRAW); } } catch (InterruptedException e) { // Ignore and attempt to continue processing requests diff --git a/java/com/android/dialer/app/contactinfo/ContactPhotoLoader.java b/java/com/android/dialer/app/contactinfo/ContactPhotoLoader.java index 537acd060..be143bbca 100644 --- a/java/com/android/dialer/app/contactinfo/ContactPhotoLoader.java +++ b/java/com/android/dialer/app/contactinfo/ContactPhotoLoader.java @@ -43,12 +43,12 @@ import java.util.Objects; */ public class ContactPhotoLoader { - private final Context mContext; - private final ContactInfo mContactInfo; + private final Context context; + private final ContactInfo contactInfo; public ContactPhotoLoader(Context context, ContactInfo contactInfo) { - mContext = Objects.requireNonNull(context); - mContactInfo = Objects.requireNonNull(contactInfo); + this.context = Objects.requireNonNull(context); + this.contactInfo = Objects.requireNonNull(contactInfo); } private static Bitmap drawableToBitmap(Drawable drawable, int width, int height) { @@ -62,7 +62,7 @@ public class ContactPhotoLoader { /** Create a contact photo icon bitmap appropriate for the ContactInfo. */ public Bitmap loadPhotoIcon() { Assert.isWorkerThread(); - int photoSize = mContext.getResources().getDimensionPixelSize(R.dimen.contact_photo_size); + int photoSize = context.getResources().getDimensionPixelSize(R.dimen.contact_photo_size); return drawableToBitmap(getIcon(), photoSize, photoSize); } @@ -81,11 +81,11 @@ public class ContactPhotoLoader { */ @Nullable private Drawable createPhotoIconDrawable() { - if (mContactInfo.photoUri == null) { + if (contactInfo.photoUri == null) { return null; } try { - InputStream input = mContext.getContentResolver().openInputStream(mContactInfo.photoUri); + InputStream input = context.getContentResolver().openInputStream(contactInfo.photoUri); if (input == null) { LogUtil.w( "ContactPhotoLoader.createPhotoIconDrawable", @@ -102,7 +102,7 @@ public class ContactPhotoLoader { return null; } final RoundedBitmapDrawable drawable = - RoundedBitmapDrawableFactory.create(mContext.getResources(), bitmap); + RoundedBitmapDrawableFactory.create(context.getResources(), bitmap); drawable.setAntiAlias(true); drawable.setCircular(true); return drawable; @@ -115,13 +115,13 @@ public class ContactPhotoLoader { /** @return a {@link LetterTileDrawable} based on the ContactInfo. */ private Drawable createLetterTileDrawable() { ContactInfoHelper helper = - new ContactInfoHelper(mContext, GeoUtil.getCurrentCountryIso(mContext)); - LetterTileDrawable drawable = new LetterTileDrawable(mContext.getResources()); + new ContactInfoHelper(context, GeoUtil.getCurrentCountryIso(context)); + LetterTileDrawable drawable = new LetterTileDrawable(context.getResources()); drawable.setCanonicalDialerLetterTileDetails( - mContactInfo.name, - mContactInfo.lookupKey, + contactInfo.name, + contactInfo.lookupKey, LetterTileDrawable.SHAPE_CIRCLE, - helper.isBusiness(mContactInfo.sourceType) + helper.isBusiness(contactInfo.sourceType) ? LetterTileDrawable.TYPE_BUSINESS : LetterTileDrawable.TYPE_DEFAULT); return drawable; diff --git a/java/com/android/dialer/app/filterednumber/BlockedNumbersFragment.java b/java/com/android/dialer/app/filterednumber/BlockedNumbersFragment.java index 36afe5429..cae35d5b6 100644 --- a/java/com/android/dialer/app/filterednumber/BlockedNumbersFragment.java +++ b/java/com/android/dialer/app/filterednumber/BlockedNumbersFragment.java @@ -53,11 +53,11 @@ public class BlockedNumbersFragment extends ListFragment private BlockedNumbersMigrator blockedNumbersMigratorForTest; private TextView blockedNumbersText; private TextView footerText; - private BlockedNumbersAdapter mAdapter; - private VisualVoicemailEnabledChecker mVoicemailEnabledChecker; - private View mImportSettings; - private View mBlockedNumbersDisabledForEmergency; - private View mBlockedNumberListDivider; + private BlockedNumbersAdapter adapter; + private VisualVoicemailEnabledChecker voicemailEnabledChecker; + private View importSettings; + private View blockedNumbersDisabledForEmergency; + private View blockedNumberListDivider; @Override public Context getContext() { @@ -81,27 +81,27 @@ public class BlockedNumbersFragment extends ListFragment drawable.setIsCircular(true); addNumberIcon.setImageDrawable(drawable); - if (mAdapter == null) { - mAdapter = + if (adapter == null) { + adapter = BlockedNumbersAdapter.newBlockedNumbersAdapter( getContext(), getActivity().getFragmentManager()); } - setListAdapter(mAdapter); + setListAdapter(adapter); blockedNumbersText = (TextView) getListView().findViewById(R.id.blocked_number_text_view); migratePromoView = getListView().findViewById(R.id.migrate_promo); getListView().findViewById(R.id.migrate_promo_allow_button).setOnClickListener(this); - mImportSettings = getListView().findViewById(R.id.import_settings); - mBlockedNumbersDisabledForEmergency = + importSettings = getListView().findViewById(R.id.import_settings); + blockedNumbersDisabledForEmergency = getListView().findViewById(R.id.blocked_numbers_disabled_for_emergency); - mBlockedNumberListDivider = getActivity().findViewById(R.id.blocked_number_list_divider); + blockedNumberListDivider = getActivity().findViewById(R.id.blocked_number_list_divider); getListView().findViewById(R.id.import_button).setOnClickListener(this); getListView().findViewById(R.id.view_numbers_button).setOnClickListener(this); getListView().findViewById(R.id.add_number_linear_layout).setOnClickListener(this); footerText = (TextView) getActivity().findViewById(R.id.blocked_number_footer_textview); - mVoicemailEnabledChecker = new VisualVoicemailEnabledChecker(getContext(), this); - mVoicemailEnabledChecker.asyncUpdate(); + voicemailEnabledChecker = new VisualVoicemailEnabledChecker(getContext(), this); + voicemailEnabledChecker.asyncUpdate(); updateActiveVoicemailProvider(); } @@ -139,11 +139,11 @@ public class BlockedNumbersFragment extends ListFragment blockedNumbersText.setVisibility(View.GONE); getListView().findViewById(R.id.add_number_linear_layout).setVisibility(View.GONE); getListView().findViewById(R.id.add_number_linear_layout).setOnClickListener(null); - mBlockedNumberListDivider.setVisibility(View.GONE); - mImportSettings.setVisibility(View.GONE); + blockedNumberListDivider.setVisibility(View.GONE); + importSettings.setVisibility(View.GONE); getListView().findViewById(R.id.import_button).setOnClickListener(null); getListView().findViewById(R.id.view_numbers_button).setOnClickListener(null); - mBlockedNumbersDisabledForEmergency.setVisibility(View.GONE); + blockedNumbersDisabledForEmergency.setVisibility(View.GONE); footerText.setVisibility(View.GONE); } else { FilteredNumbersUtil.checkForSendToVoicemailContact( @@ -152,7 +152,7 @@ public class BlockedNumbersFragment extends ListFragment @Override public void onComplete(boolean hasSendToVoicemailContact) { final int visibility = hasSendToVoicemailContact ? View.VISIBLE : View.GONE; - mImportSettings.setVisibility(visibility); + importSettings.setVisibility(visibility); } }); } @@ -160,12 +160,12 @@ public class BlockedNumbersFragment extends ListFragment // All views except migrate and the block list are hidden when new filtering is available if (!FilteredNumberCompat.canUseNewFiltering() && FilteredNumbersUtil.hasRecentEmergencyCall(getContext())) { - mBlockedNumbersDisabledForEmergency.setVisibility(View.VISIBLE); + blockedNumbersDisabledForEmergency.setVisibility(View.VISIBLE); } else { - mBlockedNumbersDisabledForEmergency.setVisibility(View.GONE); + blockedNumbersDisabledForEmergency.setVisibility(View.GONE); } - mVoicemailEnabledChecker.asyncUpdate(); + voicemailEnabledChecker.asyncUpdate(); } @Override @@ -197,17 +197,17 @@ public class BlockedNumbersFragment extends ListFragment @Override public void onLoadFinished(Loader loader, Cursor data) { - mAdapter.swapCursor(data); + adapter.swapCursor(data); if (FilteredNumberCompat.canUseNewFiltering() || data.getCount() == 0) { - mBlockedNumberListDivider.setVisibility(View.INVISIBLE); + blockedNumberListDivider.setVisibility(View.INVISIBLE); } else { - mBlockedNumberListDivider.setVisibility(View.VISIBLE); + blockedNumberListDivider.setVisibility(View.VISIBLE); } } @Override public void onLoaderReset(Loader loader) { - mAdapter.swapCursor(null); + adapter.swapCursor(null); } @Override @@ -228,7 +228,7 @@ public class BlockedNumbersFragment extends ListFragment new ImportSendToVoicemailContactsListener() { @Override public void onImportComplete() { - mImportSettings.setVisibility(View.GONE); + importSettings.setVisibility(View.GONE); } }); } else if (resId == R.id.migrate_promo_allow_button) { @@ -259,7 +259,7 @@ public class BlockedNumbersFragment extends ListFragment if (getActivity() == null || getActivity().isFinishing()) { return; } - if (mVoicemailEnabledChecker.isVisualVoicemailEnabled()) { + if (voicemailEnabledChecker.isVisualVoicemailEnabled()) { footerText.setText(R.string.block_number_footer_message_vvm); } else { footerText.setText(R.string.block_number_footer_message_no_vvm); diff --git a/java/com/android/dialer/app/filterednumber/NumbersAdapter.java b/java/com/android/dialer/app/filterednumber/NumbersAdapter.java index bdd6dcee8..3acb204e0 100644 --- a/java/com/android/dialer/app/filterednumber/NumbersAdapter.java +++ b/java/com/android/dialer/app/filterednumber/NumbersAdapter.java @@ -39,11 +39,11 @@ import com.android.dialer.util.UriUtils; /** TODO(calderwoodra): documentation */ public class NumbersAdapter extends SimpleCursorAdapter { - private final Context mContext; - private final FragmentManager mFragmentManager; - private final ContactInfoHelper mContactInfoHelper; - private final BidiFormatter mBidiFormatter = BidiFormatter.getInstance(); - private final ContactPhotoManager mContactPhotoManager; + private final Context context; + private final FragmentManager fragmentManager; + private final ContactInfoHelper contactInfoHelper; + private final BidiFormatter bidiFormatter = BidiFormatter.getInstance(); + private final ContactPhotoManager contactPhotoManager; public NumbersAdapter( Context context, @@ -51,10 +51,10 @@ public class NumbersAdapter extends SimpleCursorAdapter { ContactInfoHelper contactInfoHelper, ContactPhotoManager contactPhotoManager) { super(context, R.layout.blocked_number_item, null, new String[] {}, new int[] {}, 0); - mContext = context; - mFragmentManager = fragmentManager; - mContactInfoHelper = contactInfoHelper; - mContactPhotoManager = contactPhotoManager; + this.context = context; + this.fragmentManager = fragmentManager; + this.contactInfoHelper = contactInfoHelper; + this.contactPhotoManager = contactPhotoManager; } public void updateView(View view, String number, String countryIso) { @@ -67,7 +67,7 @@ public class NumbersAdapter extends SimpleCursorAdapter { quickContactBadge.setPrioritizedMimeType(Phone.CONTENT_ITEM_TYPE); } - ContactInfo info = mContactInfoHelper.lookupNumber(number, countryIso); + ContactInfo info = contactInfoHelper.lookupNumber(number, countryIso); if (info == null) { info = new ContactInfo(); info.number = number; @@ -75,7 +75,7 @@ public class NumbersAdapter extends SimpleCursorAdapter { final CharSequence locationOrType = getNumberTypeOrLocation(info, countryIso); final String displayNumber = getDisplayNumber(info); final String displayNumberStr = - mBidiFormatter.unicodeWrap(displayNumber, TextDirectionHeuristics.LTR); + bidiFormatter.unicodeWrap(displayNumber, TextDirectionHeuristics.LTR); String nameForDefaultImage; if (!TextUtils.isEmpty(info.name)) { @@ -99,15 +99,15 @@ public class NumbersAdapter extends SimpleCursorAdapter { final String lookupKey = info.lookupUri == null ? null : UriUtils.getLookupKeyFromUri(info.lookupUri); final int contactType = - mContactInfoHelper.isBusiness(info.sourceType) + contactInfoHelper.isBusiness(info.sourceType) ? LetterTileDrawable.TYPE_BUSINESS : LetterTileDrawable.TYPE_DEFAULT; final DefaultImageRequest request = new DefaultImageRequest(displayName, lookupKey, contactType, true /* isCircular */); badge.assignContactUri(info.lookupUri); badge.setContentDescription( - mContext.getResources().getString(R.string.description_contact_details, displayName)); - mContactPhotoManager.loadDirectoryPhoto( + context.getResources().getString(R.string.description_contact_details, displayName)); + contactPhotoManager.loadDirectoryPhoto( badge, info.photoUri, false /* darkTheme */, true /* isCircular */, request); } @@ -124,17 +124,17 @@ public class NumbersAdapter extends SimpleCursorAdapter { private CharSequence getNumberTypeOrLocation(ContactInfo info, String countryIso) { if (!TextUtils.isEmpty(info.name)) { return ContactsContract.CommonDataKinds.Phone.getTypeLabel( - mContext.getResources(), info.type, info.label); + context.getResources(), info.type, info.label); } else { - return PhoneNumberHelper.getGeoDescription(mContext, info.number, countryIso); + return PhoneNumberHelper.getGeoDescription(context, info.number, countryIso); } } protected Context getContext() { - return mContext; + return context; } protected FragmentManager getFragmentManager() { - return mFragmentManager; + return fragmentManager; } } diff --git a/java/com/android/dialer/app/filterednumber/ViewNumbersToImportFragment.java b/java/com/android/dialer/app/filterednumber/ViewNumbersToImportFragment.java index 1de768219..be3ae79f9 100644 --- a/java/com/android/dialer/app/filterednumber/ViewNumbersToImportFragment.java +++ b/java/com/android/dialer/app/filterednumber/ViewNumbersToImportFragment.java @@ -36,7 +36,7 @@ import com.android.dialer.blocking.FilteredNumbersUtil.ImportSendToVoicemailCont public class ViewNumbersToImportFragment extends ListFragment implements LoaderManager.LoaderCallbacks, View.OnClickListener { - private ViewNumbersToImportAdapter mAdapter; + private ViewNumbersToImportAdapter adapter; @Override public Context getContext() { @@ -47,12 +47,12 @@ public class ViewNumbersToImportFragment extends ListFragment public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - if (mAdapter == null) { - mAdapter = + if (adapter == null) { + adapter = ViewNumbersToImportAdapter.newViewNumbersToImportAdapter( getContext(), getActivity().getFragmentManager()); } - setListAdapter(mAdapter); + setListAdapter(adapter); } @Override @@ -103,12 +103,12 @@ public class ViewNumbersToImportFragment extends ListFragment @Override public void onLoadFinished(Loader loader, Cursor data) { - mAdapter.swapCursor(data); + adapter.swapCursor(data); } @Override public void onLoaderReset(Loader loader) { - mAdapter.swapCursor(null); + adapter.swapCursor(null); } @Override diff --git a/java/com/android/dialer/app/list/AllContactsFragment.java b/java/com/android/dialer/app/list/AllContactsFragment.java index 32a99e795..5076fd9cf 100644 --- a/java/com/android/dialer/app/list/AllContactsFragment.java +++ b/java/com/android/dialer/app/list/AllContactsFragment.java @@ -56,13 +56,13 @@ public class AllContactsFragment extends ContactEntryListFragment= 0) { // Iterate through the array of shortcuts, looking only for shortcuts where // mShortcutEnabled[i] is true - for (int i = 0; shortcutCount >= 0 && i < mShortcutEnabled.length; i++) { - if (mShortcutEnabled[i]) { + for (int i = 0; shortcutCount >= 0 && i < shortcutEnabled.length; i++) { + if (shortcutEnabled[i]) { shortcutCount--; if (shortcutCount < 0) { return i; @@ -177,7 +177,7 @@ public class DialerPhoneNumberListAdapter extends PhoneNumberListAdapter { ContactDisplayUtils.getTtsSpannedPhoneNumber( resources, R.string.search_shortcut_call_number, - mBidiFormatter.unicodeWrap(number, TextDirectionHeuristics.LTR)); + bidiFormatter.unicodeWrap(number, TextDirectionHeuristics.LTR)); drawable = ContextCompat.getDrawable(getContext(), R.drawable.quantum_ic_call_vd_theme_24); break; case SHORTCUT_CREATE_NEW_CONTACT: @@ -216,19 +216,19 @@ public class DialerPhoneNumberListAdapter extends PhoneNumberListAdapter { /** @return True if the shortcut state (disabled vs enabled) was changed by this operation */ public boolean setShortcutEnabled(int shortcutType, boolean visible) { - final boolean changed = mShortcutEnabled[shortcutType] != visible; - mShortcutEnabled[shortcutType] = visible; + final boolean changed = shortcutEnabled[shortcutType] != visible; + shortcutEnabled[shortcutType] = visible; return changed; } public String getFormattedQueryString() { - return mFormattedQueryString; + return formattedQueryString; } @Override public void setQueryString(String queryString) { - mFormattedQueryString = - PhoneNumberUtils.formatNumber(PhoneNumberUtils.normalizeNumber(queryString), mCountryIso); + formattedQueryString = + PhoneNumberUtils.formatNumber(PhoneNumberUtils.normalizeNumber(queryString), countryIso); super.setQueryString(queryString); } } diff --git a/java/com/android/dialer/app/list/DragDropController.java b/java/com/android/dialer/app/list/DragDropController.java index c22dd1318..458e31e69 100644 --- a/java/com/android/dialer/app/list/DragDropController.java +++ b/java/com/android/dialer/app/list/DragDropController.java @@ -28,12 +28,12 @@ import java.util.List; */ public class DragDropController { - private final List mOnDragDropListeners = new ArrayList(); - private final DragItemContainer mDragItemContainer; - private final int[] mLocationOnScreen = new int[2]; + private final List onDragDropListeners = new ArrayList(); + private final DragItemContainer dragItemContainer; + private final int[] locationOnScreen = new int[2]; public DragDropController(DragItemContainer dragItemContainer) { - mDragItemContainer = dragItemContainer; + this.dragItemContainer = dragItemContainer; } /** @return True if the drag is started, false if the drag is cancelled for some reason. */ @@ -43,54 +43,53 @@ public class DragDropController { // The coordinates in dragEvent of DragEvent.ACTION_DRAG_STARTED before NYC is window-related. // This is fixed in NYC. if (VERSION.SDK_INT >= VERSION_CODES.N) { - v.getLocationOnScreen(mLocationOnScreen); - screenX = x + mLocationOnScreen[0]; - screenY = y + mLocationOnScreen[1]; + v.getLocationOnScreen(locationOnScreen); + screenX = x + locationOnScreen[0]; + screenY = y + locationOnScreen[1]; } final PhoneFavoriteSquareTileView tileView = - mDragItemContainer.getViewForLocation(screenX, screenY); + dragItemContainer.getViewForLocation(screenX, screenY); if (tileView == null) { return false; } - for (int i = 0; i < mOnDragDropListeners.size(); i++) { - mOnDragDropListeners.get(i).onDragStarted(screenX, screenY, tileView); + for (int i = 0; i < onDragDropListeners.size(); i++) { + onDragDropListeners.get(i).onDragStarted(screenX, screenY, tileView); } return true; } public void handleDragHovered(View v, int x, int y) { - v.getLocationOnScreen(mLocationOnScreen); - final int screenX = x + mLocationOnScreen[0]; - final int screenY = y + mLocationOnScreen[1]; - final PhoneFavoriteSquareTileView view = - mDragItemContainer.getViewForLocation(screenX, screenY); - for (int i = 0; i < mOnDragDropListeners.size(); i++) { - mOnDragDropListeners.get(i).onDragHovered(screenX, screenY, view); + v.getLocationOnScreen(locationOnScreen); + final int screenX = x + locationOnScreen[0]; + final int screenY = y + locationOnScreen[1]; + final PhoneFavoriteSquareTileView view = dragItemContainer.getViewForLocation(screenX, screenY); + for (int i = 0; i < onDragDropListeners.size(); i++) { + onDragDropListeners.get(i).onDragHovered(screenX, screenY, view); } } public void handleDragFinished(int x, int y, boolean isRemoveView) { if (isRemoveView) { - for (int i = 0; i < mOnDragDropListeners.size(); i++) { - mOnDragDropListeners.get(i).onDroppedOnRemove(); + for (int i = 0; i < onDragDropListeners.size(); i++) { + onDragDropListeners.get(i).onDroppedOnRemove(); } } - for (int i = 0; i < mOnDragDropListeners.size(); i++) { - mOnDragDropListeners.get(i).onDragFinished(x, y); + for (int i = 0; i < onDragDropListeners.size(); i++) { + onDragDropListeners.get(i).onDragFinished(x, y); } } public void addOnDragDropListener(OnDragDropListener listener) { - if (!mOnDragDropListeners.contains(listener)) { - mOnDragDropListeners.add(listener); + if (!onDragDropListeners.contains(listener)) { + onDragDropListeners.add(listener); } } public void removeOnDragDropListener(OnDragDropListener listener) { - if (mOnDragDropListeners.contains(listener)) { - mOnDragDropListeners.remove(listener); + if (onDragDropListeners.contains(listener)) { + onDragDropListeners.remove(listener); } } diff --git a/java/com/android/dialer/app/list/ListsFragment.java b/java/com/android/dialer/app/list/ListsFragment.java index 05c647aec..7c24cc0f0 100644 --- a/java/com/android/dialer/app/list/ListsFragment.java +++ b/java/com/android/dialer/app/list/ListsFragment.java @@ -63,21 +63,21 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis private static final String TAG = "ListsFragment"; - private DialerViewPager mViewPager; - private ViewPagerTabs mViewPagerTabs; - private DialtactsPagerAdapter mAdapter; - private RemoveView mRemoveView; - private View mRemoveViewContent; - private Fragment mCurrentPage; - private SharedPreferences mPrefs; - private boolean mHasFetchedVoicemailStatus; - private boolean mShowVoicemailTabAfterVoicemailStatusIsFetched; - private final ArrayList mOnPageChangeListeners = new ArrayList<>(); + private DialerViewPager viewPager; + private ViewPagerTabs viewPagerTabs; + private DialtactsPagerAdapter adapter; + private RemoveView removeView; + private View removeViewContent; + private Fragment currentPage; + private SharedPreferences prefs; + private boolean hasFetchedVoicemailStatus; + private boolean showVoicemailTabAfterVoicemailStatusIsFetched; + private final ArrayList onPageChangeListeners = new ArrayList<>(); /** The position of the currently selected tab. */ - private int mTabIndex = DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL; + private int tabIndex = DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL; - private boolean mPaused; - private CallLogQueryHandler mCallLogQueryHandler; + private boolean paused; + private CallLogQueryHandler callLogQueryHandler; private UiAction.Type[] actionTypeList; private final DialerImpression.Type[] swipeImpressionList = @@ -88,12 +88,12 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis // Only for detecting page selected by swiping or clicking. private boolean onPageScrolledBeforeScrollStateSettling; - private final ContentObserver mVoicemailStatusObserver = + private final ContentObserver voicemailStatusObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); - mCallLogQueryHandler.fetchVoicemailStatus(); + callLogQueryHandler.fetchVoicemailStatus(); } }; @@ -102,7 +102,7 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis LogUtil.d("ListsFragment.onCreate", null); Trace.beginSection(TAG + " onCreate"); super.onCreate(savedInstanceState); - mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); + prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); Trace.endSection(); } @@ -112,19 +112,19 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis Trace.beginSection(TAG + " onResume"); super.onResume(); - mPaused = false; + paused = false; if (getUserVisibleHint()) { sendScreenViewForCurrentPosition(); } // Fetch voicemail status to determine if we should show the voicemail tab. - mCallLogQueryHandler = + callLogQueryHandler = new CallLogQueryHandler(getActivity(), getActivity().getContentResolver(), this); - mCallLogQueryHandler.fetchVoicemailStatus(); - mCallLogQueryHandler.fetchMissedCallsUnreadCount(); + callLogQueryHandler.fetchVoicemailStatus(); + callLogQueryHandler.fetchMissedCallsUnreadCount(); Trace.endSection(); - mCurrentPage = mAdapter.getItem(mViewPager.getCurrentItem()); + currentPage = adapter.getItem(viewPager.getCurrentItem()); } @Override @@ -132,13 +132,13 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis LogUtil.enterBlock("ListsFragment.onPause"); super.onPause(); - mPaused = true; + paused = true; } @Override public void onDestroyView() { super.onDestroyView(); - mViewPager.removeOnPageChangeListener(this); + viewPager.removeOnPageChangeListener(this); } @Override @@ -194,36 +194,36 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis tabIcons[DialtactsPagerAdapter.TAB_INDEX_ALL_CONTACTS] = R.drawable.quantum_ic_people_white_24; tabIcons[DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL] = R.drawable.quantum_ic_voicemail_white_24; - mViewPager = (DialerViewPager) parentView.findViewById(R.id.lists_pager); - mAdapter = + viewPager = (DialerViewPager) parentView.findViewById(R.id.lists_pager); + adapter = new DialtactsPagerAdapter( getContext(), getChildFragmentManager(), tabTitles, - mPrefs.getBoolean( + prefs.getBoolean( VisualVoicemailEnabledChecker.PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, false)); - mViewPager.setAdapter(mAdapter); + viewPager.setAdapter(adapter); // This is deliberate. See cl/172018946 for the app startup implications of using 1 here // versus loading more fragments upfront. - mViewPager.setOffscreenPageLimit(1); + viewPager.setOffscreenPageLimit(1); - mViewPager.addOnPageChangeListener(this); + viewPager.addOnPageChangeListener(this); showTab(DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL); - mViewPagerTabs = (ViewPagerTabs) parentView.findViewById(R.id.lists_pager_header); - mViewPagerTabs.configureTabIcons(tabIcons); - mViewPagerTabs.setViewPager(mViewPager); - addOnPageChangeListener(mViewPagerTabs); - mRemoveView = (RemoveView) parentView.findViewById(R.id.remove_view); - mRemoveViewContent = parentView.findViewById(R.id.remove_view_content); + viewPagerTabs = (ViewPagerTabs) parentView.findViewById(R.id.lists_pager_header); + viewPagerTabs.configureTabIcons(tabIcons); + viewPagerTabs.setViewPager(viewPager); + addOnPageChangeListener(viewPagerTabs); + removeView = (RemoveView) parentView.findViewById(R.id.remove_view); + removeViewContent = parentView.findViewById(R.id.remove_view_content); if (PermissionsUtil.hasReadVoicemailPermissions(getContext()) && PermissionsUtil.hasAddVoicemailPermissions(getContext())) { getActivity() .getContentResolver() .registerContentObserver( - VoicemailContract.Status.CONTENT_URI, true, mVoicemailStatusObserver); + VoicemailContract.Status.CONTENT_URI, true, voicemailStatusObserver); } else { LogUtil.w("ListsFragment.onCreateView", "no voicemail read permissions"); } @@ -235,13 +235,13 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis @Override public void onDestroy() { - getActivity().getContentResolver().unregisterContentObserver(mVoicemailStatusObserver); + getActivity().getContentResolver().unregisterContentObserver(voicemailStatusObserver); super.onDestroy(); } public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener) { - if (!mOnPageChangeListeners.contains(onPageChangeListener)) { - mOnPageChangeListeners.add(onPageChangeListener); + if (!onPageChangeListeners.contains(onPageChangeListener)) { + onPageChangeListeners.add(onPageChangeListener); } } @@ -252,15 +252,14 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis */ public void showTab(int index) { if (index == DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL) { - if (mAdapter.hasActiveVoicemailProvider()) { - mViewPager.setCurrentItem( - mAdapter.getRtlPosition(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL)); - } else if (!mHasFetchedVoicemailStatus) { + if (adapter.hasActiveVoicemailProvider()) { + viewPager.setCurrentItem(adapter.getRtlPosition(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL)); + } else if (!hasFetchedVoicemailStatus) { // Try to show the voicemail tab after the voicemail status returns. - mShowVoicemailTabAfterVoicemailStatusIsFetched = true; + showVoicemailTabAfterVoicemailStatusIsFetched = true; } } else if (index < getTabCount()) { - mViewPager.setCurrentItem(mAdapter.getRtlPosition(index)); + viewPager.setCurrentItem(adapter.getRtlPosition(index)); } } @@ -271,11 +270,11 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis if (positionOffsetPixels != 0) { onPageScrolledBeforeScrollStateSettling = true; } - mTabIndex = mAdapter.getRtlPosition(position); + tabIndex = adapter.getRtlPosition(position); - final int count = mOnPageChangeListeners.size(); + final int count = onPageChangeListeners.size(); for (int i = 0; i < count; i++) { - mOnPageChangeListeners.get(i).onPageScrolled(position, positionOffset, positionOffsetPixels); + onPageChangeListeners.get(i).onPageScrolled(position, positionOffset, positionOffsetPixels); } } @@ -294,23 +293,23 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis PerformanceReport.recordClick(actionTypeList[position]); LogUtil.i("ListsFragment.onPageSelected", "position: %d", position); - mTabIndex = mAdapter.getRtlPosition(position); + tabIndex = adapter.getRtlPosition(position); // Show the tab which has been selected instead. - mShowVoicemailTabAfterVoicemailStatusIsFetched = false; + showVoicemailTabAfterVoicemailStatusIsFetched = false; - final int count = mOnPageChangeListeners.size(); + final int count = onPageChangeListeners.size(); for (int i = 0; i < count; i++) { - mOnPageChangeListeners.get(i).onPageSelected(position); + onPageChangeListeners.get(i).onPageSelected(position); } sendScreenViewForCurrentPosition(); - if (mCurrentPage instanceof CallLogFragment) { - ((CallLogFragment) mCurrentPage).onNotVisible(); + if (currentPage instanceof CallLogFragment) { + ((CallLogFragment) currentPage).onNotVisible(); } - mCurrentPage = mAdapter.getItem(position); - if (mCurrentPage instanceof CallLogFragment) { - ((CallLogFragment) mCurrentPage).onVisible(); + currentPage = adapter.getItem(position); + if (currentPage instanceof CallLogFragment) { + ((CallLogFragment) currentPage).onVisible(); } } @@ -320,17 +319,17 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis onPageScrolledBeforeScrollStateSettling = false; } - final int count = mOnPageChangeListeners.size(); + final int count = onPageChangeListeners.size(); for (int i = 0; i < count; i++) { - mOnPageChangeListeners.get(i).onPageScrollStateChanged(state); + onPageChangeListeners.get(i).onPageScrollStateChanged(state); } } @Override public void onVoicemailStatusFetched(Cursor statusCursor) { - mHasFetchedVoicemailStatus = true; + hasFetchedVoicemailStatus = true; - if (getActivity() == null || mPaused) { + if (getActivity() == null || paused) { return; } @@ -340,19 +339,19 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis // Update hasActiveVoicemailProvider, which controls the number of tabs displayed. boolean hasActiveVoicemailProvider = VoicemailStatusHelper.getNumberActivityVoicemailSources(statusCursor) > 0; - if (hasActiveVoicemailProvider != mAdapter.hasActiveVoicemailProvider()) { - mAdapter.setHasActiveVoicemailProvider(hasActiveVoicemailProvider); - mAdapter.notifyDataSetChanged(); + if (hasActiveVoicemailProvider != adapter.hasActiveVoicemailProvider()) { + adapter.setHasActiveVoicemailProvider(hasActiveVoicemailProvider); + adapter.notifyDataSetChanged(); if (hasActiveVoicemailProvider) { Logger.get(getContext()).logImpression(DialerImpression.Type.VVM_TAB_VISIBLE); - mViewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); + viewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); } else { - mViewPagerTabs.removeTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); - mAdapter.removeVoicemailFragment(getChildFragmentManager()); + viewPagerTabs.removeTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); + adapter.removeVoicemailFragment(getChildFragmentManager()); } - mPrefs + prefs .edit() .putBoolean( VisualVoicemailEnabledChecker.PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, @@ -361,11 +360,11 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis } if (hasActiveVoicemailProvider) { - mCallLogQueryHandler.fetchVoicemailUnreadCount(); + callLogQueryHandler.fetchVoicemailUnreadCount(); } - if (mAdapter.hasActiveVoicemailProvider() && mShowVoicemailTabAfterVoicemailStatusIsFetched) { - mShowVoicemailTabAfterVoicemailStatusIsFetched = false; + if (adapter.hasActiveVoicemailProvider() && showVoicemailTabAfterVoicemailStatusIsFetched) { + showVoicemailTabAfterVoicemailStatusIsFetched = false; showTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); } } @@ -383,8 +382,8 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis cursor.close(); } - mViewPagerTabs.setUnreadCount(count, DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); - mViewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); + viewPagerTabs.setUnreadCount(count, DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); + viewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_VOICEMAIL); } @Override @@ -400,8 +399,8 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis cursor.close(); } - mViewPagerTabs.setUnreadCount(count, DialtactsPagerAdapter.TAB_INDEX_HISTORY); - mViewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_HISTORY); + viewPagerTabs.setUnreadCount(count, DialtactsPagerAdapter.TAB_INDEX_HISTORY); + viewPagerTabs.updateTab(DialtactsPagerAdapter.TAB_INDEX_HISTORY); } @Override @@ -411,13 +410,13 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis } public int getCurrentTabIndex() { - return mTabIndex; + return tabIndex; } public boolean shouldShowFab() { // If the VVM TOS is visible, don't show the fab - if (mCurrentPage instanceof VisualVoicemailCallLogFragment - && ((VisualVoicemailCallLogFragment) mCurrentPage).isModalAlertVisible()) { + if (currentPage instanceof VisualVoicemailCallLogFragment + && ((VisualVoicemailCallLogFragment) currentPage).isModalAlertVisible()) { return false; } @@ -429,47 +428,47 @@ public class ListsFragment extends Fragment implements OnPageChangeListener, Lis * voicemail in the call log or when the user expands an unread call in the call history tab. */ public void updateTabUnreadCounts() { - if (mCallLogQueryHandler != null) { - mCallLogQueryHandler.fetchMissedCallsUnreadCount(); - if (mAdapter.hasActiveVoicemailProvider()) { - mCallLogQueryHandler.fetchVoicemailUnreadCount(); + if (callLogQueryHandler != null) { + callLogQueryHandler.fetchMissedCallsUnreadCount(); + if (adapter.hasActiveVoicemailProvider()) { + callLogQueryHandler.fetchVoicemailUnreadCount(); } } } /** External method to mark all missed calls as read. */ public void markMissedCallsAsReadAndRemoveNotifications() { - if (mCallLogQueryHandler != null) { - mCallLogQueryHandler.markMissedCallsAsRead(); + if (callLogQueryHandler != null) { + callLogQueryHandler.markMissedCallsAsRead(); CallLogNotificationsService.cancelAllMissedCalls(getContext()); } } public void showRemoveView(boolean show) { - mRemoveViewContent.setVisibility(show ? View.VISIBLE : View.GONE); - mRemoveView.setAlpha(show ? 0 : 1); - mRemoveView.animate().alpha(show ? 1 : 0).start(); + removeViewContent.setVisibility(show ? View.VISIBLE : View.GONE); + removeView.setAlpha(show ? 0 : 1); + removeView.animate().alpha(show ? 1 : 0).start(); } public void showMultiSelectRemoveView(boolean show) { - mViewPagerTabs.setVisibility(show ? View.GONE : View.VISIBLE); - mViewPager.setEnableSwipingPages(!show); + viewPagerTabs.setVisibility(show ? View.GONE : View.VISIBLE); + viewPager.setEnableSwipingPages(!show); } public boolean hasFrequents() { Fragment page = - mAdapter.getItem(mAdapter.getRtlPosition(DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL)); + adapter.getItem(adapter.getRtlPosition(DialtactsPagerAdapter.TAB_INDEX_SPEED_DIAL)); return page instanceof OldSpeedDialFragment ? ((OldSpeedDialFragment) page).hasFrequents() : ((SpeedDialFragment) page).hasFrequents(); } public RemoveView getRemoveView() { - return mRemoveView; + return removeView; } public int getTabCount() { - return mAdapter.getCount(); + return adapter.getCount(); } public void sendScreenViewForCurrentPosition() { diff --git a/java/com/android/dialer/app/list/OldSpeedDialFragment.java b/java/com/android/dialer/app/list/OldSpeedDialFragment.java index afc7c133b..1b366c1ee 100644 --- a/java/com/android/dialer/app/list/OldSpeedDialFragment.java +++ b/java/com/android/dialer/app/list/OldSpeedDialFragment.java @@ -81,22 +81,22 @@ public class OldSpeedDialFragment extends Fragment /** Used with LoaderManager. */ private static final int LOADER_ID_CONTACT_TILE = 1; - private final LongSparseArray mItemIdTopMap = new LongSparseArray<>(); - private final LongSparseArray mItemIdLeftMap = new LongSparseArray<>(); - private final ContactTileView.Listener mContactTileAdapterListener = + private final LongSparseArray itemIdTopMap = new LongSparseArray<>(); + private final LongSparseArray itemIdLeftMap = new LongSparseArray<>(); + private final ContactTileView.Listener contactTileAdapterListener = new ContactTileAdapterListener(); - private final LoaderManager.LoaderCallbacks mContactTileLoaderListener = + private final LoaderManager.LoaderCallbacks contactTileLoaderListener = new ContactTileLoaderListener(); - private final ScrollListener mScrollListener = new ScrollListener(); - private int mAnimationDuration; - private OnPhoneNumberPickerActionListener mPhoneNumberPickerActionListener; - private OnListFragmentScrolledListener mActivityScrollListener; - private PhoneFavoritesTileAdapter mContactTileAdapter; - private View mParentView; - private PhoneFavoriteListView mListView; - private View mContactTileFrame; + private final ScrollListener scrollListener = new ScrollListener(); + private int animationDuration; + private OnPhoneNumberPickerActionListener phoneNumberPickerActionListener; + private OnListFragmentScrolledListener activityScrollListener; + private PhoneFavoritesTileAdapter contactTileAdapter; + private View parentView; + private PhoneFavoriteListView listView; + private View contactTileFrame; /** Layout used when there are no favorites. */ - private EmptyContentView mEmptyView; + private EmptyContentView emptyView; @Override public void onCreate(Bundle savedState) { @@ -109,10 +109,10 @@ public class OldSpeedDialFragment extends Fragment // Construct two base adapters which will become part of PhoneFavoriteMergedAdapter. // We don't construct the resultant adapter at this moment since it requires LayoutInflater // that will be available on onCreateView(). - mContactTileAdapter = - new PhoneFavoritesTileAdapter(getActivity(), mContactTileAdapterListener, this); - mContactTileAdapter.setPhotoLoader(ContactPhotoManager.getInstance(getActivity())); - mAnimationDuration = getResources().getInteger(R.integer.fade_duration); + contactTileAdapter = + new PhoneFavoritesTileAdapter(getActivity(), contactTileAdapterListener, this); + contactTileAdapter.setPhotoLoader(ContactPhotoManager.getInstance(getActivity())); + animationDuration = getResources().getInteger(R.integer.fade_duration); Trace.endSection(); } @@ -120,22 +120,22 @@ public class OldSpeedDialFragment extends Fragment public void onResume() { Trace.beginSection(TAG + " onResume"); super.onResume(); - if (mContactTileAdapter != null) { - mContactTileAdapter.refreshContactsPreferences(); + if (contactTileAdapter != null) { + contactTileAdapter.refreshContactsPreferences(); } if (PermissionsUtil.hasContactsReadPermissions(getActivity())) { if (getLoaderManager().getLoader(LOADER_ID_CONTACT_TILE) == null) { - getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, mContactTileLoaderListener); + getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, contactTileLoaderListener); } else { getLoaderManager().getLoader(LOADER_ID_CONTACT_TILE).forceLoad(); } - mEmptyView.setDescription(R.string.speed_dial_empty); - mEmptyView.setActionLabel(R.string.speed_dial_empty_add_favorite_action); + emptyView.setDescription(R.string.speed_dial_empty); + emptyView.setActionLabel(R.string.speed_dial_empty_add_favorite_action); } else { - mEmptyView.setDescription(R.string.permission_no_speeddial); - mEmptyView.setActionLabel(R.string.permission_single_turn_on); + emptyView.setDescription(R.string.permission_no_speeddial); + emptyView.setActionLabel(R.string.permission_single_turn_on); } Trace.endSection(); } @@ -144,62 +144,62 @@ public class OldSpeedDialFragment extends Fragment public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Trace.beginSection(TAG + " onCreateView"); - mParentView = inflater.inflate(R.layout.speed_dial_fragment, container, false); + parentView = inflater.inflate(R.layout.speed_dial_fragment, container, false); - mListView = (PhoneFavoriteListView) mParentView.findViewById(R.id.contact_tile_list); - mListView.setOnItemClickListener(this); - mListView.setVerticalScrollBarEnabled(false); - mListView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT); - mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY); - mListView.getDragDropController().addOnDragDropListener(mContactTileAdapter); + listView = (PhoneFavoriteListView) parentView.findViewById(R.id.contact_tile_list); + listView.setOnItemClickListener(this); + listView.setVerticalScrollBarEnabled(false); + listView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT); + listView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY); + listView.getDragDropController().addOnDragDropListener(contactTileAdapter); final ImageView dragShadowOverlay = (ImageView) getActivity().findViewById(R.id.contact_tile_drag_shadow_overlay); - mListView.setDragShadowOverlay(dragShadowOverlay); + listView.setDragShadowOverlay(dragShadowOverlay); - mEmptyView = (EmptyContentView) mParentView.findViewById(R.id.empty_list_view); - mEmptyView.setImage(R.drawable.empty_speed_dial); - mEmptyView.setActionClickedListener(this); + emptyView = (EmptyContentView) parentView.findViewById(R.id.empty_list_view); + emptyView.setImage(R.drawable.empty_speed_dial); + emptyView.setActionClickedListener(this); - mContactTileFrame = mParentView.findViewById(R.id.contact_tile_frame); + contactTileFrame = parentView.findViewById(R.id.contact_tile_frame); final LayoutAnimationController controller = new LayoutAnimationController( AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in)); controller.setDelay(0); - mListView.setLayoutAnimation(controller); - mListView.setAdapter(mContactTileAdapter); + listView.setLayoutAnimation(controller); + listView.setAdapter(contactTileAdapter); - mListView.setOnScrollListener(mScrollListener); - mListView.setFastScrollEnabled(false); - mListView.setFastScrollAlwaysVisible(false); + listView.setOnScrollListener(scrollListener); + listView.setFastScrollEnabled(false); + listView.setFastScrollAlwaysVisible(false); - //prevent content changes of the list from firing accessibility events. - mListView.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_NONE); - ContentChangedFilter.addToParent(mListView); + // prevent content changes of the list from firing accessibility events. + listView.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_NONE); + ContentChangedFilter.addToParent(listView); Trace.endSection(); - return mParentView; + return parentView; } public boolean hasFrequents() { - if (mContactTileAdapter == null) { + if (contactTileAdapter == null) { return false; } - return mContactTileAdapter.getNumFrequents() > 0; + return contactTileAdapter.getNumFrequents() > 0; } /* package */ void setEmptyViewVisibility(final boolean visible) { - final int previousVisibility = mEmptyView.getVisibility(); + final int previousVisibility = emptyView.getVisibility(); final int emptyViewVisibility = visible ? View.VISIBLE : View.GONE; final int listViewVisibility = visible ? View.GONE : View.VISIBLE; if (previousVisibility != emptyViewVisibility) { - final FrameLayout.LayoutParams params = (LayoutParams) mContactTileFrame.getLayoutParams(); + final FrameLayout.LayoutParams params = (LayoutParams) contactTileFrame.getLayoutParams(); params.height = visible ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT; - mContactTileFrame.setLayoutParams(params); - mEmptyView.setVisibility(emptyViewVisibility); - mListView.setVisibility(listViewVisibility); + contactTileFrame.setLayoutParams(params); + emptyView.setVisibility(emptyViewVisibility); + listView.setVisibility(listViewVisibility); } } @@ -210,7 +210,7 @@ public class OldSpeedDialFragment extends Fragment final Activity activity = getActivity(); try { - mActivityScrollListener = (OnListFragmentScrolledListener) activity; + activityScrollListener = (OnListFragmentScrolledListener) activity; } catch (ClassCastException e) { throw new ClassCastException( activity.toString() + " must implement OnListFragmentScrolledListener"); @@ -218,15 +218,15 @@ public class OldSpeedDialFragment extends Fragment try { OnDragDropListener listener = (OnDragDropListener) activity; - mListView.getDragDropController().addOnDragDropListener(listener); - ((HostInterface) activity).setDragDropController(mListView.getDragDropController()); + listView.getDragDropController().addOnDragDropListener(listener); + ((HostInterface) activity).setDragDropController(listView.getDragDropController()); } catch (ClassCastException e) { throw new ClassCastException( activity.toString() + " must implement OnDragDropListener and HostInterface"); } try { - mPhoneNumberPickerActionListener = (OnPhoneNumberPickerActionListener) activity; + phoneNumberPickerActionListener = (OnPhoneNumberPickerActionListener) activity; } catch (ClassCastException e) { throw new ClassCastException( activity.toString() + " must implement PhoneFavoritesFragment.listener"); @@ -236,7 +236,7 @@ public class OldSpeedDialFragment extends Fragment // This method call implicitly assures ContactTileLoaderListener's onLoadFinished() will // be called, on which we'll check if "all" contacts should be reloaded again or not. if (PermissionsUtil.hasContactsReadPermissions(activity)) { - getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, mContactTileLoaderListener); + getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, contactTileLoaderListener); } else { setEmptyViewVisibility(true); } @@ -245,12 +245,12 @@ public class OldSpeedDialFragment extends Fragment /** * {@inheritDoc} * - *

This is only effective for elements provided by {@link #mContactTileAdapter}. {@link - * #mContactTileAdapter} has its own logic for click events. + *

This is only effective for elements provided by {@link #contactTileAdapter}. {@link + * #contactTileAdapter} has its own logic for click events. */ @Override public void onItemClick(AdapterView parent, View view, int position, long id) { - final int contactTileAdapterCount = mContactTileAdapter.getCount(); + final int contactTileAdapterCount = contactTileAdapter.getCount(); if (position <= contactTileAdapterCount) { LogUtil.e( "OldSpeedDialFragment.onItemClick", @@ -267,36 +267,36 @@ public class OldSpeedDialFragment extends Fragment * are sliding into their new positions. */ private void saveOffsets(int removedItemHeight) { - final int firstVisiblePosition = mListView.getFirstVisiblePosition(); + final int firstVisiblePosition = listView.getFirstVisiblePosition(); if (DEBUG) { - LogUtil.d("OldSpeedDialFragment.saveOffsets", "Child count : " + mListView.getChildCount()); + LogUtil.d("OldSpeedDialFragment.saveOffsets", "Child count : " + listView.getChildCount()); } - for (int i = 0; i < mListView.getChildCount(); i++) { - final View child = mListView.getChildAt(i); + for (int i = 0; i < listView.getChildCount(); i++) { + final View child = listView.getChildAt(i); final int position = firstVisiblePosition + i; // Since we are getting the position from mListView and then querying // mContactTileAdapter, its very possible that things are out of sync // and we might index out of bounds. Let's make sure that this doesn't happen. - if (!mContactTileAdapter.isIndexInBound(position)) { + if (!contactTileAdapter.isIndexInBound(position)) { continue; } - final long itemId = mContactTileAdapter.getItemId(position); + final long itemId = contactTileAdapter.getItemId(position); if (DEBUG) { LogUtil.d( "OldSpeedDialFragment.saveOffsets", "Saving itemId: " + itemId + " for listview child " + i + " Top: " + child.getTop()); } - mItemIdTopMap.put(itemId, child.getTop()); - mItemIdLeftMap.put(itemId, child.getLeft()); + itemIdTopMap.put(itemId, child.getTop()); + itemIdLeftMap.put(itemId, child.getLeft()); } - mItemIdTopMap.put(KEY_REMOVED_ITEM_HEIGHT, removedItemHeight); + itemIdTopMap.put(KEY_REMOVED_ITEM_HEIGHT, removedItemHeight); } /* * Performs animations for the gridView */ private void animateGridView(final long... idsInPlace) { - if (mItemIdTopMap.size() == 0) { + if (itemIdTopMap.size() == 0) { // Don't do animations if the database is being queried for the first time and // the previous item offsets have not been cached, or the user hasn't done anything // (dragging, swiping etc) that requires an animation. @@ -304,34 +304,34 @@ public class OldSpeedDialFragment extends Fragment } ViewUtil.doOnPreDraw( - mListView, + listView, true, new Runnable() { @Override public void run() { - final int firstVisiblePosition = mListView.getFirstVisiblePosition(); + final int firstVisiblePosition = listView.getFirstVisiblePosition(); final AnimatorSet animSet = new AnimatorSet(); final ArrayList animators = new ArrayList(); - for (int i = 0; i < mListView.getChildCount(); i++) { - final View child = mListView.getChildAt(i); + for (int i = 0; i < listView.getChildCount(); i++) { + final View child = listView.getChildAt(i); int position = firstVisiblePosition + i; // Since we are getting the position from mListView and then querying // mContactTileAdapter, its very possible that things are out of sync // and we might index out of bounds. Let's make sure that this doesn't happen. - if (!mContactTileAdapter.isIndexInBound(position)) { + if (!contactTileAdapter.isIndexInBound(position)) { continue; } - final long itemId = mContactTileAdapter.getItemId(position); + final long itemId = contactTileAdapter.getItemId(position); if (containsId(idsInPlace, itemId)) { animators.add(ObjectAnimator.ofFloat(child, "alpha", 0.0f, 1.0f)); break; } else { - Integer startTop = mItemIdTopMap.get(itemId); - Integer startLeft = mItemIdLeftMap.get(itemId); + Integer startTop = itemIdTopMap.get(itemId); + Integer startLeft = itemIdLeftMap.get(itemId); final int top = child.getTop(); final int left = child.getLeft(); int deltaX = 0; @@ -367,12 +367,12 @@ public class OldSpeedDialFragment extends Fragment } if (animators.size() > 0) { - animSet.setDuration(mAnimationDuration).playTogether(animators); + animSet.setDuration(animationDuration).playTogether(animators); animSet.start(); } - mItemIdTopMap.clear(); - mItemIdLeftMap.clear(); + itemIdTopMap.clear(); + itemIdLeftMap.clear(); } }); } @@ -451,8 +451,8 @@ public class OldSpeedDialFragment extends Fragment if (DEBUG) { LogUtil.d("ContactTileLoaderListener.onLoadFinished", null); } - mContactTileAdapter.setContactCursor(data); - setEmptyViewVisibility(mContactTileAdapter.getCount() == 0); + contactTileAdapter.setContactCursor(data); + setEmptyViewVisibility(contactTileAdapter.getCount() == 0); } @Override @@ -468,16 +468,16 @@ public class OldSpeedDialFragment extends Fragment @Override public void onContactSelected( Uri contactUri, Rect targetRect, CallSpecificAppData callSpecificAppData) { - if (mPhoneNumberPickerActionListener != null) { - mPhoneNumberPickerActionListener.onPickDataUri( + if (phoneNumberPickerActionListener != null) { + phoneNumberPickerActionListener.onPickDataUri( contactUri, false /* isVideoCall */, callSpecificAppData); } } @Override public void onCallNumberDirectly(String phoneNumber, CallSpecificAppData callSpecificAppData) { - if (mPhoneNumberPickerActionListener != null) { - mPhoneNumberPickerActionListener.onPickPhoneNumber( + if (phoneNumberPickerActionListener != null) { + phoneNumberPickerActionListener.onPickPhoneNumber( phoneNumber, false /* isVideoCall */, callSpecificAppData); } } @@ -488,15 +488,15 @@ public class OldSpeedDialFragment extends Fragment @Override public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (mActivityScrollListener != null) { - mActivityScrollListener.onListFragmentScroll( + if (activityScrollListener != null) { + activityScrollListener.onListFragmentScroll( firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { - mActivityScrollListener.onListFragmentScrollStateChange(scrollState); + activityScrollListener.onListFragmentScrollStateChange(scrollState); } } } diff --git a/java/com/android/dialer/app/list/PhoneFavoriteListView.java b/java/com/android/dialer/app/list/PhoneFavoriteListView.java index f4f395ff0..ff867f9c0 100644 --- a/java/com/android/dialer/app/list/PhoneFavoriteListView.java +++ b/java/com/android/dialer/app/list/PhoneFavoriteListView.java @@ -38,58 +38,58 @@ public class PhoneFavoriteListView extends GridView implements OnDragDropListener, DragItemContainer { public static final String LOG_TAG = PhoneFavoriteListView.class.getSimpleName(); - final int[] mLocationOnScreen = new int[2]; + final int[] locationOnScreen = new int[2]; private static final long SCROLL_HANDLER_DELAY_MILLIS = 5; private static final int DRAG_SCROLL_PX_UNIT = 25; private static final float DRAG_SHADOW_ALPHA = 0.7f; /** - * {@link #mTopScrollBound} and {@link mBottomScrollBound} will be offseted to the top / bottom by + * {@link #topScrollBound} and {@link bottomScrollBound} will be offseted to the top / bottom by * {@link #getHeight} * {@link #BOUND_GAP_RATIO} pixels. */ private static final float BOUND_GAP_RATIO = 0.2f; - private float mTouchSlop; - private int mTopScrollBound; - private int mBottomScrollBound; - private int mLastDragY; - private Handler mScrollHandler; - private final Runnable mDragScroller = + private float touchSlop; + private int topScrollBound; + private int bottomScrollBound; + private int lastDragY; + private Handler scrollHandler; + private final Runnable dragScroller = new Runnable() { @Override public void run() { - if (mLastDragY <= mTopScrollBound) { + if (lastDragY <= topScrollBound) { smoothScrollBy(-DRAG_SCROLL_PX_UNIT, (int) SCROLL_HANDLER_DELAY_MILLIS); - } else if (mLastDragY >= mBottomScrollBound) { + } else if (lastDragY >= bottomScrollBound) { smoothScrollBy(DRAG_SCROLL_PX_UNIT, (int) SCROLL_HANDLER_DELAY_MILLIS); } - mScrollHandler.postDelayed(this, SCROLL_HANDLER_DELAY_MILLIS); + scrollHandler.postDelayed(this, SCROLL_HANDLER_DELAY_MILLIS); } }; - private boolean mIsDragScrollerRunning = false; - private int mTouchDownForDragStartY; - private Bitmap mDragShadowBitmap; - private ImageView mDragShadowOverlay; - private final AnimatorListenerAdapter mDragShadowOverAnimatorListener = + private boolean isDragScrollerRunning = false; + private int touchDownForDragStartY; + private Bitmap dragShadowBitmap; + private ImageView dragShadowOverlay; + private final AnimatorListenerAdapter dragShadowOverAnimatorListener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - if (mDragShadowBitmap != null) { - mDragShadowBitmap.recycle(); - mDragShadowBitmap = null; + if (dragShadowBitmap != null) { + dragShadowBitmap.recycle(); + dragShadowBitmap = null; } - mDragShadowOverlay.setVisibility(GONE); - mDragShadowOverlay.setImageBitmap(null); + dragShadowOverlay.setVisibility(GONE); + dragShadowOverlay.setImageBitmap(null); } }; - private View mDragShadowParent; - private int mAnimationDuration; + private View dragShadowParent; + private int animationDuration; // X and Y offsets inside the item from where the user grabbed to the // child's left coordinate. This is used to aid in the drawing of the drag shadow. - private int mTouchOffsetToChildLeft; - private int mTouchOffsetToChildTop; - private int mDragShadowLeft; - private int mDragShadowTop; - private DragDropController mDragDropController = new DragDropController(this); + private int touchOffsetToChildLeft; + private int touchOffsetToChildTop; + private int dragShadowLeft; + private int dragShadowTop; + private DragDropController dragDropController = new DragDropController(this); public PhoneFavoriteListView(Context context) { this(context, null); @@ -101,15 +101,15 @@ public class PhoneFavoriteListView extends GridView public PhoneFavoriteListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - mAnimationDuration = context.getResources().getInteger(R.integer.fade_duration); - mTouchSlop = ViewConfiguration.get(context).getScaledPagingTouchSlop(); - mDragDropController.addOnDragDropListener(this); + animationDuration = context.getResources().getInteger(R.integer.fade_duration); + touchSlop = ViewConfiguration.get(context).getScaledPagingTouchSlop(); + dragDropController.addOnDragDropListener(this); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); - mTouchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop(); + touchSlop = ViewConfiguration.get(getContext()).getScaledPagingTouchSlop(); } /** @@ -119,7 +119,7 @@ public class PhoneFavoriteListView extends GridView @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { - mTouchDownForDragStartY = (int) ev.getY(); + touchDownForDragStartY = (int) ev.getY(); } return super.onInterceptTouchEvent(ev); @@ -138,38 +138,38 @@ public class PhoneFavoriteListView extends GridView // on a {@link PhoneFavoriteTileView} return false; } - if (!mDragDropController.handleDragStarted(this, eX, eY)) { + if (!dragDropController.handleDragStarted(this, eX, eY)) { return false; } break; } case DragEvent.ACTION_DRAG_LOCATION: - mLastDragY = eY; - mDragDropController.handleDragHovered(this, eX, eY); + lastDragY = eY; + dragDropController.handleDragHovered(this, eX, eY); // Kick off {@link #mScrollHandler} if it's not started yet. - if (!mIsDragScrollerRunning + if (!isDragScrollerRunning && // And if the distance traveled while dragging exceeds the touch slop - (Math.abs(mLastDragY - mTouchDownForDragStartY) >= 4 * mTouchSlop)) { - mIsDragScrollerRunning = true; + (Math.abs(lastDragY - touchDownForDragStartY) >= 4 * touchSlop)) { + isDragScrollerRunning = true; ensureScrollHandler(); - mScrollHandler.postDelayed(mDragScroller, SCROLL_HANDLER_DELAY_MILLIS); + scrollHandler.postDelayed(dragScroller, SCROLL_HANDLER_DELAY_MILLIS); } break; case DragEvent.ACTION_DRAG_ENTERED: final int boundGap = (int) (getHeight() * BOUND_GAP_RATIO); - mTopScrollBound = (getTop() + boundGap); - mBottomScrollBound = (getBottom() - boundGap); + topScrollBound = (getTop() + boundGap); + bottomScrollBound = (getBottom() - boundGap); break; case DragEvent.ACTION_DRAG_EXITED: case DragEvent.ACTION_DRAG_ENDED: case DragEvent.ACTION_DROP: ensureScrollHandler(); - mScrollHandler.removeCallbacks(mDragScroller); - mIsDragScrollerRunning = false; + scrollHandler.removeCallbacks(dragScroller); + isDragScrollerRunning = false; // Either a successful drop or it's ended with out drop. if (action == DragEvent.ACTION_DROP || action == DragEvent.ACTION_DRAG_ENDED) { - mDragDropController.handleDragFinished(eX, eY, false); + dragDropController.handleDragFinished(eX, eY, false); } break; default: @@ -180,8 +180,8 @@ public class PhoneFavoriteListView extends GridView } public void setDragShadowOverlay(ImageView overlay) { - mDragShadowOverlay = overlay; - mDragShadowParent = (View) mDragShadowOverlay.getParent(); + dragShadowOverlay = overlay; + dragShadowParent = (View) dragShadowOverlay.getParent(); } /** Find the view under the pointer. */ @@ -201,73 +201,73 @@ public class PhoneFavoriteListView extends GridView } private void ensureScrollHandler() { - if (mScrollHandler == null) { - mScrollHandler = getHandler(); + if (scrollHandler == null) { + scrollHandler = getHandler(); } } public DragDropController getDragDropController() { - return mDragDropController; + return dragDropController; } @Override public void onDragStarted(int x, int y, PhoneFavoriteSquareTileView tileView) { - if (mDragShadowOverlay == null) { + if (dragShadowOverlay == null) { return; } - mDragShadowOverlay.clearAnimation(); - mDragShadowBitmap = createDraggedChildBitmap(tileView); - if (mDragShadowBitmap == null) { + dragShadowOverlay.clearAnimation(); + dragShadowBitmap = createDraggedChildBitmap(tileView); + if (dragShadowBitmap == null) { return; } - tileView.getLocationOnScreen(mLocationOnScreen); - mDragShadowLeft = mLocationOnScreen[0]; - mDragShadowTop = mLocationOnScreen[1]; + tileView.getLocationOnScreen(locationOnScreen); + dragShadowLeft = locationOnScreen[0]; + dragShadowTop = locationOnScreen[1]; // x and y are the coordinates of the on-screen touch event. Using these // and the on-screen location of the tileView, calculate the difference between // the position of the user's finger and the position of the tileView. These will // be used to offset the location of the drag shadow so that it appears that the // tileView is positioned directly under the user's finger. - mTouchOffsetToChildLeft = x - mDragShadowLeft; - mTouchOffsetToChildTop = y - mDragShadowTop; + touchOffsetToChildLeft = x - dragShadowLeft; + touchOffsetToChildTop = y - dragShadowTop; - mDragShadowParent.getLocationOnScreen(mLocationOnScreen); - mDragShadowLeft -= mLocationOnScreen[0]; - mDragShadowTop -= mLocationOnScreen[1]; + dragShadowParent.getLocationOnScreen(locationOnScreen); + dragShadowLeft -= locationOnScreen[0]; + dragShadowTop -= locationOnScreen[1]; - mDragShadowOverlay.setImageBitmap(mDragShadowBitmap); - mDragShadowOverlay.setVisibility(VISIBLE); - mDragShadowOverlay.setAlpha(DRAG_SHADOW_ALPHA); + dragShadowOverlay.setImageBitmap(dragShadowBitmap); + dragShadowOverlay.setVisibility(VISIBLE); + dragShadowOverlay.setAlpha(DRAG_SHADOW_ALPHA); - mDragShadowOverlay.setX(mDragShadowLeft); - mDragShadowOverlay.setY(mDragShadowTop); + dragShadowOverlay.setX(dragShadowLeft); + dragShadowOverlay.setY(dragShadowTop); } @Override public void onDragHovered(int x, int y, PhoneFavoriteSquareTileView tileView) { // Update the drag shadow location. - mDragShadowParent.getLocationOnScreen(mLocationOnScreen); - mDragShadowLeft = x - mTouchOffsetToChildLeft - mLocationOnScreen[0]; - mDragShadowTop = y - mTouchOffsetToChildTop - mLocationOnScreen[1]; + dragShadowParent.getLocationOnScreen(locationOnScreen); + dragShadowLeft = x - touchOffsetToChildLeft - locationOnScreen[0]; + dragShadowTop = y - touchOffsetToChildTop - locationOnScreen[1]; // Draw the drag shadow at its last known location if the drag shadow exists. - if (mDragShadowOverlay != null) { - mDragShadowOverlay.setX(mDragShadowLeft); - mDragShadowOverlay.setY(mDragShadowTop); + if (dragShadowOverlay != null) { + dragShadowOverlay.setX(dragShadowLeft); + dragShadowOverlay.setY(dragShadowTop); } } @Override public void onDragFinished(int x, int y) { - if (mDragShadowOverlay != null) { - mDragShadowOverlay.clearAnimation(); - mDragShadowOverlay + if (dragShadowOverlay != null) { + dragShadowOverlay.clearAnimation(); + dragShadowOverlay .animate() .alpha(0.0f) - .setDuration(mAnimationDuration) - .setListener(mDragShadowOverAnimatorListener) + .setDuration(animationDuration) + .setListener(dragShadowOverAnimatorListener) .start(); } } @@ -297,10 +297,10 @@ public class PhoneFavoriteListView extends GridView @Override public PhoneFavoriteSquareTileView getViewForLocation(int x, int y) { - getLocationOnScreen(mLocationOnScreen); + getLocationOnScreen(locationOnScreen); // Calculate the X and Y coordinates of the drag event relative to the view - final int viewX = x - mLocationOnScreen[0]; - final int viewY = y - mLocationOnScreen[1]; + final int viewX = x - locationOnScreen[0]; + final int viewY = y - locationOnScreen[1]; final View child = getViewAtPosition(viewX, viewY); if (!(child instanceof PhoneFavoriteSquareTileView)) { diff --git a/java/com/android/dialer/app/list/PhoneFavoriteSquareTileView.java b/java/com/android/dialer/app/list/PhoneFavoriteSquareTileView.java index 40f23ea6f..330a3614c 100644 --- a/java/com/android/dialer/app/list/PhoneFavoriteSquareTileView.java +++ b/java/com/android/dialer/app/list/PhoneFavoriteSquareTileView.java @@ -34,16 +34,16 @@ public class PhoneFavoriteSquareTileView extends PhoneFavoriteTileView { private static final String TAG = PhoneFavoriteSquareTileView.class.getSimpleName(); - private final float mHeightToWidthRatio; + private final float heightToWidthRatio; - private ImageButton mSecondaryButton; + private ImageButton secondaryButton; - private ContactEntry mContactEntry; + private ContactEntry contactEntry; public PhoneFavoriteSquareTileView(Context context, AttributeSet attrs) { super(context, attrs); - mHeightToWidthRatio = + heightToWidthRatio = getResources().getFraction(R.dimen.contact_tile_height_to_width_ratio, 1, 1); } @@ -54,7 +54,7 @@ public class PhoneFavoriteSquareTileView extends PhoneFavoriteTileView { nameView.setElegantTextHeight(false); final TextView phoneTypeView = (TextView) findViewById(R.id.contact_tile_phone_type); phoneTypeView.setElegantTextHeight(false); - mSecondaryButton = (ImageButton) findViewById(R.id.contact_tile_secondary_button); + secondaryButton = (ImageButton) findViewById(R.id.contact_tile_secondary_button); } @Override @@ -85,7 +85,7 @@ public class PhoneFavoriteSquareTileView extends PhoneFavoriteTileView { public void loadFromContact(ContactEntry entry) { super.loadFromContact(entry); if (entry != null) { - mSecondaryButton.setOnClickListener( + secondaryButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { @@ -95,13 +95,13 @@ public class PhoneFavoriteSquareTileView extends PhoneFavoriteTileView { } }); } - mContactEntry = entry; + contactEntry = entry; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = MeasureSpec.getSize(widthMeasureSpec); - final int height = (int) (mHeightToWidthRatio * width); + final int height = (int) (heightToWidthRatio * width); final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i) @@ -118,6 +118,6 @@ public class PhoneFavoriteSquareTileView extends PhoneFavoriteTileView { } public ContactEntry getContactEntry() { - return mContactEntry; + return contactEntry; } } diff --git a/java/com/android/dialer/app/list/PhoneFavoriteTileView.java b/java/com/android/dialer/app/list/PhoneFavoriteTileView.java index e0961be4b..3b27d3118 100644 --- a/java/com/android/dialer/app/list/PhoneFavoriteTileView.java +++ b/java/com/android/dialer/app/list/PhoneFavoriteTileView.java @@ -60,9 +60,10 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { // don't crash with an NPE if the drag shadow is released in their bounds private static final ClipData EMPTY_CLIP_DATA = ClipData.newPlainText("", ""); /** View that contains the transparent shadow that is overlaid on top of the contact image. */ - private View mShadowOverlay; + private View shadowOverlay; /** Users' most frequent phone number. */ - private String mPhoneNumberString; + private String phoneNumberString; + private boolean isPinned; private boolean isStarred; private int position = -1; @@ -74,7 +75,7 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { @Override protected void onFinishInflate() { super.onFinishInflate(); - mShadowOverlay = findViewById(R.id.shadow_overlay); + shadowOverlay = findViewById(R.id.shadow_overlay); setOnLongClickListener( new OnLongClickListener() { @@ -93,13 +94,13 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { public void loadFromContact(ContactEntry entry) { super.loadFromContact(entry); // Set phone number to null in case we're reusing the view. - mPhoneNumberString = null; + phoneNumberString = null; isPinned = (entry.pinned != PinnedPositions.UNPINNED); isStarred = entry.isFavorite; if (entry != null) { sendViewNotification(getContext(), entry.lookupUri); // Grab the phone-number to call directly. See {@link onClick()}. - mPhoneNumberString = entry.phoneNumber; + phoneNumberString = entry.phoneNumber; // If this is a blank entry, don't show anything. For this to truly look like an empty row // the entire ContactTileRow needs to be hidden. @@ -141,7 +142,7 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { callSpecificAppData.addSpeedDialContactType(SpeedDialContactType.Type.PINNED_CONTACT); } - if (TextUtils.isEmpty(mPhoneNumberString)) { + if (TextUtils.isEmpty(phoneNumberString)) { // Don't set performance report now, since user may spend some time on picking a number // Copy "superclass" implementation @@ -156,7 +157,7 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { // call them at the number that you usually talk to them // at (i.e. the one displayed in the UI), regardless of // whether that's their default number. - mListener.onCallNumberDirectly(mPhoneNumberString, callSpecificAppData.build()); + mListener.onCallNumberDirectly(phoneNumberString, callSpecificAppData.build()); } } }; @@ -176,8 +177,8 @@ public abstract class PhoneFavoriteTileView extends ContactTileView { @Override protected void configureViewForImage(boolean isDefaultImage) { // Hide the shadow overlay if the image is a default image (i.e. colored letter tile) - if (mShadowOverlay != null) { - mShadowOverlay.setVisibility(isDefaultImage ? View.GONE : View.VISIBLE); + if (shadowOverlay != null) { + shadowOverlay.setVisibility(isDefaultImage ? View.GONE : View.VISIBLE); } } diff --git a/java/com/android/dialer/app/list/PhoneFavoritesTileAdapter.java b/java/com/android/dialer/app/list/PhoneFavoritesTileAdapter.java index cd5843c85..ed64f7a52 100644 --- a/java/com/android/dialer/app/list/PhoneFavoritesTileAdapter.java +++ b/java/com/android/dialer/app/list/PhoneFavoritesTileAdapter.java @@ -68,17 +68,17 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop */ private static final int TILES_SOFT_LIMIT = 20; /** Contact data stored in cache. This is used to populate the associated view. */ - private ArrayList mContactEntries = null; + private ArrayList contactEntries = null; - private int mNumFrequents; - private int mNumStarred; + private int numFrequents; + private int numStarred; - private ContactTileView.Listener mListener; - private OnDataSetChangedForAnimationListener mDataSetChangedListener; - private Context mContext; - private Resources mResources; - private ContactsPreferences mContactsPreferences; - private final Comparator mContactEntryComparator = + private ContactTileView.Listener listener; + private OnDataSetChangedForAnimationListener dataSetChangedListener; + private Context context; + private Resources resources; + private ContactsPreferences contactsPreferences; + private final Comparator contactEntryComparator = new Comparator() { @Override public int compare(ContactEntry lhs, ContactEntry rhs) { @@ -89,7 +89,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop } private String getPreferredSortName(ContactEntry contactEntry) { - if (mContactsPreferences.getSortOrder() == ContactsPreferences.SORT_ORDER_PRIMARY + if (contactsPreferences.getSortOrder() == ContactsPreferences.SORT_ORDER_PRIMARY || TextUtils.isEmpty(contactEntry.nameAlternative)) { return contactEntry.namePrimary; } @@ -97,36 +97,36 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop } }; /** Back up of the temporarily removed Contact during dragging. */ - private ContactEntry mDraggedEntry = null; + private ContactEntry draggedEntry = null; /** Position of the temporarily removed contact in the cache. */ - private int mDraggedEntryIndex = -1; + private int draggedEntryIndex = -1; /** New position of the temporarily removed contact in the cache. */ - private int mDropEntryIndex = -1; + private int dropEntryIndex = -1; /** New position of the temporarily entered contact in the cache. */ - private int mDragEnteredEntryIndex = -1; + private int dragEnteredEntryIndex = -1; - private boolean mAwaitingRemove = false; - private boolean mDelayCursorUpdates = false; - private ContactPhotoManager mPhotoManager; + private boolean awaitingRemove = false; + private boolean delayCursorUpdates = false; + private ContactPhotoManager photoManager; /** Indicates whether a drag is in process. */ - private boolean mInDragging = false; + private boolean inDragging = false; public PhoneFavoritesTileAdapter( Context context, ContactTileView.Listener listener, OnDataSetChangedForAnimationListener dataSetChangedListener) { - mDataSetChangedListener = dataSetChangedListener; - mListener = listener; - mContext = context; - mResources = context.getResources(); - mContactsPreferences = new ContactsPreferences(mContext); - mNumFrequents = 0; - mContactEntries = new ArrayList<>(); + this.dataSetChangedListener = dataSetChangedListener; + this.listener = listener; + this.context = context; + resources = context.getResources(); + contactsPreferences = new ContactsPreferences(this.context); + numFrequents = 0; + contactEntries = new ArrayList<>(); } void setPhotoLoader(ContactPhotoManager photoLoader) { - mPhotoManager = photoLoader; + photoManager = photoLoader; } /** @@ -135,13 +135,13 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop * @param inDragging Boolean variable indicating whether there is a drag in process. */ private void setInDragging(boolean inDragging) { - mDelayCursorUpdates = inDragging; - mInDragging = inDragging; + delayCursorUpdates = inDragging; + this.inDragging = inDragging; } void refreshContactsPreferences() { - mContactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); - mContactsPreferences.refreshValue(ContactsPreferences.SORT_ORDER_KEY); + contactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); + contactsPreferences.refreshValue(ContactsPreferences.SORT_ORDER_KEY); } /** @@ -152,7 +152,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop * @param cursor The cursor to get number of frequents from. */ private void saveNumFrequentsFromCursor(Cursor cursor) { - mNumFrequents = cursor.getCount() - mNumStarred; + numFrequents = cursor.getCount() - numStarred; } /** @@ -161,10 +161,10 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop *

Else use {@link ContactTileLoaderFactory} */ void setContactCursor(Cursor cursor) { - if (!mDelayCursorUpdates && cursor != null && !cursor.isClosed()) { - mNumStarred = getNumStarredContacts(cursor); - if (mAwaitingRemove) { - mDataSetChangedListener.cacheOffsetsForDatasetChange(); + if (!delayCursorUpdates && cursor != null && !cursor.isClosed()) { + numStarred = getNumStarredContacts(cursor); + if (awaitingRemove) { + dataSetChangedListener.cacheOffsetsForDatasetChange(); } saveNumFrequentsFromCursor(cursor); @@ -172,7 +172,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop // cause a refresh of any views that rely on this data notifyDataSetChanged(); // about to start redraw - mDataSetChangedListener.onDataSetChangedForAnimation(); + dataSetChangedListener.onDataSetChangedForAnimation(); } } @@ -183,7 +183,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop * view. */ private void saveCursorToCache(Cursor cursor) { - mContactEntries.clear(); + contactEntries.clear(); if (cursor == null) { return; @@ -250,12 +250,12 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop contact.id = id; contact.namePrimary = - (!TextUtils.isEmpty(name)) ? name : mResources.getString(R.string.missing_name); + (!TextUtils.isEmpty(name)) ? name : resources.getString(R.string.missing_name); contact.nameAlternative = (!TextUtils.isEmpty(nameAlternative)) ? nameAlternative - : mResources.getString(R.string.missing_name); - contact.nameDisplayOrder = mContactsPreferences.getDisplayOrder(); + : resources.getString(R.string.missing_name); + contact.nameDisplayOrder = contactsPreferences.getDisplayOrder(); contact.photoUri = (photoUri != null ? Uri.parse(photoUri) : null); contact.lookupKey = lookupKey; contact.lookupUri = @@ -268,11 +268,11 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop final int phoneNumberType = cursor.getInt(phoneTypeColumn); final String phoneNumberCustomLabel = cursor.getString(phoneLabelColumn); contact.phoneLabel = - (String) Phone.getTypeLabel(mResources, phoneNumberType, phoneNumberCustomLabel); + (String) Phone.getTypeLabel(resources, phoneNumberType, phoneNumberCustomLabel); contact.phoneNumber = cursor.getString(phoneNumberColumn); contact.pinned = pinned; - mContactEntries.add(contact); + contactEntries.add(contact); // Set counts for logging if (isStarred) { @@ -296,23 +296,23 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop } while (cursor.moveToNext()); } - mAwaitingRemove = false; + awaitingRemove = false; - arrangeContactsByPinnedPosition(mContactEntries); + arrangeContactsByPinnedPosition(contactEntries); - ShortcutRefresher.refresh(mContext, mContactEntries); + ShortcutRefresher.refresh(context, contactEntries); notifyDataSetChanged(); - Duo duo = DuoComponent.get(mContext).getDuo(); - for (ContactEntry contact : mContactEntries) { + Duo duo = DuoComponent.get(context).getDuo(); + for (ContactEntry contact : contactEntries) { if (contact.phoneNumber == null) { multipleNumbersContactsCount++; - } else if (duo.isReachable(mContext, contact.phoneNumber)) { + } else if (duo.isReachable(context, contact.phoneNumber)) { lightbringerReachableContactsCount++; } } - Logger.get(mContext) + Logger.get(context) .logSpeedDialContactComposition( counter, starredContactsCount, @@ -366,16 +366,16 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop /** Returns the number of frequents that will be displayed in the list. */ int getNumFrequents() { - return mNumFrequents; + return numFrequents; } @Override public int getCount() { - if (mContactEntries == null) { + if (contactEntries == null) { return 0; } - return mContactEntries.size(); + return contactEntries.size(); } /** @@ -384,7 +384,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop */ @Override public ContactEntry getItem(int position) { - return mContactEntries.get(position); + return contactEntries.get(position); } /** @@ -435,10 +435,10 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop if (tileView == null) { tileView = - (PhoneFavoriteTileView) View.inflate(mContext, R.layout.phone_favorite_tile_view, null); + (PhoneFavoriteTileView) View.inflate(context, R.layout.phone_favorite_tile_view, null); } - tileView.setPhotoManager(mPhotoManager); - tileView.setListener(mListener); + tileView.setPhotoManager(photoManager); + tileView.setListener(listener); tileView.loadFromContact(getItem(position)); tileView.setPosition(position); return tileView; @@ -462,37 +462,37 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop */ private void popContactEntry(int index) { if (isIndexInBound(index)) { - mDraggedEntry = mContactEntries.get(index); - mDraggedEntryIndex = index; - mDragEnteredEntryIndex = index; - markDropArea(mDragEnteredEntryIndex); + draggedEntry = contactEntries.get(index); + draggedEntryIndex = index; + dragEnteredEntryIndex = index; + markDropArea(dragEnteredEntryIndex); } } /** - * @param itemIndex Position of the contact in {@link #mContactEntries}. - * @return True if the given index is valid for {@link #mContactEntries}. + * @param itemIndex Position of the contact in {@link #contactEntries}. + * @return True if the given index is valid for {@link #contactEntries}. */ boolean isIndexInBound(int itemIndex) { - return itemIndex >= 0 && itemIndex < mContactEntries.size(); + return itemIndex >= 0 && itemIndex < contactEntries.size(); } /** - * Mark the tile as drop area by given the item index in {@link #mContactEntries}. + * Mark the tile as drop area by given the item index in {@link #contactEntries}. * - * @param itemIndex Position of the contact in {@link #mContactEntries}. + * @param itemIndex Position of the contact in {@link #contactEntries}. */ private void markDropArea(int itemIndex) { - if (mDraggedEntry != null - && isIndexInBound(mDragEnteredEntryIndex) + if (draggedEntry != null + && isIndexInBound(dragEnteredEntryIndex) && isIndexInBound(itemIndex)) { - mDataSetChangedListener.cacheOffsetsForDatasetChange(); + dataSetChangedListener.cacheOffsetsForDatasetChange(); // Remove the old placeholder item and place the new placeholder item. - mContactEntries.remove(mDragEnteredEntryIndex); - mDragEnteredEntryIndex = itemIndex; - mContactEntries.add(mDragEnteredEntryIndex, ContactEntry.BLANK_ENTRY); - ContactEntry.BLANK_ENTRY.id = mDraggedEntry.id; - mDataSetChangedListener.onDataSetChangedForAnimation(); + contactEntries.remove(dragEnteredEntryIndex); + dragEnteredEntryIndex = itemIndex; + contactEntries.add(dragEnteredEntryIndex, ContactEntry.BLANK_ENTRY); + ContactEntry.BLANK_ENTRY.id = draggedEntry.id; + dataSetChangedListener.onDataSetChangedForAnimation(); notifyDataSetChanged(); } } @@ -500,38 +500,38 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop /** Drops the temporarily removed contact to the desired location in the list. */ private void handleDrop() { boolean changed = false; - if (mDraggedEntry != null) { - if (isIndexInBound(mDragEnteredEntryIndex) && mDragEnteredEntryIndex != mDraggedEntryIndex) { + if (draggedEntry != null) { + if (isIndexInBound(dragEnteredEntryIndex) && dragEnteredEntryIndex != draggedEntryIndex) { // Don't add the ContactEntry here (to prevent a double animation from occuring). // When we receive a new cursor the list of contact entries will automatically be // populated with the dragged ContactEntry at the correct spot. - mDropEntryIndex = mDragEnteredEntryIndex; - mContactEntries.set(mDropEntryIndex, mDraggedEntry); - mDataSetChangedListener.cacheOffsetsForDatasetChange(); + dropEntryIndex = dragEnteredEntryIndex; + contactEntries.set(dropEntryIndex, draggedEntry); + dataSetChangedListener.cacheOffsetsForDatasetChange(); changed = true; - } else if (isIndexInBound(mDraggedEntryIndex)) { + } else if (isIndexInBound(draggedEntryIndex)) { // If {@link #mDragEnteredEntryIndex} is invalid, // falls back to the original position of the contact. - mContactEntries.remove(mDragEnteredEntryIndex); - mContactEntries.add(mDraggedEntryIndex, mDraggedEntry); - mDropEntryIndex = mDraggedEntryIndex; + contactEntries.remove(dragEnteredEntryIndex); + contactEntries.add(draggedEntryIndex, draggedEntry); + dropEntryIndex = draggedEntryIndex; notifyDataSetChanged(); } - if (changed && mDropEntryIndex < PIN_LIMIT) { + if (changed && dropEntryIndex < PIN_LIMIT) { final ArrayList operations = - getReflowedPinningOperations(mContactEntries, mDraggedEntryIndex, mDropEntryIndex); + getReflowedPinningOperations(contactEntries, draggedEntryIndex, dropEntryIndex); if (!operations.isEmpty()) { // update the database here with the new pinned positions try { - mContext.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations); - Logger.get(mContext).logInteraction(InteractionEvent.Type.SPEED_DIAL_PIN_CONTACT); + context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations); + Logger.get(context).logInteraction(InteractionEvent.Type.SPEED_DIAL_PIN_CONTACT); } catch (RemoteException | OperationApplicationException e) { LogUtil.e(TAG, "Exception thrown when pinning contacts", e); } } } - mDraggedEntry = null; + draggedEntry = null; } } @@ -543,7 +543,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop final ContentValues values = new ContentValues(2); values.put(Contacts.STARRED, false); values.put(Contacts.PINNED, PinnedPositions.DEMOTED); - mContext.getContentResolver().update(contactUri, values, null, null); + context.getContentResolver().update(contactUri, values, null, null); } /** @@ -559,7 +559,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop @VisibleForTesting private void arrangeContactsByPinnedPosition(ArrayList toArrange) { final PriorityQueue pinnedQueue = - new PriorityQueue<>(PIN_LIMIT, mContactEntryComparator); + new PriorityQueue<>(PIN_LIMIT, contactEntryComparator); final List unpinnedContacts = new LinkedList<>(); @@ -643,7 +643,7 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop @Override public void onDragStarted(int x, int y, PhoneFavoriteSquareTileView view) { setInDragging(true); - final int itemIndex = mContactEntries.indexOf(view.getContactEntry()); + final int itemIndex = contactEntries.indexOf(view.getContactEntry()); popContactEntry(itemIndex); } @@ -654,9 +654,9 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop // anything here. return; } - final int itemIndex = mContactEntries.indexOf(view.getContactEntry()); - if (mInDragging - && mDragEnteredEntryIndex != itemIndex + final int itemIndex = contactEntries.indexOf(view.getContactEntry()); + if (inDragging + && dragEnteredEntryIndex != itemIndex && isIndexInBound(itemIndex) && itemIndex < PIN_LIMIT && itemIndex >= 0) { @@ -670,17 +670,17 @@ public class PhoneFavoritesTileAdapter extends BaseAdapter implements OnDragDrop // A contact has been dragged to the RemoveView in order to be unstarred, so simply wait // for the new contact cursor which will cause the UI to be refreshed without the unstarred // contact. - if (!mAwaitingRemove) { + if (!awaitingRemove) { handleDrop(); } } @Override public void onDroppedOnRemove() { - if (mDraggedEntry != null) { - unstarAndUnpinContact(mDraggedEntry.lookupUri); - mAwaitingRemove = true; - Logger.get(mContext).logInteraction(InteractionEvent.Type.SPEED_DIAL_REMOVE_CONTACT); + if (draggedEntry != null) { + unstarAndUnpinContact(draggedEntry.lookupUri); + awaitingRemove = true; + Logger.get(context).logInteraction(InteractionEvent.Type.SPEED_DIAL_REMOVE_CONTACT); } } diff --git a/java/com/android/dialer/app/list/RegularSearchFragment.java b/java/com/android/dialer/app/list/RegularSearchFragment.java index 48f77dcdc..d1927f08a 100644 --- a/java/com/android/dialer/app/list/RegularSearchFragment.java +++ b/java/com/android/dialer/app/list/RegularSearchFragment.java @@ -48,7 +48,7 @@ public class RegularSearchFragment extends SearchFragment public static final int PERMISSION_REQUEST_CODE = 1; private static final int SEARCH_DIRECTORY_RESULT_LIMIT = 5; - protected String mPermissionToRequest; + protected String permissionToRequest; private DialerExecutor addContactTask; @@ -104,7 +104,7 @@ public class RegularSearchFragment extends SearchFragment @Override protected void setupEmptyView() { - if (mEmptyView != null && getActivity() != null) { + if (emptyView != null && getActivity() != null) { final int imageResource; final int actionLabelResource; final int descriptionResource; @@ -114,20 +114,20 @@ public class RegularSearchFragment extends SearchFragment actionLabelResource = R.string.permission_single_turn_on; descriptionResource = R.string.permission_no_search; listener = this; - mPermissionToRequest = READ_CONTACTS; + permissionToRequest = READ_CONTACTS; } else { imageResource = EmptyContentView.NO_IMAGE; actionLabelResource = EmptyContentView.NO_LABEL; descriptionResource = EmptyContentView.NO_LABEL; listener = null; - mPermissionToRequest = null; + permissionToRequest = null; } - mEmptyView.setImage(imageResource); - mEmptyView.setActionLabel(actionLabelResource); - mEmptyView.setDescription(descriptionResource); + emptyView.setImage(imageResource); + emptyView.setActionLabel(actionLabelResource); + emptyView.setDescription(descriptionResource); if (listener != null) { - mEmptyView.setActionClickedListener(listener); + emptyView.setActionClickedListener(listener); } } } @@ -139,7 +139,7 @@ public class RegularSearchFragment extends SearchFragment return; } - if (READ_CONTACTS.equals(mPermissionToRequest)) { + if (READ_CONTACTS.equals(permissionToRequest)) { String[] deniedPermissions = PermissionsUtil.getPermissionsCurrentlyDenied( getContext(), PermissionsUtil.allContactsGroupPermissionsUsedInDialer); diff --git a/java/com/android/dialer/app/list/RegularSearchListAdapter.java b/java/com/android/dialer/app/list/RegularSearchListAdapter.java index 94544d2db..aee68ae58 100644 --- a/java/com/android/dialer/app/list/RegularSearchListAdapter.java +++ b/java/com/android/dialer/app/list/RegularSearchListAdapter.java @@ -31,7 +31,7 @@ import com.android.dialer.util.CallUtil; /** List adapter to display regular search results. */ public class RegularSearchListAdapter extends DialerPhoneNumberListAdapter { - protected boolean mIsQuerySipAddress; + protected boolean isQuerySipAddress; public RegularSearchListAdapter(Context context) { super(context); @@ -82,7 +82,7 @@ public class RegularSearchListAdapter extends DialerPhoneNumberListAdapter { @Override public String getFormattedQueryString() { - if (mIsQuerySipAddress) { + if (isQuerySipAddress) { // Return unnormalized SIP address return getQueryString(); } @@ -94,7 +94,7 @@ public class RegularSearchListAdapter extends DialerPhoneNumberListAdapter { // Don't show actions if the query string contains a letter. final boolean showNumberShortcuts = !TextUtils.isEmpty(getFormattedQueryString()) && hasDigitsInQueryString(); - mIsQuerySipAddress = PhoneNumberHelper.isUriNumber(queryString); + isQuerySipAddress = PhoneNumberHelper.isUriNumber(queryString); if (isChanged(showNumberShortcuts)) { notifyDataSetChanged(); @@ -104,7 +104,7 @@ public class RegularSearchListAdapter extends DialerPhoneNumberListAdapter { protected boolean isChanged(boolean showNumberShortcuts) { boolean changed = false; - changed |= setShortcutEnabled(SHORTCUT_DIRECT_CALL, showNumberShortcuts || mIsQuerySipAddress); + changed |= setShortcutEnabled(SHORTCUT_DIRECT_CALL, showNumberShortcuts || isQuerySipAddress); changed |= setShortcutEnabled(SHORTCUT_SEND_SMS_MESSAGE, showNumberShortcuts); changed |= setShortcutEnabled( diff --git a/java/com/android/dialer/app/list/RemoveView.java b/java/com/android/dialer/app/list/RemoveView.java index 244f2da24..ed133d45b 100644 --- a/java/com/android/dialer/app/list/RemoveView.java +++ b/java/com/android/dialer/app/list/RemoveView.java @@ -29,12 +29,12 @@ import com.android.dialer.app.R; public class RemoveView extends FrameLayout { - DragDropController mDragDropController; - TextView mRemoveText; - ImageView mRemoveIcon; - int mUnhighlightedColor; - int mHighlightedColor; - Drawable mRemoveDrawable; + DragDropController dragDropController; + TextView removeText; + ImageView removeIcon; + int unhighlightedColor; + int highlightedColor; + Drawable removeDrawable; public RemoveView(Context context) { super(context); @@ -50,16 +50,16 @@ public class RemoveView extends FrameLayout { @Override protected void onFinishInflate() { - mRemoveText = (TextView) findViewById(R.id.remove_view_text); - mRemoveIcon = (ImageView) findViewById(R.id.remove_view_icon); + removeText = (TextView) findViewById(R.id.remove_view_text); + removeIcon = (ImageView) findViewById(R.id.remove_view_icon); final Resources r = getResources(); - mUnhighlightedColor = r.getColor(R.color.remove_text_color); - mHighlightedColor = r.getColor(R.color.remove_highlighted_text_color); - mRemoveDrawable = r.getDrawable(R.drawable.ic_remove); + unhighlightedColor = r.getColor(R.color.remove_text_color); + highlightedColor = r.getColor(R.color.remove_highlighted_text_color); + removeDrawable = r.getDrawable(R.drawable.ic_remove); } public void setDragDropController(DragDropController controller) { - mDragDropController = controller; + dragDropController = controller; } @Override @@ -76,14 +76,14 @@ public class RemoveView extends FrameLayout { setAppearanceNormal(); break; case DragEvent.ACTION_DRAG_LOCATION: - if (mDragDropController != null) { - mDragDropController.handleDragHovered(this, (int) event.getX(), (int) event.getY()); + if (dragDropController != null) { + dragDropController.handleDragHovered(this, (int) event.getX(), (int) event.getY()); } break; case DragEvent.ACTION_DROP: sendAccessibilityEvent(AccessibilityEvent.TYPE_ANNOUNCEMENT); - if (mDragDropController != null) { - mDragDropController.handleDragFinished((int) event.getX(), (int) event.getY(), true); + if (dragDropController != null) { + dragDropController.handleDragFinished((int) event.getX(), (int) event.getY(), true); } setAppearanceNormal(); break; @@ -92,14 +92,14 @@ public class RemoveView extends FrameLayout { } private void setAppearanceNormal() { - mRemoveText.setTextColor(mUnhighlightedColor); - mRemoveIcon.setColorFilter(mUnhighlightedColor); + removeText.setTextColor(unhighlightedColor); + removeIcon.setColorFilter(unhighlightedColor); invalidate(); } private void setAppearanceHighlighted() { - mRemoveText.setTextColor(mHighlightedColor); - mRemoveIcon.setColorFilter(mHighlightedColor); + removeText.setTextColor(highlightedColor); + removeIcon.setColorFilter(highlightedColor); invalidate(); } } diff --git a/java/com/android/dialer/app/list/SearchFragment.java b/java/com/android/dialer/app/list/SearchFragment.java index 9330fc8c7..afb678969 100644 --- a/java/com/android/dialer/app/list/SearchFragment.java +++ b/java/com/android/dialer/app/list/SearchFragment.java @@ -51,28 +51,28 @@ import com.android.dialer.widget.EmptyContentView; public class SearchFragment extends PhoneNumberPickerFragment { - protected EmptyContentView mEmptyView; - private OnListFragmentScrolledListener mActivityScrollListener; - private View.OnTouchListener mActivityOnTouchListener; + protected EmptyContentView emptyView; + private OnListFragmentScrolledListener activityScrollListener; + private View.OnTouchListener activityOnTouchListener; /* * Stores the untouched user-entered string that is used to populate the add to contacts * intent. */ - private String mAddToContactNumber; - private int mActionBarHeight; - private int mShadowHeight; - private int mPaddingTop; - private int mShowDialpadDuration; - private int mHideDialpadDuration; + private String addToContactNumber; + private int actionBarHeight; + private int shadowHeight; + private int paddingTop; + private int showDialpadDuration; + private int hideDialpadDuration; /** * Used to resize the list view containing search results so that it fits the available space * above the dialpad. Does not have a user-visible effect in regular touch usage (since the * dialpad hides that portion of the ListView anyway), but improves usability in accessibility * mode. */ - private Space mSpacer; + private Space spacer; - private HostInterface mActivity; + private HostInterface activity; @Override public void onAttach(Activity activity) { @@ -84,7 +84,7 @@ public class SearchFragment extends PhoneNumberPickerFragment { setUseCallableUri(true); try { - mActivityScrollListener = (OnListFragmentScrolledListener) activity; + activityScrollListener = (OnListFragmentScrolledListener) activity; } catch (ClassCastException e) { LogUtil.v( "SearchFragment.onAttach", @@ -99,25 +99,25 @@ public class SearchFragment extends PhoneNumberPickerFragment { LogUtil.d("SearchFragment.onStart", ""); super.onStart(); - mActivity = (HostInterface) getActivity(); + activity = (HostInterface) getActivity(); final Resources res = getResources(); - mActionBarHeight = mActivity.getActionBarHeight(); - mShadowHeight = res.getDrawable(R.drawable.search_shadow).getIntrinsicHeight(); - mPaddingTop = res.getDimensionPixelSize(R.dimen.search_list_padding_top); - mShowDialpadDuration = res.getInteger(R.integer.dialpad_slide_in_duration); - mHideDialpadDuration = res.getInteger(R.integer.dialpad_slide_out_duration); + actionBarHeight = activity.getActionBarHeight(); + shadowHeight = res.getDrawable(R.drawable.search_shadow).getIntrinsicHeight(); + paddingTop = res.getDimensionPixelSize(R.dimen.search_list_padding_top); + showDialpadDuration = res.getInteger(R.integer.dialpad_slide_in_duration); + hideDialpadDuration = res.getInteger(R.integer.dialpad_slide_out_duration); final ListView listView = getListView(); - if (mEmptyView == null) { + if (emptyView == null) { if (this instanceof SmartDialSearchFragment) { - mEmptyView = new DialpadSearchEmptyContentView(getActivity()); + emptyView = new DialpadSearchEmptyContentView(getActivity()); } else { - mEmptyView = new EmptyContentView(getActivity()); + emptyView = new EmptyContentView(getActivity()); } - ((ViewGroup) getListView().getParent()).addView(mEmptyView); - getListView().setEmptyView(mEmptyView); + ((ViewGroup) getListView().getParent()).addView(emptyView); + getListView().setEmptyView(emptyView); setupEmptyView(); } @@ -133,8 +133,8 @@ public class SearchFragment extends PhoneNumberPickerFragment { new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { - if (mActivityScrollListener != null) { - mActivityScrollListener.onListFragmentScrollStateChange(scrollState); + if (activityScrollListener != null) { + activityScrollListener.onListFragmentScrollStateChange(scrollState); } } @@ -142,8 +142,8 @@ public class SearchFragment extends PhoneNumberPickerFragment { public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {} }); - if (mActivityOnTouchListener != null) { - listView.setOnTouchListener(mActivityOnTouchListener); + if (activityOnTouchListener != null) { + listView.setOnTouchListener(activityOnTouchListener); } updatePosition(false /* animate */); @@ -170,7 +170,7 @@ public class SearchFragment extends PhoneNumberPickerFragment { } public void setAddToContactNumber(String addToContactNumber) { - mAddToContactNumber = addToContactNumber; + this.addToContactNumber = addToContactNumber; } /** @@ -241,9 +241,9 @@ public class SearchFragment extends PhoneNumberPickerFragment { .logImpression(DialerImpression.Type.CREATE_NEW_CONTACT_FROM_DIALPAD); } number = - TextUtils.isEmpty(mAddToContactNumber) + TextUtils.isEmpty(addToContactNumber) ? adapter.getFormattedQueryString() - : mAddToContactNumber; + : addToContactNumber; intent = IntentUtil.getNewContactIntent(number); DialerUtils.startActivityWithErrorToast(getActivity(), intent); break; @@ -253,24 +253,24 @@ public class SearchFragment extends PhoneNumberPickerFragment { .logImpression(DialerImpression.Type.ADD_TO_A_CONTACT_FROM_DIALPAD); } number = - TextUtils.isEmpty(mAddToContactNumber) + TextUtils.isEmpty(addToContactNumber) ? adapter.getFormattedQueryString() - : mAddToContactNumber; + : addToContactNumber; intent = IntentUtil.getAddToExistingContactIntent(number); DialerUtils.startActivityWithErrorToast( getActivity(), intent, R.string.add_contact_not_available); break; case DialerPhoneNumberListAdapter.SHORTCUT_SEND_SMS_MESSAGE: number = - TextUtils.isEmpty(mAddToContactNumber) + TextUtils.isEmpty(addToContactNumber) ? adapter.getFormattedQueryString() - : mAddToContactNumber; + : addToContactNumber; intent = IntentUtil.getSendSmsIntent(number); DialerUtils.startActivityWithErrorToast(getActivity(), intent); break; case DialerPhoneNumberListAdapter.SHORTCUT_MAKE_VIDEO_CALL: number = - TextUtils.isEmpty(mAddToContactNumber) ? adapter.getQueryString() : mAddToContactNumber; + TextUtils.isEmpty(addToContactNumber) ? adapter.getQueryString() : addToContactNumber; listener = getOnPhoneNumberPickerListener(); if (listener != null && !checkForProhibitedPhoneNumber(number)) { CallSpecificAppData callSpecificAppData = @@ -296,25 +296,25 @@ public class SearchFragment extends PhoneNumberPickerFragment { */ public void updatePosition(boolean animate) { LogUtil.d("SearchFragment.updatePosition", "animate: %b", animate); - if (mActivity == null) { + if (activity == null) { // Activity will be set in onStart, and this method will be called again return; } // Use negative shadow height instead of 0 to account for the 9-patch's shadow. int startTranslationValue = - mActivity.isDialpadShown() ? mActionBarHeight - mShadowHeight : -mShadowHeight; + activity.isDialpadShown() ? actionBarHeight - shadowHeight : -shadowHeight; int endTranslationValue = 0; // Prevents ListView from being translated down after a rotation when the ActionBar is up. - if (animate || mActivity.isActionBarShowing()) { - endTranslationValue = mActivity.isDialpadShown() ? 0 : mActionBarHeight - mShadowHeight; + if (animate || activity.isActionBarShowing()) { + endTranslationValue = activity.isDialpadShown() ? 0 : actionBarHeight - shadowHeight; } if (animate) { // If the dialpad will be shown, then this animation involves sliding the list up. - final boolean slideUp = mActivity.isDialpadShown(); + final boolean slideUp = activity.isDialpadShown(); Interpolator interpolator = slideUp ? AnimUtils.EASE_IN : AnimUtils.EASE_OUT; - int duration = slideUp ? mShowDialpadDuration : mHideDialpadDuration; + int duration = slideUp ? showDialpadDuration : hideDialpadDuration; getView().setTranslationY(startTranslationValue); getView() .animate() @@ -344,7 +344,7 @@ public class SearchFragment extends PhoneNumberPickerFragment { } // There is padding which should only be applied when the dialpad is not shown. - int paddingTop = mActivity.isDialpadShown() ? 0 : mPaddingTop; + int paddingTop = activity.isDialpadShown() ? 0 : this.paddingTop; final ListView listView = getListView(); listView.setPaddingRelative( listView.getPaddingStart(), @@ -354,21 +354,21 @@ public class SearchFragment extends PhoneNumberPickerFragment { } public void resizeListView() { - if (mSpacer == null) { + if (spacer == null) { return; } - int spacerHeight = mActivity.isDialpadShown() ? mActivity.getDialpadHeight() : 0; + int spacerHeight = activity.isDialpadShown() ? activity.getDialpadHeight() : 0; LogUtil.d( "SearchFragment.resizeListView", "spacerHeight: %d -> %d, isDialpadShown: %b, dialpad height: %d", - mSpacer.getHeight(), + spacer.getHeight(), spacerHeight, - mActivity.isDialpadShown(), - mActivity.getDialpadHeight()); - if (spacerHeight != mSpacer.getHeight()) { - final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mSpacer.getLayoutParams(); + activity.isDialpadShown(), + activity.getDialpadHeight()); + if (spacerHeight != spacer.getHeight()) { + final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) spacer.getLayoutParams(); lp.height = spacerHeight; - mSpacer.setLayoutParams(lp); + spacer.setLayoutParams(lp); } } @@ -395,7 +395,7 @@ public class SearchFragment extends PhoneNumberPickerFragment { } public void setOnTouchListener(View.OnTouchListener onTouchListener) { - mActivityOnTouchListener = onTouchListener; + activityOnTouchListener = onTouchListener; } @Override @@ -403,9 +403,9 @@ public class SearchFragment extends PhoneNumberPickerFragment { final LinearLayout parent = (LinearLayout) super.inflateView(inflater, container); final int orientation = getResources().getConfiguration().orientation; if (orientation == Configuration.ORIENTATION_PORTRAIT) { - mSpacer = new Space(getActivity()); + spacer = new Space(getActivity()); parent.addView( - mSpacer, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0)); + spacer, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0)); } return parent; } diff --git a/java/com/android/dialer/app/list/SmartDialNumberListAdapter.java b/java/com/android/dialer/app/list/SmartDialNumberListAdapter.java index 1d2cda3ea..c84bff7fc 100644 --- a/java/com/android/dialer/app/list/SmartDialNumberListAdapter.java +++ b/java/com/android/dialer/app/list/SmartDialNumberListAdapter.java @@ -34,13 +34,13 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { private static final String TAG = SmartDialNumberListAdapter.class.getSimpleName(); private static final boolean DEBUG = false; - private final Context mContext; - @NonNull private final SmartDialNameMatcher mNameMatcher; + private final Context context; + @NonNull private final SmartDialNameMatcher nameMatcher; public SmartDialNumberListAdapter(Context context) { super(context); - mContext = context; - mNameMatcher = new SmartDialNameMatcher(""); + this.context = context; + nameMatcher = new SmartDialNameMatcher(""); setShortcutEnabled(SmartDialNumberListAdapter.SHORTCUT_DIRECT_CALL, false); if (DEBUG) { @@ -56,10 +56,10 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { if (getQueryString() == null) { loader.configureQuery(""); - mNameMatcher.setQuery(""); + nameMatcher.setQuery(""); } else { loader.configureQuery(getQueryString()); - mNameMatcher.setQuery(PhoneNumberUtils.normalizeNumber(getQueryString())); + nameMatcher.setQuery(PhoneNumberUtils.normalizeNumber(getQueryString())); } } @@ -73,8 +73,8 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { protected void setHighlight(ContactListItemView view, Cursor cursor) { view.clearHighlightSequences(); - if (mNameMatcher.matches(mContext, cursor.getString(PhoneQuery.DISPLAY_NAME))) { - final ArrayList nameMatches = mNameMatcher.getMatchPositions(); + if (nameMatcher.matches(context, cursor.getString(PhoneQuery.DISPLAY_NAME))) { + final ArrayList nameMatches = nameMatcher.getMatchPositions(); for (SmartDialMatchPosition match : nameMatches) { view.addNameHighlightSequence(match.start, match.end); if (DEBUG) { @@ -82,7 +82,7 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { TAG, cursor.getString(PhoneQuery.DISPLAY_NAME) + " " - + mNameMatcher.getQuery() + + nameMatcher.getQuery() + " " + String.valueOf(match.start)); } @@ -90,7 +90,7 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { } final SmartDialMatchPosition numberMatch = - mNameMatcher.matchesNumber(mContext, cursor.getString(PhoneQuery.PHONE_NUMBER)); + nameMatcher.matchesNumber(context, cursor.getString(PhoneQuery.PHONE_NUMBER)); if (numberMatch != null) { view.addNumberHighlightSequence(numberMatch.start, numberMatch.end); } @@ -113,6 +113,6 @@ public class SmartDialNumberListAdapter extends DialerPhoneNumberListAdapter { } public void setShowEmptyListForNullQuery(boolean show) { - mNameMatcher.setShouldMatchEmptyQuery(!show); + nameMatcher.setShouldMatchEmptyQuery(!show); } } diff --git a/java/com/android/dialer/app/list/SmartDialSearchFragment.java b/java/com/android/dialer/app/list/SmartDialSearchFragment.java index 1a7f19515..fdf0b5a56 100644 --- a/java/com/android/dialer/app/list/SmartDialSearchFragment.java +++ b/java/com/android/dialer/app/list/SmartDialSearchFragment.java @@ -43,7 +43,7 @@ public class SmartDialSearchFragment extends SearchFragment private static final int CALL_PHONE_PERMISSION_REQUEST_CODE = 1; - private final BroadcastReceiver mSmartDialUpdatedReceiver = + private final BroadcastReceiver smartDialUpdatedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { @@ -87,16 +87,16 @@ public class SmartDialSearchFragment extends SearchFragment @Override protected void setupEmptyView() { - if (mEmptyView != null && getActivity() != null) { + if (emptyView != null && getActivity() != null) { if (!PermissionsUtil.hasPermission(getActivity(), CALL_PHONE)) { - mEmptyView.setImage(R.drawable.empty_contacts); - mEmptyView.setActionLabel(R.string.permission_single_turn_on); - mEmptyView.setDescription(R.string.permission_place_call); - mEmptyView.setActionClickedListener(this); + emptyView.setImage(R.drawable.empty_contacts); + emptyView.setActionLabel(R.string.permission_single_turn_on); + emptyView.setDescription(R.string.permission_place_call); + emptyView.setActionClickedListener(this); } else { - mEmptyView.setImage(EmptyContentView.NO_IMAGE); - mEmptyView.setActionLabel(EmptyContentView.NO_LABEL); - mEmptyView.setDescription(EmptyContentView.NO_LABEL); + emptyView.setImage(EmptyContentView.NO_IMAGE); + emptyView.setActionLabel(EmptyContentView.NO_LABEL); + emptyView.setDescription(EmptyContentView.NO_LABEL); } } } @@ -109,7 +109,7 @@ public class SmartDialSearchFragment extends SearchFragment getActivity() .registerReceiver( - mSmartDialUpdatedReceiver, + smartDialUpdatedReceiver, new IntentFilter(DialerDatabaseHelper.ACTION_SMART_DIAL_UPDATED)); } @@ -119,7 +119,7 @@ public class SmartDialSearchFragment extends SearchFragment LogUtil.i("SmartDialSearchFragment.onStop", "unregistering smart dial update receiver"); - getActivity().unregisterReceiver(mSmartDialUpdatedReceiver); + getActivity().unregisterReceiver(smartDialUpdatedReceiver); } @Override @@ -155,7 +155,7 @@ public class SmartDialSearchFragment extends SearchFragment } public boolean isShowingPermissionRequest() { - return mEmptyView != null && mEmptyView.isShowingContent(); + return emptyView != null && emptyView.isShowingContent(); } @Override diff --git a/java/com/android/dialer/app/settings/AppCompatPreferenceActivity.java b/java/com/android/dialer/app/settings/AppCompatPreferenceActivity.java index e8e425626..b2cb03ed3 100644 --- a/java/com/android/dialer/app/settings/AppCompatPreferenceActivity.java +++ b/java/com/android/dialer/app/settings/AppCompatPreferenceActivity.java @@ -30,16 +30,16 @@ import android.view.ViewGroup; */ public class AppCompatPreferenceActivity extends PreferenceActivity { - private AppCompatDelegate mDelegate; + private AppCompatDelegate delegate; - private boolean mIsSafeToCommitTransactions; + private boolean isSafeToCommitTransactions; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override @@ -113,28 +113,28 @@ public class AppCompatPreferenceActivity extends PreferenceActivity { } private AppCompatDelegate getDelegate() { - if (mDelegate == null) { - mDelegate = AppCompatDelegate.create(this, null); + if (delegate == null) { + delegate = AppCompatDelegate.create(this, null); } - return mDelegate; + return delegate; } @Override protected void onStart() { super.onStart(); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override protected void onResume() { super.onResume(); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - mIsSafeToCommitTransactions = false; + isSafeToCommitTransactions = false; } /** @@ -145,6 +145,6 @@ public class AppCompatPreferenceActivity extends PreferenceActivity { * outState)} (if that method is overridden), so the flag is properly set. */ public boolean isSafeToCommitTransactions() { - return mIsSafeToCommitTransactions; + return isSafeToCommitTransactions; } } diff --git a/java/com/android/dialer/app/settings/DialerSettingsActivity.java b/java/com/android/dialer/app/settings/DialerSettingsActivity.java index fc56fa7e0..cbd9e7950 100644 --- a/java/com/android/dialer/app/settings/DialerSettingsActivity.java +++ b/java/com/android/dialer/app/settings/DialerSettingsActivity.java @@ -50,7 +50,7 @@ import java.util.List; @UsedByReflection(value = "AndroidManifest-app.xml") public class DialerSettingsActivity extends AppCompatPreferenceActivity { - protected SharedPreferences mPreferences; + protected SharedPreferences preferences; private boolean migrationStatusOnBuildHeaders; private List

headers; @@ -58,7 +58,7 @@ public class DialerSettingsActivity extends AppCompatPreferenceActivity { protected void onCreate(Bundle savedInstanceState) { LogUtil.enterBlock("DialerSettingsActivity.onCreate"); super.onCreate(savedInstanceState); - mPreferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); + preferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext()); Intent intent = getIntent(); Uri data = intent.getData(); diff --git a/java/com/android/dialer/app/settings/SoundSettingsFragment.java b/java/com/android/dialer/app/settings/SoundSettingsFragment.java index dcfb7a595..19cddbc4f 100644 --- a/java/com/android/dialer/app/settings/SoundSettingsFragment.java +++ b/java/com/android/dialer/app/settings/SoundSettingsFragment.java @@ -49,28 +49,28 @@ public class SoundSettingsFragment extends PreferenceFragment private static final int MSG_UPDATE_RINGTONE_SUMMARY = 1; - private Preference mRingtonePreference; - private final Handler mRingtoneLookupComplete = + private Preference ringtonePreference; + private final Handler ringtoneLookupComplete = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_RINGTONE_SUMMARY: - mRingtonePreference.setSummary((CharSequence) msg.obj); + ringtonePreference.setSummary((CharSequence) msg.obj); break; } } }; - private final Runnable mRingtoneLookupRunnable = + private final Runnable ringtoneLookupRunnable = new Runnable() { @Override public void run() { updateRingtonePreferenceSummary(); } }; - private SwitchPreference mVibrateWhenRinging; - private SwitchPreference mPlayDtmfTone; - private ListPreference mDtmfToneLength; + private SwitchPreference vibrateWhenRinging; + private SwitchPreference playDtmfTone; + private ListPreference dtmfToneLength; @Override public Context getContext() { @@ -85,39 +85,39 @@ public class SoundSettingsFragment extends PreferenceFragment Context context = getActivity(); - mRingtonePreference = findPreference(context.getString(R.string.ringtone_preference_key)); - mVibrateWhenRinging = + ringtonePreference = findPreference(context.getString(R.string.ringtone_preference_key)); + vibrateWhenRinging = (SwitchPreference) findPreference(context.getString(R.string.vibrate_on_preference_key)); - mPlayDtmfTone = + playDtmfTone = (SwitchPreference) findPreference(context.getString(R.string.play_dtmf_preference_key)); - mDtmfToneLength = + dtmfToneLength = (ListPreference) findPreference(context.getString(R.string.dtmf_tone_length_preference_key)); if (hasVibrator()) { - mVibrateWhenRinging.setOnPreferenceChangeListener(this); + vibrateWhenRinging.setOnPreferenceChangeListener(this); } else { - getPreferenceScreen().removePreference(mVibrateWhenRinging); - mVibrateWhenRinging = null; + getPreferenceScreen().removePreference(vibrateWhenRinging); + vibrateWhenRinging = null; } - mPlayDtmfTone.setOnPreferenceChangeListener(this); - mPlayDtmfTone.setChecked(shouldPlayDtmfTone()); + playDtmfTone.setOnPreferenceChangeListener(this); + playDtmfTone.setChecked(shouldPlayDtmfTone()); TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE); if (SdkVersionOverride.getSdkVersion(Build.VERSION_CODES.M) >= Build.VERSION_CODES.M && telephonyManager.canChangeDtmfToneLength() && (telephonyManager.isWorldPhone() || !shouldHideCarrierSettings())) { - mDtmfToneLength.setOnPreferenceChangeListener(this); - mDtmfToneLength.setValueIndex( + dtmfToneLength.setOnPreferenceChangeListener(this); + dtmfToneLength.setValueIndex( Settings.System.getInt( context.getContentResolver(), Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, DTMF_TONE_TYPE_NORMAL)); } else { - getPreferenceScreen().removePreference(mDtmfToneLength); - mDtmfToneLength = null; + getPreferenceScreen().removePreference(dtmfToneLength); + dtmfToneLength = null; } } @@ -132,12 +132,12 @@ public class SoundSettingsFragment extends PreferenceFragment return; } - if (mVibrateWhenRinging != null) { - mVibrateWhenRinging.setChecked(shouldVibrateWhenRinging()); + if (vibrateWhenRinging != null) { + vibrateWhenRinging.setChecked(shouldVibrateWhenRinging()); } // Lookup the ringtone name asynchronously. - new Thread(mRingtoneLookupRunnable).start(); + new Thread(ringtoneLookupRunnable).start(); } /** @@ -157,14 +157,14 @@ public class SoundSettingsFragment extends PreferenceFragment .show(); return true; } - if (preference == mVibrateWhenRinging) { + if (preference == vibrateWhenRinging) { boolean doVibrate = (Boolean) objValue; Settings.System.putInt( getActivity().getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, doVibrate ? DO_VIBRATION_FOR_CALLS : NO_VIBRATION_FOR_CALLS); - } else if (preference == mDtmfToneLength) { - int index = mDtmfToneLength.findIndexOfValue((String) objValue); + } else if (preference == dtmfToneLength) { + int index = dtmfToneLength.findIndexOfValue((String) objValue); Settings.System.putInt( getActivity().getContentResolver(), Settings.System.DTMF_TONE_TYPE_WHEN_DIALING, index); } @@ -182,11 +182,11 @@ public class SoundSettingsFragment extends PreferenceFragment .show(); return true; } - if (preference == mPlayDtmfTone) { + if (preference == playDtmfTone) { Settings.System.putInt( getActivity().getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, - mPlayDtmfTone.isChecked() ? PLAY_DTMF_TONE : NO_DTMF_TONE); + playDtmfTone.isChecked() ? PLAY_DTMF_TONE : NO_DTMF_TONE); } return true; } @@ -195,9 +195,9 @@ public class SoundSettingsFragment extends PreferenceFragment private void updateRingtonePreferenceSummary() { SettingsUtil.updateRingtoneName( getActivity(), - mRingtoneLookupComplete, + ringtoneLookupComplete, RingtoneManager.TYPE_RINGTONE, - mRingtonePreference.getKey(), + ringtonePreference.getKey(), MSG_UPDATE_RINGTONE_SUMMARY); } diff --git a/java/com/android/dialer/app/voicemail/VoicemailAudioManager.java b/java/com/android/dialer/app/voicemail/VoicemailAudioManager.java index d3c3820d7..79716cb38 100644 --- a/java/com/android/dialer/app/voicemail/VoicemailAudioManager.java +++ b/java/com/android/dialer/app/voicemail/VoicemailAudioManager.java @@ -32,28 +32,28 @@ public final class VoicemailAudioManager public static final int PLAYBACK_STREAM = AudioManager.STREAM_VOICE_CALL; - private AudioManager mAudioManager; - private VoicemailPlaybackPresenter mVoicemailPlaybackPresenter; - private WiredHeadsetManager mWiredHeadsetManager; - private boolean mWasSpeakerOn; - private CallAudioState mCallAudioState; - private boolean mBluetoothScoEnabled; + private AudioManager audioManager; + private VoicemailPlaybackPresenter voicemailPlaybackPresenter; + private WiredHeadsetManager wiredHeadsetManager; + private boolean wasSpeakerOn; + private CallAudioState callAudioState; + private boolean bluetoothScoEnabled; public VoicemailAudioManager( Context context, VoicemailPlaybackPresenter voicemailPlaybackPresenter) { - mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); - mVoicemailPlaybackPresenter = voicemailPlaybackPresenter; - mWiredHeadsetManager = new WiredHeadsetManager(context); - mWiredHeadsetManager.setListener(this); + audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); + this.voicemailPlaybackPresenter = voicemailPlaybackPresenter; + wiredHeadsetManager = new WiredHeadsetManager(context); + wiredHeadsetManager.setListener(this); - mCallAudioState = getInitialAudioState(); + callAudioState = getInitialAudioState(); LogUtil.i( - "VoicemailAudioManager.VoicemailAudioManager", "Initial audioState = " + mCallAudioState); + "VoicemailAudioManager.VoicemailAudioManager", "Initial audioState = " + callAudioState); } public void requestAudioFocus() { int result = - mAudioManager.requestAudioFocus( + audioManager.requestAudioFocus( this, PLAYBACK_STREAM, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { throw new RejectedExecutionException("Could not capture audio focus."); @@ -63,13 +63,13 @@ public final class VoicemailAudioManager public void abandonAudioFocus() { updateBluetoothScoState(false); - mAudioManager.abandonAudioFocus(this); + audioManager.abandonAudioFocus(this); } @Override public void onAudioFocusChange(int focusChange) { LogUtil.d("VoicemailAudioManager.onAudioFocusChange", "focusChange=" + focusChange); - mVoicemailPlaybackPresenter.onAudioFocusChange(focusChange == AudioManager.AUDIOFOCUS_GAIN); + voicemailPlaybackPresenter.onAudioFocusChange(focusChange == AudioManager.AUDIOFOCUS_GAIN); } @Override @@ -82,19 +82,19 @@ public final class VoicemailAudioManager return; } - int newRoute = mCallAudioState.getRoute(); // start out with existing route + int newRoute = callAudioState.getRoute(); // start out with existing route if (newIsPluggedIn) { newRoute = CallAudioState.ROUTE_WIRED_HEADSET; } else { - mVoicemailPlaybackPresenter.pausePlayback(); - if (mWasSpeakerOn) { + voicemailPlaybackPresenter.pausePlayback(); + if (wasSpeakerOn) { newRoute = CallAudioState.ROUTE_SPEAKER; } else { newRoute = CallAudioState.ROUTE_EARPIECE; } } - mVoicemailPlaybackPresenter.setSpeakerphoneOn(newRoute == CallAudioState.ROUTE_SPEAKER); + voicemailPlaybackPresenter.setSpeakerphoneOn(newRoute == CallAudioState.ROUTE_SPEAKER); // We need to call this every time even if we do not change the route because the supported // routes changed either to include or not include WIRED_HEADSET. @@ -107,16 +107,16 @@ public final class VoicemailAudioManager } public boolean isWiredHeadsetPluggedIn() { - return mWiredHeadsetManager.isPluggedIn(); + return wiredHeadsetManager.isPluggedIn(); } public void registerReceivers() { // Receivers is plural because we expect to add bluetooth support. - mWiredHeadsetManager.registerReceiver(); + wiredHeadsetManager.registerReceiver(); } public void unregisterReceivers() { - mWiredHeadsetManager.unregisterReceiver(); + wiredHeadsetManager.unregisterReceiver(); } /** @@ -127,34 +127,34 @@ public final class VoicemailAudioManager private void updateBluetoothScoState(boolean hasAudioFocus) { if (hasAudioFocus) { if (hasMediaAudioCapability()) { - mBluetoothScoEnabled = false; + bluetoothScoEnabled = false; } else { - mBluetoothScoEnabled = true; + bluetoothScoEnabled = true; LogUtil.i( "VoicemailAudioManager.updateBluetoothScoState", "bluetooth device doesn't support media, using SCO instead"); } } else { - mBluetoothScoEnabled = false; + bluetoothScoEnabled = false; } applyBluetoothScoState(); } private void applyBluetoothScoState() { - if (mBluetoothScoEnabled) { - mAudioManager.startBluetoothSco(); + if (bluetoothScoEnabled) { + audioManager.startBluetoothSco(); // The doc for startBluetoothSco() states it could take seconds to establish the SCO // connection, so we should probably resume the playback after we've acquired SCO. // In practice the delay is unnoticeable so this is ignored for simplicity. - mAudioManager.setBluetoothScoOn(true); + audioManager.setBluetoothScoOn(true); } else { - mAudioManager.setBluetoothScoOn(false); - mAudioManager.stopBluetoothSco(); + audioManager.setBluetoothScoOn(false); + audioManager.stopBluetoothSco(); } } private boolean hasMediaAudioCapability() { - for (AudioDeviceInfo info : mAudioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) { + for (AudioDeviceInfo info : audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)) { if (info.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP) { return true; } @@ -173,10 +173,10 @@ public final class VoicemailAudioManager "route: " + CallAudioState.audioRouteToString(route)); // Change ROUTE_WIRED_OR_EARPIECE to a single entry. - int newRoute = selectWiredOrEarpiece(route, mCallAudioState.getSupportedRouteMask()); + int newRoute = selectWiredOrEarpiece(route, callAudioState.getSupportedRouteMask()); // If route is unsupported, do nothing. - if ((mCallAudioState.getSupportedRouteMask() | newRoute) == 0) { + if ((callAudioState.getSupportedRouteMask() | newRoute) == 0) { LogUtil.w( "VoicemailAudioManager.setAudioRoute", "Asking to set to a route that is unsupported: " + newRoute); @@ -185,9 +185,9 @@ public final class VoicemailAudioManager // Remember the new speaker state so it can be restored when the user plugs and unplugs // a headset. - mWasSpeakerOn = newRoute == CallAudioState.ROUTE_SPEAKER; + wasSpeakerOn = newRoute == CallAudioState.ROUTE_SPEAKER; setSystemAudioState( - new CallAudioState(false /* muted */, newRoute, mCallAudioState.getSupportedRouteMask())); + new CallAudioState(false /* muted */, newRoute, callAudioState.getSupportedRouteMask())); } private CallAudioState getInitialAudioState() { @@ -198,7 +198,7 @@ public final class VoicemailAudioManager private int calculateSupportedRoutes() { int routeMask = CallAudioState.ROUTE_SPEAKER; - if (mWiredHeadsetManager.isPluggedIn()) { + if (wiredHeadsetManager.isPluggedIn()) { routeMask |= CallAudioState.ROUTE_WIRED_HEADSET; } else { routeMask |= CallAudioState.ROUTE_EARPIECE; @@ -224,18 +224,18 @@ public final class VoicemailAudioManager } private void setSystemAudioState(CallAudioState callAudioState) { - CallAudioState oldAudioState = mCallAudioState; - mCallAudioState = callAudioState; + CallAudioState oldAudioState = this.callAudioState; + this.callAudioState = callAudioState; LogUtil.i( "VoicemailAudioManager.setSystemAudioState", - "changing from " + oldAudioState + " to " + mCallAudioState); + "changing from " + oldAudioState + " to " + this.callAudioState); // Audio route. - if (mCallAudioState.getRoute() == CallAudioState.ROUTE_SPEAKER) { + if (this.callAudioState.getRoute() == CallAudioState.ROUTE_SPEAKER) { turnOnSpeaker(true); - } else if (mCallAudioState.getRoute() == CallAudioState.ROUTE_EARPIECE - || mCallAudioState.getRoute() == CallAudioState.ROUTE_WIRED_HEADSET) { + } else if (this.callAudioState.getRoute() == CallAudioState.ROUTE_EARPIECE + || this.callAudioState.getRoute() == CallAudioState.ROUTE_WIRED_HEADSET) { // Just handle turning off the speaker, the system will handle switching between wired // headset and earpiece. turnOnSpeaker(false); @@ -245,9 +245,9 @@ public final class VoicemailAudioManager } private void turnOnSpeaker(boolean on) { - if (mAudioManager.isSpeakerphoneOn() != on) { + if (audioManager.isSpeakerphoneOn() != on) { LogUtil.i("VoicemailAudioManager.turnOnSpeaker", "turning speaker phone on: " + on); - mAudioManager.setSpeakerphoneOn(on); + audioManager.setSpeakerphoneOn(on); } } } diff --git a/java/com/android/dialer/app/voicemail/VoicemailPlaybackLayout.java b/java/com/android/dialer/app/voicemail/VoicemailPlaybackLayout.java index 9c1e446ab..010f55fa8 100644 --- a/java/com/android/dialer/app/voicemail/VoicemailPlaybackLayout.java +++ b/java/com/android/dialer/app/voicemail/VoicemailPlaybackLayout.java @@ -58,27 +58,27 @@ public class VoicemailPlaybackLayout extends LinearLayout private static final String TAG = VoicemailPlaybackLayout.class.getSimpleName(); private static final int VOICEMAIL_DELETE_DELAY_MS = 3000; - private Context mContext; - private CallLogListItemViewHolder mViewHolder; - private VoicemailPlaybackPresenter mPresenter; + private Context context; + private CallLogListItemViewHolder viewHolder; + private VoicemailPlaybackPresenter presenter; /** Click listener to toggle speakerphone. */ - private final View.OnClickListener mSpeakerphoneListener = + private final View.OnClickListener speakerphoneListener = new View.OnClickListener() { @Override public void onClick(View v) { - if (mPresenter != null) { - mPresenter.toggleSpeakerphone(); + if (presenter != null) { + presenter.toggleSpeakerphone(); } } }; - private Uri mVoicemailUri; - private final View.OnClickListener mDeleteButtonListener = + private Uri voicemailUri; + private final View.OnClickListener deleteButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { - Logger.get(mContext).logImpression(DialerImpression.Type.VOICEMAIL_DELETE_ENTRY); - if (mPresenter == null) { + Logger.get(context).logImpression(DialerImpression.Type.VOICEMAIL_DELETE_ENTRY); + if (presenter == null) { return; } @@ -86,19 +86,19 @@ public class VoicemailPlaybackLayout extends LinearLayout // we hide the view it is binded to something else, and the layout is not updated for // hidden items. copy the adapter position so we can update the view upon undo. // TODO(twyen): refactor this so the view holder will always be valid. - final int adapterPosition = mViewHolder.getAdapterPosition(); + final int adapterPosition = viewHolder.getAdapterPosition(); - mPresenter.pausePlayback(); - mPresenter.onVoicemailDeleted(mViewHolder); + presenter.pausePlayback(); + presenter.onVoicemailDeleted(viewHolder); - final Uri deleteUri = mVoicemailUri; + final Uri deleteUri = voicemailUri; final Runnable deleteCallback = new Runnable() { @Override public void run() { - if (Objects.equals(deleteUri, mVoicemailUri)) { + if (Objects.equals(deleteUri, voicemailUri)) { CallLogAsyncTaskUtil.deleteVoicemail( - mContext, deleteUri, VoicemailPlaybackLayout.this); + context, deleteUri, VoicemailPlaybackLayout.this); } } }; @@ -118,56 +118,56 @@ public class VoicemailPlaybackLayout extends LinearLayout new View.OnClickListener() { @Override public void onClick(View view) { - mPresenter.onVoicemailDeleteUndo(adapterPosition); + presenter.onVoicemailDeleteUndo(adapterPosition); handler.removeCallbacks(deleteCallback); } }) .setActionTextColor( - mContext.getResources().getColor(R.color.dialer_snackbar_action_text_color)) + context.getResources().getColor(R.color.dialer_snackbar_action_text_color)) .show(); } }; - private boolean mIsPlaying = false; + private boolean isPlaying = false; /** Click listener to play or pause voicemail playback. */ - private final View.OnClickListener mStartStopButtonListener = + private final View.OnClickListener startStopButtonListener = new View.OnClickListener() { @Override public void onClick(View view) { - if (mPresenter == null) { + if (presenter == null) { return; } - if (mIsPlaying) { - mPresenter.pausePlayback(); + if (isPlaying) { + presenter.pausePlayback(); } else { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.VOICEMAIL_PLAY_AUDIO_AFTER_EXPANDING_ENTRY); - mPresenter.resumePlayback(); + presenter.resumePlayback(); } } }; - private SeekBar mPlaybackSeek; - private ImageButton mStartStopButton; - private ImageButton mPlaybackSpeakerphone; - private ImageButton mDeleteButton; - private TextView mStateText; - private TextView mPositionText; - private TextView mTotalDurationText; + private SeekBar playbackSeek; + private ImageButton startStopButton; + private ImageButton playbackSpeakerphone; + private ImageButton deleteButton; + private TextView stateText; + private TextView positionText; + private TextView totalDurationText; /** Handle state changes when the user manipulates the seek bar. */ - private final OnSeekBarChangeListener mSeekBarChangeListener = + private final OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() { @Override public void onStartTrackingTouch(SeekBar seekBar) { - if (mPresenter != null) { - mPresenter.pausePlaybackForSeeking(); + if (presenter != null) { + presenter.pausePlaybackForSeeking(); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { - if (mPresenter != null) { - mPresenter.resumePlaybackAfterSeeking(seekBar.getProgress()); + if (presenter != null) { + presenter.resumePlaybackAfterSeeking(seekBar.getProgress()); } } @@ -177,14 +177,14 @@ public class VoicemailPlaybackLayout extends LinearLayout // Update the seek position if user manually changed it. This makes sure position gets // updated when user use volume button to seek playback in talkback mode. if (fromUser) { - mPresenter.seek(progress); + presenter.seek(progress); } } }; - private PositionUpdater mPositionUpdater; - private Drawable mVoicemailSeekHandleEnabled; - private Drawable mVoicemailSeekHandleDisabled; + private PositionUpdater positionUpdater; + private Drawable voicemailSeekHandleEnabled; + private Drawable voicemailSeekHandleDisabled; public VoicemailPlaybackLayout(Context context) { this(context, null); @@ -192,99 +192,97 @@ public class VoicemailPlaybackLayout extends LinearLayout public VoicemailPlaybackLayout(Context context, AttributeSet attrs) { super(context, attrs); - mContext = context; + this.context = context; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.voicemail_playback_layout, this); } public void setViewHolder(CallLogListItemViewHolder mViewHolder) { - this.mViewHolder = mViewHolder; + this.viewHolder = mViewHolder; } @Override public void setPresenter(VoicemailPlaybackPresenter presenter, Uri voicemailUri) { - mPresenter = presenter; - mVoicemailUri = voicemailUri; + this.presenter = presenter; + this.voicemailUri = voicemailUri; } @Override protected void onFinishInflate() { super.onFinishInflate(); - mPlaybackSeek = (SeekBar) findViewById(R.id.playback_seek); - mStartStopButton = (ImageButton) findViewById(R.id.playback_start_stop); - mPlaybackSpeakerphone = (ImageButton) findViewById(R.id.playback_speakerphone); - mDeleteButton = (ImageButton) findViewById(R.id.delete_voicemail); + playbackSeek = (SeekBar) findViewById(R.id.playback_seek); + startStopButton = (ImageButton) findViewById(R.id.playback_start_stop); + playbackSpeakerphone = (ImageButton) findViewById(R.id.playback_speakerphone); + deleteButton = (ImageButton) findViewById(R.id.delete_voicemail); - mStateText = (TextView) findViewById(R.id.playback_state_text); - mStateText.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE); - mPositionText = (TextView) findViewById(R.id.playback_position_text); - mTotalDurationText = (TextView) findViewById(R.id.total_duration_text); + stateText = (TextView) findViewById(R.id.playback_state_text); + stateText.setAccessibilityLiveRegion(ACCESSIBILITY_LIVE_REGION_POLITE); + positionText = (TextView) findViewById(R.id.playback_position_text); + totalDurationText = (TextView) findViewById(R.id.total_duration_text); - mPlaybackSeek.setOnSeekBarChangeListener(mSeekBarChangeListener); - mStartStopButton.setOnClickListener(mStartStopButtonListener); - mPlaybackSpeakerphone.setOnClickListener(mSpeakerphoneListener); - mDeleteButton.setOnClickListener(mDeleteButtonListener); + playbackSeek.setOnSeekBarChangeListener(seekBarChangeListener); + startStopButton.setOnClickListener(startStopButtonListener); + playbackSpeakerphone.setOnClickListener(speakerphoneListener); + deleteButton.setOnClickListener(deleteButtonListener); - mPositionText.setText(formatAsMinutesAndSeconds(0)); - mTotalDurationText.setText(formatAsMinutesAndSeconds(0)); + positionText.setText(formatAsMinutesAndSeconds(0)); + totalDurationText.setText(formatAsMinutesAndSeconds(0)); - mVoicemailSeekHandleEnabled = - getResources().getDrawable(R.drawable.ic_voicemail_seek_handle, mContext.getTheme()); - mVoicemailSeekHandleDisabled = + voicemailSeekHandleEnabled = + getResources().getDrawable(R.drawable.ic_voicemail_seek_handle, context.getTheme()); + voicemailSeekHandleDisabled = getResources() - .getDrawable(R.drawable.ic_voicemail_seek_handle_disabled, mContext.getTheme()); + .getDrawable(R.drawable.ic_voicemail_seek_handle_disabled, context.getTheme()); } @Override public void onPlaybackStarted(int duration, ScheduledExecutorService executorService) { - mIsPlaying = true; + isPlaying = true; - mStartStopButton.setImageResource(R.drawable.ic_pause); + startStopButton.setImageResource(R.drawable.ic_pause); - if (mPositionUpdater != null) { - mPositionUpdater.stopUpdating(); - mPositionUpdater = null; + if (positionUpdater != null) { + positionUpdater.stopUpdating(); + positionUpdater = null; } - mPositionUpdater = new PositionUpdater(duration, executorService); - mPositionUpdater.startUpdating(); + positionUpdater = new PositionUpdater(duration, executorService); + positionUpdater.startUpdating(); } @Override public void onPlaybackStopped() { - mIsPlaying = false; + isPlaying = false; - mStartStopButton.setImageResource(R.drawable.ic_play_arrow); + startStopButton.setImageResource(R.drawable.ic_play_arrow); - if (mPositionUpdater != null) { - mPositionUpdater.stopUpdating(); - mPositionUpdater = null; + if (positionUpdater != null) { + positionUpdater.stopUpdating(); + positionUpdater = null; } } @Override public void onPlaybackError() { - if (mPositionUpdater != null) { - mPositionUpdater.stopUpdating(); + if (positionUpdater != null) { + positionUpdater.stopUpdating(); } disableUiElements(); - mStateText.setText(getString(R.string.voicemail_playback_error)); + stateText.setText(getString(R.string.voicemail_playback_error)); } @Override public void onSpeakerphoneOn(boolean on) { if (on) { - mPlaybackSpeakerphone.setImageResource(R.drawable.quantum_ic_volume_up_white_24); + playbackSpeakerphone.setImageResource(R.drawable.quantum_ic_volume_up_white_24); // Speaker is now on, tapping button will turn it off. - mPlaybackSpeakerphone.setContentDescription( - mContext.getString(R.string.voicemail_speaker_off)); + playbackSpeakerphone.setContentDescription(context.getString(R.string.voicemail_speaker_off)); } else { - mPlaybackSpeakerphone.setImageResource(R.drawable.quantum_ic_volume_down_white_24); + playbackSpeakerphone.setImageResource(R.drawable.quantum_ic_volume_down_white_24); // Speaker is now off, tapping button will turn it on. - mPlaybackSpeakerphone.setContentDescription( - mContext.getString(R.string.voicemail_speaker_on)); + playbackSpeakerphone.setContentDescription(context.getString(R.string.voicemail_speaker_on)); } } @@ -292,66 +290,66 @@ public class VoicemailPlaybackLayout extends LinearLayout public void setClipPosition(int positionMs, int durationMs) { int seekBarPositionMs = Math.max(0, positionMs); int seekBarMax = Math.max(seekBarPositionMs, durationMs); - if (mPlaybackSeek.getMax() != seekBarMax) { - mPlaybackSeek.setMax(seekBarMax); + if (playbackSeek.getMax() != seekBarMax) { + playbackSeek.setMax(seekBarMax); } - mPlaybackSeek.setProgress(seekBarPositionMs); + playbackSeek.setProgress(seekBarPositionMs); - mPositionText.setText(formatAsMinutesAndSeconds(seekBarPositionMs)); - mTotalDurationText.setText(formatAsMinutesAndSeconds(durationMs)); + positionText.setText(formatAsMinutesAndSeconds(seekBarPositionMs)); + totalDurationText.setText(formatAsMinutesAndSeconds(durationMs)); } @Override public void setSuccess() { - mStateText.setText(null); + stateText.setText(null); } @Override public void setIsFetchingContent() { disableUiElements(); - mStateText.setText(getString(R.string.voicemail_fetching_content)); + stateText.setText(getString(R.string.voicemail_fetching_content)); } @Override public void setFetchContentTimeout() { - mStartStopButton.setEnabled(true); - mStateText.setText(getString(R.string.voicemail_fetching_timout)); + startStopButton.setEnabled(true); + stateText.setText(getString(R.string.voicemail_fetching_timout)); } @Override public int getDesiredClipPosition() { - return mPlaybackSeek.getProgress(); + return playbackSeek.getProgress(); } @Override public void disableUiElements() { - mStartStopButton.setEnabled(false); + startStopButton.setEnabled(false); resetSeekBar(); } @Override public void enableUiElements() { - mDeleteButton.setEnabled(true); - mStartStopButton.setEnabled(true); - mPlaybackSeek.setEnabled(true); - mPlaybackSeek.setThumb(mVoicemailSeekHandleEnabled); + deleteButton.setEnabled(true); + startStopButton.setEnabled(true); + playbackSeek.setEnabled(true); + playbackSeek.setThumb(voicemailSeekHandleEnabled); } @Override public void resetSeekBar() { - mPlaybackSeek.setProgress(0); - mPlaybackSeek.setEnabled(false); - mPlaybackSeek.setThumb(mVoicemailSeekHandleDisabled); + playbackSeek.setProgress(0); + playbackSeek.setEnabled(false); + playbackSeek.setThumb(voicemailSeekHandleDisabled); } @Override public void onDeleteVoicemail() { - mPresenter.onVoicemailDeletedInDatabase(); + presenter.onVoicemailDeletedInDatabase(); } private String getString(int resId) { - return mContext.getString(resId); + return context.getString(resId); } /** @@ -372,7 +370,7 @@ public class VoicemailPlaybackLayout extends LinearLayout @VisibleForTesting public String getStateText() { - return mStateText.getText().toString(); + return stateText.getText().toString(); } /** Controls the animation of the playback slider. */ @@ -382,61 +380,61 @@ public class VoicemailPlaybackLayout extends LinearLayout /** Update rate for the slider, 30fps. */ private static final int SLIDER_UPDATE_PERIOD_MILLIS = 1000 / 30; - private final ScheduledExecutorService mExecutorService; - private final Object mLock = new Object(); - private int mDurationMs; + private final ScheduledExecutorService executorService; + private final Object lock = new Object(); + private int durationMs; - @GuardedBy("mLock") - private ScheduledFuture mScheduledFuture; + @GuardedBy("lock") + private ScheduledFuture scheduledFuture; - private Runnable mUpdateClipPositionRunnable = + private Runnable updateClipPositionRunnable = new Runnable() { @Override public void run() { int currentPositionMs = 0; - synchronized (mLock) { - if (mScheduledFuture == null || mPresenter == null) { + synchronized (lock) { + if (scheduledFuture == null || presenter == null) { // This task has been canceled. Just stop now. return; } - currentPositionMs = mPresenter.getMediaPlayerPosition(); + currentPositionMs = presenter.getMediaPlayerPosition(); } - setClipPosition(currentPositionMs, mDurationMs); + setClipPosition(currentPositionMs, durationMs); } }; public PositionUpdater(int durationMs, ScheduledExecutorService executorService) { - mDurationMs = durationMs; - mExecutorService = executorService; + this.durationMs = durationMs; + this.executorService = executorService; } @Override public void run() { - post(mUpdateClipPositionRunnable); + post(updateClipPositionRunnable); } public void startUpdating() { - synchronized (mLock) { + synchronized (lock) { cancelPendingRunnables(); - mScheduledFuture = - mExecutorService.scheduleAtFixedRate( + scheduledFuture = + executorService.scheduleAtFixedRate( this, 0, SLIDER_UPDATE_PERIOD_MILLIS, TimeUnit.MILLISECONDS); } } public void stopUpdating() { - synchronized (mLock) { + synchronized (lock) { cancelPendingRunnables(); } } - @GuardedBy("mLock") + @GuardedBy("lock") private void cancelPendingRunnables() { - if (mScheduledFuture != null) { - mScheduledFuture.cancel(true); - mScheduledFuture = null; + if (scheduledFuture != null) { + scheduledFuture.cancel(true); + scheduledFuture = null; } - removeCallbacks(mUpdateClipPositionRunnable); + removeCallbacks(updateClipPositionRunnable); } } } diff --git a/java/com/android/dialer/app/voicemail/VoicemailPlaybackPresenter.java b/java/com/android/dialer/app/voicemail/VoicemailPlaybackPresenter.java index 10afe479f..e9b64dfe3 100644 --- a/java/com/android/dialer/app/voicemail/VoicemailPlaybackPresenter.java +++ b/java/com/android/dialer/app/voicemail/VoicemailPlaybackPresenter.java @@ -113,41 +113,41 @@ public class VoicemailPlaybackPresenter private static final String VOICEMAIL_SHARE_FILE_NAME_DATE_FORMAT = "MM-dd-yy_hhmmaa"; private static final String CONFIG_SHARE_VOICEMAIL_ALLOWED = "share_voicemail_allowed"; - private static VoicemailPlaybackPresenter sInstance; - private static ScheduledExecutorService mScheduledExecutorService; + private static VoicemailPlaybackPresenter instance; + private static ScheduledExecutorService scheduledExecutorService; /** * The most recently cached duration. We cache this since we don't want to keep requesting it from * the player, as this can easily lead to throwing {@link IllegalStateException} (any time the * player is released, it's illegal to ask for the duration). */ - private final AtomicInteger mDuration = new AtomicInteger(0); + private final AtomicInteger duration = new AtomicInteger(0); - protected Context mContext; - private long mRowId; - protected Uri mVoicemailUri; - protected MediaPlayer mMediaPlayer; + protected Context context; + private long rowId; + protected Uri voicemailUri; + protected MediaPlayer mediaPlayer; // Used to run async tasks that need to interact with the UI. - protected AsyncTaskExecutor mAsyncTaskExecutor; - private Activity mActivity; - private PlaybackView mView; - private int mPosition; - private boolean mIsPlaying; + protected AsyncTaskExecutor asyncTaskExecutor; + private Activity activity; + private PlaybackView view; + private int position; + private boolean isPlaying; // MediaPlayer crashes on some method calls if not prepared but does not have a method which // exposes its prepared state. Store this locally, so we can check and prevent crashes. - private boolean mIsPrepared; - private boolean mIsSpeakerphoneOn; + private boolean isPrepared; + private boolean isSpeakerphoneOn; - private boolean mShouldResumePlaybackAfterSeeking; + private boolean shouldResumePlaybackAfterSeeking; /** * Used to handle the result of a successful or time-out fetch result. * *

This variable is thread-contained, accessed only on the ui thread. */ - private FetchResultHandler mFetchResultHandler; + private FetchResultHandler fetchResultHandler; - private PowerManager.WakeLock mProximityWakeLock; - private VoicemailAudioManager mVoicemailAudioManager; - private OnVoicemailDeletedListener mOnVoicemailDeletedListener; + private PowerManager.WakeLock proximityWakeLock; + private VoicemailAudioManager voicemailAudioManager; + private OnVoicemailDeletedListener onVoicemailDeletedListener; private View shareVoicemailButtonView; private DialerExecutor> shareVoicemailExecutor; @@ -155,11 +155,11 @@ public class VoicemailPlaybackPresenter /** Initialize variables which are activity-independent and state-independent. */ protected VoicemailPlaybackPresenter(Activity activity) { Context context = activity.getApplicationContext(); - mAsyncTaskExecutor = AsyncTaskExecutors.createAsyncTaskExecutor(); - mVoicemailAudioManager = new VoicemailAudioManager(context, this); + asyncTaskExecutor = AsyncTaskExecutors.createAsyncTaskExecutor(); + voicemailAudioManager = new VoicemailAudioManager(context, this); PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { - mProximityWakeLock = + proximityWakeLock = powerManager.newWakeLock( PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "VoicemailPlaybackPresenter"); } @@ -177,63 +177,63 @@ public class VoicemailPlaybackPresenter @MainThread public static VoicemailPlaybackPresenter getInstance( Activity activity, Bundle savedInstanceState) { - if (sInstance == null) { - sInstance = new VoicemailPlaybackPresenter(activity); + if (instance == null) { + instance = new VoicemailPlaybackPresenter(activity); } - sInstance.init(activity, savedInstanceState); - return sInstance; + instance.init(activity, savedInstanceState); + return instance; } private static synchronized ScheduledExecutorService getScheduledExecutorServiceInstance() { - if (mScheduledExecutorService == null) { - mScheduledExecutorService = Executors.newScheduledThreadPool(NUMBER_OF_THREADS_IN_POOL); + if (scheduledExecutorService == null) { + scheduledExecutorService = Executors.newScheduledThreadPool(NUMBER_OF_THREADS_IN_POOL); } - return mScheduledExecutorService; + return scheduledExecutorService; } /** Update variables which are activity-dependent or state-dependent. */ @MainThread protected void init(Activity activity, Bundle savedInstanceState) { Assert.isMainThread(); - mActivity = activity; - mContext = activity; + this.activity = activity; + context = activity; if (savedInstanceState != null) { // Restores playback state when activity is recreated, such as after rotation. - mVoicemailUri = savedInstanceState.getParcelable(VOICEMAIL_URI_KEY); - mIsPrepared = savedInstanceState.getBoolean(IS_PREPARED_KEY); - mPosition = savedInstanceState.getInt(CLIP_POSITION_KEY, 0); - mIsPlaying = savedInstanceState.getBoolean(IS_PLAYING_STATE_KEY, false); - mIsSpeakerphoneOn = savedInstanceState.getBoolean(IS_SPEAKERPHONE_ON_KEY, false); + voicemailUri = savedInstanceState.getParcelable(VOICEMAIL_URI_KEY); + isPrepared = savedInstanceState.getBoolean(IS_PREPARED_KEY); + position = savedInstanceState.getInt(CLIP_POSITION_KEY, 0); + isPlaying = savedInstanceState.getBoolean(IS_PLAYING_STATE_KEY, false); + isSpeakerphoneOn = savedInstanceState.getBoolean(IS_SPEAKERPHONE_ON_KEY, false); } - if (mMediaPlayer == null) { - mIsPrepared = false; - mIsPlaying = false; + if (mediaPlayer == null) { + isPrepared = false; + isPlaying = false; } - if (mActivity != null) { + if (this.activity != null) { if (isPlaying()) { - mActivity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); + this.activity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); } else { - mActivity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); + this.activity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); } shareVoicemailExecutor = - DialerExecutorComponent.get(mContext) + DialerExecutorComponent.get(context) .dialerExecutorFactory() .createUiTaskBuilder( - mActivity.getFragmentManager(), "shareVoicemail", new ShareVoicemailWorker()) + this.activity.getFragmentManager(), "shareVoicemail", new ShareVoicemailWorker()) .onSuccess( output -> { if (output == null) { LogUtil.e("VoicemailAsyncTaskUtil.shareVoicemail", "failed to get voicemail"); return; } - mContext.startActivity( + context.startActivity( Intent.createChooser( - getShareIntent(mContext, output.first, output.second), - mContext + getShareIntent(context, output.first, output.second), + context .getResources() .getText(R.string.call_log_action_share_voicemail))); }) @@ -243,12 +243,12 @@ public class VoicemailPlaybackPresenter /** Must be invoked when the parent Activity is saving it state. */ public void onSaveInstanceState(Bundle outState) { - if (mView != null) { - outState.putParcelable(VOICEMAIL_URI_KEY, mVoicemailUri); - outState.putBoolean(IS_PREPARED_KEY, mIsPrepared); - outState.putInt(CLIP_POSITION_KEY, mView.getDesiredClipPosition()); - outState.putBoolean(IS_PLAYING_STATE_KEY, mIsPlaying); - outState.putBoolean(IS_SPEAKERPHONE_ON_KEY, mIsSpeakerphoneOn); + if (view != null) { + outState.putParcelable(VOICEMAIL_URI_KEY, voicemailUri); + outState.putBoolean(IS_PREPARED_KEY, isPrepared); + outState.putInt(CLIP_POSITION_KEY, view.getDesiredClipPosition()); + outState.putBoolean(IS_PLAYING_STATE_KEY, isPlaying); + outState.putBoolean(IS_SPEAKERPHONE_ON_KEY, isSpeakerphoneOn); } } @@ -259,26 +259,26 @@ public class VoicemailPlaybackPresenter Uri voicemailUri, final boolean startPlayingImmediately, View shareVoicemailButtonView) { - mRowId = rowId; - mView = view; - mView.setPresenter(this, voicemailUri); - mView.onSpeakerphoneOn(mIsSpeakerphoneOn); + this.rowId = rowId; + this.view = view; + this.view.setPresenter(this, voicemailUri); + this.view.onSpeakerphoneOn(isSpeakerphoneOn); this.shareVoicemailButtonView = shareVoicemailButtonView; showShareVoicemailButton(false); // Handles cases where the same entry is binded again when scrolling in list, or where // the MediaPlayer was retained after an orientation change. - if (mMediaPlayer != null && mIsPrepared && voicemailUri.equals(mVoicemailUri)) { + if (mediaPlayer != null && isPrepared && voicemailUri.equals(this.voicemailUri)) { // If the voicemail card was rebinded, we need to set the position to the appropriate // point. Since we retain the media player, we can just set it to the position of the // media player. - mPosition = mMediaPlayer.getCurrentPosition(); - onPrepared(mMediaPlayer); + position = mediaPlayer.getCurrentPosition(); + onPrepared(mediaPlayer); showShareVoicemailButton(true); } else { - if (!voicemailUri.equals(mVoicemailUri)) { - mVoicemailUri = voicemailUri; - mPosition = 0; + if (!voicemailUri.equals(this.voicemailUri)) { + this.voicemailUri = voicemailUri; + position = 0; } /* * Check to see if the content field in the DB is set. If set, we proceed to @@ -294,9 +294,9 @@ public class VoicemailPlaybackPresenter if (startPlayingImmediately) { requestContent(PLAYBACK_REQUEST); } - if (mView != null) { - mView.resetSeekBar(); - mView.setClipPosition(0, mDuration.get()); + if (this.view != null) { + this.view.resetSeekBar(); + this.view.setClipPosition(0, duration.get()); } } }); @@ -305,7 +305,7 @@ public class VoicemailPlaybackPresenter // Since setPlaybackView can get called during the view binding process, we don't // want to reset mIsPlaying to false if the user is currently playing the // voicemail and the view is rebound. - mIsPlaying = startPlayingImmediately; + isPlaying = startPlayingImmediately; } } } @@ -314,8 +314,8 @@ public class VoicemailPlaybackPresenter public void resetAll() { pausePresenter(true); - mView = null; - mVoicemailUri = null; + view = null; + voicemailUri = null; } /** @@ -327,41 +327,41 @@ public class VoicemailPlaybackPresenter */ public void pausePresenter(boolean reset) { pausePlayback(); - if (mMediaPlayer != null) { - mMediaPlayer.release(); - mMediaPlayer = null; + if (mediaPlayer != null) { + mediaPlayer.release(); + mediaPlayer = null; } disableProximitySensor(false /* waitForFarState */); - mIsPrepared = false; - mIsPlaying = false; + isPrepared = false; + isPlaying = false; if (reset) { // We want to reset the position whether or not the view is valid. - mPosition = 0; + position = 0; } - if (mView != null) { - mView.onPlaybackStopped(); + if (view != null) { + view.onPlaybackStopped(); if (reset) { - mView.setClipPosition(0, mDuration.get()); + view.setClipPosition(0, duration.get()); } else { - mPosition = mView.getDesiredClipPosition(); + position = view.getDesiredClipPosition(); } } } /** Must be invoked when the parent activity is resumed. */ public void onResume() { - mVoicemailAudioManager.registerReceivers(); + voicemailAudioManager.registerReceivers(); } /** Must be invoked when the parent activity is paused. */ public void onPause() { - mVoicemailAudioManager.unregisterReceivers(); + voicemailAudioManager.unregisterReceivers(); - if (mActivity != null && mIsPrepared && mActivity.isChangingConfigurations()) { + if (activity != null && isPrepared && activity.isChangingConfigurations()) { // If an configuration change triggers the pause, retain the MediaPlayer. LogUtil.d("VoicemailPlaybackPresenter.onPause", "configuration changed."); return; @@ -374,28 +374,28 @@ public class VoicemailPlaybackPresenter /** Must be invoked when the parent activity is destroyed. */ public void onDestroy() { // Clear references to avoid leaks from the singleton instance. - mActivity = null; - mContext = null; + activity = null; + context = null; - if (mScheduledExecutorService != null) { - mScheduledExecutorService.shutdown(); - mScheduledExecutorService = null; + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdown(); + scheduledExecutorService = null; } - if (mFetchResultHandler != null) { - mFetchResultHandler.destroy(); - mFetchResultHandler = null; + if (fetchResultHandler != null) { + fetchResultHandler.destroy(); + fetchResultHandler = null; } } /** Checks to see if we have content available for this voicemail. */ protected void checkForContent(final OnContentCheckedListener callback) { - mAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.CHECK_FOR_CONTENT, new AsyncTask() { @Override public Boolean doInBackground(Void... params) { - return queryHasContent(mVoicemailUri); + return queryHasContent(voicemailUri); } @Override @@ -406,17 +406,17 @@ public class VoicemailPlaybackPresenter } private boolean queryHasContent(Uri voicemailUri) { - if (voicemailUri == null || mContext == null) { + if (voicemailUri == null || context == null) { return false; } - ContentResolver contentResolver = mContext.getContentResolver(); + ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(voicemailUri, null, null, null, null); try { if (cursor != null && cursor.moveToNext()) { int duration = cursor.getInt(cursor.getColumnIndex(VoicemailContract.Voicemails.DURATION)); // Convert database duration (seconds) into mDuration (milliseconds) - mDuration.set(duration > 0 ? duration * 1000 : 0); + this.duration.set(duration > 0 ? duration * 1000 : 0); return cursor.getInt(cursor.getColumnIndex(VoicemailContract.Voicemails.HAS_CONTENT)) == 1; } } finally { @@ -440,38 +440,34 @@ public class VoicemailPlaybackPresenter * @return whether issued request to fetch content */ protected boolean requestContent(int code) { - if (mContext == null || mVoicemailUri == null) { + if (context == null || voicemailUri == null) { return false; } FetchResultHandler tempFetchResultHandler = - new FetchResultHandler(new Handler(), mVoicemailUri, code); + new FetchResultHandler(new Handler(), voicemailUri, code); switch (code) { default: - if (mFetchResultHandler != null) { - mFetchResultHandler.destroy(); + if (fetchResultHandler != null) { + fetchResultHandler.destroy(); } - mView.setIsFetchingContent(); - mFetchResultHandler = tempFetchResultHandler; + view.setIsFetchingContent(); + fetchResultHandler = tempFetchResultHandler; break; } - mAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.SEND_FETCH_REQUEST, new AsyncTask() { @Override protected Void doInBackground(Void... voids) { try (Cursor cursor = - mContext + context .getContentResolver() .query( - mVoicemailUri, - new String[] {Voicemails.SOURCE_PACKAGE}, - null, - null, - null)) { + voicemailUri, new String[] {Voicemails.SOURCE_PACKAGE}, null, null, null)) { String sourcePackage; if (!hasContent(cursor)) { LogUtil.e( @@ -482,12 +478,12 @@ public class VoicemailPlaybackPresenter sourcePackage = cursor.getString(0); } // Send voicemail fetch request. - Intent intent = new Intent(VoicemailContract.ACTION_FETCH_VOICEMAIL, mVoicemailUri); + Intent intent = new Intent(VoicemailContract.ACTION_FETCH_VOICEMAIL, voicemailUri); intent.setPackage(sourcePackage); LogUtil.i( "VoicemailPlaybackPresenter.requestContent", "Sending ACTION_FETCH_VOICEMAIL to " + sourcePackage); - mContext.sendBroadcast(intent); + context.sendBroadcast(intent); } return null; } @@ -504,35 +500,35 @@ public class VoicemailPlaybackPresenter * will call {@link #onError()} otherwise. */ protected void prepareContent() { - if (mView == null || mContext == null) { + if (view == null || context == null) { return; } LogUtil.d("VoicemailPlaybackPresenter.prepareContent", null); // Release the previous media player, otherwise there may be failures. - if (mMediaPlayer != null) { - mMediaPlayer.release(); - mMediaPlayer = null; + if (mediaPlayer != null) { + mediaPlayer.release(); + mediaPlayer = null; } - mView.disableUiElements(); - mIsPrepared = false; + view.disableUiElements(); + isPrepared = false; - if (mContext != null && TelecomUtil.isInManagedCall(mContext)) { + if (context != null && TelecomUtil.isInManagedCall(context)) { handleError(new IllegalStateException("Cannot play voicemail when call is in progress")); return; } try { - mMediaPlayer = new MediaPlayer(); - mMediaPlayer.setOnPreparedListener(this); - mMediaPlayer.setOnErrorListener(this); - mMediaPlayer.setOnCompletionListener(this); - - mMediaPlayer.reset(); - mMediaPlayer.setDataSource(mContext, mVoicemailUri); - mMediaPlayer.setAudioStreamType(VoicemailAudioManager.PLAYBACK_STREAM); - mMediaPlayer.prepareAsync(); + mediaPlayer = new MediaPlayer(); + mediaPlayer.setOnPreparedListener(this); + mediaPlayer.setOnErrorListener(this); + mediaPlayer.setOnCompletionListener(this); + + mediaPlayer.reset(); + mediaPlayer.setDataSource(context, voicemailUri); + mediaPlayer.setAudioStreamType(VoicemailAudioManager.PLAYBACK_STREAM); + mediaPlayer.prepareAsync(); } catch (IOException e) { handleError(e); } @@ -543,23 +539,23 @@ public class VoicemailPlaybackPresenter */ @Override public void onPrepared(MediaPlayer mp) { - if (mView == null || mContext == null) { + if (view == null || context == null) { return; } LogUtil.d("VoicemailPlaybackPresenter.onPrepared", null); - mIsPrepared = true; + isPrepared = true; - mDuration.set(mMediaPlayer.getDuration()); + duration.set(mediaPlayer.getDuration()); - LogUtil.d("VoicemailPlaybackPresenter.onPrepared", "mPosition=" + mPosition); - mView.setClipPosition(mPosition, mDuration.get()); - mView.enableUiElements(); - mView.setSuccess(); + LogUtil.d("VoicemailPlaybackPresenter.onPrepared", "mPosition=" + position); + view.setClipPosition(position, duration.get()); + view.enableUiElements(); + view.setSuccess(); if (!mp.isPlaying()) { - mMediaPlayer.seekTo(mPosition); + mediaPlayer.seekTo(position); } - if (mIsPlaying) { + if (isPlaying) { resumePlayback(); } else { pausePlayback(); @@ -579,18 +575,18 @@ public class VoicemailPlaybackPresenter protected void handleError(Exception e) { LogUtil.e("VoicemailPlaybackPresenter.handlerError", "could not play voicemail", e); - if (mIsPrepared) { - mMediaPlayer.release(); - mMediaPlayer = null; - mIsPrepared = false; + if (isPrepared) { + mediaPlayer.release(); + mediaPlayer = null; + isPrepared = false; } - if (mView != null) { - mView.onPlaybackError(); + if (view != null) { + view.onPlaybackError(); } - mPosition = 0; - mIsPlaying = false; + position = 0; + isPlaying = false; showShareVoicemailButton(false); } @@ -600,10 +596,10 @@ public class VoicemailPlaybackPresenter pausePlayback(); // Reset the seekbar position to the beginning. - mPosition = 0; - if (mView != null) { + position = 0; + if (view != null) { mediaPlayer.seekTo(0); - mView.setClipPosition(0, mDuration.get()); + view.setClipPosition(0, duration.get()); } } @@ -617,7 +613,7 @@ public class VoicemailPlaybackPresenter * @param gainedFocus {@code true} if the audio focus was gained, {@code} false otherwise. */ public void onAudioFocusChange(boolean gainedFocus) { - if (mIsPlaying == gainedFocus) { + if (isPlaying == gainedFocus) { // Nothing new here, just exit. return; } @@ -634,11 +630,11 @@ public class VoicemailPlaybackPresenter * playing. */ public void resumePlayback() { - if (mView == null) { + if (view == null) { return; } - if (!mIsPrepared) { + if (!isPrepared) { /* * Check content before requesting content to avoid duplicated requests. It is possible * that the UI doesn't know content has arrived if the fetch took too long causing a @@ -649,41 +645,41 @@ public class VoicemailPlaybackPresenter if (!hasContent) { // No local content, download from server. Queue playing if the request was // issued, - mIsPlaying = requestContent(PLAYBACK_REQUEST); + isPlaying = requestContent(PLAYBACK_REQUEST); } else { showShareVoicemailButton(true); // Queue playing once the media play loaded the content. - mIsPlaying = true; + isPlaying = true; prepareContent(); } }); return; } - mIsPlaying = true; + isPlaying = true; - mActivity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); + activity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); - if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) { + if (mediaPlayer != null && !mediaPlayer.isPlaying()) { // Clamp the start position between 0 and the duration. - mPosition = Math.max(0, Math.min(mPosition, mDuration.get())); + position = Math.max(0, Math.min(position, duration.get())); - mMediaPlayer.seekTo(mPosition); + mediaPlayer.seekTo(position); try { // Grab audio focus. // Can throw RejectedExecutionException. - mVoicemailAudioManager.requestAudioFocus(); - mMediaPlayer.start(); - setSpeakerphoneOn(mIsSpeakerphoneOn); - mVoicemailAudioManager.setSpeakerphoneOn(mIsSpeakerphoneOn); + voicemailAudioManager.requestAudioFocus(); + mediaPlayer.start(); + setSpeakerphoneOn(isSpeakerphoneOn); + voicemailAudioManager.setSpeakerphoneOn(isSpeakerphoneOn); } catch (RejectedExecutionException e) { handleError(e); } } - LogUtil.d("VoicemailPlaybackPresenter.resumePlayback", "resumed playback at %d.", mPosition); - mView.onPlaybackStarted(mDuration.get(), getScheduledExecutorServiceInstance()); + LogUtil.d("VoicemailPlaybackPresenter.resumePlayback", "resumed playback at %d.", position); + view.onPlaybackStarted(duration.get(), getScheduledExecutorServiceInstance()); } /** Pauses voicemail playback at the current position. Null-op if already paused. */ @@ -692,29 +688,29 @@ public class VoicemailPlaybackPresenter } private void pausePlayback(boolean keepFocus) { - if (!mIsPrepared) { + if (!isPrepared) { return; } - mIsPlaying = false; + isPlaying = false; - if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { - mMediaPlayer.pause(); + if (mediaPlayer != null && mediaPlayer.isPlaying()) { + mediaPlayer.pause(); } - mPosition = mMediaPlayer == null ? 0 : mMediaPlayer.getCurrentPosition(); + position = mediaPlayer == null ? 0 : mediaPlayer.getCurrentPosition(); - LogUtil.d("VoicemailPlaybackPresenter.pausePlayback", "paused playback at %d.", mPosition); + LogUtil.d("VoicemailPlaybackPresenter.pausePlayback", "paused playback at %d.", position); - if (mView != null) { - mView.onPlaybackStopped(); + if (view != null) { + view.onPlaybackStopped(); } if (!keepFocus) { - mVoicemailAudioManager.abandonAudioFocus(); + voicemailAudioManager.abandonAudioFocus(); } - if (mActivity != null) { - mActivity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); + if (activity != null) { + activity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON); } disableProximitySensor(true /* waitForFarState */); } @@ -724,16 +720,16 @@ public class VoicemailPlaybackPresenter * playing to know whether to resume playback once the user selects a new position. */ public void pausePlaybackForSeeking() { - if (mMediaPlayer != null) { - mShouldResumePlaybackAfterSeeking = mMediaPlayer.isPlaying(); + if (mediaPlayer != null) { + shouldResumePlaybackAfterSeeking = mediaPlayer.isPlaying(); } pausePlayback(true); } public void resumePlaybackAfterSeeking(int desiredPosition) { - mPosition = desiredPosition; - if (mShouldResumePlaybackAfterSeeking) { - mShouldResumePlaybackAfterSeeking = false; + position = desiredPosition; + if (shouldResumePlaybackAfterSeeking) { + shouldResumePlaybackAfterSeeking = false; resumePlayback(); } } @@ -743,23 +739,23 @@ public class VoicemailPlaybackPresenter * touch or volume button while in talkback mode. */ public void seek(int position) { - mPosition = position; - mMediaPlayer.seekTo(mPosition); + this.position = position; + mediaPlayer.seekTo(this.position); } private void enableProximitySensor() { - if (mProximityWakeLock == null - || mIsSpeakerphoneOn - || !mIsPrepared - || mMediaPlayer == null - || !mMediaPlayer.isPlaying()) { + if (proximityWakeLock == null + || isSpeakerphoneOn + || !isPrepared + || mediaPlayer == null + || !mediaPlayer.isPlaying()) { return; } - if (!mProximityWakeLock.isHeld()) { + if (!proximityWakeLock.isHeld()) { LogUtil.i( "VoicemailPlaybackPresenter.enableProximitySensor", "acquiring proximity wake lock"); - mProximityWakeLock.acquire(); + proximityWakeLock.acquire(); } else { LogUtil.i( "VoicemailPlaybackPresenter.enableProximitySensor", @@ -768,14 +764,14 @@ public class VoicemailPlaybackPresenter } private void disableProximitySensor(boolean waitForFarState) { - if (mProximityWakeLock == null) { + if (proximityWakeLock == null) { return; } - if (mProximityWakeLock.isHeld()) { + if (proximityWakeLock.isHeld()) { LogUtil.i( "VoicemailPlaybackPresenter.disableProximitySensor", "releasing proximity wake lock"); int flags = waitForFarState ? PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY : 0; - mProximityWakeLock.release(flags); + proximityWakeLock.release(flags); } else { LogUtil.i( "VoicemailPlaybackPresenter.disableProximitySensor", @@ -785,44 +781,44 @@ public class VoicemailPlaybackPresenter /** This is for use by UI interactions only. It simplifies UI logic. */ public void toggleSpeakerphone() { - mVoicemailAudioManager.setSpeakerphoneOn(!mIsSpeakerphoneOn); - setSpeakerphoneOn(!mIsSpeakerphoneOn); + voicemailAudioManager.setSpeakerphoneOn(!isSpeakerphoneOn); + setSpeakerphoneOn(!isSpeakerphoneOn); } public void setOnVoicemailDeletedListener(OnVoicemailDeletedListener listener) { - mOnVoicemailDeletedListener = listener; + onVoicemailDeletedListener = listener; } public int getMediaPlayerPosition() { - return mIsPrepared && mMediaPlayer != null ? mMediaPlayer.getCurrentPosition() : 0; + return isPrepared && mediaPlayer != null ? mediaPlayer.getCurrentPosition() : 0; } void onVoicemailDeleted(CallLogListItemViewHolder viewHolder) { - if (mOnVoicemailDeletedListener != null) { - mOnVoicemailDeletedListener.onVoicemailDeleted(viewHolder, mVoicemailUri); + if (onVoicemailDeletedListener != null) { + onVoicemailDeletedListener.onVoicemailDeleted(viewHolder, voicemailUri); } } void onVoicemailDeleteUndo(int adapterPosition) { - if (mOnVoicemailDeletedListener != null) { - mOnVoicemailDeletedListener.onVoicemailDeleteUndo(mRowId, adapterPosition, mVoicemailUri); + if (onVoicemailDeletedListener != null) { + onVoicemailDeletedListener.onVoicemailDeleteUndo(rowId, adapterPosition, voicemailUri); } } void onVoicemailDeletedInDatabase() { - if (mOnVoicemailDeletedListener != null) { - mOnVoicemailDeletedListener.onVoicemailDeletedInDatabase(mRowId, mVoicemailUri); + if (onVoicemailDeletedListener != null) { + onVoicemailDeletedListener.onVoicemailDeletedInDatabase(rowId, voicemailUri); } } @VisibleForTesting public boolean isPlaying() { - return mIsPlaying; + return isPlaying; } @VisibleForTesting public boolean isSpeakerphoneOn() { - return mIsSpeakerphoneOn; + return isSpeakerphoneOn; } /** @@ -831,19 +827,19 @@ public class VoicemailPlaybackPresenter * presenter without the presenter triggering the audio manager and duplicating actions. */ public void setSpeakerphoneOn(boolean on) { - if (mView == null) { + if (view == null) { return; } - mView.onSpeakerphoneOn(on); + view.onSpeakerphoneOn(on); - mIsSpeakerphoneOn = on; + isSpeakerphoneOn = on; // This should run even if speakerphone is not being toggled because we may be switching // from earpiece to headphone and vise versa. Also upon initial setup the default audio // source is the earpiece, so we want to trigger the proximity sensor. - if (mIsPlaying) { - if (on || mVoicemailAudioManager.isWiredHeadsetPluggedIn()) { + if (isPlaying) { + if (on || voicemailAudioManager.isWiredHeadsetPluggedIn()) { disableProximitySensor(false /* waitForFarState */); } else { enableProximitySensor(); @@ -853,16 +849,16 @@ public class VoicemailPlaybackPresenter @VisibleForTesting public void clearInstance() { - sInstance = null; + instance = null; } private void showShareVoicemailButton(boolean show) { - if (mContext == null) { + if (context == null) { return; } - if (isShareVoicemailAllowed(mContext) && shareVoicemailButtonView != null) { + if (isShareVoicemailAllowed(context) && shareVoicemailButtonView != null) { if (show) { - Logger.get(mContext).logImpression(DialerImpression.Type.VVM_SHARE_VISIBLE); + Logger.get(context).logImpression(DialerImpression.Type.VVM_SHARE_VISIBLE); } LogUtil.d("VoicemailPlaybackPresenter.showShareVoicemailButton", "show: %b", show); shareVoicemailButtonView.setVisibility(show ? View.VISIBLE : View.GONE); @@ -931,7 +927,7 @@ public class VoicemailPlaybackPresenter * voicemail to a temporary file in background and launch a chooser intent to share it. */ public void shareVoicemail() { - shareVoicemailExecutor.executeParallel(new Pair<>(mContext, mVoicemailUri)); + shareVoicemailExecutor.executeParallel(new Pair<>(context, voicemailUri)); } private static String getFileName(String cachedName, String number, String mimeType, long date) { @@ -1052,55 +1048,55 @@ public class VoicemailPlaybackPresenter @ThreadSafe private class FetchResultHandler extends ContentObserver implements Runnable { - private final Handler mFetchResultHandler; - private final Uri mVoicemailUri; - private AtomicBoolean mIsWaitingForResult = new AtomicBoolean(true); + private final Handler fetchResultHandler; + private final Uri voicemailUri; + private AtomicBoolean isWaitingForResult = new AtomicBoolean(true); public FetchResultHandler(Handler handler, Uri uri, int code) { super(handler); - mFetchResultHandler = handler; - mVoicemailUri = uri; - if (mContext != null) { - if (PermissionsUtil.hasReadVoicemailPermissions(mContext)) { - mContext.getContentResolver().registerContentObserver(mVoicemailUri, false, this); + fetchResultHandler = handler; + voicemailUri = uri; + if (context != null) { + if (PermissionsUtil.hasReadVoicemailPermissions(context)) { + context.getContentResolver().registerContentObserver(voicemailUri, false, this); } - mFetchResultHandler.postDelayed(this, FETCH_CONTENT_TIMEOUT_MS); + fetchResultHandler.postDelayed(this, FETCH_CONTENT_TIMEOUT_MS); } } /** Stop waiting for content and notify UI if {@link FETCH_CONTENT_TIMEOUT_MS} has elapsed. */ @Override public void run() { - if (mIsWaitingForResult.getAndSet(false) && mContext != null) { - mContext.getContentResolver().unregisterContentObserver(this); - if (mView != null) { - mView.setFetchContentTimeout(); + if (isWaitingForResult.getAndSet(false) && context != null) { + context.getContentResolver().unregisterContentObserver(this); + if (view != null) { + view.setFetchContentTimeout(); } } } public void destroy() { - if (mIsWaitingForResult.getAndSet(false) && mContext != null) { - mContext.getContentResolver().unregisterContentObserver(this); - mFetchResultHandler.removeCallbacks(this); + if (isWaitingForResult.getAndSet(false) && context != null) { + context.getContentResolver().unregisterContentObserver(this); + fetchResultHandler.removeCallbacks(this); } } @Override public void onChange(boolean selfChange) { - mAsyncTaskExecutor.submit( + asyncTaskExecutor.submit( Tasks.CHECK_CONTENT_AFTER_CHANGE, new AsyncTask() { @Override public Boolean doInBackground(Void... params) { - return queryHasContent(mVoicemailUri); + return queryHasContent(voicemailUri); } @Override public void onPostExecute(Boolean hasContent) { - if (hasContent && mContext != null && mIsWaitingForResult.getAndSet(false)) { - mContext.getContentResolver().unregisterContentObserver(FetchResultHandler.this); + if (hasContent && context != null && isWaitingForResult.getAndSet(false)) { + context.getContentResolver().unregisterContentObserver(FetchResultHandler.this); showShareVoicemailButton(true); prepareContent(); } diff --git a/java/com/android/dialer/app/voicemail/WiredHeadsetManager.java b/java/com/android/dialer/app/voicemail/WiredHeadsetManager.java index 24d4c6ff7..2873f8d5e 100644 --- a/java/com/android/dialer/app/voicemail/WiredHeadsetManager.java +++ b/java/com/android/dialer/app/voicemail/WiredHeadsetManager.java @@ -20,50 +20,52 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; -import android.util.Log; +import com.android.dialer.common.LogUtil; /** Listens for and caches headset state. */ class WiredHeadsetManager { private static final String TAG = WiredHeadsetManager.class.getSimpleName(); - private final WiredHeadsetBroadcastReceiver mReceiver; - private boolean mIsPluggedIn; - private Listener mListener; - private Context mContext; + private final WiredHeadsetBroadcastReceiver receiver; + private boolean isPluggedIn; + private Listener listener; + private Context context; WiredHeadsetManager(Context context) { - mContext = context; - mReceiver = new WiredHeadsetBroadcastReceiver(); + this.context = context; + receiver = new WiredHeadsetBroadcastReceiver(); AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); - mIsPluggedIn = audioManager.isWiredHeadsetOn(); + isPluggedIn = audioManager.isWiredHeadsetOn(); } void setListener(Listener listener) { - mListener = listener; + this.listener = listener; } boolean isPluggedIn() { - return mIsPluggedIn; + return isPluggedIn; } void registerReceiver() { // Register for misc other intent broadcasts. IntentFilter intentFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); - mContext.registerReceiver(mReceiver, intentFilter); + context.registerReceiver(receiver, intentFilter); } void unregisterReceiver() { - mContext.unregisterReceiver(mReceiver); + context.unregisterReceiver(receiver); } private void onHeadsetPluggedInChanged(boolean isPluggedIn) { - if (mIsPluggedIn != isPluggedIn) { - Log.v(TAG, "onHeadsetPluggedInChanged, mIsPluggedIn: " + mIsPluggedIn + " -> " + isPluggedIn); - boolean oldIsPluggedIn = mIsPluggedIn; - mIsPluggedIn = isPluggedIn; - if (mListener != null) { - mListener.onWiredHeadsetPluggedInChanged(oldIsPluggedIn, mIsPluggedIn); + if (this.isPluggedIn != isPluggedIn) { + LogUtil.v( + TAG, + "onHeadsetPluggedInChanged, mIsPluggedIn: " + this.isPluggedIn + " -> " + isPluggedIn); + boolean oldIsPluggedIn = this.isPluggedIn; + this.isPluggedIn = isPluggedIn; + if (listener != null) { + listener.onWiredHeadsetPluggedInChanged(oldIsPluggedIn, this.isPluggedIn); } } } @@ -80,7 +82,7 @@ class WiredHeadsetManager { public void onReceive(Context context, Intent intent) { if (AudioManager.ACTION_HEADSET_PLUG.equals(intent.getAction())) { boolean isPluggedIn = intent.getIntExtra("state", 0) == 1; - Log.v(TAG, "ACTION_HEADSET_PLUG event, plugged in: " + isPluggedIn); + LogUtil.v(TAG, "ACTION_HEADSET_PLUG event, plugged in: " + isPluggedIn); onHeadsetPluggedInChanged(isPluggedIn); } } diff --git a/java/com/android/dialer/app/widget/ActionBarController.java b/java/com/android/dialer/app/widget/ActionBarController.java index 3daa0e2d4..8ab57bcfb 100644 --- a/java/com/android/dialer/app/widget/ActionBarController.java +++ b/java/com/android/dialer/app/widget/ActionBarController.java @@ -31,12 +31,12 @@ public class ActionBarController { private static final String KEY_IS_FADED_OUT = "key_actionbar_is_faded_out"; private static final String KEY_IS_EXPANDED = "key_actionbar_is_expanded"; - private ActivityUi mActivityUi; - private SearchEditTextLayout mSearchBox; + private ActivityUi activityUi; + private SearchEditTextLayout searchBox; - private boolean mIsActionBarSlidUp; + private boolean isActionBarSlidUp; - private final AnimationCallback mFadeOutCallback = + private final AnimationCallback fadeOutCallback = new AnimationCallback() { @Override public void onAnimationEnd() { @@ -49,24 +49,23 @@ public class ActionBarController { } }; - private ValueAnimator mAnimator; + private ValueAnimator animator; public ActionBarController(ActivityUi activityUi, SearchEditTextLayout searchBox) { - mActivityUi = activityUi; - mSearchBox = searchBox; + this.activityUi = activityUi; + this.searchBox = searchBox; } /** @return Whether or not the action bar is currently showing (both slid down and visible) */ public boolean isActionBarShowing() { - return !mIsActionBarSlidUp && !mSearchBox.isFadedOut(); + return !isActionBarSlidUp && !searchBox.isFadedOut(); } /** Called when the user has tapped on the collapsed search box, to start a new search query. */ public void onSearchBoxTapped() { - LogUtil.d( - "ActionBarController.onSearchBoxTapped", "isInSearchUi " + mActivityUi.isInSearchUi()); - if (!mActivityUi.isInSearchUi()) { - mSearchBox.expand(true /* animate */, true /* requestFocus */); + LogUtil.d("ActionBarController.onSearchBoxTapped", "isInSearchUi " + activityUi.isInSearchUi()); + if (!activityUi.isInSearchUi()) { + searchBox.expand(true /* animate */, true /* requestFocus */); } } @@ -75,13 +74,13 @@ public class ActionBarController { LogUtil.d( "ActionBarController.onSearchUIExited", "isExpanded: %b, isFadedOut %b", - mSearchBox.isExpanded(), - mSearchBox.isFadedOut()); - if (mSearchBox.isExpanded()) { - mSearchBox.collapse(true /* animate */); + searchBox.isExpanded(), + searchBox.isFadedOut()); + if (searchBox.isExpanded()) { + searchBox.collapse(true /* animate */); } - if (mSearchBox.isFadedOut()) { - mSearchBox.fadeIn(); + if (searchBox.isFadedOut()) { + searchBox.fadeIn(); } slideActionBar(false /* slideUp */, false /* animate */); @@ -95,16 +94,16 @@ public class ActionBarController { LogUtil.d( "ActionBarController.onDialpadDown", "isInSearchUi: %b, hasSearchQuery: %b, isFadedOut: %b, isExpanded: %b", - mActivityUi.isInSearchUi(), - mActivityUi.hasSearchQuery(), - mSearchBox.isFadedOut(), - mSearchBox.isExpanded()); - if (mActivityUi.isInSearchUi()) { - if (mSearchBox.isFadedOut()) { - mSearchBox.setVisible(true); + activityUi.isInSearchUi(), + activityUi.hasSearchQuery(), + searchBox.isFadedOut(), + searchBox.isExpanded()); + if (activityUi.isInSearchUi()) { + if (searchBox.isFadedOut()) { + searchBox.setVisible(true); } - if (!mSearchBox.isExpanded()) { - mSearchBox.expand(false /* animate */, false /* requestFocus */); + if (!searchBox.isExpanded()) { + searchBox.expand(false /* animate */, false /* requestFocus */); } slideActionBar(false /* slideUp */, true /* animate */); } @@ -115,71 +114,71 @@ public class ActionBarController { * state changes have actually occurred. */ public void onDialpadUp() { - LogUtil.d("ActionBarController.onDialpadUp", "isInSearchUi " + mActivityUi.isInSearchUi()); - if (mActivityUi.isInSearchUi()) { + LogUtil.d("ActionBarController.onDialpadUp", "isInSearchUi " + activityUi.isInSearchUi()); + if (activityUi.isInSearchUi()) { slideActionBar(true /* slideUp */, true /* animate */); } else { // From the lists fragment - mSearchBox.fadeOut(mFadeOutCallback); + searchBox.fadeOut(fadeOutCallback); } } public void slideActionBar(boolean slideUp, boolean animate) { LogUtil.d("ActionBarController.slidingActionBar", "up: %b, animate: %b", slideUp, animate); - if (mAnimator != null && mAnimator.isRunning()) { - mAnimator.cancel(); - mAnimator.removeAllUpdateListeners(); + if (animator != null && animator.isRunning()) { + animator.cancel(); + animator.removeAllUpdateListeners(); } if (animate) { - mAnimator = slideUp ? ValueAnimator.ofFloat(0, 1) : ValueAnimator.ofFloat(1, 0); - mAnimator.addUpdateListener( + animator = slideUp ? ValueAnimator.ofFloat(0, 1) : ValueAnimator.ofFloat(1, 0); + animator.addUpdateListener( animation -> { final float value = (float) animation.getAnimatedValue(); - setHideOffset((int) (mActivityUi.getActionBarHeight() * value)); + setHideOffset((int) (activityUi.getActionBarHeight() * value)); }); - mAnimator.start(); + animator.start(); } else { - setHideOffset(slideUp ? mActivityUi.getActionBarHeight() : 0); + setHideOffset(slideUp ? activityUi.getActionBarHeight() : 0); } - mIsActionBarSlidUp = slideUp; + isActionBarSlidUp = slideUp; } public void setAlpha(float alphaValue) { - mSearchBox.animate().alpha(alphaValue).start(); + searchBox.animate().alpha(alphaValue).start(); } private void setHideOffset(int offset) { - mActivityUi.setActionBarHideOffset(offset); + activityUi.setActionBarHideOffset(offset); } /** Saves the current state of the action bar into a provided {@link Bundle} */ public void saveInstanceState(Bundle outState) { - outState.putBoolean(KEY_IS_SLID_UP, mIsActionBarSlidUp); - outState.putBoolean(KEY_IS_FADED_OUT, mSearchBox.isFadedOut()); - outState.putBoolean(KEY_IS_EXPANDED, mSearchBox.isExpanded()); + outState.putBoolean(KEY_IS_SLID_UP, isActionBarSlidUp); + outState.putBoolean(KEY_IS_FADED_OUT, searchBox.isFadedOut()); + outState.putBoolean(KEY_IS_EXPANDED, searchBox.isExpanded()); } /** Restores the action bar state from a provided {@link Bundle}. */ public void restoreInstanceState(Bundle inState) { - mIsActionBarSlidUp = inState.getBoolean(KEY_IS_SLID_UP); + isActionBarSlidUp = inState.getBoolean(KEY_IS_SLID_UP); final boolean isSearchBoxFadedOut = inState.getBoolean(KEY_IS_FADED_OUT); if (isSearchBoxFadedOut) { - if (!mSearchBox.isFadedOut()) { - mSearchBox.setVisible(false); + if (!searchBox.isFadedOut()) { + searchBox.setVisible(false); } - } else if (mSearchBox.isFadedOut()) { - mSearchBox.setVisible(true); + } else if (searchBox.isFadedOut()) { + searchBox.setVisible(true); } final boolean isSearchBoxExpanded = inState.getBoolean(KEY_IS_EXPANDED); if (isSearchBoxExpanded) { - if (!mSearchBox.isExpanded()) { - mSearchBox.expand(false, false); + if (!searchBox.isExpanded()) { + searchBox.expand(false, false); } - } else if (mSearchBox.isExpanded()) { - mSearchBox.collapse(false); + } else if (searchBox.isExpanded()) { + searchBox.collapse(false); } } @@ -188,7 +187,7 @@ public class ActionBarController { * laid out and actually has a height. */ public void restoreActionBarOffset() { - slideActionBar(mIsActionBarSlidUp /* slideUp */, false /* animate */); + slideActionBar(isActionBarSlidUp /* slideUp */, false /* animate */); } public interface ActivityUi { diff --git a/java/com/android/dialer/app/widget/SearchEditTextLayout.java b/java/com/android/dialer/app/widget/SearchEditTextLayout.java index ebd62080b..40189a873 100644 --- a/java/com/android/dialer/app/widget/SearchEditTextLayout.java +++ b/java/com/android/dialer/app/widget/SearchEditTextLayout.java @@ -36,83 +36,83 @@ public class SearchEditTextLayout extends FrameLayout { private static final float EXPAND_MARGIN_FRACTION_START = 0.8f; private static final int ANIMATION_DURATION = 200; /* Subclass-visible for testing */ - protected boolean mIsExpanded = false; - protected boolean mIsFadedOut = false; - private OnKeyListener mPreImeKeyListener; - private int mTopMargin; - private int mBottomMargin; - private int mLeftMargin; - private int mRightMargin; - private float mCollapsedElevation; - private View mCollapsed; - private View mExpanded; - private EditText mSearchView; - private View mSearchIcon; - private View mCollapsedSearchBox; - private View mVoiceSearchButtonView; - private View mOverflowButtonView; - private View mClearButtonView; - - private ValueAnimator mAnimator; - - private Callback mCallback; - - private boolean mVoiceSearchEnabled; + protected boolean isExpanded = false; + protected boolean isFadedOut = false; + private OnKeyListener preImeKeyListener; + private int topMargin; + private int bottomMargin; + private int leftMargin; + private int rightMargin; + private float collapsedElevation; + private View collapsed; + private View expanded; + private EditText searchView; + private View searchIcon; + private View collapsedSearchBox; + private View voiceSearchButtonView; + private View overflowButtonView; + private View clearButtonView; + + private ValueAnimator animator; + + private Callback callback; + + private boolean voiceSearchEnabled; public SearchEditTextLayout(Context context, AttributeSet attrs) { super(context, attrs); } public void setPreImeKeyListener(OnKeyListener listener) { - mPreImeKeyListener = listener; + preImeKeyListener = listener; } public void setCallback(Callback listener) { - mCallback = listener; + callback = listener; } public void setVoiceSearchEnabled(boolean enabled) { - mVoiceSearchEnabled = enabled; - updateVisibility(mIsExpanded); + voiceSearchEnabled = enabled; + updateVisibility(isExpanded); } @Override protected void onFinishInflate() { MarginLayoutParams params = (MarginLayoutParams) getLayoutParams(); - mTopMargin = params.topMargin; - mBottomMargin = params.bottomMargin; - mLeftMargin = params.leftMargin; - mRightMargin = params.rightMargin; + topMargin = params.topMargin; + bottomMargin = params.bottomMargin; + leftMargin = params.leftMargin; + rightMargin = params.rightMargin; - mCollapsedElevation = getElevation(); + collapsedElevation = getElevation(); - mCollapsed = findViewById(R.id.search_box_collapsed); - mExpanded = findViewById(R.id.search_box_expanded); - mSearchView = (EditText) mExpanded.findViewById(R.id.search_view); + collapsed = findViewById(R.id.search_box_collapsed); + expanded = findViewById(R.id.search_box_expanded); + searchView = (EditText) expanded.findViewById(R.id.search_view); - mSearchIcon = findViewById(R.id.search_magnifying_glass); - mCollapsedSearchBox = findViewById(R.id.search_box_start_search); - mVoiceSearchButtonView = findViewById(R.id.voice_search_button); - mOverflowButtonView = findViewById(R.id.dialtacts_options_menu_button); - mClearButtonView = findViewById(R.id.search_close_button); + searchIcon = findViewById(R.id.search_magnifying_glass); + collapsedSearchBox = findViewById(R.id.search_box_start_search); + voiceSearchButtonView = findViewById(R.id.voice_search_button); + overflowButtonView = findViewById(R.id.dialtacts_options_menu_button); + clearButtonView = findViewById(R.id.search_close_button); // Convert a long click into a click to expand the search box. Touch events are also // forwarded to the searchView. This accelerates the long-press scenario for copy/paste. - mCollapsed.setOnLongClickListener( + collapsed.setOnLongClickListener( new OnLongClickListener() { @Override public boolean onLongClick(View view) { - mCollapsed.performClick(); + collapsed.performClick(); return false; } }); - mCollapsed.setOnTouchListener( + collapsed.setOnTouchListener( (v, event) -> { - mSearchView.onTouchEvent(event); + searchView.onTouchEvent(event); return false; }); - mSearchView.setOnFocusChangeListener( + searchView.setOnFocusChangeListener( new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { @@ -124,24 +124,24 @@ public class SearchEditTextLayout extends FrameLayout { } }); - mSearchView.setOnClickListener( + searchView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { - if (mCallback != null) { - mCallback.onSearchViewClicked(); + if (callback != null) { + callback.onSearchViewClicked(); } } }); - mSearchView.addTextChangedListener( + searchView.addTextChangedListener( new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { - mClearButtonView.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE); + clearButtonView.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE); } @Override @@ -153,7 +153,7 @@ public class SearchEditTextLayout extends FrameLayout { new OnClickListener() { @Override public void onClick(View v) { - mSearchView.setText(null); + searchView.setText(null); } }); @@ -162,8 +162,8 @@ public class SearchEditTextLayout extends FrameLayout { new OnClickListener() { @Override public void onClick(View v) { - if (mCallback != null) { - mCallback.onBackButtonClicked(); + if (callback != null) { + callback.onBackButtonClicked(); } } }); @@ -173,8 +173,8 @@ public class SearchEditTextLayout extends FrameLayout { @Override public boolean dispatchKeyEventPreIme(KeyEvent event) { - if (mPreImeKeyListener != null) { - if (mPreImeKeyListener.onKey(this, event.getKeyCode(), event)) { + if (preImeKeyListener != null) { + if (preImeKeyListener.onKey(this, event.getKeyCode(), event)) { return true; } } @@ -187,28 +187,28 @@ public class SearchEditTextLayout extends FrameLayout { public void fadeOut(AnimUtils.AnimationCallback callback) { AnimUtils.fadeOut(this, ANIMATION_DURATION, callback); - mIsFadedOut = true; + isFadedOut = true; } public void fadeIn() { AnimUtils.fadeIn(this, ANIMATION_DURATION); - mIsFadedOut = false; + isFadedOut = false; } public void fadeIn(AnimUtils.AnimationCallback callback) { AnimUtils.fadeIn(this, ANIMATION_DURATION, AnimUtils.NO_DELAY, callback); - mIsFadedOut = false; + isFadedOut = false; } public void setVisible(boolean visible) { if (visible) { setAlpha(1); setVisibility(View.VISIBLE); - mIsFadedOut = false; + isFadedOut = false; } else { setAlpha(0); setVisibility(View.GONE); - mIsFadedOut = true; + isFadedOut = true; } } @@ -216,15 +216,15 @@ public class SearchEditTextLayout extends FrameLayout { updateVisibility(true /* isExpand */); if (animate) { - AnimUtils.crossFadeViews(mExpanded, mCollapsed, ANIMATION_DURATION); - mAnimator = ValueAnimator.ofFloat(EXPAND_MARGIN_FRACTION_START, 0f); + AnimUtils.crossFadeViews(expanded, collapsed, ANIMATION_DURATION); + animator = ValueAnimator.ofFloat(EXPAND_MARGIN_FRACTION_START, 0f); setMargins(EXPAND_MARGIN_FRACTION_START); prepareAnimator(); } else { - mExpanded.setVisibility(View.VISIBLE); - mExpanded.setAlpha(1); + expanded.setVisibility(View.VISIBLE); + expanded.setAlpha(1); setMargins(0f); - mCollapsed.setVisibility(View.GONE); + collapsed.setVisibility(View.GONE); } // Set 9-patch background. This owns the padding, so we need to restore the original values. @@ -237,27 +237,27 @@ public class SearchEditTextLayout extends FrameLayout { setPaddingRelative(paddingStart, paddingTop, paddingEnd, paddingBottom); if (requestFocus) { - mSearchView.requestFocus(); + searchView.requestFocus(); } - mIsExpanded = true; + isExpanded = true; } public void collapse(boolean animate) { updateVisibility(false /* isExpand */); if (animate) { - AnimUtils.crossFadeViews(mCollapsed, mExpanded, ANIMATION_DURATION); - mAnimator = ValueAnimator.ofFloat(0f, 1f); + AnimUtils.crossFadeViews(collapsed, expanded, ANIMATION_DURATION); + animator = ValueAnimator.ofFloat(0f, 1f); prepareAnimator(); } else { - mCollapsed.setVisibility(View.VISIBLE); - mCollapsed.setAlpha(1); + collapsed.setVisibility(View.VISIBLE); + collapsed.setAlpha(1); setMargins(1f); - mExpanded.setVisibility(View.GONE); + expanded.setVisibility(View.GONE); } - mIsExpanded = false; - setElevation(mCollapsedElevation); + isExpanded = false; + setElevation(collapsedElevation); setBackgroundResource(R.drawable.rounded_corner); } @@ -271,30 +271,30 @@ public class SearchEditTextLayout extends FrameLayout { int collapsedViewVisibility = isExpand ? View.GONE : View.VISIBLE; int expandedViewVisibility = isExpand ? View.VISIBLE : View.GONE; - mSearchIcon.setVisibility(collapsedViewVisibility); - mCollapsedSearchBox.setVisibility(collapsedViewVisibility); - if (mVoiceSearchEnabled) { - mVoiceSearchButtonView.setVisibility(collapsedViewVisibility); + searchIcon.setVisibility(collapsedViewVisibility); + collapsedSearchBox.setVisibility(collapsedViewVisibility); + if (voiceSearchEnabled) { + voiceSearchButtonView.setVisibility(collapsedViewVisibility); } else { - mVoiceSearchButtonView.setVisibility(View.GONE); + voiceSearchButtonView.setVisibility(View.GONE); } - mOverflowButtonView.setVisibility(collapsedViewVisibility); + overflowButtonView.setVisibility(collapsedViewVisibility); // TODO: Prevents keyboard from jumping up in landscape mode after exiting the // SearchFragment when the query string is empty. More elegant fix? - //mExpandedSearchBox.setVisibility(expandedViewVisibility); - if (TextUtils.isEmpty(mSearchView.getText())) { - mClearButtonView.setVisibility(View.GONE); + // mExpandedSearchBox.setVisibility(expandedViewVisibility); + if (TextUtils.isEmpty(searchView.getText())) { + clearButtonView.setVisibility(View.GONE); } else { - mClearButtonView.setVisibility(expandedViewVisibility); + clearButtonView.setVisibility(expandedViewVisibility); } } private void prepareAnimator() { - if (mAnimator != null) { - mAnimator.cancel(); + if (animator != null) { + animator.cancel(); } - mAnimator.addUpdateListener( + animator.addUpdateListener( new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { @@ -303,16 +303,16 @@ public class SearchEditTextLayout extends FrameLayout { } }); - mAnimator.setDuration(ANIMATION_DURATION); - mAnimator.start(); + animator.setDuration(ANIMATION_DURATION); + animator.start(); } public boolean isExpanded() { - return mIsExpanded; + return isExpanded; } public boolean isFadedOut() { - return mIsFadedOut; + return isFadedOut; } /** @@ -322,10 +322,10 @@ public class SearchEditTextLayout extends FrameLayout { */ private void setMargins(float fraction) { MarginLayoutParams params = (MarginLayoutParams) getLayoutParams(); - params.topMargin = (int) (mTopMargin * fraction); - params.bottomMargin = (int) (mBottomMargin * fraction); - params.leftMargin = (int) (mLeftMargin * fraction); - params.rightMargin = (int) (mRightMargin * fraction); + params.topMargin = (int) (topMargin * fraction); + params.bottomMargin = (int) (bottomMargin * fraction); + params.leftMargin = (int) (leftMargin * fraction); + params.rightMargin = (int) (rightMargin * fraction); requestLayout(); } diff --git a/java/com/android/dialer/blocking/BlockNumberDialogFragment.java b/java/com/android/dialer/blocking/BlockNumberDialogFragment.java index 7ef77c4b6..f723a9cbe 100644 --- a/java/com/android/dialer/blocking/BlockNumberDialogFragment.java +++ b/java/com/android/dialer/blocking/BlockNumberDialogFragment.java @@ -49,13 +49,13 @@ public class BlockNumberDialogFragment extends DialogFragment { private static final String ARG_COUNTRY_ISO = "argCountryIso"; private static final String ARG_DISPLAY_NUMBER = "argDisplayNumber"; private static final String ARG_PARENT_VIEW_ID = "parentViewId"; - private String mNumber; - private String mDisplayNumber; - private String mCountryIso; - private FilteredNumberAsyncQueryHandler mHandler; - private View mParentView; - private VisualVoicemailEnabledChecker mVoicemailEnabledChecker; - private Callback mCallback; + private String number; + private String displayNumber; + private String countryIso; + private FilteredNumberAsyncQueryHandler handler; + private View parentView; + private VisualVoicemailEnabledChecker voicemailEnabledChecker; + private Callback callback; public static BlockNumberDialogFragment show( Integer blockId, @@ -97,7 +97,7 @@ public class BlockNumberDialogFragment extends DialogFragment { public void setFilteredNumberAsyncQueryHandlerForTesting( FilteredNumberAsyncQueryHandler handler) { - mHandler = handler; + this.handler = handler; } @Override @@ -110,19 +110,19 @@ public class BlockNumberDialogFragment extends DialogFragment { super.onCreateDialog(savedInstanceState); final boolean isBlocked = getArguments().containsKey(ARG_BLOCK_ID); - mNumber = getArguments().getString(ARG_NUMBER); - mDisplayNumber = getArguments().getString(ARG_DISPLAY_NUMBER); - mCountryIso = getArguments().getString(ARG_COUNTRY_ISO); + number = getArguments().getString(ARG_NUMBER); + displayNumber = getArguments().getString(ARG_DISPLAY_NUMBER); + countryIso = getArguments().getString(ARG_COUNTRY_ISO); - if (TextUtils.isEmpty(mDisplayNumber)) { - mDisplayNumber = mNumber; + if (TextUtils.isEmpty(displayNumber)) { + displayNumber = number; } - mHandler = new FilteredNumberAsyncQueryHandler(getContext()); - mVoicemailEnabledChecker = new VisualVoicemailEnabledChecker(getActivity(), null); + handler = new FilteredNumberAsyncQueryHandler(getContext()); + voicemailEnabledChecker = new VisualVoicemailEnabledChecker(getActivity(), null); // Choose not to update VoicemailEnabledChecker, as checks should already been done in // all current use cases. - mParentView = getActivity().findViewById(getArguments().getInt(ARG_PARENT_VIEW_ID)); + parentView = getActivity().findViewById(getArguments().getInt(ARG_PARENT_VIEW_ID)); CharSequence title; String okText; @@ -132,16 +132,16 @@ public class BlockNumberDialogFragment extends DialogFragment { okText = getString(R.string.unblock_number_ok); message = ContactDisplayUtils.getTtsSpannedPhoneNumber( - getResources(), R.string.unblock_number_confirmation_title, mDisplayNumber) + getResources(), R.string.unblock_number_confirmation_title, displayNumber) .toString(); } else { title = ContactDisplayUtils.getTtsSpannedPhoneNumber( - getResources(), R.string.block_number_confirmation_title, mDisplayNumber); + getResources(), R.string.block_number_confirmation_title, displayNumber); okText = getString(R.string.block_number_ok); if (FilteredNumberCompat.useNewFiltering(getContext())) { message = getString(R.string.block_number_confirmation_message_new_filtering); - } else if (mVoicemailEnabledChecker.isVisualVoicemailEnabled()) { + } else if (voicemailEnabledChecker.isVisualVoicemailEnabled()) { message = getString(R.string.block_number_confirmation_message_vvm); } else { message = getString(R.string.block_number_confirmation_message_no_vvm); @@ -171,13 +171,13 @@ public class BlockNumberDialogFragment extends DialogFragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - String e164Number = PhoneNumberUtils.formatNumberToE164(mNumber, mCountryIso); - if (!FilteredNumbersUtil.canBlockNumber(getContext(), e164Number, mNumber)) { + String e164Number = PhoneNumberUtils.formatNumberToE164(number, countryIso); + if (!FilteredNumbersUtil.canBlockNumber(getContext(), e164Number, number)) { dismiss(); Toast.makeText( getContext(), ContactDisplayUtils.getTtsSpannedPhoneNumber( - getResources(), R.string.invalidNumber, mDisplayNumber), + getResources(), R.string.invalidNumber, displayNumber), Toast.LENGTH_SHORT) .show(); } @@ -187,23 +187,23 @@ public class BlockNumberDialogFragment extends DialogFragment { public void onPause() { // Dismiss on rotation. dismiss(); - mCallback = null; + callback = null; super.onPause(); } public void setCallback(Callback callback) { - mCallback = callback; + this.callback = callback; } private CharSequence getBlockedMessage() { return ContactDisplayUtils.getTtsSpannedPhoneNumber( - getResources(), R.string.snackbar_number_blocked, mDisplayNumber); + getResources(), R.string.snackbar_number_blocked, displayNumber); } private CharSequence getUnblockedMessage() { return ContactDisplayUtils.getTtsSpannedPhoneNumber( - getResources(), R.string.snackbar_number_unblocked, mDisplayNumber); + getResources(), R.string.snackbar_number_unblocked, displayNumber); } private int getActionTextColor() { @@ -213,7 +213,7 @@ public class BlockNumberDialogFragment extends DialogFragment { private void blockNumber() { final CharSequence message = getBlockedMessage(); final CharSequence undoMessage = getUnblockedMessage(); - final Callback callback = mCallback; + final Callback callback = this.callback; final int actionTextColor = getActionTextColor(); final Context applicationContext = getContext().getApplicationContext(); @@ -221,7 +221,7 @@ public class BlockNumberDialogFragment extends DialogFragment { new OnUnblockNumberListener() { @Override public void onUnblockComplete(int rows, ContentValues values) { - Snackbar.make(mParentView, undoMessage, Snackbar.LENGTH_LONG).show(); + Snackbar.make(parentView, undoMessage, Snackbar.LENGTH_LONG).show(); if (callback != null) { callback.onChangeFilteredNumberUndo(); } @@ -239,11 +239,11 @@ public class BlockNumberDialogFragment extends DialogFragment { // Delete the newly created row on 'undo'. Logger.get(applicationContext) .logInteraction(InteractionEvent.Type.UNDO_BLOCK_NUMBER); - mHandler.unblock(onUndoListener, uri); + handler.unblock(onUndoListener, uri); } }; - Snackbar.make(mParentView, message, Snackbar.LENGTH_LONG) + Snackbar.make(parentView, message, Snackbar.LENGTH_LONG) .setAction(R.string.block_number_undo, undoListener) .setActionTextColor(actionTextColor) .show(); @@ -258,13 +258,13 @@ public class BlockNumberDialogFragment extends DialogFragment { } }; - mHandler.blockNumber(onBlockNumberListener, mNumber, mCountryIso); + handler.blockNumber(onBlockNumberListener, number, countryIso); } private void unblockNumber() { final CharSequence message = getUnblockedMessage(); final CharSequence undoMessage = getBlockedMessage(); - final Callback callback = mCallback; + final Callback callback = this.callback; final int actionTextColor = getActionTextColor(); final Context applicationContext = getContext().getApplicationContext(); @@ -272,14 +272,14 @@ public class BlockNumberDialogFragment extends DialogFragment { new OnBlockNumberListener() { @Override public void onBlockComplete(final Uri uri) { - Snackbar.make(mParentView, undoMessage, Snackbar.LENGTH_LONG).show(); + Snackbar.make(parentView, undoMessage, Snackbar.LENGTH_LONG).show(); if (callback != null) { callback.onChangeFilteredNumberUndo(); } } }; - mHandler.unblock( + handler.unblock( new OnUnblockNumberListener() { @Override public void onUnblockComplete(int rows, final ContentValues values) { @@ -290,11 +290,11 @@ public class BlockNumberDialogFragment extends DialogFragment { // Re-insert the row on 'undo', with a new ID. Logger.get(applicationContext) .logInteraction(InteractionEvent.Type.UNDO_UNBLOCK_NUMBER); - mHandler.blockNumber(onUndoListener, values); + handler.blockNumber(onUndoListener, values); } }; - Snackbar.make(mParentView, message, Snackbar.LENGTH_LONG) + Snackbar.make(parentView, message, Snackbar.LENGTH_LONG) .setAction(R.string.block_number_undo, undoListener) .setActionTextColor(actionTextColor) .show(); diff --git a/java/com/android/dialer/blocking/BlockReportSpamDialogs.java b/java/com/android/dialer/blocking/BlockReportSpamDialogs.java index b5f81fcc5..255d7cbf9 100644 --- a/java/com/android/dialer/blocking/BlockReportSpamDialogs.java +++ b/java/com/android/dialer/blocking/BlockReportSpamDialogs.java @@ -102,18 +102,18 @@ public class BlockReportSpamDialogs { private static class CommonDialogsFragment extends DialogFragment { /** The number to display in the dialog title. */ - protected String mDisplayNumber; + protected String displayNumber; /** Called when dialog positive button is pressed. */ - protected OnConfirmListener mPositiveListener; + protected OnConfirmListener positiveListener; /** Called when dialog is dismissed. */ - @Nullable protected DialogInterface.OnDismissListener mDismissListener; + @Nullable protected DialogInterface.OnDismissListener dismissListener; @Override public void onDismiss(DialogInterface dialog) { - if (mDismissListener != null) { - mDismissListener.onDismiss(dialog); + if (dismissListener != null) { + dismissListener.onDismiss(dialog); } super.onDismiss(dialog); } @@ -122,9 +122,9 @@ public class BlockReportSpamDialogs { public void onPause() { // The dialog is dismissed onPause, i.e. rotation. dismiss(); - mDismissListener = null; - mPositiveListener = null; - mDisplayNumber = null; + dismissListener = null; + positiveListener = null; + displayNumber = null; super.onPause(); } } @@ -133,10 +133,10 @@ public class BlockReportSpamDialogs { public static class BlockReportSpamDialogFragment extends CommonDialogsFragment { /** Called when dialog positive button is pressed. */ - private OnSpamDialogClickListener mPositiveListener; + private OnSpamDialogClickListener positiveListener; /** Whether the mark as spam checkbox is checked before displaying the dialog. */ - private boolean mSpamChecked; + private boolean spamChecked; public static DialogFragment newInstance( String displayNumber, @@ -144,10 +144,10 @@ public class BlockReportSpamDialogs { OnSpamDialogClickListener positiveListener, @Nullable DialogInterface.OnDismissListener dismissListener) { BlockReportSpamDialogFragment fragment = new BlockReportSpamDialogFragment(); - fragment.mSpamChecked = spamChecked; - fragment.mDisplayNumber = displayNumber; - fragment.mPositiveListener = positiveListener; - fragment.mDismissListener = dismissListener; + fragment.spamChecked = spamChecked; + fragment.displayNumber = displayNumber; + fragment.positiveListener = positiveListener; + fragment.dismissListener = dismissListener; return fragment; } @@ -158,12 +158,12 @@ public class BlockReportSpamDialogs { final CheckBox isSpamCheckbox = (CheckBox) dialogView.findViewById(R.id.report_number_as_spam_action); // Listen for changes on the checkbox and update if orientation changes - isSpamCheckbox.setChecked(mSpamChecked); + isSpamCheckbox.setChecked(spamChecked); isSpamCheckbox.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - mSpamChecked = isChecked; + spamChecked = isChecked; } }); @@ -174,14 +174,14 @@ public class BlockReportSpamDialogs { Dialog dialog = alertDialogBuilder .setView(dialogView) - .setTitle(getString(R.string.block_report_number_alert_title, mDisplayNumber)) + .setTitle(getString(R.string.block_report_number_alert_title, displayNumber)) .setPositiveButton( R.string.block_number_ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); - mPositiveListener.onClick(isSpamCheckbox.isChecked()); + positiveListener.onClick(isSpamCheckbox.isChecked()); } }) .create(); @@ -201,9 +201,9 @@ public class BlockReportSpamDialogs { OnConfirmListener positiveListener, @Nullable DialogInterface.OnDismissListener dismissListener) { BlockDialogFragment fragment = new BlockDialogFragment(); - fragment.mDisplayNumber = displayNumber; - fragment.mPositiveListener = positiveListener; - fragment.mDismissListener = dismissListener; + fragment.displayNumber = displayNumber; + fragment.positiveListener = positiveListener; + fragment.dismissListener = dismissListener; fragment.isSpamEnabled = isSpamEnabled; return fragment; } @@ -215,14 +215,14 @@ public class BlockReportSpamDialogs { AlertDialog.Builder alertDialogBuilder = createDialogBuilder(getActivity(), this); Dialog dialog = alertDialogBuilder - .setTitle(getString(R.string.block_number_confirmation_title, mDisplayNumber)) + .setTitle(getString(R.string.block_number_confirmation_title, displayNumber)) .setMessage( isSpamEnabled ? getString( R.string.block_number_alert_details, getBlockMessage(getContext())) : getString(R.string.block_report_number_alert_details)) .setPositiveButton( - R.string.block_number_ok, createGenericOnClickListener(this, mPositiveListener)) + R.string.block_number_ok, createGenericOnClickListener(this, positiveListener)) .create(); dialog.setCanceledOnTouchOutside(true); return dialog; @@ -233,7 +233,7 @@ public class BlockReportSpamDialogs { public static class UnblockDialogFragment extends CommonDialogsFragment { /** Whether or not the number is spam. */ - private boolean mIsSpam; + private boolean isSpam; public static DialogFragment newInstance( String displayNumber, @@ -241,10 +241,10 @@ public class BlockReportSpamDialogs { OnConfirmListener positiveListener, @Nullable DialogInterface.OnDismissListener dismissListener) { UnblockDialogFragment fragment = new UnblockDialogFragment(); - fragment.mDisplayNumber = displayNumber; - fragment.mIsSpam = isSpam; - fragment.mPositiveListener = positiveListener; - fragment.mDismissListener = dismissListener; + fragment.displayNumber = displayNumber; + fragment.isSpam = isSpam; + fragment.positiveListener = positiveListener; + fragment.dismissListener = dismissListener; return fragment; } @@ -253,18 +253,18 @@ public class BlockReportSpamDialogs { super.onCreateDialog(savedInstanceState); // Return the newly created dialog AlertDialog.Builder alertDialogBuilder = createDialogBuilder(getActivity(), this); - if (mIsSpam) { + if (isSpam) { alertDialogBuilder .setMessage(R.string.unblock_number_alert_details) - .setTitle(getString(R.string.unblock_report_number_alert_title, mDisplayNumber)); + .setTitle(getString(R.string.unblock_report_number_alert_title, displayNumber)); } else { alertDialogBuilder.setMessage( - getString(R.string.unblock_report_number_alert_title, mDisplayNumber)); + getString(R.string.unblock_report_number_alert_title, displayNumber)); } Dialog dialog = alertDialogBuilder .setPositiveButton( - R.string.unblock_number_ok, createGenericOnClickListener(this, mPositiveListener)) + R.string.unblock_number_ok, createGenericOnClickListener(this, positiveListener)) .create(); dialog.setCanceledOnTouchOutside(true); return dialog; @@ -279,9 +279,9 @@ public class BlockReportSpamDialogs { OnConfirmListener positiveListener, @Nullable DialogInterface.OnDismissListener dismissListener) { ReportNotSpamDialogFragment fragment = new ReportNotSpamDialogFragment(); - fragment.mDisplayNumber = displayNumber; - fragment.mPositiveListener = positiveListener; - fragment.mDismissListener = dismissListener; + fragment.displayNumber = displayNumber; + fragment.positiveListener = positiveListener; + fragment.dismissListener = dismissListener; return fragment; } @@ -293,10 +293,10 @@ public class BlockReportSpamDialogs { Dialog dialog = alertDialogBuilder .setTitle(R.string.report_not_spam_alert_title) - .setMessage(getString(R.string.report_not_spam_alert_details, mDisplayNumber)) + .setMessage(getString(R.string.report_not_spam_alert_details, displayNumber)) .setPositiveButton( R.string.report_not_spam_alert_button, - createGenericOnClickListener(this, mPositiveListener)) + createGenericOnClickListener(this, positiveListener)) .create(); dialog.setCanceledOnTouchOutside(true); return dialog; diff --git a/java/com/android/dialer/blocking/FilteredNumberProvider.java b/java/com/android/dialer/blocking/FilteredNumberProvider.java index 8ed781e73..3fad4e24f 100644 --- a/java/com/android/dialer/blocking/FilteredNumberProvider.java +++ b/java/com/android/dialer/blocking/FilteredNumberProvider.java @@ -38,20 +38,20 @@ public class FilteredNumberProvider extends ContentProvider { private static final int FILTERED_NUMBERS_TABLE = 1; private static final int FILTERED_NUMBERS_TABLE_ID = 2; - private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); - private DialerDatabaseHelper mDialerDatabaseHelper; + private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + private DialerDatabaseHelper dialerDatabaseHelper; @Override public boolean onCreate() { - mDialerDatabaseHelper = Database.get(getContext()).getDatabaseHelper(getContext()); - if (mDialerDatabaseHelper == null) { + dialerDatabaseHelper = Database.get(getContext()).getDatabaseHelper(getContext()); + if (dialerDatabaseHelper == null) { return false; } - sUriMatcher.addURI( + uriMatcher.addURI( FilteredNumberContract.AUTHORITY, FilteredNumberContract.FilteredNumber.FILTERED_NUMBERS_TABLE, FILTERED_NUMBERS_TABLE); - sUriMatcher.addURI( + uriMatcher.addURI( FilteredNumberContract.AUTHORITY, FilteredNumberContract.FilteredNumber.FILTERED_NUMBERS_TABLE + "/#", FILTERED_NUMBERS_TABLE_ID); @@ -61,10 +61,10 @@ public class FilteredNumberProvider extends ContentProvider { @Override public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - final SQLiteDatabase db = mDialerDatabaseHelper.getReadableDatabase(); + final SQLiteDatabase db = dialerDatabaseHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(DialerDatabaseHelper.Tables.FILTERED_NUMBER_TABLE); - final int match = sUriMatcher.match(uri); + final int match = uriMatcher.match(uri); switch (match) { case FILTERED_NUMBERS_TABLE: break; @@ -91,7 +91,7 @@ public class FilteredNumberProvider extends ContentProvider { @Override public Uri insert(Uri uri, ContentValues values) { - SQLiteDatabase db = mDialerDatabaseHelper.getWritableDatabase(); + SQLiteDatabase db = dialerDatabaseHelper.getWritableDatabase(); setDefaultValues(values); long id = db.insert(DialerDatabaseHelper.Tables.FILTERED_NUMBER_TABLE, null, values); if (id < 0) { @@ -120,8 +120,8 @@ public class FilteredNumberProvider extends ContentProvider { @Override public int delete(Uri uri, String selection, String[] selectionArgs) { - SQLiteDatabase db = mDialerDatabaseHelper.getWritableDatabase(); - final int match = sUriMatcher.match(uri); + SQLiteDatabase db = dialerDatabaseHelper.getWritableDatabase(); + final int match = uriMatcher.match(uri); switch (match) { case FILTERED_NUMBERS_TABLE: break; @@ -141,8 +141,8 @@ public class FilteredNumberProvider extends ContentProvider { @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { - SQLiteDatabase db = mDialerDatabaseHelper.getWritableDatabase(); - final int match = sUriMatcher.match(uri); + SQLiteDatabase db = dialerDatabaseHelper.getWritableDatabase(); + final int match = uriMatcher.match(uri); switch (match) { case FILTERED_NUMBERS_TABLE: break; diff --git a/java/com/android/dialer/blocking/MigrateBlockedNumbersDialogFragment.java b/java/com/android/dialer/blocking/MigrateBlockedNumbersDialogFragment.java index 76e50b38e..9b416ff5e 100644 --- a/java/com/android/dialer/blocking/MigrateBlockedNumbersDialogFragment.java +++ b/java/com/android/dialer/blocking/MigrateBlockedNumbersDialogFragment.java @@ -32,8 +32,8 @@ import java.util.Objects; */ public class MigrateBlockedNumbersDialogFragment extends DialogFragment { - private BlockedNumbersMigrator mBlockedNumbersMigrator; - private BlockedNumbersMigrator.Listener mMigrationListener; + private BlockedNumbersMigrator blockedNumbersMigrator; + private BlockedNumbersMigrator.Listener migrationListener; /** * Creates a new MigrateBlockedNumbersDialogFragment. @@ -49,8 +49,8 @@ public class MigrateBlockedNumbersDialogFragment extends DialogFragment { BlockedNumbersMigrator blockedNumbersMigrator, BlockedNumbersMigrator.Listener migrationListener) { MigrateBlockedNumbersDialogFragment fragment = new MigrateBlockedNumbersDialogFragment(); - fragment.mBlockedNumbersMigrator = Objects.requireNonNull(blockedNumbersMigrator); - fragment.mMigrationListener = Objects.requireNonNull(migrationListener); + fragment.blockedNumbersMigrator = Objects.requireNonNull(blockedNumbersMigrator); + fragment.migrationListener = Objects.requireNonNull(migrationListener); return fragment; } @@ -90,12 +90,12 @@ public class MigrateBlockedNumbersDialogFragment extends DialogFragment { public void onClick(View v) { alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setEnabled(false); - mBlockedNumbersMigrator.migrate( + blockedNumbersMigrator.migrate( new Listener() { @Override public void onComplete() { alertDialog.dismiss(); - mMigrationListener.onComplete(); + migrationListener.onComplete(); } }); } @@ -106,8 +106,8 @@ public class MigrateBlockedNumbersDialogFragment extends DialogFragment { public void onPause() { // The dialog is dismissed and state is cleaned up onPause, i.e. rotation. dismiss(); - mBlockedNumbersMigrator = null; - mMigrationListener = null; + blockedNumbersMigrator = null; + migrationListener = null; super.onPause(); } } diff --git a/java/com/android/dialer/callcomposer/camera/CameraManager.java b/java/com/android/dialer/callcomposer/camera/CameraManager.java index b850a193f..c61f57050 100644 --- a/java/com/android/dialer/callcomposer/camera/CameraManager.java +++ b/java/com/android/dialer/callcomposer/camera/CameraManager.java @@ -93,28 +93,28 @@ public class CameraManager implements FocusOverlayManager.Listener { } }; - private static CameraManager sInstance; + private static CameraManager instance; /** The CameraInfo for the currently selected camera */ - private final CameraInfo mCameraInfo; + private final CameraInfo cameraInfo; /** The index of the selected camera or NO_CAMERA_SELECTED if a camera hasn't been selected yet */ - private int mCameraIndex; + private int cameraIndex; /** True if the device has front and back cameras */ - private final boolean mHasFrontAndBackCamera; + private final boolean hasFrontAndBackCamera; /** True if the camera should be open (may not yet be actually open) */ - private boolean mOpenRequested; + private boolean openRequested; /** The preview view to show the preview on */ - private CameraPreview mCameraPreview; + private CameraPreview cameraPreview; /** The helper classs to handle orientation changes */ - private OrientationHandler mOrientationHandler; + private OrientationHandler orientationHandler; /** Tracks whether the preview has hardware acceleration */ - private boolean mIsHardwareAccelerationSupported; + private boolean isHardwareAccelerationSupported; /** * The task for opening the camera, so it doesn't block the UI thread Using AsyncTask rather than @@ -122,32 +122,32 @@ public class CameraManager implements FocusOverlayManager.Listener { * TODO(blemmon): If we have other AyncTasks (not SafeAsyncTasks) this may contend and we may need * to create a dedicated thread, or synchronize the threads in the thread pool */ - private AsyncTask mOpenCameraTask; + private AsyncTask openCameraTask; /** * The camera index that is queued to be opened, but not completed yet, or NO_CAMERA_SELECTED if * no open task is pending */ - private int mPendingOpenCameraIndex = NO_CAMERA_SELECTED; + private int pendingOpenCameraIndex = NO_CAMERA_SELECTED; /** The instance of the currently opened camera */ - private Camera mCamera; + private Camera camera; /** The rotation of the screen relative to the camera's natural orientation */ - private int mRotation; + private int rotation; /** The callback to notify when errors or other events occur */ - private CameraManagerListener mListener; + private CameraManagerListener listener; /** True if the camera is currently in the process of taking an image */ - private boolean mTakingPicture; + private boolean takingPicture; /** Manages auto focus visual and behavior */ - private final FocusOverlayManager mFocusOverlayManager; + private final FocusOverlayManager focusOverlayManager; private CameraManager() { - mCameraInfo = new CameraInfo(); - mCameraIndex = NO_CAMERA_SELECTED; + this.cameraInfo = new CameraInfo(); + cameraIndex = NO_CAMERA_SELECTED; // Check to see if a front and back camera exist boolean hasFrontCamera = false; @@ -169,19 +169,19 @@ public class CameraManager implements FocusOverlayManager.Listener { } catch (final RuntimeException e) { LogUtil.e("CameraManager.CameraManager", "Unable to load camera info", e); } - mHasFrontAndBackCamera = hasFrontCamera && hasBackCamera; - mFocusOverlayManager = new FocusOverlayManager(this, Looper.getMainLooper()); + hasFrontAndBackCamera = hasFrontCamera && hasBackCamera; + focusOverlayManager = new FocusOverlayManager(this, Looper.getMainLooper()); // Assume the best until we are proven otherwise - mIsHardwareAccelerationSupported = true; + isHardwareAccelerationSupported = true; } /** Gets the singleton instance */ public static CameraManager get() { - if (sInstance == null) { - sInstance = new CameraManager(); + if (instance == null) { + instance = new CameraManager(); } - return sInstance; + return instance; } /** @@ -191,7 +191,7 @@ public class CameraManager implements FocusOverlayManager.Listener { * @param preview The preview surface view */ void setSurface(final CameraPreview preview) { - if (preview == mCameraPreview) { + if (preview == cameraPreview) { return; } @@ -203,8 +203,8 @@ public class CameraManager implements FocusOverlayManager.Listener { public boolean onTouch(final View view, final MotionEvent motionEvent) { if ((motionEvent.getActionMasked() & MotionEvent.ACTION_UP) == MotionEvent.ACTION_UP) { - mFocusOverlayManager.setPreviewSize(view.getWidth(), view.getHeight()); - mFocusOverlayManager.onSingleTapUp( + focusOverlayManager.setPreviewSize(view.getWidth(), view.getHeight()); + focusOverlayManager.onSingleTapUp( (int) motionEvent.getX() + view.getLeft(), (int) motionEvent.getY() + view.getTop()); } @@ -213,20 +213,20 @@ public class CameraManager implements FocusOverlayManager.Listener { } }); } - mCameraPreview = preview; + cameraPreview = preview; tryShowPreview(); } public void setRenderOverlay(final RenderOverlay renderOverlay) { - mFocusOverlayManager.setFocusRenderer( + focusOverlayManager.setFocusRenderer( renderOverlay != null ? renderOverlay.getPieRenderer() : null); } /** Convenience function to swap between front and back facing cameras */ public void swapCamera() { - Assert.checkState(mCameraIndex >= 0); + Assert.checkState(cameraIndex >= 0); selectCamera( - mCameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT + cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT ? CameraInfo.CAMERA_FACING_BACK : CameraInfo.CAMERA_FACING_FRONT); } @@ -241,59 +241,59 @@ public class CameraManager implements FocusOverlayManager.Listener { public boolean selectCamera(final int desiredFacing) { try { // We already selected a camera facing that direction - if (mCameraIndex >= 0 && mCameraInfo.facing == desiredFacing) { + if (cameraIndex >= 0 && this.cameraInfo.facing == desiredFacing) { return true; } final int cameraCount = Camera.getNumberOfCameras(); Assert.checkState(cameraCount > 0); - mCameraIndex = NO_CAMERA_SELECTED; + cameraIndex = NO_CAMERA_SELECTED; setCamera(null); final CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < cameraCount; i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == desiredFacing) { - mCameraIndex = i; - Camera.getCameraInfo(i, mCameraInfo); + cameraIndex = i; + Camera.getCameraInfo(i, this.cameraInfo); break; } } // There's no camera in the desired facing direction, just select the first camera // regardless of direction - if (mCameraIndex < 0) { - mCameraIndex = 0; - Camera.getCameraInfo(0, mCameraInfo); + if (cameraIndex < 0) { + cameraIndex = 0; + Camera.getCameraInfo(0, this.cameraInfo); } - if (mOpenRequested) { + if (openRequested) { // The camera is open, so reopen with the newly selected camera openCamera(); } return true; } catch (final RuntimeException e) { LogUtil.e("CameraManager.selectCamera", "RuntimeException in CameraManager.selectCamera", e); - if (mListener != null) { - mListener.onCameraError(ERROR_OPENING_CAMERA, e); + if (listener != null) { + listener.onCameraError(ERROR_OPENING_CAMERA, e); } return false; } } public int getCameraIndex() { - return mCameraIndex; + return cameraIndex; } public void selectCameraByIndex(final int cameraIndex) { - if (mCameraIndex == cameraIndex) { + if (this.cameraIndex == cameraIndex) { return; } try { - mCameraIndex = cameraIndex; - Camera.getCameraInfo(mCameraIndex, mCameraInfo); - if (mOpenRequested) { + this.cameraIndex = cameraIndex; + Camera.getCameraInfo(this.cameraIndex, cameraInfo); + if (openRequested) { openCamera(); } } catch (final RuntimeException e) { @@ -301,8 +301,8 @@ public class CameraManager implements FocusOverlayManager.Listener { "CameraManager.selectCameraByIndex", "RuntimeException in CameraManager.selectCameraByIndex", e); - if (mListener != null) { - mListener.onCameraError(ERROR_OPENING_CAMERA, e); + if (listener != null) { + listener.onCameraError(ERROR_OPENING_CAMERA, e); } } } @@ -310,27 +310,27 @@ public class CameraManager implements FocusOverlayManager.Listener { @Nullable @VisibleForTesting public CameraInfo getCameraInfo() { - if (mCameraIndex == NO_CAMERA_SELECTED) { + if (cameraIndex == NO_CAMERA_SELECTED) { return null; } - return mCameraInfo; + return cameraInfo; } /** @return True if the device has both a front and back camera */ public boolean hasFrontAndBackCamera() { - return mHasFrontAndBackCamera; + return hasFrontAndBackCamera; } /** Opens the camera on a separate thread and initiates the preview if one is available */ void openCamera() { - if (mCameraIndex == NO_CAMERA_SELECTED) { + if (this.cameraIndex == NO_CAMERA_SELECTED) { // Ensure a selected camera if none is currently selected. This may happen if the // camera chooser is not the default media chooser. selectCamera(CameraInfo.CAMERA_FACING_BACK); } - mOpenRequested = true; + openRequested = true; // We're already opening the camera or already have the camera handle, nothing more to do - if (mPendingOpenCameraIndex == mCameraIndex || mCamera != null) { + if (pendingOpenCameraIndex == this.cameraIndex || this.camera != null) { return; } @@ -338,25 +338,27 @@ public class CameraManager implements FocusOverlayManager.Listener { boolean delayTask = false; // Cancel any previous open camera tasks - if (mOpenCameraTask != null) { - mPendingOpenCameraIndex = NO_CAMERA_SELECTED; + if (openCameraTask != null) { + pendingOpenCameraIndex = NO_CAMERA_SELECTED; delayTask = true; } - mPendingOpenCameraIndex = mCameraIndex; - mOpenCameraTask = + pendingOpenCameraIndex = this.cameraIndex; + openCameraTask = new AsyncTask() { - private Exception mException; + private Exception exception; @Override protected Camera doInBackground(final Integer... params) { try { final int cameraIndex = params[0]; - LogUtil.v("CameraManager.doInBackground", "Opening camera " + mCameraIndex); + LogUtil.v( + "CameraManager.doInBackground", + "Opening camera " + CameraManager.this.cameraIndex); return Camera.open(cameraIndex); } catch (final Exception e) { LogUtil.e("CameraManager.doInBackground", "Exception while opening camera", e); - mException = e; + exception = e; return null; } } @@ -364,7 +366,7 @@ public class CameraManager implements FocusOverlayManager.Listener { @Override protected void onPostExecute(final Camera camera) { // If we completed, but no longer want this camera, then release the camera - if (mOpenCameraTask != this || !mOpenRequested) { + if (openCameraTask != this || !openRequested) { releaseCamera(camera); cleanup(); return; @@ -374,11 +376,11 @@ public class CameraManager implements FocusOverlayManager.Listener { LogUtil.v( "CameraManager.onPostExecute", - "Opened camera " + mCameraIndex + " " + (camera != null)); + "Opened camera " + CameraManager.this.cameraIndex + " " + (camera != null)); setCamera(camera); if (camera == null) { - if (mListener != null) { - mListener.onCameraError(ERROR_OPENING_CAMERA, mException); + if (listener != null) { + listener.onCameraError(ERROR_OPENING_CAMERA, exception); } LogUtil.e("CameraManager.onPostExecute", "Error opening camera"); } @@ -391,24 +393,24 @@ public class CameraManager implements FocusOverlayManager.Listener { } private void cleanup() { - mPendingOpenCameraIndex = NO_CAMERA_SELECTED; - if (mOpenCameraTask != null && mOpenCameraTask.getStatus() == Status.PENDING) { + pendingOpenCameraIndex = NO_CAMERA_SELECTED; + if (openCameraTask != null && openCameraTask.getStatus() == Status.PENDING) { // If there's another task waiting on this one to complete, start it now - mOpenCameraTask.execute(mCameraIndex); + openCameraTask.execute(CameraManager.this.cameraIndex); } else { - mOpenCameraTask = null; + openCameraTask = null; } } }; - LogUtil.v("CameraManager.openCamera", "Start opening camera " + mCameraIndex); + LogUtil.v("CameraManager.openCamera", "Start opening camera " + this.cameraIndex); if (!delayTask) { - mOpenCameraTask.execute(mCameraIndex); + openCameraTask.execute(this.cameraIndex); } } /** Closes the camera releasing the resources it uses */ void closeCamera() { - mOpenRequested = false; + openRequested = false; setCamera(null); } @@ -419,18 +421,18 @@ public class CameraManager implements FocusOverlayManager.Listener { */ public void setListener(final CameraManagerListener listener) { Assert.isMainThread(); - mListener = listener; - if (!mIsHardwareAccelerationSupported && mListener != null) { - mListener.onCameraError(ERROR_HARDWARE_ACCELERATION_DISABLED, null); + this.listener = listener; + if (!isHardwareAccelerationSupported && this.listener != null) { + this.listener.onCameraError(ERROR_HARDWARE_ACCELERATION_DISABLED, null); } } public void takePicture(final float heightPercent, @NonNull final MediaCallback callback) { - Assert.checkState(!mTakingPicture); + Assert.checkState(!takingPicture); Assert.isNotNull(callback); - mCameraPreview.setFocusable(false); - mFocusOverlayManager.cancelAutoFocus(); - if (mCamera == null) { + cameraPreview.setFocusable(false); + focusOverlayManager.cancelAutoFocus(); + if (this.camera == null) { // The caller should have checked isCameraAvailable first, but just in case, protect // against a null camera by notifying the callback that taking the picture didn't work callback.onMediaFailed(null); @@ -440,8 +442,8 @@ public class CameraManager implements FocusOverlayManager.Listener { new Camera.PictureCallback() { @Override public void onPictureTaken(final byte[] bytes, final Camera camera) { - mTakingPicture = false; - if (mCamera != camera) { + takingPicture = false; + if (CameraManager.this.camera != camera) { // This may happen if the camera was changed between front/back while the // picture is being taken. callback.onMediaInfo(MediaCallback.MEDIA_CAMERA_CHANGED); @@ -456,7 +458,7 @@ public class CameraManager implements FocusOverlayManager.Listener { final Camera.Size size = camera.getParameters().getPictureSize(); int width; int height; - if (mRotation == 90 || mRotation == 270) { + if (rotation == 90 || rotation == 270) { // Is rotated, so swapping dimensions is desired // noinspection SuspiciousNameCombination width = size.height; @@ -468,11 +470,11 @@ public class CameraManager implements FocusOverlayManager.Listener { } LogUtil.i( "CameraManager.onPictureTaken", "taken picture size: " + bytes.length + " bytes"); - DialerExecutorComponent.get(mCameraPreview.getContext()) + DialerExecutorComponent.get(cameraPreview.getContext()) .dialerExecutorFactory() .createNonUiTaskBuilder( new ImagePersistWorker( - width, height, heightPercent, bytes, mCameraPreview.getContext())) + width, height, heightPercent, bytes, cameraPreview.getContext())) .onSuccess( (result) -> { callback.onMediaReady( @@ -487,16 +489,16 @@ public class CameraManager implements FocusOverlayManager.Listener { } }; - mTakingPicture = true; + takingPicture = true; try { - mCamera.takePicture( + this.camera.takePicture( // A shutter callback is required to enable shutter sound DUMMY_SHUTTER_CALLBACK, null /* raw */, null /* postView */, jpegCallback); } catch (final RuntimeException e) { LogUtil.e("CameraManager.takePicture", "RuntimeException in CameraManager.takePicture", e); - mTakingPicture = false; - if (mListener != null) { - mListener.onCameraError(ERROR_TAKING_PICTURE, e); + takingPicture = false; + if (listener != null) { + listener.onCameraError(ERROR_TAKING_PICTURE, e); } } } @@ -511,12 +513,12 @@ public class CameraManager implements FocusOverlayManager.Listener { return; } - mFocusOverlayManager.onCameraReleased(); + focusOverlayManager.onCameraReleased(); new AsyncTask() { @Override protected Void doInBackground(final Void... params) { - LogUtil.v("CameraManager.doInBackground", "Releasing camera " + mCameraIndex); + LogUtil.v("CameraManager.doInBackground", "Releasing camera " + cameraIndex); camera.release(); return null; } @@ -583,47 +585,47 @@ public class CameraManager implements FocusOverlayManager.Listener { /** Sets the current camera, releasing any previously opened camera */ private void setCamera(final Camera camera) { - if (mCamera == camera) { + if (this.camera == camera) { return; } - releaseCamera(mCamera); - mCamera = camera; + releaseCamera(this.camera); + this.camera = camera; tryShowPreview(); - if (mListener != null) { - mListener.onCameraChanged(); + if (listener != null) { + listener.onCameraChanged(); } } /** Shows the preview if the camera is open and the preview is loaded */ private void tryShowPreview() { - if (mCameraPreview == null || mCamera == null) { - if (mOrientationHandler != null) { - mOrientationHandler.disable(); - mOrientationHandler = null; + if (cameraPreview == null || this.camera == null) { + if (orientationHandler != null) { + orientationHandler.disable(); + orientationHandler = null; } - mFocusOverlayManager.onPreviewStopped(); + focusOverlayManager.onPreviewStopped(); return; } try { - mCamera.stopPreview(); - if (!mTakingPicture) { - mRotation = + this.camera.stopPreview(); + if (!takingPicture) { + rotation = updateCameraRotation( - mCamera, + this.camera, getScreenRotation(), - mCameraInfo.orientation, - mCameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT); + cameraInfo.orientation, + cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT); } - final Camera.Parameters params = mCamera.getParameters(); + final Camera.Parameters params = this.camera.getParameters(); final Camera.Size pictureSize = chooseBestPictureSize(); final Camera.Size previewSize = chooseBestPreviewSize(pictureSize); params.setPreviewSize(previewSize.width, previewSize.height); params.setPictureSize(pictureSize.width, pictureSize.height); logCameraSize("Setting preview size: ", previewSize); logCameraSize("Setting picture size: ", pictureSize); - mCameraPreview.setSize(previewSize, mCameraInfo.orientation); + cameraPreview.setSize(previewSize, cameraInfo.orientation); for (final String focusMode : params.getSupportedFocusModes()) { if (TextUtils.equals(focusMode, Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { // Use continuous focus if available @@ -632,39 +634,39 @@ public class CameraManager implements FocusOverlayManager.Listener { } } - mCamera.setParameters(params); - mCameraPreview.startPreview(mCamera); - mCamera.startPreview(); - mCamera.setAutoFocusMoveCallback( + this.camera.setParameters(params); + cameraPreview.startPreview(this.camera); + this.camera.startPreview(); + this.camera.setAutoFocusMoveCallback( new Camera.AutoFocusMoveCallback() { @Override public void onAutoFocusMoving(final boolean start, final Camera camera) { - mFocusOverlayManager.onAutoFocusMoving(start); + focusOverlayManager.onAutoFocusMoving(start); } }); - mFocusOverlayManager.setParameters(mCamera.getParameters()); - mFocusOverlayManager.setMirror(mCameraInfo.facing == CameraInfo.CAMERA_FACING_BACK); - mFocusOverlayManager.onPreviewStarted(); - if (mOrientationHandler == null) { - mOrientationHandler = new OrientationHandler(mCameraPreview.getContext()); - mOrientationHandler.enable(); + focusOverlayManager.setParameters(this.camera.getParameters()); + focusOverlayManager.setMirror(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK); + focusOverlayManager.onPreviewStarted(); + if (orientationHandler == null) { + orientationHandler = new OrientationHandler(cameraPreview.getContext()); + orientationHandler.enable(); } } catch (final IOException e) { LogUtil.e("CameraManager.tryShowPreview", "IOException in CameraManager.tryShowPreview", e); - if (mListener != null) { - mListener.onCameraError(ERROR_SHOWING_PREVIEW, e); + if (listener != null) { + listener.onCameraError(ERROR_SHOWING_PREVIEW, e); } } catch (final RuntimeException e) { LogUtil.e( "CameraManager.tryShowPreview", "RuntimeException in CameraManager.tryShowPreview", e); - if (mListener != null) { - mListener.onCameraError(ERROR_SHOWING_PREVIEW, e); + if (listener != null) { + listener.onCameraError(ERROR_SHOWING_PREVIEW, e); } } } private int getScreenRotation() { - return mCameraPreview + return cameraPreview .getContext() .getSystemService(WindowManager.class) .getDefaultDisplay() @@ -672,7 +674,7 @@ public class CameraManager implements FocusOverlayManager.Listener { } public boolean isCameraAvailable() { - return mCamera != null && !mTakingPicture && mIsHardwareAccelerationSupported; + return camera != null && !takingPicture && isHardwareAccelerationSupported; } /** @@ -680,7 +682,7 @@ public class CameraManager implements FocusOverlayManager.Listener { * is closest to the screen aspect ratio. In case of RCS conversation returns default size. */ private Camera.Size chooseBestPictureSize() { - return mCamera.getParameters().getPictureSize(); + return camera.getParameters().getPictureSize(); } /** @@ -689,7 +691,7 @@ public class CameraManager implements FocusOverlayManager.Listener { */ private Camera.Size chooseBestPreviewSize(final Camera.Size pictureSize) { final List sizes = - new ArrayList(mCamera.getParameters().getSupportedPreviewSizes()); + new ArrayList(camera.getParameters().getSupportedPreviewSizes()); final float aspectRatio = pictureSize.width / (float) pictureSize.height; final int capturePixels = pictureSize.width * pictureSize.height; @@ -708,13 +710,13 @@ public class CameraManager implements FocusOverlayManager.Listener { @Override public void onOrientationChanged(final int orientation) { - if (!mTakingPicture) { - mRotation = + if (!takingPicture) { + rotation = updateCameraRotation( - mCamera, + camera, getScreenRotation(), - mCameraInfo.orientation, - mCameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT); + cameraInfo.orientation, + cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT); } } } @@ -724,24 +726,24 @@ public class CameraManager implements FocusOverlayManager.Listener { private static final int PREFER_RIGHT = 1; // The max width/height for the preferred size. Integer.MAX_VALUE if no size limit - private final int mMaxWidth; - private final int mMaxHeight; + private final int maxWidth; + private final int maxHeight; // The desired aspect ratio - private final float mTargetAspectRatio; + private final float targetAspectRatio; // The desired size (width x height) to try to match - private final int mTargetPixels; + private final int targetPixels; public SizeComparator( final int maxWidth, final int maxHeight, final float targetAspectRatio, final int targetPixels) { - mMaxWidth = maxWidth; - mMaxHeight = maxHeight; - mTargetAspectRatio = targetAspectRatio; - mTargetPixels = targetPixels; + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + this.targetAspectRatio = targetAspectRatio; + this.targetPixels = targetPixels; } /** @@ -751,16 +753,16 @@ public class CameraManager implements FocusOverlayManager.Listener { @Override public int compare(final Camera.Size left, final Camera.Size right) { // If one size is less than the max size prefer it over the other - if ((left.width <= mMaxWidth && left.height <= mMaxHeight) - != (right.width <= mMaxWidth && right.height <= mMaxHeight)) { - return left.width <= mMaxWidth ? PREFER_LEFT : PREFER_RIGHT; + if ((left.width <= maxWidth && left.height <= maxHeight) + != (right.width <= maxWidth && right.height <= maxHeight)) { + return left.width <= maxWidth ? PREFER_LEFT : PREFER_RIGHT; } // If one is closer to the target aspect ratio, prefer it. final float leftAspectRatio = left.width / (float) left.height; final float rightAspectRatio = right.width / (float) right.height; - final float leftAspectRatioDiff = Math.abs(leftAspectRatio - mTargetAspectRatio); - final float rightAspectRatioDiff = Math.abs(rightAspectRatio - mTargetAspectRatio); + final float leftAspectRatioDiff = Math.abs(leftAspectRatio - targetAspectRatio); + final float rightAspectRatioDiff = Math.abs(rightAspectRatio - targetAspectRatio); if (leftAspectRatioDiff != rightAspectRatioDiff) { return (leftAspectRatioDiff - rightAspectRatioDiff) < 0 ? PREFER_LEFT : PREFER_RIGHT; } @@ -768,41 +770,41 @@ public class CameraManager implements FocusOverlayManager.Listener { // At this point they have the same aspect ratio diff and are either both bigger // than the max size or both smaller than the max size, so prefer the one closest // to target size - final int leftDiff = Math.abs((left.width * left.height) - mTargetPixels); - final int rightDiff = Math.abs((right.width * right.height) - mTargetPixels); + final int leftDiff = Math.abs((left.width * left.height) - targetPixels); + final int rightDiff = Math.abs((right.width * right.height) - targetPixels); return leftDiff - rightDiff; } } @Override // From FocusOverlayManager.Listener public void autoFocus() { - if (mCamera == null) { + if (this.camera == null) { return; } try { - mCamera.autoFocus( + this.camera.autoFocus( new Camera.AutoFocusCallback() { @Override public void onAutoFocus(final boolean success, final Camera camera) { - mFocusOverlayManager.onAutoFocus(success, false /* shutterDown */); + focusOverlayManager.onAutoFocus(success, false /* shutterDown */); } }); } catch (final RuntimeException e) { LogUtil.e("CameraManager.autoFocus", "RuntimeException in CameraManager.autoFocus", e); // If autofocus fails, the camera should have called the callback with success=false, // but some throw an exception here - mFocusOverlayManager.onAutoFocus(false /*success*/, false /*shutterDown*/); + focusOverlayManager.onAutoFocus(false /*success*/, false /*shutterDown*/); } } @Override // From FocusOverlayManager.Listener public void cancelAutoFocus() { - if (mCamera == null) { + if (camera == null) { return; } try { - mCamera.cancelAutoFocus(); + camera.cancelAutoFocus(); } catch (final RuntimeException e) { // Ignore LogUtil.e( @@ -817,19 +819,19 @@ public class CameraManager implements FocusOverlayManager.Listener { @Override // From FocusOverlayManager.Listener public void setFocusParameters() { - if (mCamera == null) { + if (camera == null) { return; } try { - final Camera.Parameters parameters = mCamera.getParameters(); - parameters.setFocusMode(mFocusOverlayManager.getFocusMode()); + final Camera.Parameters parameters = camera.getParameters(); + parameters.setFocusMode(focusOverlayManager.getFocusMode()); if (parameters.getMaxNumFocusAreas() > 0) { // Don't set focus areas (even to null) if focus areas aren't supported, camera may // crash - parameters.setFocusAreas(mFocusOverlayManager.getFocusAreas()); + parameters.setFocusAreas(focusOverlayManager.getFocusAreas()); } - parameters.setMeteringAreas(mFocusOverlayManager.getMeteringAreas()); - mCamera.setParameters(parameters); + parameters.setMeteringAreas(focusOverlayManager.getMeteringAreas()); + camera.setParameters(parameters); } catch (final RuntimeException e) { // This occurs when the device is out of space or when the camera is locked LogUtil.e( @@ -839,9 +841,9 @@ public class CameraManager implements FocusOverlayManager.Listener { } public void resetPreview() { - mCamera.startPreview(); - if (mCameraPreview != null) { - mCameraPreview.setFocusable(true); + camera.startPreview(); + if (cameraPreview != null) { + cameraPreview.setFocusable(true); } } @@ -855,6 +857,6 @@ public class CameraManager implements FocusOverlayManager.Listener { @VisibleForTesting public void resetCameraManager() { - sInstance = null; + instance = null; } } diff --git a/java/com/android/dialer/callcomposer/camera/CameraPreview.java b/java/com/android/dialer/callcomposer/camera/CameraPreview.java index eaea78961..901833b95 100644 --- a/java/com/android/dialer/callcomposer/camera/CameraPreview.java +++ b/java/com/android/dialer/callcomposer/camera/CameraPreview.java @@ -45,30 +45,30 @@ public class CameraPreview { void setShown(); } - private int mCameraWidth = -1; - private int mCameraHeight = -1; - private boolean mTabHasBeenShown = false; - private OnTouchListener mListener; + private int cameraWidth = -1; + private int cameraHeight = -1; + private boolean tabHasBeenShown = false; + private OnTouchListener listener; - private final CameraPreviewHost mHost; + private final CameraPreviewHost host; public CameraPreview(final CameraPreviewHost host) { Assert.isNotNull(host); Assert.isNotNull(host.getView()); - mHost = host; + this.host = host; } // This is set when the tab is actually selected. public void setShown() { - mTabHasBeenShown = true; + tabHasBeenShown = true; maybeOpenCamera(); } // Opening camera is very expensive. Most of the ANR reports seem to be related to the camera. // So we delay until the camera is actually needed. See a bug private void maybeOpenCamera() { - boolean visible = mHost.getView().getVisibility() == View.VISIBLE; - if (mTabHasBeenShown && visible && PermissionsUtil.hasCameraPermissions(getContext())) { + boolean visible = host.getView().getVisibility() == View.VISIBLE; + if (tabHasBeenShown && visible && PermissionsUtil.hasCameraPermissions(getContext())) { CameraManager.get().openCamera(); } } @@ -77,20 +77,20 @@ public class CameraPreview { switch (orientation) { case 0: case 180: - mCameraWidth = size.width; - mCameraHeight = size.height; + cameraWidth = size.width; + cameraHeight = size.height; break; case 90: case 270: default: - mCameraWidth = size.height; - mCameraHeight = size.width; + cameraWidth = size.height; + cameraHeight = size.width; } - mHost.getView().requestLayout(); + host.getView().requestLayout(); } public int getWidthMeasureSpec(final int widthMeasureSpec, final int heightMeasureSpec) { - if (mCameraHeight >= 0) { + if (cameraHeight >= 0) { final int width = View.MeasureSpec.getSize(widthMeasureSpec); return MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY); } else { @@ -99,10 +99,10 @@ public class CameraPreview { } public int getHeightMeasureSpec(final int widthMeasureSpec, final int heightMeasureSpec) { - if (mCameraHeight >= 0) { + if (cameraHeight >= 0) { final int orientation = getContext().getResources().getConfiguration().orientation; final int width = View.MeasureSpec.getSize(widthMeasureSpec); - final float aspectRatio = (float) mCameraWidth / (float) mCameraHeight; + final float aspectRatio = (float) cameraWidth / (float) cameraHeight; int height; if (orientation == Configuration.ORIENTATION_LANDSCAPE) { height = (int) (width * aspectRatio); @@ -128,20 +128,20 @@ public class CameraPreview { } public Context getContext() { - return mHost.getView().getContext(); + return host.getView().getContext(); } public void setOnTouchListener(final View.OnTouchListener listener) { - mListener = listener; - mHost.getView().setOnTouchListener(listener); + this.listener = listener; + host.getView().setOnTouchListener(listener); } public void setFocusable(boolean focusable) { - mHost.getView().setOnTouchListener(focusable ? mListener : null); + host.getView().setOnTouchListener(focusable ? listener : null); } public int getHeight() { - return mHost.getView().getHeight(); + return host.getView().getHeight(); } public void onAttachedToWindow() { @@ -162,7 +162,7 @@ public class CameraPreview { /** @return True if the view is valid and prepared for the camera to start showing the preview */ public boolean isValid() { - return mHost.isValid(); + return host.isValid(); } /** @@ -172,6 +172,6 @@ public class CameraPreview { * @throws IOException Which is caught by the CameraManager to display an error */ public void startPreview(final Camera camera) throws IOException { - mHost.startPreview(camera); + host.startPreview(camera); } } diff --git a/java/com/android/dialer/callcomposer/camera/HardwareCameraPreview.java b/java/com/android/dialer/callcomposer/camera/HardwareCameraPreview.java index c0d61f3f8..3373f1a8d 100644 --- a/java/com/android/dialer/callcomposer/camera/HardwareCameraPreview.java +++ b/java/com/android/dialer/callcomposer/camera/HardwareCameraPreview.java @@ -35,23 +35,23 @@ import java.io.IOException; * implementations of the shared methods are delegated to CameraPreview */ public class HardwareCameraPreview extends TextureView implements CameraPreview.CameraPreviewHost { - private CameraPreview mPreview; + private CameraPreview preview; public HardwareCameraPreview(final Context context, final AttributeSet attrs) { super(context, attrs); - mPreview = new CameraPreview(this); + preview = new CameraPreview(this); setSurfaceTextureListener( new SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable( final SurfaceTexture surfaceTexture, final int i, final int i2) { - CameraManager.get().setSurface(mPreview); + CameraManager.get().setSurface(preview); } @Override public void onSurfaceTextureSizeChanged( final SurfaceTexture surfaceTexture, final int i, final int i2) { - CameraManager.get().setSurface(mPreview); + CameraManager.get().setSurface(preview); } @Override @@ -62,44 +62,44 @@ public class HardwareCameraPreview extends TextureView implements CameraPreview. @Override public void onSurfaceTextureUpdated(final SurfaceTexture surfaceTexture) { - CameraManager.get().setSurface(mPreview); + CameraManager.get().setSurface(preview); } }); } @Override public void setShown() { - mPreview.setShown(); + preview.setShown(); } @Override protected void onVisibilityChanged(final View changedView, final int visibility) { super.onVisibilityChanged(changedView, visibility); - mPreview.onVisibilityChanged(visibility); + preview.onVisibilityChanged(visibility); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - mPreview.onDetachedFromWindow(); + preview.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); - mPreview.onAttachedToWindow(); + preview.onAttachedToWindow(); } @Override protected void onRestoreInstanceState(final Parcelable state) { super.onRestoreInstanceState(state); - mPreview.onRestoreInstanceState(); + preview.onRestoreInstanceState(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - widthMeasureSpec = mPreview.getWidthMeasureSpec(widthMeasureSpec, heightMeasureSpec); - heightMeasureSpec = mPreview.getHeightMeasureSpec(widthMeasureSpec, heightMeasureSpec); + widthMeasureSpec = preview.getWidthMeasureSpec(widthMeasureSpec, heightMeasureSpec); + heightMeasureSpec = preview.getHeightMeasureSpec(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @@ -120,6 +120,6 @@ public class HardwareCameraPreview extends TextureView implements CameraPreview. @Override public void onCameraPermissionGranted() { - mPreview.onCameraPermissionGranted(); + preview.onCameraPermissionGranted(); } } diff --git a/java/com/android/dialer/callcomposer/camera/ImagePersistWorker.java b/java/com/android/dialer/callcomposer/camera/ImagePersistWorker.java index 26b0bde00..69f546929 100644 --- a/java/com/android/dialer/callcomposer/camera/ImagePersistWorker.java +++ b/java/com/android/dialer/callcomposer/camera/ImagePersistWorker.java @@ -40,11 +40,11 @@ import java.io.OutputStream; /** Persisting image routine. */ @TargetApi(VERSION_CODES.M) public class ImagePersistWorker implements Worker { - private int mWidth; - private int mHeight; - private final float mHeightPercent; - private final byte[] mBytes; - private final Context mContext; + private int width; + private int height; + private final float heightPercent; + private final byte[] bytes; + private final Context context; @AutoValue abstract static class Result { @@ -81,16 +81,16 @@ public class ImagePersistWorker implements Worker { Assert.checkArgument(heightPercent >= 0 && heightPercent <= 1); Assert.isNotNull(bytes); Assert.isNotNull(context); - mWidth = width; - mHeight = height; - mHeightPercent = heightPercent; - mBytes = bytes; - mContext = context; + this.width = width; + this.height = height; + this.heightPercent = heightPercent; + this.bytes = bytes; + this.context = context; } @Override public Result doInBackground(Void unused) throws Exception { - File outputFile = DialerUtils.createShareableFile(mContext); + File outputFile = DialerUtils.createShareableFile(context); try (OutputStream outputStream = new FileOutputStream(outputFile)) { writeClippedBitmap(outputStream); @@ -99,9 +99,9 @@ public class ImagePersistWorker implements Worker { return Result.builder() .setUri( FileProvider.getUriForFile( - mContext, Constants.get().getFileProviderAuthority(), outputFile)) - .setWidth(mWidth) - .setHeight(mHeight) + context, Constants.get().getFileProviderAuthority(), outputFile)) + .setWidth(width) + .setHeight(height) .build(); } @@ -109,7 +109,7 @@ public class ImagePersistWorker implements Worker { int orientation = android.media.ExifInterface.ORIENTATION_UNDEFINED; final ExifInterface exifInterface = new ExifInterface(); try { - exifInterface.readExif(mBytes); + exifInterface.readExif(bytes); final Integer orientationValue = exifInterface.getTagIntValue(ExifInterface.TAG_ORIENTATION); if (orientationValue != null) { orientation = orientationValue.intValue(); @@ -119,25 +119,25 @@ public class ImagePersistWorker implements Worker { } ExifInterface.OrientationParams params = ExifInterface.getOrientationParams(orientation); - Bitmap bitmap = BitmapFactory.decodeByteArray(mBytes, 0, mBytes.length); + Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); final int clippedWidth; final int clippedHeight; if (params.invertDimensions) { - Assert.checkState(mWidth == bitmap.getHeight()); - Assert.checkState(mHeight == bitmap.getWidth()); - clippedWidth = (int) (mHeight * mHeightPercent); - clippedHeight = mWidth; + Assert.checkState(width == bitmap.getHeight()); + Assert.checkState(height == bitmap.getWidth()); + clippedWidth = (int) (height * heightPercent); + clippedHeight = width; } else { - Assert.checkState(mWidth == bitmap.getWidth()); - Assert.checkState(mHeight == bitmap.getHeight()); - clippedWidth = mWidth; - clippedHeight = (int) (mHeight * mHeightPercent); + Assert.checkState(width == bitmap.getWidth()); + Assert.checkState(height == bitmap.getHeight()); + clippedWidth = width; + clippedHeight = (int) (height * heightPercent); } int offsetTop = (bitmap.getHeight() - clippedHeight) / 2; int offsetLeft = (bitmap.getWidth() - clippedWidth) / 2; - mWidth = clippedWidth; - mHeight = clippedHeight; + width = clippedWidth; + height = clippedHeight; Bitmap clippedBitmap = Bitmap.createBitmap(bitmap, offsetLeft, offsetTop, clippedWidth, clippedHeight); diff --git a/java/com/android/dialer/callcomposer/camera/SoftwareCameraPreview.java b/java/com/android/dialer/callcomposer/camera/SoftwareCameraPreview.java index fe2c600df..58458a894 100644 --- a/java/com/android/dialer/callcomposer/camera/SoftwareCameraPreview.java +++ b/java/com/android/dialer/callcomposer/camera/SoftwareCameraPreview.java @@ -33,17 +33,17 @@ import java.io.IOException; * implementations of the shared methods are delegated to CameraPreview */ public class SoftwareCameraPreview extends SurfaceView implements CameraPreview.CameraPreviewHost { - private final CameraPreview mPreview; + private final CameraPreview preview; public SoftwareCameraPreview(final Context context) { super(context); - mPreview = new CameraPreview(this); + preview = new CameraPreview(this); getHolder() .addCallback( new SurfaceHolder.Callback() { @Override public void surfaceCreated(final SurfaceHolder surfaceHolder) { - CameraManager.get().setSurface(mPreview); + CameraManager.get().setSurface(preview); } @Override @@ -52,7 +52,7 @@ public class SoftwareCameraPreview extends SurfaceView implements CameraPreview. final int format, final int width, final int height) { - CameraManager.get().setSurface(mPreview); + CameraManager.get().setSurface(preview); } @Override @@ -64,37 +64,37 @@ public class SoftwareCameraPreview extends SurfaceView implements CameraPreview. @Override public void setShown() { - mPreview.setShown(); + preview.setShown(); } @Override protected void onVisibilityChanged(final View changedView, final int visibility) { super.onVisibilityChanged(changedView, visibility); - mPreview.onVisibilityChanged(visibility); + preview.onVisibilityChanged(visibility); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - mPreview.onDetachedFromWindow(); + preview.onDetachedFromWindow(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); - mPreview.onAttachedToWindow(); + preview.onAttachedToWindow(); } @Override protected void onRestoreInstanceState(final Parcelable state) { super.onRestoreInstanceState(state); - mPreview.onRestoreInstanceState(); + preview.onRestoreInstanceState(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - widthMeasureSpec = mPreview.getWidthMeasureSpec(widthMeasureSpec, heightMeasureSpec); - heightMeasureSpec = mPreview.getHeightMeasureSpec(widthMeasureSpec, heightMeasureSpec); + widthMeasureSpec = preview.getWidthMeasureSpec(widthMeasureSpec, heightMeasureSpec); + heightMeasureSpec = preview.getHeightMeasureSpec(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @@ -115,6 +115,6 @@ public class SoftwareCameraPreview extends SurfaceView implements CameraPreview. @Override public void onCameraPermissionGranted() { - mPreview.onCameraPermissionGranted(); + preview.onCameraPermissionGranted(); } } diff --git a/java/com/android/dialer/callcomposer/camera/camerafocus/FocusOverlayManager.java b/java/com/android/dialer/callcomposer/camera/camerafocus/FocusOverlayManager.java index a5edf3309..c3f1a5ddd 100644 --- a/java/com/android/dialer/callcomposer/camera/camerafocus/FocusOverlayManager.java +++ b/java/com/android/dialer/callcomposer/camera/camerafocus/FocusOverlayManager.java @@ -54,7 +54,7 @@ public class FocusOverlayManager { private static final int RESET_TOUCH_FOCUS = 0; private static final int RESET_TOUCH_FOCUS_DELAY = 3000; - private int mState = STATE_IDLE; + private int state = STATE_IDLE; private static final int STATE_IDLE = 0; // Focus is not active. private static final int STATE_FOCUSING = 1; // Focus is in progress. // Focus is in progress and the camera should take a picture after focus finishes. @@ -62,24 +62,24 @@ public class FocusOverlayManager { private static final int STATE_SUCCESS = 3; // Focus finishes and succeeds. private static final int STATE_FAIL = 4; // Focus finishes and fails. - private boolean mInitialized; - private boolean mFocusAreaSupported; - private boolean mMeteringAreaSupported; - private boolean mLockAeAwbNeeded; - private boolean mAeAwbLock; - private Matrix mMatrix; - - private PieRenderer mPieRenderer; - - private int mPreviewWidth; // The width of the preview frame layout. - private int mPreviewHeight; // The height of the preview frame layout. - private boolean mMirror; // true if the camera is front-facing. - private List mFocusArea; // focus area in driver format - private List mMeteringArea; // metering area in driver format - private String mFocusMode; - private Parameters mParameters; - private Handler mHandler; - private Listener mListener; + private boolean initialized; + private boolean focusAreaSupported; + private boolean meteringAreaSupported; + private boolean lockAeAwbNeeded; + private boolean aeAwbLock; + private Matrix matrix; + + private PieRenderer pieRenderer; + + private int previewWidth; // The width of the preview frame layout. + private int previewHeight; // The height of the preview frame layout. + private boolean mirror; // true if the camera is front-facing. + private List focusArea; // focus area in driver format + private List meteringArea; // metering area in driver format + private String focusMode; + private Parameters parameters; + private Handler handler; + private Listener listener; /** Listener used for the focus indicator to communicate back to the camera. */ public interface Listener { @@ -110,14 +110,14 @@ public class FocusOverlayManager { } public FocusOverlayManager(Listener listener, Looper looper) { - mHandler = new MainHandler(looper); - mMatrix = new Matrix(); - mListener = listener; + handler = new MainHandler(looper); + matrix = new Matrix(); + this.listener = listener; } public void setFocusRenderer(PieRenderer renderer) { - mPieRenderer = renderer; - mInitialized = (mMatrix != null); + pieRenderer = renderer; + initialized = (matrix != null); } public void setParameters(Parameters parameters) { @@ -128,182 +128,176 @@ public class FocusOverlayManager { if (parameters == null) { return; } - mParameters = parameters; - mFocusAreaSupported = isFocusAreaSupported(parameters); - mMeteringAreaSupported = isMeteringAreaSupported(parameters); - mLockAeAwbNeeded = - (isAutoExposureLockSupported(mParameters) || isAutoWhiteBalanceLockSupported(mParameters)); + this.parameters = parameters; + focusAreaSupported = isFocusAreaSupported(parameters); + meteringAreaSupported = isMeteringAreaSupported(parameters); + lockAeAwbNeeded = + (isAutoExposureLockSupported(this.parameters) + || isAutoWhiteBalanceLockSupported(this.parameters)); } public void setPreviewSize(int previewWidth, int previewHeight) { - if (mPreviewWidth != previewWidth || mPreviewHeight != previewHeight) { - mPreviewWidth = previewWidth; - mPreviewHeight = previewHeight; + if (this.previewWidth != previewWidth || this.previewHeight != previewHeight) { + this.previewWidth = previewWidth; + this.previewHeight = previewHeight; setMatrix(); } } public void setMirror(boolean mirror) { - mMirror = mirror; + this.mirror = mirror; setMatrix(); } private void setMatrix() { - if (mPreviewWidth != 0 && mPreviewHeight != 0) { + if (previewWidth != 0 && previewHeight != 0) { Matrix matrix = new Matrix(); - prepareMatrix(matrix, mMirror, mPreviewWidth, mPreviewHeight); + prepareMatrix(matrix, mirror, previewWidth, previewHeight); // In face detection, the matrix converts the driver coordinates to UI // coordinates. In tap focus, the inverted matrix converts the UI // coordinates to driver coordinates. - matrix.invert(mMatrix); - mInitialized = (mPieRenderer != null); + matrix.invert(this.matrix); + initialized = (pieRenderer != null); } } private void lockAeAwbIfNeeded() { - if (mLockAeAwbNeeded && !mAeAwbLock) { - mAeAwbLock = true; - mListener.setFocusParameters(); + if (lockAeAwbNeeded && !aeAwbLock) { + aeAwbLock = true; + listener.setFocusParameters(); } } public void onAutoFocus(boolean focused, boolean shutterButtonPressed) { - if (mState == STATE_FOCUSING_SNAP_ON_FINISH) { + if (state == STATE_FOCUSING_SNAP_ON_FINISH) { // Take the picture no matter focus succeeds or fails. No need // to play the AF sound if we're about to play the shutter // sound. if (focused) { - mState = STATE_SUCCESS; + state = STATE_SUCCESS; } else { - mState = STATE_FAIL; + state = STATE_FAIL; } updateFocusUI(); capture(); - } else if (mState == STATE_FOCUSING) { + } else if (state == STATE_FOCUSING) { // This happens when (1) user is half-pressing the focus key or // (2) touch focus is triggered. Play the focus tone. Do not // take the picture now. if (focused) { - mState = STATE_SUCCESS; + state = STATE_SUCCESS; } else { - mState = STATE_FAIL; + state = STATE_FAIL; } updateFocusUI(); // If this is triggered by touch focus, cancel focus after a // while. - if (mFocusArea != null) { - mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY); + if (focusArea != null) { + handler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY); } if (shutterButtonPressed) { // Lock AE & AWB so users can half-press shutter and recompose. lockAeAwbIfNeeded(); } - } else if (mState == STATE_IDLE) { + } else if (state == STATE_IDLE) { // User has released the focus key before focus completes. // Do nothing. } } public void onAutoFocusMoving(boolean moving) { - if (!mInitialized) { + if (!initialized) { return; } // Ignore if we have requested autofocus. This method only handles // continuous autofocus. - if (mState != STATE_IDLE) { + if (state != STATE_IDLE) { return; } if (moving) { - mPieRenderer.showStart(); + pieRenderer.showStart(); } else { - mPieRenderer.showSuccess(true); + pieRenderer.showSuccess(true); } } private void initializeFocusAreas( int focusWidth, int focusHeight, int x, int y, int previewWidth, int previewHeight) { - if (mFocusArea == null) { - mFocusArea = new ArrayList<>(); - mFocusArea.add(new Area(new Rect(), 1)); + if (focusArea == null) { + focusArea = new ArrayList<>(); + focusArea.add(new Area(new Rect(), 1)); } // Convert the coordinates to driver format. calculateTapArea( - focusWidth, focusHeight, 1f, x, y, previewWidth, previewHeight, mFocusArea.get(0).rect); + focusWidth, focusHeight, 1f, x, y, previewWidth, previewHeight, focusArea.get(0).rect); } private void initializeMeteringAreas( int focusWidth, int focusHeight, int x, int y, int previewWidth, int previewHeight) { - if (mMeteringArea == null) { - mMeteringArea = new ArrayList<>(); - mMeteringArea.add(new Area(new Rect(), 1)); + if (meteringArea == null) { + meteringArea = new ArrayList<>(); + meteringArea.add(new Area(new Rect(), 1)); } // Convert the coordinates to driver format. // AE area is bigger because exposure is sensitive and // easy to over- or underexposure if area is too small. calculateTapArea( - focusWidth, - focusHeight, - 1.5f, - x, - y, - previewWidth, - previewHeight, - mMeteringArea.get(0).rect); + focusWidth, focusHeight, 1.5f, x, y, previewWidth, previewHeight, meteringArea.get(0).rect); } public void onSingleTapUp(int x, int y) { - if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) { + if (!initialized || state == STATE_FOCUSING_SNAP_ON_FINISH) { return; } // Let users be able to cancel previous touch focus. - if ((mFocusArea != null) - && (mState == STATE_FOCUSING || mState == STATE_SUCCESS || mState == STATE_FAIL)) { + if ((focusArea != null) + && (state == STATE_FOCUSING || state == STATE_SUCCESS || state == STATE_FAIL)) { cancelAutoFocus(); } // Initialize variables. - int focusWidth = mPieRenderer.getSize(); - int focusHeight = mPieRenderer.getSize(); - if (focusWidth == 0 || mPieRenderer.getWidth() == 0 || mPieRenderer.getHeight() == 0) { + int focusWidth = pieRenderer.getSize(); + int focusHeight = pieRenderer.getSize(); + if (focusWidth == 0 || pieRenderer.getWidth() == 0 || pieRenderer.getHeight() == 0) { return; } - int previewWidth = mPreviewWidth; - int previewHeight = mPreviewHeight; + int previewWidth = this.previewWidth; + int previewHeight = this.previewHeight; // Initialize mFocusArea. - if (mFocusAreaSupported) { + if (focusAreaSupported) { initializeFocusAreas(focusWidth, focusHeight, x, y, previewWidth, previewHeight); } // Initialize mMeteringArea. - if (mMeteringAreaSupported) { + if (meteringAreaSupported) { initializeMeteringAreas(focusWidth, focusHeight, x, y, previewWidth, previewHeight); } // Use margin to set the focus indicator to the touched area. - mPieRenderer.setFocus(x, y); + pieRenderer.setFocus(x, y); // Set the focus area and metering area. - mListener.setFocusParameters(); - if (mFocusAreaSupported) { + listener.setFocusParameters(); + if (focusAreaSupported) { autoFocus(); } else { // Just show the indicator in all other cases. updateFocusUI(); // Reset the metering area in 3 seconds. - mHandler.removeMessages(RESET_TOUCH_FOCUS); - mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY); + handler.removeMessages(RESET_TOUCH_FOCUS); + handler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY); } } public void onPreviewStarted() { - mState = STATE_IDLE; + state = STATE_IDLE; } public void onPreviewStopped() { // If auto focus was in progress, it would have been stopped. - mState = STATE_IDLE; + state = STATE_IDLE; resetTouchFocus(); updateFocusUI(); } @@ -314,10 +308,10 @@ public class FocusOverlayManager { private void autoFocus() { LogUtil.v("FocusOverlayManager.autoFocus", "Start autofocus."); - mListener.autoFocus(); - mState = STATE_FOCUSING; + listener.autoFocus(); + state = STATE_FOCUSING; updateFocusUI(); - mHandler.removeMessages(RESET_TOUCH_FOCUS); + handler.removeMessages(RESET_TOUCH_FOCUS); } public void cancelAutoFocus() { @@ -327,57 +321,57 @@ public class FocusOverlayManager { // Otherwise, focus mode stays at auto and the tap area passed to the // driver is not reset. resetTouchFocus(); - mListener.cancelAutoFocus(); - mState = STATE_IDLE; + listener.cancelAutoFocus(); + state = STATE_IDLE; updateFocusUI(); - mHandler.removeMessages(RESET_TOUCH_FOCUS); + handler.removeMessages(RESET_TOUCH_FOCUS); } private void capture() { - if (mListener.capture()) { - mState = STATE_IDLE; - mHandler.removeMessages(RESET_TOUCH_FOCUS); + if (listener.capture()) { + state = STATE_IDLE; + handler.removeMessages(RESET_TOUCH_FOCUS); } } public String getFocusMode() { - List supportedFocusModes = mParameters.getSupportedFocusModes(); + List supportedFocusModes = parameters.getSupportedFocusModes(); - if (mFocusAreaSupported && mFocusArea != null) { + if (focusAreaSupported && focusArea != null) { // Always use autofocus in tap-to-focus. - mFocusMode = Parameters.FOCUS_MODE_AUTO; + focusMode = Parameters.FOCUS_MODE_AUTO; } else { - mFocusMode = Parameters.FOCUS_MODE_CONTINUOUS_PICTURE; + focusMode = Parameters.FOCUS_MODE_CONTINUOUS_PICTURE; } - if (!isSupported(mFocusMode, supportedFocusModes)) { + if (!isSupported(focusMode, supportedFocusModes)) { // For some reasons, the driver does not support the current // focus mode. Fall back to auto. - if (isSupported(Parameters.FOCUS_MODE_AUTO, mParameters.getSupportedFocusModes())) { - mFocusMode = Parameters.FOCUS_MODE_AUTO; + if (isSupported(Parameters.FOCUS_MODE_AUTO, parameters.getSupportedFocusModes())) { + focusMode = Parameters.FOCUS_MODE_AUTO; } else { - mFocusMode = mParameters.getFocusMode(); + focusMode = parameters.getFocusMode(); } } - return mFocusMode; + return focusMode; } public List getFocusAreas() { - return mFocusArea; + return focusArea; } public List getMeteringAreas() { - return mMeteringArea; + return meteringArea; } private void updateFocusUI() { - if (!mInitialized) { + if (!initialized) { return; } - FocusIndicator focusIndicator = mPieRenderer; + FocusIndicator focusIndicator = pieRenderer; - if (mState == STATE_IDLE) { - if (mFocusArea == null) { + if (state == STATE_IDLE) { + if (focusArea == null) { focusIndicator.clear(); } else { // Users touch on the preview and the indicator represents the @@ -385,30 +379,30 @@ public class FocusOverlayManager { // autoFocus call is not required. focusIndicator.showStart(); } - } else if (mState == STATE_FOCUSING || mState == STATE_FOCUSING_SNAP_ON_FINISH) { + } else if (state == STATE_FOCUSING || state == STATE_FOCUSING_SNAP_ON_FINISH) { focusIndicator.showStart(); } else { - if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(mFocusMode)) { + if (Parameters.FOCUS_MODE_CONTINUOUS_PICTURE.equals(focusMode)) { // TODO(blemmon): check HAL behavior and decide if this can be removed. focusIndicator.showSuccess(false); - } else if (mState == STATE_SUCCESS) { + } else if (state == STATE_SUCCESS) { focusIndicator.showSuccess(false); - } else if (mState == STATE_FAIL) { + } else if (state == STATE_FAIL) { focusIndicator.showFail(false); } } } private void resetTouchFocus() { - if (!mInitialized) { + if (!initialized) { return; } // Put focus indicator to the center. clear reset position - mPieRenderer.clear(); + pieRenderer.clear(); - mFocusArea = null; - mMeteringArea = null; + focusArea = null; + meteringArea = null; } private void calculateTapArea( @@ -428,7 +422,7 @@ public class FocusOverlayManager { int top = maxH > 0 ? clamp(y - areaHeight / 2, 0, maxH) : 0; RectF rectF = new RectF(left, top, left + areaWidth, top + areaHeight); - mMatrix.mapRect(rectF); + matrix.mapRect(rectF); rectFToRect(rectF, rect); } diff --git a/java/com/android/dialer/callcomposer/camera/camerafocus/OverlayRenderer.java b/java/com/android/dialer/callcomposer/camera/camerafocus/OverlayRenderer.java index 4a3b522bb..ac9512ed7 100644 --- a/java/com/android/dialer/callcomposer/camera/camerafocus/OverlayRenderer.java +++ b/java/com/android/dialer/callcomposer/camera/camerafocus/OverlayRenderer.java @@ -23,21 +23,21 @@ import android.view.MotionEvent; /** Abstract class that all Camera overlays should implement. */ public abstract class OverlayRenderer implements RenderOverlay.Renderer { - protected RenderOverlay mOverlay; + protected RenderOverlay overlay; - private int mLeft; - private int mTop; - private int mRight; - private int mBottom; - private boolean mVisible; + private int left; + private int top; + private int right; + private int bottom; + private boolean visible; public void setVisible(boolean vis) { - mVisible = vis; + visible = vis; update(); } public boolean isVisible() { - return mVisible; + return visible; } // default does not handle touch @@ -55,43 +55,43 @@ public abstract class OverlayRenderer implements RenderOverlay.Renderer { @Override public void draw(Canvas canvas) { - if (mVisible) { + if (visible) { onDraw(canvas); } } @Override public void setOverlay(RenderOverlay overlay) { - mOverlay = overlay; + this.overlay = overlay; } @Override public void layout(int left, int top, int right, int bottom) { - mLeft = left; - mRight = right; - mTop = top; - mBottom = bottom; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; } protected Context getContext() { - if (mOverlay != null) { - return mOverlay.getContext(); + if (overlay != null) { + return overlay.getContext(); } else { return null; } } public int getWidth() { - return mRight - mLeft; + return right - left; } public int getHeight() { - return mBottom - mTop; + return bottom - top; } protected void update() { - if (mOverlay != null) { - mOverlay.update(); + if (overlay != null) { + overlay.update(); } } } diff --git a/java/com/android/dialer/callcomposer/camera/camerafocus/PieItem.java b/java/com/android/dialer/callcomposer/camera/camerafocus/PieItem.java index 86f69c0ae..1c442958e 100644 --- a/java/com/android/dialer/callcomposer/camera/camerafocus/PieItem.java +++ b/java/com/android/dialer/callcomposer/camera/camerafocus/PieItem.java @@ -30,54 +30,54 @@ public class PieItem { void onClick(PieItem item); } - private Drawable mDrawable; + private Drawable drawable; private int level; - private float mCenter; + private float center; private float start; private float sweep; private float animate; private int inner; private int outer; - private boolean mSelected; - private boolean mEnabled; - private List mItems; - private Path mPath; - private OnClickListener mOnClickListener; - private float mAlpha; + private boolean selected; + private boolean enabled; + private List items; + private Path path; + private OnClickListener onClickListener; + private float alpha; // Gray out the view when disabled private static final float ENABLED_ALPHA = 1; private static final float DISABLED_ALPHA = (float) 0.3; public PieItem(Drawable drawable, int level) { - mDrawable = drawable; + this.drawable = drawable; this.level = level; setAlpha(1f); - mEnabled = true; + enabled = true; setAnimationAngle(getAnimationAngle()); start = -1; - mCenter = -1; + center = -1; } public boolean hasItems() { - return mItems != null; + return items != null; } public List getItems() { - return mItems; + return items; } public void setPath(Path p) { - mPath = p; + path = p; } public Path getPath() { - return mPath; + return path; } public void setAlpha(float alpha) { - mAlpha = alpha; - mDrawable.setAlpha((int) (255 * alpha)); + this.alpha = alpha; + drawable.setAlpha((int) (255 * alpha)); } public void setAnimationAngle(float a) { @@ -89,8 +89,8 @@ public class PieItem { } public void setEnabled(boolean enabled) { - mEnabled = enabled; - if (mEnabled) { + this.enabled = enabled; + if (this.enabled) { setAlpha(ENABLED_ALPHA); } else { setAlpha(DISABLED_ALPHA); @@ -98,15 +98,15 @@ public class PieItem { } public boolean isEnabled() { - return mEnabled; + return enabled; } public void setSelected(boolean s) { - mSelected = s; + selected = s; } public boolean isSelected() { - return mSelected; + return selected; } public int getLevel() { @@ -121,7 +121,7 @@ public class PieItem { } public float getCenter() { - return mCenter; + return center; } public float getStart() { @@ -145,35 +145,35 @@ public class PieItem { } public void setOnClickListener(OnClickListener listener) { - mOnClickListener = listener; + onClickListener = listener; } public void performClick() { - if (mOnClickListener != null) { - mOnClickListener.onClick(this); + if (onClickListener != null) { + onClickListener.onClick(this); } } public int getIntrinsicWidth() { - return mDrawable.getIntrinsicWidth(); + return drawable.getIntrinsicWidth(); } public int getIntrinsicHeight() { - return mDrawable.getIntrinsicHeight(); + return drawable.getIntrinsicHeight(); } public void setBounds(int left, int top, int right, int bottom) { - mDrawable.setBounds(left, top, right, bottom); + drawable.setBounds(left, top, right, bottom); } public void draw(Canvas canvas) { - mDrawable.draw(canvas); + drawable.draw(canvas); } public void setImageResource(Context context, int resId) { Drawable d = context.getResources().getDrawable(resId).mutate(); - d.setBounds(mDrawable.getBounds()); - mDrawable = d; - setAlpha(mAlpha); + d.setBounds(drawable.getBounds()); + drawable = d; + setAlpha(alpha); } } diff --git a/java/com/android/dialer/callcomposer/camera/camerafocus/PieRenderer.java b/java/com/android/dialer/callcomposer/camera/camerafocus/PieRenderer.java index 59b57b002..7629252e5 100644 --- a/java/com/android/dialer/callcomposer/camera/camerafocus/PieRenderer.java +++ b/java/com/android/dialer/callcomposer/camera/camerafocus/PieRenderer.java @@ -43,15 +43,15 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { // Sometimes continuous autofocus starts and stops several times quickly. // These states are used to make sure the animation is run for at least some // time. - private volatile int mState; - private ScaleAnimation mAnimation = new ScaleAnimation(); + private volatile int state; + private ScaleAnimation animation = new ScaleAnimation(); private static final int STATE_IDLE = 0; private static final int STATE_FOCUSING = 1; private static final int STATE_FINISHING = 2; private static final int STATE_PIE = 8; - private Runnable mDisappear = new Disappear(); - private Animation.AnimationListener mEndAction = new EndAction(); + private Runnable disappear = new Disappear(); + private Animation.AnimationListener endAction = new EndAction(); private static final int SCALING_UP_TIME = 600; private static final int SCALING_DOWN_TIME = 100; private static final int DISAPPEAR_TIMEOUT = 200; @@ -65,73 +65,73 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { private static final int MSG_CLOSE = 1; private static final float PIE_SWEEP = (float) (Math.PI * 2 / 3); // geometry - private Point mCenter; - private int mRadius; - private int mRadiusInc; + private Point center; + private int radius; + private int radiusInc; // the detection if touch is inside a slice is offset // inbounds by this amount to allow the selection to show before the // finger covers it - private int mTouchOffset; + private int touchOffset; - private List mItems; + private List items; - private PieItem mOpenItem; + private PieItem openItem; - private Paint mSelectedPaint; - private Paint mSubPaint; + private Paint selectedPaint; + private Paint subPaint; // touch handling - private PieItem mCurrentItem; - - private Paint mFocusPaint; - private int mSuccessColor; - private int mFailColor; - private int mCircleSize; - private int mFocusX; - private int mFocusY; - private int mCenterX; - private int mCenterY; - - private int mDialAngle; - private RectF mCircle; - private RectF mDial; - private Point mPoint1; - private Point mPoint2; - private int mStartAnimationAngle; - private boolean mFocused; - private int mInnerOffset; - private int mOuterStroke; - private int mInnerStroke; - private boolean mTapMode; - private boolean mBlockFocus; - private int mTouchSlopSquared; - private Point mDown; - private boolean mOpening; - private LinearAnimation mXFade; - private LinearAnimation mFadeIn; - private volatile boolean mFocusCancelled; - - private Handler mHandler = + private PieItem currentItem; + + private Paint focusPaint; + private int successColor; + private int failColor; + private int circleSize; + private int focusX; + private int focusY; + private int centerX; + private int centerY; + + private int dialAngle; + private RectF circle; + private RectF dial; + private Point point1; + private Point point2; + private int startAnimationAngle; + private boolean focused; + private int innerOffset; + private int outerStroke; + private int innerStroke; + private boolean tapMode; + private boolean blockFocus; + private int touchSlopSquared; + private Point down; + private boolean opening; + private LinearAnimation xFade; + private LinearAnimation fadeIn; + private volatile boolean focusCancelled; + + private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_OPEN: - if (mListener != null) { - mListener.onPieOpened(mCenter.x, mCenter.y); + if (listener != null) { + listener.onPieOpened(center.x, center.y); } break; case MSG_CLOSE: - if (mListener != null) { - mListener.onPieClosed(); + if (listener != null) { + listener.onPieClosed(); } break; } } }; - private PieListener mListener; + private PieListener listener; /** Listener for the pie item to communicate back to the renderer. */ public interface PieListener { @@ -141,7 +141,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { } public void setPieListener(PieListener pl) { - mListener = pl; + listener = pl; } public PieRenderer(Context context) { @@ -150,67 +150,67 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { private void init(Context ctx) { setVisible(false); - mItems = new ArrayList(); + items = new ArrayList(); Resources res = ctx.getResources(); - mRadius = res.getDimensionPixelSize(R.dimen.pie_radius_start); - mCircleSize = mRadius - res.getDimensionPixelSize(R.dimen.focus_radius_offset); - mRadiusInc = res.getDimensionPixelSize(R.dimen.pie_radius_increment); - mTouchOffset = res.getDimensionPixelSize(R.dimen.pie_touch_offset); - mCenter = new Point(0, 0); - mSelectedPaint = new Paint(); - mSelectedPaint.setColor(Color.argb(255, 51, 181, 229)); - mSelectedPaint.setAntiAlias(true); - mSubPaint = new Paint(); - mSubPaint.setAntiAlias(true); - mSubPaint.setColor(Color.argb(200, 250, 230, 128)); - mFocusPaint = new Paint(); - mFocusPaint.setAntiAlias(true); - mFocusPaint.setColor(Color.WHITE); - mFocusPaint.setStyle(Paint.Style.STROKE); - mSuccessColor = Color.GREEN; - mFailColor = Color.RED; - mCircle = new RectF(); - mDial = new RectF(); - mPoint1 = new Point(); - mPoint2 = new Point(); - mInnerOffset = res.getDimensionPixelSize(R.dimen.focus_inner_offset); - mOuterStroke = res.getDimensionPixelSize(R.dimen.focus_outer_stroke); - mInnerStroke = res.getDimensionPixelSize(R.dimen.focus_inner_stroke); - mState = STATE_IDLE; - mBlockFocus = false; - mTouchSlopSquared = ViewConfiguration.get(ctx).getScaledTouchSlop(); - mTouchSlopSquared = mTouchSlopSquared * mTouchSlopSquared; - mDown = new Point(); + radius = res.getDimensionPixelSize(R.dimen.pie_radius_start); + circleSize = radius - res.getDimensionPixelSize(R.dimen.focus_radius_offset); + radiusInc = res.getDimensionPixelSize(R.dimen.pie_radius_increment); + touchOffset = res.getDimensionPixelSize(R.dimen.pie_touch_offset); + center = new Point(0, 0); + selectedPaint = new Paint(); + selectedPaint.setColor(Color.argb(255, 51, 181, 229)); + selectedPaint.setAntiAlias(true); + subPaint = new Paint(); + subPaint.setAntiAlias(true); + subPaint.setColor(Color.argb(200, 250, 230, 128)); + focusPaint = new Paint(); + focusPaint.setAntiAlias(true); + focusPaint.setColor(Color.WHITE); + focusPaint.setStyle(Paint.Style.STROKE); + successColor = Color.GREEN; + failColor = Color.RED; + circle = new RectF(); + dial = new RectF(); + point1 = new Point(); + point2 = new Point(); + innerOffset = res.getDimensionPixelSize(R.dimen.focus_inner_offset); + outerStroke = res.getDimensionPixelSize(R.dimen.focus_outer_stroke); + innerStroke = res.getDimensionPixelSize(R.dimen.focus_inner_stroke); + state = STATE_IDLE; + blockFocus = false; + touchSlopSquared = ViewConfiguration.get(ctx).getScaledTouchSlop(); + touchSlopSquared = touchSlopSquared * touchSlopSquared; + down = new Point(); } public boolean showsItems() { - return mTapMode; + return tapMode; } public void addItem(PieItem item) { // add the item to the pie itself - mItems.add(item); + items.add(item); } public void removeItem(PieItem item) { - mItems.remove(item); + items.remove(item); } public void clearItems() { - mItems.clear(); + items.clear(); } public void showInCenter() { - if ((mState == STATE_PIE) && isVisible()) { - mTapMode = false; + if ((state == STATE_PIE) && isVisible()) { + tapMode = false; show(false); } else { - if (mState != STATE_IDLE) { + if (state != STATE_IDLE) { cancelFocus(); } - mState = STATE_PIE; - setCenter(mCenterX, mCenterY); - mTapMode = true; + state = STATE_PIE; + setCenter(centerX, centerY); + tapMode = true; show(true); } } @@ -226,59 +226,59 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { */ private void show(boolean show) { if (show) { - mState = STATE_PIE; + state = STATE_PIE; // ensure clean state - mCurrentItem = null; - mOpenItem = null; - for (PieItem item : mItems) { + currentItem = null; + openItem = null; + for (PieItem item : items) { item.setSelected(false); } layoutPie(); fadeIn(); } else { - mState = STATE_IDLE; - mTapMode = false; - if (mXFade != null) { - mXFade.cancel(); + state = STATE_IDLE; + tapMode = false; + if (xFade != null) { + xFade.cancel(); } } setVisible(show); - mHandler.sendEmptyMessage(show ? MSG_OPEN : MSG_CLOSE); + handler.sendEmptyMessage(show ? MSG_OPEN : MSG_CLOSE); } private void fadeIn() { - mFadeIn = new LinearAnimation(0, 1); - mFadeIn.setDuration(PIE_FADE_IN_DURATION); - mFadeIn.setAnimationListener( + fadeIn = new LinearAnimation(0, 1); + fadeIn.setDuration(PIE_FADE_IN_DURATION); + fadeIn.setAnimationListener( new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { - mFadeIn = null; + fadeIn = null; } @Override public void onAnimationRepeat(Animation animation) {} }); - mFadeIn.startNow(); - mOverlay.startAnimation(mFadeIn); + fadeIn.startNow(); + overlay.startAnimation(fadeIn); } public void setCenter(int x, int y) { - mCenter.x = x; - mCenter.y = y; + center.x = x; + center.y = y; // when using the pie menu, align the focus ring alignFocus(x, y); } private void layoutPie() { int rgap = 2; - int inner = mRadius + rgap; - int outer = mRadius + mRadiusInc - rgap; + int inner = radius + rgap; + int outer = radius + radiusInc - rgap; int gap = 1; - layoutItems(mItems, (float) (Math.PI / 2), inner, outer, gap); + layoutItems(items, (float) (Math.PI / 2), inner, outer, gap); } private void layoutItems(List items, float centerAngle, int inner, int outer, int gap) { @@ -294,7 +294,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { break; } } - Path path = makeSlice(getDegrees(0) - gap, getDegrees(sweep) + gap, outer, inner, mCenter); + Path path = makeSlice(getDegrees(0) - gap, getDegrees(sweep) + gap, outer, inner, center); for (PieItem item : items) { // shared between items item.setPath(path); @@ -306,13 +306,13 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { // move views to outer border int r = inner + (outer - inner) * 2 / 3; int x = (int) (r * Math.cos(angle)); - int y = mCenter.y - (int) (r * Math.sin(angle)) - h / 2; - x = mCenter.x + x - w / 2; + int y = center.y - (int) (r * Math.sin(angle)) - h / 2; + x = center.x + x - w / 2; item.setBounds(x, y, x + w, y + h); float itemstart = angle - sweep / 2; item.setGeometry(itemstart, sweep, inner, outer); if (item.hasItems()) { - layoutItems(item.getItems(), angle, inner, outer + mRadiusInc / 2, gap); + layoutItems(item.getItems(), angle, inner, outer + radiusInc / 2, gap); } angle += sweep; } @@ -339,7 +339,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { } private void startFadeOut() { - mOverlay + overlay .animate() .alpha(0) .setListener( @@ -348,7 +348,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { public void onAnimationEnd(Animator animation) { deselect(); show(false); - mOverlay.setAlpha(1); + overlay.setAlpha(1); super.onAnimationEnd(animation); } }) @@ -358,43 +358,43 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { @Override public void onDraw(Canvas canvas) { float alpha = 1; - if (mXFade != null) { - alpha = mXFade.getValue(); - } else if (mFadeIn != null) { - alpha = mFadeIn.getValue(); + if (xFade != null) { + alpha = xFade.getValue(); + } else if (fadeIn != null) { + alpha = fadeIn.getValue(); } int state = canvas.save(); - if (mFadeIn != null) { + if (fadeIn != null) { float sf = 0.9f + alpha * 0.1f; - canvas.scale(sf, sf, mCenter.x, mCenter.y); + canvas.scale(sf, sf, center.x, center.y); } drawFocus(canvas); - if (mState == STATE_FINISHING) { + if (this.state == STATE_FINISHING) { canvas.restoreToCount(state); return; } - if ((mOpenItem == null) || (mXFade != null)) { + if ((openItem == null) || (xFade != null)) { // draw base menu - for (PieItem item : mItems) { + for (PieItem item : items) { drawItem(canvas, item, alpha); } } - if (mOpenItem != null) { - for (PieItem inner : mOpenItem.getItems()) { - drawItem(canvas, inner, (mXFade != null) ? (1 - 0.5f * alpha) : 1); + if (openItem != null) { + for (PieItem inner : openItem.getItems()) { + drawItem(canvas, inner, (xFade != null) ? (1 - 0.5f * alpha) : 1); } } canvas.restoreToCount(state); } private void drawItem(Canvas canvas, PieItem item, float alpha) { - if (mState == STATE_PIE) { + if (this.state == STATE_PIE) { if (item.getPath() != null) { if (item.isSelected()) { - Paint p = mSelectedPaint; + Paint p = selectedPaint; int state = canvas.save(); float r = getDegrees(item.getStartAngle()); - canvas.rotate(r, mCenter.x, mCenter.y); + canvas.rotate(r, center.x, center.y); canvas.drawPath(item.getPath(), p); canvas.restoreToCount(state); } @@ -411,15 +411,15 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { float x = evt.getX(); float y = evt.getY(); int action = evt.getActionMasked(); - PointF polar = getPolar(x, y, !(mTapMode)); + PointF polar = getPolar(x, y, !(tapMode)); if (MotionEvent.ACTION_DOWN == action) { - mDown.x = (int) evt.getX(); - mDown.y = (int) evt.getY(); - mOpening = false; - if (mTapMode) { + down.x = (int) evt.getX(); + down.y = (int) evt.getY(); + opening = false; + if (tapMode) { PieItem item = findItem(polar); - if ((item != null) && (mCurrentItem != item)) { - mState = STATE_PIE; + if ((item != null) && (currentItem != item)) { + state = STATE_PIE; onEnter(item); } } else { @@ -429,34 +429,34 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { return true; } else if (MotionEvent.ACTION_UP == action) { if (isVisible()) { - PieItem item = mCurrentItem; - if (mTapMode) { + PieItem item = currentItem; + if (tapMode) { item = findItem(polar); - if (item != null && mOpening) { - mOpening = false; + if (item != null && opening) { + opening = false; return true; } } if (item == null) { - mTapMode = false; + tapMode = false; show(false); - } else if (!mOpening && !item.hasItems()) { + } else if (!opening && !item.hasItems()) { item.performClick(); startFadeOut(); - mTapMode = false; + tapMode = false; } return true; } } else if (MotionEvent.ACTION_CANCEL == action) { - if (isVisible() || mTapMode) { + if (isVisible() || tapMode) { show(false); } deselect(); return false; } else if (MotionEvent.ACTION_MOVE == action) { - if (polar.y < mRadius) { - if (mOpenItem != null) { - mOpenItem = null; + if (polar.y < radius) { + if (openItem != null) { + openItem = null; } else { deselect(); } @@ -464,12 +464,12 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { } PieItem item = findItem(polar); boolean moved = hasMoved(evt); - if ((item != null) && (mCurrentItem != item) && (!mOpening || moved)) { + if ((item != null) && (currentItem != item) && (!opening || moved)) { // only select if we didn't just open or have moved past slop - mOpening = false; + opening = false; if (moved) { // switch back to swipe mode - mTapMode = false; + tapMode = false; } onEnter(item); } @@ -478,8 +478,8 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { } private boolean hasMoved(MotionEvent e) { - return mTouchSlopSquared - < (e.getX() - mDown.x) * (e.getX() - mDown.x) + (e.getY() - mDown.y) * (e.getY() - mDown.y); + return touchSlopSquared + < (e.getX() - down.x) * (e.getX() - down.x) + (e.getY() - down.y) * (e.getY() - down.y); } /** @@ -488,52 +488,52 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { * @param item */ private void onEnter(PieItem item) { - if (mCurrentItem != null) { - mCurrentItem.setSelected(false); + if (currentItem != null) { + currentItem.setSelected(false); } if (item != null && item.isEnabled()) { item.setSelected(true); - mCurrentItem = item; - if ((mCurrentItem != mOpenItem) && mCurrentItem.hasItems()) { + currentItem = item; + if ((currentItem != openItem) && currentItem.hasItems()) { openCurrentItem(); } } else { - mCurrentItem = null; + currentItem = null; } } private void deselect() { - if (mCurrentItem != null) { - mCurrentItem.setSelected(false); + if (currentItem != null) { + currentItem.setSelected(false); } - if (mOpenItem != null) { - mOpenItem = null; + if (openItem != null) { + openItem = null; } - mCurrentItem = null; + currentItem = null; } private void openCurrentItem() { - if ((mCurrentItem != null) && mCurrentItem.hasItems()) { - mCurrentItem.setSelected(false); - mOpenItem = mCurrentItem; - mOpening = true; - mXFade = new LinearAnimation(1, 0); - mXFade.setDuration(PIE_XFADE_DURATION); - mXFade.setAnimationListener( + if ((currentItem != null) && currentItem.hasItems()) { + currentItem.setSelected(false); + openItem = currentItem; + opening = true; + xFade = new LinearAnimation(1, 0); + xFade.setDuration(PIE_XFADE_DURATION); + xFade.setAnimationListener( new AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { - mXFade = null; + xFade = null; } @Override public void onAnimationRepeat(Animation animation) {} }); - mXFade.startNow(); - mOverlay.startAnimation(mXFade); + xFade.startNow(); + overlay.startAnimation(xFade); } } @@ -541,8 +541,8 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { PointF res = new PointF(); // get angle and radius from x/y res.x = (float) Math.PI / 2; - x = x - mCenter.x; - y = mCenter.y - y; + x = x - center.x; + y = center.y - y; res.y = (float) Math.sqrt(x * x + y * y); if (x != 0) { res.x = (float) Math.atan2(y, x); @@ -550,7 +550,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { res.x = (float) (2 * Math.PI + res.x); } } - res.y = res.y + (useOffset ? mTouchOffset : 0); + res.y = res.y + (useOffset ? touchOffset : 0); return res; } @@ -560,7 +560,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { */ private PieItem findItem(PointF polar) { // find the matching item: - List items = (mOpenItem != null) ? mOpenItem.getItems() : mItems; + List items = (openItem != null) ? openItem.getItems() : this.items; for (PieItem item : items) { if (inside(polar, item)) { return item; @@ -573,7 +573,7 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { return (item.getInnerRadius() < polar.y) && (item.getStartAngle() < polar.x) && (item.getStartAngle() + item.getSweep() > polar.x) - && (!mTapMode || (item.getOuterRadius() > polar.y)); + && (!tapMode || (item.getOuterRadius() > polar.y)); } @Override @@ -584,31 +584,31 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { // focus specific code public void setBlockFocus(boolean blocked) { - mBlockFocus = blocked; + blockFocus = blocked; if (blocked) { clear(); } } public void setFocus(int x, int y) { - mFocusX = x; - mFocusY = y; - setCircle(mFocusX, mFocusY); + focusX = x; + focusY = y; + setCircle(focusX, focusY); } public void alignFocus(int x, int y) { - mOverlay.removeCallbacks(mDisappear); - mAnimation.cancel(); - mAnimation.reset(); - mFocusX = x; - mFocusY = y; - mDialAngle = DIAL_HORIZONTAL; + overlay.removeCallbacks(disappear); + animation.cancel(); + animation.reset(); + focusX = x; + focusY = y; + dialAngle = DIAL_HORIZONTAL; setCircle(x, y); - mFocused = false; + focused = false; } public int getSize() { - return 2 * mCircleSize; + return 2 * circleSize; } private int getRandomRange() { @@ -618,58 +618,57 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { @Override public void layout(int l, int t, int r, int b) { super.layout(l, t, r, b); - mCenterX = (r - l) / 2; - mCenterY = (b - t) / 2; - mFocusX = mCenterX; - mFocusY = mCenterY; - setCircle(mFocusX, mFocusY); - if (isVisible() && mState == STATE_PIE) { - setCenter(mCenterX, mCenterY); + centerX = (r - l) / 2; + centerY = (b - t) / 2; + focusX = centerX; + focusY = centerY; + setCircle(focusX, focusY); + if (isVisible() && state == STATE_PIE) { + setCenter(centerX, centerY); layoutPie(); } } private void setCircle(int cx, int cy) { - mCircle.set(cx - mCircleSize, cy - mCircleSize, cx + mCircleSize, cy + mCircleSize); - mDial.set( - cx - mCircleSize + mInnerOffset, - cy - mCircleSize + mInnerOffset, - cx + mCircleSize - mInnerOffset, - cy + mCircleSize - mInnerOffset); + circle.set(cx - circleSize, cy - circleSize, cx + circleSize, cy + circleSize); + dial.set( + cx - circleSize + innerOffset, + cy - circleSize + innerOffset, + cx + circleSize - innerOffset, + cy + circleSize - innerOffset); } public void drawFocus(Canvas canvas) { - if (mBlockFocus) { + if (blockFocus) { return; } - mFocusPaint.setStrokeWidth(mOuterStroke); - canvas.drawCircle((float) mFocusX, (float) mFocusY, (float) mCircleSize, mFocusPaint); - if (mState == STATE_PIE) { + focusPaint.setStrokeWidth(outerStroke); + canvas.drawCircle((float) focusX, (float) focusY, (float) circleSize, focusPaint); + if (state == STATE_PIE) { return; } - int color = mFocusPaint.getColor(); - if (mState == STATE_FINISHING) { - mFocusPaint.setColor(mFocused ? mSuccessColor : mFailColor); + int color = focusPaint.getColor(); + if (state == STATE_FINISHING) { + focusPaint.setColor(focused ? successColor : failColor); } - mFocusPaint.setStrokeWidth(mInnerStroke); - drawLine(canvas, mDialAngle, mFocusPaint); - drawLine(canvas, mDialAngle + 45, mFocusPaint); - drawLine(canvas, mDialAngle + 180, mFocusPaint); - drawLine(canvas, mDialAngle + 225, mFocusPaint); + focusPaint.setStrokeWidth(innerStroke); + drawLine(canvas, dialAngle, focusPaint); + drawLine(canvas, dialAngle + 45, focusPaint); + drawLine(canvas, dialAngle + 180, focusPaint); + drawLine(canvas, dialAngle + 225, focusPaint); canvas.save(); // rotate the arc instead of its offset to better use framework's shape caching - canvas.rotate(mDialAngle, mFocusX, mFocusY); - canvas.drawArc(mDial, 0, 45, false, mFocusPaint); - canvas.drawArc(mDial, 180, 45, false, mFocusPaint); + canvas.rotate(dialAngle, focusX, focusY); + canvas.drawArc(dial, 0, 45, false, focusPaint); + canvas.drawArc(dial, 180, 45, false, focusPaint); canvas.restore(); - mFocusPaint.setColor(color); + focusPaint.setColor(color); } private void drawLine(Canvas canvas, int angle, Paint p) { - convertCart(angle, mCircleSize - mInnerOffset, mPoint1); - convertCart(angle, mCircleSize - mInnerOffset + mInnerOffset / 3, mPoint2); - canvas.drawLine( - mPoint1.x + mFocusX, mPoint1.y + mFocusY, mPoint2.x + mFocusX, mPoint2.y + mFocusY, p); + convertCart(angle, circleSize - innerOffset, point1); + convertCart(angle, circleSize - innerOffset + innerOffset / 3, point2); + canvas.drawLine(point1.x + focusX, point1.y + focusY, point2.x + focusX, point2.y + focusY, p); } private static void convertCart(int angle, int radius, Point out) { @@ -680,65 +679,65 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { @Override public void showStart() { - if (mState == STATE_PIE) { + if (state == STATE_PIE) { return; } cancelFocus(); - mStartAnimationAngle = 67; + startAnimationAngle = 67; int range = getRandomRange(); - startAnimation(SCALING_UP_TIME, false, mStartAnimationAngle, mStartAnimationAngle + range); - mState = STATE_FOCUSING; + startAnimation(SCALING_UP_TIME, false, startAnimationAngle, startAnimationAngle + range); + state = STATE_FOCUSING; } @Override public void showSuccess(boolean timeout) { - if (mState == STATE_FOCUSING) { - startAnimation(SCALING_DOWN_TIME, timeout, mStartAnimationAngle); - mState = STATE_FINISHING; - mFocused = true; + if (state == STATE_FOCUSING) { + startAnimation(SCALING_DOWN_TIME, timeout, startAnimationAngle); + state = STATE_FINISHING; + focused = true; } } @Override public void showFail(boolean timeout) { - if (mState == STATE_FOCUSING) { - startAnimation(SCALING_DOWN_TIME, timeout, mStartAnimationAngle); - mState = STATE_FINISHING; - mFocused = false; + if (state == STATE_FOCUSING) { + startAnimation(SCALING_DOWN_TIME, timeout, startAnimationAngle); + state = STATE_FINISHING; + focused = false; } } private void cancelFocus() { - mFocusCancelled = true; - mOverlay.removeCallbacks(mDisappear); - if (mAnimation != null) { - mAnimation.cancel(); + focusCancelled = true; + overlay.removeCallbacks(disappear); + if (animation != null) { + animation.cancel(); } - mFocusCancelled = false; - mFocused = false; - mState = STATE_IDLE; + focusCancelled = false; + focused = false; + state = STATE_IDLE; } @Override public void clear() { - if (mState == STATE_PIE) { + if (state == STATE_PIE) { return; } cancelFocus(); - mOverlay.post(mDisappear); + overlay.post(disappear); } private void startAnimation(long duration, boolean timeout, float toScale) { - startAnimation(duration, timeout, mDialAngle, toScale); + startAnimation(duration, timeout, dialAngle, toScale); } private void startAnimation(long duration, boolean timeout, float fromScale, float toScale) { setVisible(true); - mAnimation.reset(); - mAnimation.setDuration(duration); - mAnimation.setScale(fromScale, toScale); - mAnimation.setAnimationListener(timeout ? mEndAction : null); - mOverlay.startAnimation(mAnimation); + animation.reset(); + animation.setDuration(duration); + animation.setScale(fromScale, toScale); + animation.setAnimationListener(timeout ? endAction : null); + overlay.startAnimation(animation); update(); } @@ -746,8 +745,8 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { @Override public void onAnimationEnd(Animation animation) { // Keep the focus indicator for some time. - if (!mFocusCancelled) { - mOverlay.postDelayed(mDisappear, DISAPPEAR_TIMEOUT); + if (!focusCancelled) { + overlay.postDelayed(disappear, DISAPPEAR_TIMEOUT); } } @@ -761,56 +760,56 @@ public class PieRenderer extends OverlayRenderer implements FocusIndicator { private class Disappear implements Runnable { @Override public void run() { - if (mState == STATE_PIE) { + if (state == STATE_PIE) { return; } setVisible(false); - mFocusX = mCenterX; - mFocusY = mCenterY; - mState = STATE_IDLE; - setCircle(mFocusX, mFocusY); - mFocused = false; + focusX = centerX; + focusY = centerY; + state = STATE_IDLE; + setCircle(focusX, focusY); + focused = false; } } private class ScaleAnimation extends Animation { - private float mFrom = 1f; - private float mTo = 1f; + private float from = 1f; + private float to = 1f; public ScaleAnimation() { setFillAfter(true); } public void setScale(float from, float to) { - mFrom = from; - mTo = to; + this.from = from; + this.to = to; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { - mDialAngle = (int) (mFrom + (mTo - mFrom) * interpolatedTime); + dialAngle = (int) (from + (to - from) * interpolatedTime); } } private static class LinearAnimation extends Animation { - private float mFrom; - private float mTo; - private float mValue; + private float from; + private float to; + private float value; public LinearAnimation(float from, float to) { setFillAfter(true); setInterpolator(new LinearInterpolator()); - mFrom = from; - mTo = to; + this.from = from; + this.to = to; } public float getValue() { - return mValue; + return value; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { - mValue = (mFrom + (mTo - mFrom) * interpolatedTime); + value = (from + (to - from) * interpolatedTime); } } } diff --git a/java/com/android/dialer/callcomposer/camera/camerafocus/RenderOverlay.java b/java/com/android/dialer/callcomposer/camera/camerafocus/RenderOverlay.java index c38ae6c81..458e852fa 100644 --- a/java/com/android/dialer/callcomposer/camera/camerafocus/RenderOverlay.java +++ b/java/com/android/dialer/callcomposer/camera/camerafocus/RenderOverlay.java @@ -42,26 +42,26 @@ public class RenderOverlay extends FrameLayout { void draw(Canvas canvas); } - private RenderView mRenderView; - private List mClients; + private RenderView renderView; + private List clients; // reverse list of touch clients - private List mTouchClients; - private int[] mPosition = new int[2]; + private List touchClients; + private int[] position = new int[2]; public RenderOverlay(Context context, AttributeSet attrs) { super(context, attrs); - mRenderView = new RenderView(context); - addView(mRenderView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); - mClients = new ArrayList<>(10); - mTouchClients = new ArrayList<>(10); + renderView = new RenderView(context); + addView(renderView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + clients = new ArrayList<>(10); + touchClients = new ArrayList<>(10); setWillNotDraw(false); addRenderer(new PieRenderer(context)); } public PieRenderer getPieRenderer() { - for (Renderer renderer : mClients) { + for (Renderer renderer : clients) { if (renderer instanceof PieRenderer) { return (PieRenderer) renderer; } @@ -70,22 +70,22 @@ public class RenderOverlay extends FrameLayout { } public void addRenderer(Renderer renderer) { - mClients.add(renderer); + clients.add(renderer); renderer.setOverlay(this); if (renderer.handlesTouch()) { - mTouchClients.add(0, renderer); + touchClients.add(0, renderer); } renderer.layout(getLeft(), getTop(), getRight(), getBottom()); } public void addRenderer(int pos, Renderer renderer) { - mClients.add(pos, renderer); + clients.add(pos, renderer); renderer.setOverlay(this); renderer.layout(getLeft(), getTop(), getRight(), getBottom()); } public void remove(Renderer renderer) { - mClients.remove(renderer); + clients.remove(renderer); renderer.setOverlay(null); } @@ -95,11 +95,11 @@ public class RenderOverlay extends FrameLayout { } private void adjustPosition() { - getLocationInWindow(mPosition); + getLocationInWindow(position); } public void update() { - mRenderView.invalidate(); + renderView.invalidate(); } @SuppressLint("ClickableViewAccessibility") @@ -112,9 +112,9 @@ public class RenderOverlay extends FrameLayout { @Override public boolean onTouchEvent(MotionEvent evt) { - if (mTouchClients != null) { + if (touchClients != null) { boolean res = false; - for (Renderer client : mTouchClients) { + for (Renderer client : touchClients) { res |= client.onTouchEvent(evt); } return res; @@ -126,10 +126,10 @@ public class RenderOverlay extends FrameLayout { public void onLayout(boolean changed, int left, int top, int right, int bottom) { adjustPosition(); super.onLayout(changed, left, top, right, bottom); - if (mClients == null) { + if (clients == null) { return; } - for (Renderer renderer : mClients) { + for (Renderer renderer : clients) { renderer.layout(left, top, right, bottom); } } @@ -137,11 +137,11 @@ public class RenderOverlay extends FrameLayout { @Override public void draw(Canvas canvas) { super.draw(canvas); - if (mClients == null) { + if (clients == null) { return; } boolean redraw = false; - for (Renderer renderer : mClients) { + for (Renderer renderer : clients) { renderer.draw(canvas); redraw = redraw || ((OverlayRenderer) renderer).isVisible(); } diff --git a/java/com/android/dialer/callcomposer/camera/exif/CountedDataInputStream.java b/java/com/android/dialer/callcomposer/camera/exif/CountedDataInputStream.java index e2c8185da..cb5143a92 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/CountedDataInputStream.java +++ b/java/com/android/dialer/callcomposer/camera/exif/CountedDataInputStream.java @@ -27,45 +27,45 @@ import java.nio.charset.Charset; class CountedDataInputStream extends FilterInputStream { - private int mCount = 0; + private int count = 0; // allocate a byte buffer for a long value; - private final byte[] mByteArray = new byte[8]; - private final ByteBuffer mByteBuffer = ByteBuffer.wrap(mByteArray); + private final byte[] byteArray = new byte[8]; + private final ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray); CountedDataInputStream(InputStream in) { super(in); } int getReadByteCount() { - return mCount; + return count; } @Override public int read(byte[] b) throws IOException { int r = in.read(b); - mCount += (r >= 0) ? r : 0; + count += (r >= 0) ? r : 0; return r; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = in.read(b, off, len); - mCount += (r >= 0) ? r : 0; + count += (r >= 0) ? r : 0; return r; } @Override public int read() throws IOException { int r = in.read(); - mCount += (r >= 0) ? 1 : 0; + count += (r >= 0) ? 1 : 0; return r; } @Override public long skip(long length) throws IOException { long skip = in.skip(length); - mCount += skip; + count += skip; return skip; } @@ -76,7 +76,7 @@ class CountedDataInputStream extends FilterInputStream { } void skipTo(long target) throws IOException { - long cur = mCount; + long cur = count; long diff = target - cur; Assert.checkArgument(diff >= 0); skipOrThrow(diff); @@ -94,17 +94,17 @@ class CountedDataInputStream extends FilterInputStream { } void setByteOrder(ByteOrder order) { - mByteBuffer.order(order); + byteBuffer.order(order); } ByteOrder getByteOrder() { - return mByteBuffer.order(); + return byteBuffer.order(); } short readShort() throws IOException { - readOrThrow(mByteArray, 0, 2); - mByteBuffer.rewind(); - return mByteBuffer.getShort(); + readOrThrow(byteArray, 0, 2); + byteBuffer.rewind(); + return byteBuffer.getShort(); } int readUnsignedShort() throws IOException { @@ -112,9 +112,9 @@ class CountedDataInputStream extends FilterInputStream { } int readInt() throws IOException { - readOrThrow(mByteArray, 0, 4); - mByteBuffer.rewind(); - return mByteBuffer.getInt(); + readOrThrow(byteArray, 0, 4); + byteBuffer.rewind(); + return byteBuffer.getInt(); } long readUnsignedInt() throws IOException { diff --git a/java/com/android/dialer/callcomposer/camera/exif/ExifData.java b/java/com/android/dialer/callcomposer/camera/exif/ExifData.java index 27936ae2f..fef9d870c 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/ExifData.java +++ b/java/com/android/dialer/callcomposer/camera/exif/ExifData.java @@ -25,20 +25,20 @@ package com.android.dialer.callcomposer.camera.exif; */ public class ExifData { - private final IfdData[] mIfdDatas = new IfdData[IfdId.TYPE_IFD_COUNT]; + private final IfdData[] ifdDatas = new IfdData[IfdId.TYPE_IFD_COUNT]; /** * Adds IFD data. If IFD data of the same type already exists, it will be replaced by the new * data. */ void addIfdData(IfdData data) { - mIfdDatas[data.getId()] = data; + ifdDatas[data.getId()] = data; } /** Returns the {@link IfdData} object corresponding to a given IFD if it exists or null. */ IfdData getIfdData(int ifdId) { if (ExifTag.isValidIfd(ifdId)) { - return mIfdDatas[ifdId]; + return ifdDatas[ifdId]; } return null; } @@ -47,7 +47,7 @@ public class ExifData { * Returns the tag with a given TID in the given IFD if the tag exists. Otherwise returns null. */ protected ExifTag getTag(short tag, int ifd) { - IfdData ifdData = mIfdDatas[ifd]; + IfdData ifdData = ifdDatas[ifd]; return (ifdData == null) ? null : ifdData.getTag(tag); } @@ -79,10 +79,10 @@ public class ExifData { * Returns the {@link IfdData} object corresponding to a given IFD or generates one if none exist. */ private IfdData getOrCreateIfdData(int ifdId) { - IfdData ifdData = mIfdDatas[ifdId]; + IfdData ifdData = ifdDatas[ifdId]; if (ifdData == null) { ifdData = new IfdData(ifdId); - mIfdDatas[ifdId] = ifdData; + ifdDatas[ifdId] = ifdData; } return ifdData; } diff --git a/java/com/android/dialer/callcomposer/camera/exif/ExifInterface.java b/java/com/android/dialer/callcomposer/camera/exif/ExifInterface.java index 1bf9519ad..737401f64 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/ExifInterface.java +++ b/java/com/android/dialer/callcomposer/camera/exif/ExifInterface.java @@ -61,21 +61,21 @@ public class ExifInterface { static final int TAG_INTEROPERABILITY_IFD = defineTag(IfdId.TYPE_IFD_EXIF, (short) 0xA005); /** Tags that contain offset markers. These are included in the banned defines. */ - private static HashSet sOffsetTags = new HashSet<>(); + private static HashSet offsetTags = new HashSet<>(); static { - sOffsetTags.add(getTrueTagKey(TAG_GPS_IFD)); - sOffsetTags.add(getTrueTagKey(TAG_EXIF_IFD)); - sOffsetTags.add(getTrueTagKey(TAG_JPEG_INTERCHANGE_FORMAT)); - sOffsetTags.add(getTrueTagKey(TAG_INTEROPERABILITY_IFD)); - sOffsetTags.add(getTrueTagKey(TAG_STRIP_OFFSETS)); + offsetTags.add(getTrueTagKey(TAG_GPS_IFD)); + offsetTags.add(getTrueTagKey(TAG_EXIF_IFD)); + offsetTags.add(getTrueTagKey(TAG_JPEG_INTERCHANGE_FORMAT)); + offsetTags.add(getTrueTagKey(TAG_INTEROPERABILITY_IFD)); + offsetTags.add(getTrueTagKey(TAG_STRIP_OFFSETS)); } private static final String NULL_ARGUMENT_STRING = "Argument is null"; private static final String GPS_DATE_FORMAT_STR = "yyyy:MM:dd"; - private ExifData mData = new ExifData(); + private ExifData data = new ExifData(); @SuppressLint("SimpleDateFormat") public ExifInterface() { @@ -110,7 +110,7 @@ public class ExifInterface { } catch (ExifInvalidFormatException e) { throw new IOException("Invalid exif format : " + e); } - mData = d; + data = d; } /** Returns the TID for a tag constant. */ @@ -151,17 +151,17 @@ public class ExifInterface { * @return true if the TID is that of an offset tag. */ static boolean isOffsetTag(short tag) { - return sOffsetTags.contains(tag); + return offsetTags.contains(tag); } - private SparseIntArray mTagInfo = null; + private SparseIntArray tagInfo = null; SparseIntArray getTagInfo() { - if (mTagInfo == null) { - mTagInfo = new SparseIntArray(); + if (tagInfo == null) { + tagInfo = new SparseIntArray(); initTagInfo(); } - return mTagInfo; + return tagInfo; } private void initTagInfo() { @@ -173,24 +173,24 @@ public class ExifInterface { // IFD0 tags int[] ifdAllowedIfds = {IfdId.TYPE_IFD_0, IfdId.TYPE_IFD_1}; int ifdFlags = getFlagsFromAllowedIfds(ifdAllowedIfds) << 24; - mTagInfo.put(ExifInterface.TAG_STRIP_OFFSETS, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16); - mTagInfo.put(ExifInterface.TAG_EXIF_IFD, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); - mTagInfo.put(ExifInterface.TAG_GPS_IFD, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); - mTagInfo.put(ExifInterface.TAG_ORIENTATION, ifdFlags | ExifTag.TYPE_UNSIGNED_SHORT << 16 | 1); - mTagInfo.put(ExifInterface.TAG_STRIP_BYTE_COUNTS, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16); + tagInfo.put(ExifInterface.TAG_STRIP_OFFSETS, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16); + tagInfo.put(ExifInterface.TAG_EXIF_IFD, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); + tagInfo.put(ExifInterface.TAG_GPS_IFD, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); + tagInfo.put(ExifInterface.TAG_ORIENTATION, ifdFlags | ExifTag.TYPE_UNSIGNED_SHORT << 16 | 1); + tagInfo.put(ExifInterface.TAG_STRIP_BYTE_COUNTS, ifdFlags | ExifTag.TYPE_UNSIGNED_LONG << 16); // IFD1 tags int[] ifd1AllowedIfds = {IfdId.TYPE_IFD_1}; int ifdFlags1 = getFlagsFromAllowedIfds(ifd1AllowedIfds) << 24; - mTagInfo.put( + tagInfo.put( ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT, ifdFlags1 | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); - mTagInfo.put( + tagInfo.put( ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, ifdFlags1 | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); // Exif tags int[] exifAllowedIfds = {IfdId.TYPE_IFD_EXIF}; int exifFlags = getFlagsFromAllowedIfds(exifAllowedIfds) << 24; - mTagInfo.put( + tagInfo.put( ExifInterface.TAG_INTEROPERABILITY_IFD, exifFlags | ExifTag.TYPE_UNSIGNED_LONG << 16 | 1); } @@ -232,7 +232,7 @@ public class ExifInterface { if (!ExifTag.isValidIfd(ifdId)) { return null; } - return mData.getTag(getTrueTagKey(tagId), ifdId); + return data.getTag(getTrueTagKey(tagId), ifdId); } public Integer getTagIntValue(int tagId) { @@ -328,7 +328,7 @@ public class ExifInterface { /** Clears this ExifInterface object's existing exif tags. */ public void clearExif() { - mData = new ExifData(); + data = new ExifData(); } /** @@ -340,7 +340,7 @@ public class ExifInterface { * @return the previous ExifTag with the same TID and IFD or null if none exists. */ public ExifTag setTag(ExifTag tag) { - return mData.addTag(tag); + return data.addTag(tag); } /** diff --git a/java/com/android/dialer/callcomposer/camera/exif/ExifParser.java b/java/com/android/dialer/callcomposer/camera/exif/ExifParser.java index c728845a1..1aec4ab12 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/ExifParser.java +++ b/java/com/android/dialer/callcomposer/camera/exif/ExifParser.java @@ -119,20 +119,20 @@ public class ExifParser { private static final int DEFAULT_IFD0_OFFSET = 8; - private final CountedDataInputStream mTiffStream; - private final int mOptions; - private int mIfdStartOffset = 0; - private int mNumOfTagInIfd = 0; - private int mIfdType; - private ExifTag mTag; - private ImageEvent mImageEvent; - private ExifTag mStripSizeTag; - private ExifTag mJpegSizeTag; - private boolean mNeedToParseOffsetsInCurrentIfd; - private boolean mContainExifData = false; - private int mApp1End; - private byte[] mDataAboveIfd0; - private int mIfd0Position; + private final CountedDataInputStream tiffStream; + private final int options; + private int ifdStartOffset = 0; + private int numOfTagInIfd = 0; + private int ifdType; + private ExifTag tag; + private ImageEvent imageEvent; + private ExifTag stripSizeTag; + private ExifTag jpegSizeTag; + private boolean needToParseOffsetsInCurrentIfd; + private boolean containExifData = false; + private int app1End; + private byte[] dataAboveIfd0; + private int ifd0Position; private final ExifInterface mInterface; private static final short TAG_EXIF_IFD = ExifInterface.getTrueTagKey(ExifInterface.TAG_EXIF_IFD); @@ -148,26 +148,26 @@ public class ExifParser { private static final short TAG_STRIP_BYTE_COUNTS = ExifInterface.getTrueTagKey(ExifInterface.TAG_STRIP_BYTE_COUNTS); - private final TreeMap mCorrespondingEvent = new TreeMap<>(); + private final TreeMap correspondingEvent = new TreeMap<>(); private boolean isIfdRequested(int ifdType) { switch (ifdType) { case IfdId.TYPE_IFD_0: - return (mOptions & OPTION_IFD_0) != 0; + return (options & OPTION_IFD_0) != 0; case IfdId.TYPE_IFD_1: - return (mOptions & OPTION_IFD_1) != 0; + return (options & OPTION_IFD_1) != 0; case IfdId.TYPE_IFD_EXIF: - return (mOptions & OPTION_IFD_EXIF) != 0; + return (options & OPTION_IFD_EXIF) != 0; case IfdId.TYPE_IFD_GPS: - return (mOptions & OPTION_IFD_GPS) != 0; + return (options & OPTION_IFD_GPS) != 0; case IfdId.TYPE_IFD_INTEROPERABILITY: - return (mOptions & OPTION_IFD_INTEROPERABILITY) != 0; + return (options & OPTION_IFD_INTEROPERABILITY) != 0; } return false; } private boolean isThumbnailRequested() { - return (mOptions & OPTION_THUMBNAIL) != 0; + return (options & OPTION_THUMBNAIL) != 0; } private ExifParser(InputStream inputStream, int options, ExifInterface iRef) @@ -179,25 +179,25 @@ public class ExifParser { LogUtil.v("ExifParser.ExifParser", "Reading exif..."); } mInterface = iRef; - mContainExifData = seekTiffData(inputStream); - mTiffStream = new CountedDataInputStream(inputStream); - mOptions = options; - if (!mContainExifData) { + containExifData = seekTiffData(inputStream); + tiffStream = new CountedDataInputStream(inputStream); + this.options = options; + if (!containExifData) { return; } parseTiffHeader(); - long offset = mTiffStream.readUnsignedInt(); + long offset = tiffStream.readUnsignedInt(); if (offset > Integer.MAX_VALUE) { throw new ExifInvalidFormatException("Invalid offset " + offset); } - mIfd0Position = (int) offset; - mIfdType = IfdId.TYPE_IFD_0; + ifd0Position = (int) offset; + ifdType = IfdId.TYPE_IFD_0; if (isIfdRequested(IfdId.TYPE_IFD_0) || needToParseOffsetsInCurrentIfd()) { registerIfd(IfdId.TYPE_IFD_0, offset); if (offset != DEFAULT_IFD0_OFFSET) { - mDataAboveIfd0 = new byte[(int) offset - DEFAULT_IFD0_OFFSET]; - read(mDataAboveIfd0); + dataAboveIfd0 = new byte[(int) offset - DEFAULT_IFD0_OFFSET]; + read(dataAboveIfd0); } } } @@ -247,23 +247,23 @@ public class ExifParser { * @see #EVENT_END */ protected int next() throws IOException, ExifInvalidFormatException { - if (!mContainExifData) { + if (!containExifData) { return EVENT_END; } - int offset = mTiffStream.getReadByteCount(); - int endOfTags = mIfdStartOffset + OFFSET_SIZE + TAG_SIZE * mNumOfTagInIfd; + int offset = tiffStream.getReadByteCount(); + int endOfTags = ifdStartOffset + OFFSET_SIZE + TAG_SIZE * numOfTagInIfd; if (offset < endOfTags) { - mTag = readTag(); - if (mTag == null) { + tag = readTag(); + if (tag == null) { return next(); } - if (mNeedToParseOffsetsInCurrentIfd) { - checkOffsetOrImageTag(mTag); + if (needToParseOffsetsInCurrentIfd) { + checkOffsetOrImageTag(tag); } return EVENT_NEW_TAG; } else if (offset == endOfTags) { // There is a link to ifd1 at the end of ifd0 - if (mIfdType == IfdId.TYPE_IFD_0) { + if (ifdType == IfdId.TYPE_IFD_0) { long ifdOffset = readUnsignedLong(); if (isIfdRequested(IfdId.TYPE_IFD_1) || isThumbnailRequested()) { if (ifdOffset != 0) { @@ -273,8 +273,8 @@ public class ExifParser { } else { int offsetSize = 4; // Some camera models use invalid length of the offset - if (mCorrespondingEvent.size() > 0) { - offsetSize = mCorrespondingEvent.firstEntry().getKey() - mTiffStream.getReadByteCount(); + if (correspondingEvent.size() > 0) { + offsetSize = correspondingEvent.firstEntry().getKey() - tiffStream.getReadByteCount(); } if (offsetSize < 4) { LogUtil.i("ExifParser.next", "Invalid size of link to next IFD: " + offsetSize); @@ -286,8 +286,8 @@ public class ExifParser { } } } - while (mCorrespondingEvent.size() != 0) { - Entry entry = mCorrespondingEvent.pollFirstEntry(); + while (correspondingEvent.size() != 0) { + Entry entry = correspondingEvent.pollFirstEntry(); Object event = entry.getValue(); try { skipTo(entry.getKey()); @@ -302,30 +302,30 @@ public class ExifParser { continue; } if (event instanceof IfdEvent) { - mIfdType = ((IfdEvent) event).ifd; - mNumOfTagInIfd = mTiffStream.readUnsignedShort(); - mIfdStartOffset = entry.getKey(); + ifdType = ((IfdEvent) event).ifd; + numOfTagInIfd = tiffStream.readUnsignedShort(); + ifdStartOffset = entry.getKey(); - if (mNumOfTagInIfd * TAG_SIZE + mIfdStartOffset + OFFSET_SIZE > mApp1End) { - LogUtil.i("ExifParser.next", "Invalid size of IFD " + mIfdType); + if (numOfTagInIfd * TAG_SIZE + ifdStartOffset + OFFSET_SIZE > app1End) { + LogUtil.i("ExifParser.next", "Invalid size of IFD " + ifdType); return EVENT_END; } - mNeedToParseOffsetsInCurrentIfd = needToParseOffsetsInCurrentIfd(); + needToParseOffsetsInCurrentIfd = needToParseOffsetsInCurrentIfd(); if (((IfdEvent) event).isRequested) { return EVENT_START_OF_IFD; } else { skipRemainingTagsInCurrentIfd(); } } else if (event instanceof ImageEvent) { - mImageEvent = (ImageEvent) event; - return mImageEvent.type; + imageEvent = (ImageEvent) event; + return imageEvent.type; } else { ExifTagEvent tagEvent = (ExifTagEvent) event; - mTag = tagEvent.tag; - if (mTag.getDataType() != ExifTag.TYPE_UNDEFINED) { - readFullTagValue(mTag); - checkOffsetOrImageTag(mTag); + tag = tagEvent.tag; + if (tag.getDataType() != ExifTag.TYPE_UNDEFINED) { + readFullTagValue(tag); + checkOffsetOrImageTag(tag); } if (tagEvent.isRequested) { return EVENT_VALUE_OF_REGISTERED_TAG; @@ -342,26 +342,26 @@ public class ExifParser { * @throws ExifInvalidFormatException */ private void skipRemainingTagsInCurrentIfd() throws IOException, ExifInvalidFormatException { - int endOfTags = mIfdStartOffset + OFFSET_SIZE + TAG_SIZE * mNumOfTagInIfd; - int offset = mTiffStream.getReadByteCount(); + int endOfTags = ifdStartOffset + OFFSET_SIZE + TAG_SIZE * numOfTagInIfd; + int offset = tiffStream.getReadByteCount(); if (offset > endOfTags) { return; } - if (mNeedToParseOffsetsInCurrentIfd) { + if (needToParseOffsetsInCurrentIfd) { while (offset < endOfTags) { - mTag = readTag(); + tag = readTag(); offset += TAG_SIZE; - if (mTag == null) { + if (tag == null) { continue; } - checkOffsetOrImageTag(mTag); + checkOffsetOrImageTag(tag); } } else { skipTo(endOfTags); } long ifdOffset = readUnsignedLong(); // For ifd0, there is a link to ifd1 in the end of all tags - if (mIfdType == IfdId.TYPE_IFD_0 + if (ifdType == IfdId.TYPE_IFD_0 && (isIfdRequested(IfdId.TYPE_IFD_1) || isThumbnailRequested())) { if (ifdOffset > 0) { registerIfd(IfdId.TYPE_IFD_1, ifdOffset); @@ -370,7 +370,7 @@ public class ExifParser { } private boolean needToParseOffsetsInCurrentIfd() { - switch (mIfdType) { + switch (ifdType) { case IfdId.TYPE_IFD_0: return isIfdRequested(IfdId.TYPE_IFD_EXIF) || isIfdRequested(IfdId.TYPE_IFD_GPS) @@ -408,7 +408,7 @@ public class ExifParser { * @see #readString(int, java.nio.charset.Charset) */ protected ExifTag getTag() { - return mTag; + return tag; } /** @@ -421,7 +421,7 @@ public class ExifParser { * @see IfdId#TYPE_IFD_EXIF */ int getCurrentIfd() { - return mIfdType; + return ifdType; } /** @@ -429,31 +429,31 @@ public class ExifParser { * strip. */ int getStripIndex() { - return mImageEvent.stripIndex; + return imageEvent.stripIndex; } /** When receiving {@link #EVENT_UNCOMPRESSED_STRIP}, call this function to get the strip size. */ int getStripSize() { - if (mStripSizeTag == null) { + if (stripSizeTag == null) { return 0; } - return (int) mStripSizeTag.getValueAt(0); + return (int) stripSizeTag.getValueAt(0); } /** * When receiving {@link #EVENT_COMPRESSED_IMAGE}, call this function to get the image data size. */ int getCompressedImageSize() { - if (mJpegSizeTag == null) { + if (jpegSizeTag == null) { return 0; } - return (int) mJpegSizeTag.getValueAt(0); + return (int) jpegSizeTag.getValueAt(0); } private void skipTo(int offset) throws IOException { - mTiffStream.skipTo(offset); - while (!mCorrespondingEvent.isEmpty() && mCorrespondingEvent.firstKey() < offset) { - mCorrespondingEvent.pollFirstEntry(); + tiffStream.skipTo(offset); + while (!correspondingEvent.isEmpty() && correspondingEvent.firstKey() < offset) { + correspondingEvent.pollFirstEntry(); } } @@ -466,37 +466,37 @@ public class ExifParser { * @see #EVENT_VALUE_OF_REGISTERED_TAG */ void registerForTagValue(ExifTag tag) { - if (tag.getOffset() >= mTiffStream.getReadByteCount()) { - mCorrespondingEvent.put(tag.getOffset(), new ExifTagEvent(tag, true)); + if (tag.getOffset() >= tiffStream.getReadByteCount()) { + correspondingEvent.put(tag.getOffset(), new ExifTagEvent(tag, true)); } } private void registerIfd(int ifdType, long offset) { // Cast unsigned int to int since the offset is always smaller // than the size of APP1 (65536) - mCorrespondingEvent.put((int) offset, new IfdEvent(ifdType, isIfdRequested(ifdType))); + correspondingEvent.put((int) offset, new IfdEvent(ifdType, isIfdRequested(ifdType))); } private void registerCompressedImage(long offset) { - mCorrespondingEvent.put((int) offset, new ImageEvent(EVENT_COMPRESSED_IMAGE)); + correspondingEvent.put((int) offset, new ImageEvent(EVENT_COMPRESSED_IMAGE)); } private void registerUncompressedStrip(int stripIndex, long offset) { - mCorrespondingEvent.put((int) offset, new ImageEvent(EVENT_UNCOMPRESSED_STRIP, stripIndex)); + correspondingEvent.put((int) offset, new ImageEvent(EVENT_UNCOMPRESSED_STRIP, stripIndex)); } @SuppressLint("DefaultLocale") private ExifTag readTag() throws IOException, ExifInvalidFormatException { - short tagId = mTiffStream.readShort(); - short dataFormat = mTiffStream.readShort(); - long numOfComp = mTiffStream.readUnsignedInt(); + short tagId = tiffStream.readShort(); + short dataFormat = tiffStream.readShort(); + long numOfComp = tiffStream.readUnsignedInt(); if (numOfComp > Integer.MAX_VALUE) { throw new ExifInvalidFormatException("Number of component is larger then Integer.MAX_VALUE"); } // Some invalid image file contains invalid data type. Ignore those tags if (!ExifTag.isValidType(dataFormat)) { LogUtil.i("ExifParser.readTag", "Tag %04x: Invalid data type %d", tagId, dataFormat); - mTiffStream.skip(4); + tiffStream.skip(4); return null; } // TODO(blemmon): handle numOfComp overflow @@ -505,20 +505,20 @@ public class ExifParser { tagId, dataFormat, (int) numOfComp, - mIfdType, + ifdType, ((int) numOfComp) != ExifTag.SIZE_UNDEFINED); int dataSize = tag.getDataSize(); if (dataSize > 4) { - long offset = mTiffStream.readUnsignedInt(); + long offset = tiffStream.readUnsignedInt(); if (offset > Integer.MAX_VALUE) { throw new ExifInvalidFormatException("offset is larger then Integer.MAX_VALUE"); } // Some invalid images put some undefined data before IFD0. // Read the data here. - if ((offset < mIfd0Position) && (dataFormat == ExifTag.TYPE_UNDEFINED)) { + if ((offset < ifd0Position) && (dataFormat == ExifTag.TYPE_UNDEFINED)) { byte[] buf = new byte[(int) numOfComp]; System.arraycopy( - mDataAboveIfd0, (int) offset - DEFAULT_IFD0_OFFSET, buf, 0, (int) numOfComp); + dataAboveIfd0, (int) offset - DEFAULT_IFD0_OFFSET, buf, 0, (int) numOfComp); tag.setValue(buf); } else { tag.setOffset((int) offset); @@ -530,9 +530,9 @@ public class ExifParser { // Read value readFullTagValue(tag); tag.setHasDefinedCount(defCount); - mTiffStream.skip(4 - dataSize); + tiffStream.skip(4 - dataSize); // Set the offset to the position of value. - tag.setOffset(mTiffStream.getReadByteCount() - 4); + tag.setOffset(tiffStream.getReadByteCount() - 4); } return tag; } @@ -569,7 +569,7 @@ public class ExifParser { } else if (tid == TAG_JPEG_INTERCHANGE_FORMAT_LENGTH && checkAllowed(ifd, ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH)) { if (isThumbnailRequested()) { - mJpegSizeTag = tag; + jpegSizeTag = tag; } } else if (tid == TAG_STRIP_OFFSETS && checkAllowed(ifd, ExifInterface.TAG_STRIP_OFFSETS)) { if (isThumbnailRequested()) { @@ -582,14 +582,14 @@ public class ExifParser { } } } else { - mCorrespondingEvent.put(tag.getOffset(), new ExifTagEvent(tag, false)); + correspondingEvent.put(tag.getOffset(), new ExifTagEvent(tag, false)); } } } else if (tid == TAG_STRIP_BYTE_COUNTS && checkAllowed(ifd, ExifInterface.TAG_STRIP_BYTE_COUNTS) && isThumbnailRequested() && tag.hasValue()) { - mStripSizeTag = tag; + stripSizeTag = tag; } } @@ -605,15 +605,15 @@ public class ExifParser { || type == ExifTag.TYPE_UNDEFINED || type == ExifTag.TYPE_UNSIGNED_BYTE) { int size = tag.getComponentCount(); - if (mCorrespondingEvent.size() > 0) { - if (mCorrespondingEvent.firstEntry().getKey() < mTiffStream.getReadByteCount() + size) { - Object event = mCorrespondingEvent.firstEntry().getValue(); + if (correspondingEvent.size() > 0) { + if (correspondingEvent.firstEntry().getKey() < tiffStream.getReadByteCount() + size) { + Object event = correspondingEvent.firstEntry().getValue(); if (event instanceof ImageEvent) { // Tag value overlaps thumbnail, ignore thumbnail. LogUtil.i( "ExifParser.readFullTagValue", "Thumbnail overlaps value for tag: \n" + tag.toString()); - Entry entry = mCorrespondingEvent.pollFirstEntry(); + Entry entry = correspondingEvent.pollFirstEntry(); LogUtil.i("ExifParser.readFullTagValue", "Invalid thumbnail offset: " + entry.getKey()); } else { // Tag value overlaps another shorten count @@ -629,7 +629,7 @@ public class ExifParser { + " overlaps value for tag: \n" + tag.toString()); } - size = mCorrespondingEvent.firstEntry().getKey() - mTiffStream.getReadByteCount(); + size = correspondingEvent.firstEntry().getKey() - tiffStream.getReadByteCount(); LogUtil.i( "ExifParser.readFullTagValue", "Invalid size of tag: \n" + tag.toString() + " setting count to: " + size); @@ -702,16 +702,16 @@ public class ExifParser { } private void parseTiffHeader() throws IOException, ExifInvalidFormatException { - short byteOrder = mTiffStream.readShort(); + short byteOrder = tiffStream.readShort(); if (LITTLE_ENDIAN_TAG == byteOrder) { - mTiffStream.setByteOrder(ByteOrder.LITTLE_ENDIAN); + tiffStream.setByteOrder(ByteOrder.LITTLE_ENDIAN); } else if (BIG_ENDIAN_TAG == byteOrder) { - mTiffStream.setByteOrder(ByteOrder.BIG_ENDIAN); + tiffStream.setByteOrder(ByteOrder.BIG_ENDIAN); } else { throw new ExifInvalidFormatException("Invalid TIFF header"); } - if (mTiffStream.readShort() != TIFF_HEADER_TAIL) { + if (tiffStream.readShort() != TIFF_HEADER_TAIL) { throw new ExifInvalidFormatException("Invalid TIFF header"); } } @@ -736,7 +736,7 @@ public class ExifParser { headerTail = dataStream.readShort(); length -= 6; if (header == EXIF_HEADER && headerTail == EXIF_HEADER_TAIL) { - mApp1End = length; + app1End = length; return true; } } @@ -752,12 +752,12 @@ public class ExifParser { /** Reads bytes from the InputStream. */ protected int read(byte[] buffer, int offset, int length) throws IOException { - return mTiffStream.read(buffer, offset, length); + return tiffStream.read(buffer, offset, length); } /** Equivalent to read(buffer, 0, buffer.length). */ protected int read(byte[] buffer) throws IOException { - return mTiffStream.read(buffer); + return tiffStream.read(buffer); } /** @@ -774,7 +774,7 @@ public class ExifParser { */ private String readString(int n, Charset charset) throws IOException { if (n > 0) { - return mTiffStream.readString(n, charset); + return tiffStream.readString(n, charset); } else { return ""; } @@ -782,7 +782,7 @@ public class ExifParser { /** Reads value of type {@link ExifTag#TYPE_UNSIGNED_SHORT} from the InputStream. */ private int readUnsignedShort() throws IOException { - return mTiffStream.readShort() & 0xffff; + return tiffStream.readShort() & 0xffff; } /** Reads value of type {@link ExifTag#TYPE_UNSIGNED_LONG} from the InputStream. */ @@ -799,7 +799,7 @@ public class ExifParser { /** Reads value of type {@link ExifTag#TYPE_LONG} from the InputStream. */ private int readLong() throws IOException { - return mTiffStream.readInt(); + return tiffStream.readInt(); } /** Reads value of type {@link ExifTag#TYPE_RATIONAL} from the InputStream. */ diff --git a/java/com/android/dialer/callcomposer/camera/exif/ExifTag.java b/java/com/android/dialer/callcomposer/camera/exif/ExifTag.java index 9a03c103c..23948ed62 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/ExifTag.java +++ b/java/com/android/dialer/callcomposer/camera/exif/ExifTag.java @@ -81,19 +81,19 @@ public class ExifTag { static final int SIZE_UNDEFINED = 0; // Exif TagId - private final short mTagId; + private final short tagId; // Exif Tag Type - private final short mDataType; + private final short dataType; // If tag has defined count - private boolean mHasDefinedDefaultComponentCount; + private boolean hasDefinedDefaultComponentCount; // Actual data count in tag (should be number of elements in value array) - private int mComponentCountActual; + private int componentCountActual; // The ifd that this tag should be put in - private int mIfd; + private int ifd; // The value (array of elements of type Tag Type) - private Object mValue; + private Object value; // Value offset in exif header. - private int mOffset; + private int offset; /** Returns true if the given IFD is a valid IFD. */ static boolean isValidIfd(int ifdId) { @@ -118,12 +118,12 @@ public class ExifTag { // Use builtTag in ExifInterface instead of constructor. ExifTag(short tagId, short type, int componentCount, int ifd, boolean hasDefinedComponentCount) { - mTagId = tagId; - mDataType = type; - mComponentCountActual = componentCount; - mHasDefinedDefaultComponentCount = hasDefinedComponentCount; - mIfd = ifd; - mValue = null; + this.tagId = tagId; + dataType = type; + componentCountActual = componentCount; + hasDefinedDefaultComponentCount = hasDefinedComponentCount; + this.ifd = ifd; + value = null; } /** @@ -152,16 +152,16 @@ public class ExifTag { * @see IfdId#TYPE_IFD_INTEROPERABILITY */ int getIfd() { - return mIfd; + return ifd; } void setIfd(int ifdId) { - mIfd = ifdId; + ifd = ifdId; } /** Gets the TID of this tag. */ short getTagId() { - return mTagId; + return tagId; } /** @@ -177,7 +177,7 @@ public class ExifTag { * @see #TYPE_UNSIGNED_SHORT */ short getDataType() { - return mDataType; + return dataType; } /** Gets the total data size in bytes of the value of this tag. */ @@ -189,7 +189,7 @@ public class ExifTag { // TODO(blemmon): fix integer overflows with this int getComponentCount() { - return mComponentCountActual; + return componentCountActual; } /** @@ -197,7 +197,7 @@ public class ExifTag { * value does not match the component count. */ void forceSetComponentCount(int count) { - mComponentCountActual = count; + componentCountActual = count; } /** @@ -205,7 +205,7 @@ public class ExifTag { * that is determined when the tag is written. */ boolean hasValue() { - return mValue != null; + return value != null; } /** @@ -223,14 +223,14 @@ public class ExifTag { if (checkBadComponentCount(value.length)) { return false; } - if (mDataType != TYPE_UNSIGNED_SHORT - && mDataType != TYPE_LONG - && mDataType != TYPE_UNSIGNED_LONG) { + if (dataType != TYPE_UNSIGNED_SHORT + && dataType != TYPE_LONG + && dataType != TYPE_UNSIGNED_LONG) { return false; } - if (mDataType == TYPE_UNSIGNED_SHORT && checkOverflowForUnsignedShort(value)) { + if (dataType == TYPE_UNSIGNED_SHORT && checkOverflowForUnsignedShort(value)) { return false; - } else if (mDataType == TYPE_UNSIGNED_LONG && checkOverflowForUnsignedLong(value)) { + } else if (dataType == TYPE_UNSIGNED_LONG && checkOverflowForUnsignedLong(value)) { return false; } @@ -238,8 +238,8 @@ public class ExifTag { for (int i = 0; i < value.length; i++) { data[i] = value[i]; } - mValue = data; - mComponentCountActual = value.length; + this.value = data; + componentCountActual = value.length; return true; } @@ -254,14 +254,14 @@ public class ExifTag { * */ boolean setValue(long[] value) { - if (checkBadComponentCount(value.length) || mDataType != TYPE_UNSIGNED_LONG) { + if (checkBadComponentCount(value.length) || dataType != TYPE_UNSIGNED_LONG) { return false; } if (checkOverflowForUnsignedLong(value)) { return false; } - mValue = value; - mComponentCountActual = value.length; + this.value = value; + componentCountActual = value.length; return true; } @@ -280,7 +280,7 @@ public class ExifTag { * */ boolean setValue(String value) { - if (mDataType != TYPE_ASCII && mDataType != TYPE_UNDEFINED) { + if (dataType != TYPE_ASCII && dataType != TYPE_UNDEFINED) { return false; } @@ -288,18 +288,18 @@ public class ExifTag { byte[] finalBuf = buf; if (buf.length > 0) { finalBuf = - (buf[buf.length - 1] == 0 || mDataType == TYPE_UNDEFINED) + (buf[buf.length - 1] == 0 || dataType == TYPE_UNDEFINED) ? buf : Arrays.copyOf(buf, buf.length + 1); - } else if (mDataType == TYPE_ASCII && mComponentCountActual == 1) { + } else if (dataType == TYPE_ASCII && componentCountActual == 1) { finalBuf = new byte[] {0}; } int count = finalBuf.length; if (checkBadComponentCount(count)) { return false; } - mComponentCountActual = count; - mValue = finalBuf; + componentCountActual = count; + this.value = finalBuf; return true; } @@ -320,17 +320,17 @@ public class ExifTag { if (checkBadComponentCount(value.length)) { return false; } - if (mDataType != TYPE_UNSIGNED_RATIONAL && mDataType != TYPE_RATIONAL) { + if (dataType != TYPE_UNSIGNED_RATIONAL && dataType != TYPE_RATIONAL) { return false; } - if (mDataType == TYPE_UNSIGNED_RATIONAL && checkOverflowForUnsignedRational(value)) { + if (dataType == TYPE_UNSIGNED_RATIONAL && checkOverflowForUnsignedRational(value)) { return false; - } else if (mDataType == TYPE_RATIONAL && checkOverflowForRational(value)) { + } else if (dataType == TYPE_RATIONAL && checkOverflowForRational(value)) { return false; } - mValue = value; - mComponentCountActual = value.length; + this.value = value; + componentCountActual = value.length; return true; } @@ -348,12 +348,12 @@ public class ExifTag { if (checkBadComponentCount(length)) { return false; } - if (mDataType != TYPE_UNSIGNED_BYTE && mDataType != TYPE_UNDEFINED) { + if (dataType != TYPE_UNSIGNED_BYTE && dataType != TYPE_UNDEFINED) { return false; } - mValue = new byte[length]; - System.arraycopy(value, offset, mValue, 0, length); - mComponentCountActual = length; + this.value = new byte[length]; + System.arraycopy(value, offset, this.value, 0, length); + componentCountActual = length; return true; } @@ -370,10 +370,10 @@ public class ExifTag { * be converted to an array of ints. */ int[] getValueAsInts() { - if (mValue == null) { + if (value == null) { return null; - } else if (mValue instanceof long[]) { - long[] val = (long[]) mValue; + } else if (value instanceof long[]) { + long[] val = (long[]) value; int[] arr = new int[val.length]; for (int i = 0; i < val.length; i++) { arr[i] = (int) val[i]; // Truncates @@ -385,38 +385,38 @@ public class ExifTag { /** Gets the tag's value or null if none exists. */ public Object getValue() { - return mValue; + return value; } /** Gets a string representation of the value. */ private String forceGetValueAsString() { - if (mValue == null) { + if (value == null) { return ""; - } else if (mValue instanceof byte[]) { - if (mDataType == TYPE_ASCII) { - return new String((byte[]) mValue, US_ASCII); + } else if (value instanceof byte[]) { + if (dataType == TYPE_ASCII) { + return new String((byte[]) value, US_ASCII); } else { - return Arrays.toString((byte[]) mValue); + return Arrays.toString((byte[]) value); } - } else if (mValue instanceof long[]) { - if (((long[]) mValue).length == 1) { - return String.valueOf(((long[]) mValue)[0]); + } else if (value instanceof long[]) { + if (((long[]) value).length == 1) { + return String.valueOf(((long[]) value)[0]); } else { - return Arrays.toString((long[]) mValue); + return Arrays.toString((long[]) value); } - } else if (mValue instanceof Object[]) { - if (((Object[]) mValue).length == 1) { - Object val = ((Object[]) mValue)[0]; + } else if (value instanceof Object[]) { + if (((Object[]) value).length == 1) { + Object val = ((Object[]) value)[0]; if (val == null) { return ""; } else { return val.toString(); } } else { - return Arrays.toString((Object[]) mValue); + return Arrays.toString((Object[]) value); } } else { - return mValue.toString(); + return value.toString(); } } @@ -428,13 +428,13 @@ public class ExifTag { * #TYPE_UNSIGNED_RATIONAL}. */ long getValueAt(int index) { - if (mValue instanceof long[]) { - return ((long[]) mValue)[index]; - } else if (mValue instanceof byte[]) { - return ((byte[]) mValue)[index]; + if (value instanceof long[]) { + return ((long[]) value)[index]; + } else if (value instanceof byte[]) { + return ((byte[]) value)[index]; } throw new IllegalArgumentException( - "Cannot get integer value from " + convertTypeToString(mDataType)); + "Cannot get integer value from " + convertTypeToString(dataType)); } /** @@ -443,11 +443,11 @@ public class ExifTag { * @exception IllegalArgumentException If the type is NOT {@link #TYPE_ASCII}. */ protected String getString() { - if (mDataType != TYPE_ASCII) { + if (dataType != TYPE_ASCII) { throw new IllegalArgumentException( - "Cannot get ASCII value from " + convertTypeToString(mDataType)); + "Cannot get ASCII value from " + convertTypeToString(dataType)); } - return new String((byte[]) mValue, US_ASCII); + return new String((byte[]) value, US_ASCII); } /** @@ -455,24 +455,24 @@ public class ExifTag { * the location of the actual value. */ protected int getOffset() { - return mOffset; + return offset; } /** Sets the offset of this tag. */ protected void setOffset(int offset) { - mOffset = offset; + this.offset = offset; } void setHasDefinedCount(boolean d) { - mHasDefinedDefaultComponentCount = d; + hasDefinedDefaultComponentCount = d; } boolean hasDefinedCount() { - return mHasDefinedDefaultComponentCount; + return hasDefinedDefaultComponentCount; } private boolean checkBadComponentCount(int count) { - return mHasDefinedDefaultComponentCount && (mComponentCountActual != count); + return hasDefinedDefaultComponentCount && (componentCountActual != count); } private static String convertTypeToString(short type) { @@ -556,34 +556,34 @@ public class ExifTag { } if (obj instanceof ExifTag) { ExifTag tag = (ExifTag) obj; - if (tag.mTagId != this.mTagId - || tag.mComponentCountActual != this.mComponentCountActual - || tag.mDataType != this.mDataType) { + if (tag.tagId != this.tagId + || tag.componentCountActual != this.componentCountActual + || tag.dataType != this.dataType) { return false; } - if (mValue != null) { - if (tag.mValue == null) { + if (value != null) { + if (tag.value == null) { return false; - } else if (mValue instanceof long[]) { - if (!(tag.mValue instanceof long[])) { + } else if (value instanceof long[]) { + if (!(tag.value instanceof long[])) { return false; } - return Arrays.equals((long[]) mValue, (long[]) tag.mValue); - } else if (mValue instanceof Rational[]) { - if (!(tag.mValue instanceof Rational[])) { + return Arrays.equals((long[]) value, (long[]) tag.value); + } else if (value instanceof Rational[]) { + if (!(tag.value instanceof Rational[])) { return false; } - return Arrays.equals((Rational[]) mValue, (Rational[]) tag.mValue); - } else if (mValue instanceof byte[]) { - if (!(tag.mValue instanceof byte[])) { + return Arrays.equals((Rational[]) value, (Rational[]) tag.value); + } else if (value instanceof byte[]) { + if (!(tag.value instanceof byte[])) { return false; } - return Arrays.equals((byte[]) mValue, (byte[]) tag.mValue); + return Arrays.equals((byte[]) value, (byte[]) tag.value); } else { - return mValue.equals(tag.mValue); + return value.equals(tag.value); } } else { - return tag.mValue == null; + return tag.value == null; } } return false; @@ -592,26 +592,20 @@ public class ExifTag { @Override public int hashCode() { return Objects.hash( - mTagId, - mDataType, - mHasDefinedDefaultComponentCount, - mComponentCountActual, - mIfd, - mValue, - mOffset); + tagId, dataType, hasDefinedDefaultComponentCount, componentCountActual, ifd, value, offset); } @Override public String toString() { - return String.format("tag id: %04X\n", mTagId) + return String.format("tag id: %04X\n", tagId) + "ifd id: " - + mIfd + + ifd + "\ntype: " - + convertTypeToString(mDataType) + + convertTypeToString(dataType) + "\ncount: " - + mComponentCountActual + + componentCountActual + "\noffset: " - + mOffset + + offset + "\nvalue: " + forceGetValueAsString() + "\n"; diff --git a/java/com/android/dialer/callcomposer/camera/exif/IfdData.java b/java/com/android/dialer/callcomposer/camera/exif/IfdData.java index b808defc6..e85919e0a 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/IfdData.java +++ b/java/com/android/dialer/callcomposer/camera/exif/IfdData.java @@ -16,7 +16,7 @@ package com.android.dialer.callcomposer.camera.exif; -import java.util.HashMap; +import android.support.v4.util.ArrayMap; import java.util.Map; import java.util.Objects; @@ -28,9 +28,9 @@ import java.util.Objects; */ class IfdData { - private final int mIfdId; - private final Map mExifTags = new HashMap<>(); - private static final int[] sIfds = { + private final int ifdId; + private final Map exifTags = new ArrayMap<>(); + private static final int[] ifds = { IfdId.TYPE_IFD_0, IfdId.TYPE_IFD_1, IfdId.TYPE_IFD_EXIF, @@ -47,16 +47,16 @@ class IfdData { * @see IfdId#TYPE_IFD_INTEROPERABILITY */ IfdData(int ifdId) { - mIfdId = ifdId; + this.ifdId = ifdId; } static int[] getIfds() { - return sIfds; + return ifds; } /** Get a array the contains all {@link ExifTag} in this IFD. */ private ExifTag[] getAllTags() { - return mExifTags.values().toArray(new ExifTag[mExifTags.size()]); + return exifTags.values().toArray(new ExifTag[exifTags.size()]); } /** @@ -69,23 +69,23 @@ class IfdData { * @see IfdId#TYPE_IFD_INTEROPERABILITY */ protected int getId() { - return mIfdId; + return ifdId; } /** Gets the {@link ExifTag} with given tag id. Return null if there is no such tag. */ protected ExifTag getTag(short tagId) { - return mExifTags.get(tagId); + return exifTags.get(tagId); } /** Adds or replaces a {@link ExifTag}. */ protected ExifTag setTag(ExifTag tag) { - tag.setIfd(mIfdId); - return mExifTags.put(tag.getTagId(), tag); + tag.setIfd(ifdId); + return exifTags.put(tag.getTagId(), tag); } /** Gets the tags count in the IFD. */ private int getTagCount() { - return mExifTags.size(); + return exifTags.size(); } /** @@ -102,13 +102,13 @@ class IfdData { } if (obj instanceof IfdData) { IfdData data = (IfdData) obj; - if (data.getId() == mIfdId && data.getTagCount() == getTagCount()) { + if (data.getId() == ifdId && data.getTagCount() == getTagCount()) { ExifTag[] tags = data.getAllTags(); for (ExifTag tag : tags) { if (ExifInterface.isOffsetTag(tag.getTagId())) { continue; } - ExifTag tag2 = mExifTags.get(tag.getTagId()); + ExifTag tag2 = exifTags.get(tag.getTagId()); if (!tag.equals(tag2)) { return false; } @@ -121,6 +121,6 @@ class IfdData { @Override public int hashCode() { - return Objects.hash(mIfdId, mExifTags); + return Objects.hash(ifdId, exifTags); } } diff --git a/java/com/android/dialer/callcomposer/camera/exif/Rational.java b/java/com/android/dialer/callcomposer/camera/exif/Rational.java index 9afca8449..d07778c31 100644 --- a/java/com/android/dialer/callcomposer/camera/exif/Rational.java +++ b/java/com/android/dialer/callcomposer/camera/exif/Rational.java @@ -24,23 +24,23 @@ import java.util.Objects; */ public class Rational { - private final long mNumerator; - private final long mDenominator; + private final long numerator; + private final long denominator; /** Create a Rational with a given numerator and denominator. */ Rational(long nominator, long denominator) { - mNumerator = nominator; - mDenominator = denominator; + numerator = nominator; + this.denominator = denominator; } /** Gets the numerator of the rational. */ long getNumerator() { - return mNumerator; + return numerator; } /** Gets the denominator of the rational */ long getDenominator() { - return mDenominator; + return denominator; } @Override @@ -53,18 +53,18 @@ public class Rational { } if (obj instanceof Rational) { Rational data = (Rational) obj; - return mNumerator == data.mNumerator && mDenominator == data.mDenominator; + return numerator == data.numerator && denominator == data.denominator; } return false; } @Override public int hashCode() { - return Objects.hash(mNumerator, mDenominator); + return Objects.hash(numerator, denominator); } @Override public String toString() { - return mNumerator + "/" + mDenominator; + return numerator + "/" + denominator; } } diff --git a/java/com/android/dialer/callcomposer/cameraui/CameraMediaChooserView.java b/java/com/android/dialer/callcomposer/cameraui/CameraMediaChooserView.java index 85c64e477..df0e7ad3f 100644 --- a/java/com/android/dialer/callcomposer/cameraui/CameraMediaChooserView.java +++ b/java/com/android/dialer/callcomposer/cameraui/CameraMediaChooserView.java @@ -36,7 +36,7 @@ public class CameraMediaChooserView extends FrameLayout { // True if we have at least queued an update to the view tree to support software rendering // fallback - private boolean mIsSoftwareFallbackActive; + private boolean isSoftwareFallbackActive; public CameraMediaChooserView(final Context context, final AttributeSet attrs) { super(context, attrs); @@ -80,8 +80,8 @@ public class CameraMediaChooserView extends FrameLayout { super.onDraw(canvas); // If the canvas isn't hardware accelerated, we have to replace the HardwareCameraPreview // with a SoftwareCameraPreview which supports software rendering - if (!canvas.isHardwareAccelerated() && !mIsSoftwareFallbackActive) { - mIsSoftwareFallbackActive = true; + if (!canvas.isHardwareAccelerated() && !isSoftwareFallbackActive) { + isSoftwareFallbackActive = true; // Post modifying the tree since we can't modify the view tree during a draw pass post( new Runnable() { diff --git a/java/com/android/dialer/calllogutils/CallTypeHelper.java b/java/com/android/dialer/calllogutils/CallTypeHelper.java index e3c711d99..6feaeb998 100644 --- a/java/com/android/dialer/calllogutils/CallTypeHelper.java +++ b/java/com/android/dialer/calllogutils/CallTypeHelper.java @@ -24,65 +24,65 @@ import com.android.dialer.duo.Duo; public class CallTypeHelper { /** Name used to identify incoming calls. */ - private final CharSequence mIncomingName; + private final CharSequence incomingName; /** Name used to identify incoming calls which were transferred to another device. */ - private final CharSequence mIncomingPulledName; + private final CharSequence incomingPulledName; /** Name used to identify outgoing calls. */ - private final CharSequence mOutgoingName; + private final CharSequence outgoingName; /** Name used to identify outgoing calls which were transferred to another device. */ - private final CharSequence mOutgoingPulledName; + private final CharSequence outgoingPulledName; /** Name used to identify missed calls. */ - private final CharSequence mMissedName; + private final CharSequence missedName; /** Name used to identify incoming video calls. */ - private final CharSequence mIncomingVideoName; + private final CharSequence incomingVideoName; /** Name used to identify incoming video calls which were transferred to another device. */ - private final CharSequence mIncomingVideoPulledName; + private final CharSequence incomingVideoPulledName; /** Name used to identify outgoing video calls. */ - private final CharSequence mOutgoingVideoName; + private final CharSequence outgoingVideoName; /** Name used to identify outgoing video calls which were transferred to another device. */ - private final CharSequence mOutgoingVideoPulledName; + private final CharSequence outgoingVideoPulledName; /** Name used to identify missed video calls. */ - private final CharSequence mMissedVideoName; + private final CharSequence missedVideoName; /** Name used to identify voicemail calls. */ - private final CharSequence mVoicemailName; + private final CharSequence voicemailName; /** Name used to identify rejected calls. */ - private final CharSequence mRejectedName; + private final CharSequence rejectedName; /** Name used to identify blocked calls. */ - private final CharSequence mBlockedName; + private final CharSequence blockedName; /** Name used to identify calls which were answered on another device. */ - private final CharSequence mAnsweredElsewhereName; + private final CharSequence answeredElsewhereName; /** Name used to identify incoming Duo calls. */ - private final CharSequence mIncomingDuoCall; + private final CharSequence incomingDuoCall; /** Name used to identify outgoing Duo calls. */ - private final CharSequence mOutgoingDuoCall; + private final CharSequence outgoingDuoCall; public CallTypeHelper(Resources resources, Duo duo) { // Cache these values so that we do not need to look them up each time. - mIncomingName = resources.getString(R.string.type_incoming); - mIncomingPulledName = resources.getString(R.string.type_incoming_pulled); - mOutgoingName = resources.getString(R.string.type_outgoing); - mOutgoingPulledName = resources.getString(R.string.type_outgoing_pulled); - mMissedName = resources.getString(R.string.type_missed); - mIncomingVideoName = resources.getString(R.string.type_incoming_video); - mIncomingVideoPulledName = resources.getString(R.string.type_incoming_video_pulled); - mOutgoingVideoName = resources.getString(R.string.type_outgoing_video); - mOutgoingVideoPulledName = resources.getString(R.string.type_outgoing_video_pulled); - mMissedVideoName = resources.getString(R.string.type_missed_video); - mVoicemailName = resources.getString(R.string.type_voicemail); - mRejectedName = resources.getString(R.string.type_rejected); - mBlockedName = resources.getString(R.string.type_blocked); - mAnsweredElsewhereName = resources.getString(R.string.type_answered_elsewhere); + incomingName = resources.getString(R.string.type_incoming); + incomingPulledName = resources.getString(R.string.type_incoming_pulled); + outgoingName = resources.getString(R.string.type_outgoing); + outgoingPulledName = resources.getString(R.string.type_outgoing_pulled); + missedName = resources.getString(R.string.type_missed); + incomingVideoName = resources.getString(R.string.type_incoming_video); + incomingVideoPulledName = resources.getString(R.string.type_incoming_video_pulled); + outgoingVideoName = resources.getString(R.string.type_outgoing_video); + outgoingVideoPulledName = resources.getString(R.string.type_outgoing_video_pulled); + missedVideoName = resources.getString(R.string.type_missed_video); + voicemailName = resources.getString(R.string.type_voicemail); + rejectedName = resources.getString(R.string.type_rejected); + blockedName = resources.getString(R.string.type_blocked); + answeredElsewhereName = resources.getString(R.string.type_answered_elsewhere); if (duo.getIncomingCallTypeText() != -1) { - mIncomingDuoCall = resources.getString(duo.getIncomingCallTypeText()); + incomingDuoCall = resources.getString(duo.getIncomingCallTypeText()); } else { - mIncomingDuoCall = mIncomingVideoName; + incomingDuoCall = incomingVideoName; } if (duo.getOutgoingCallTypeText() != -1) { - mOutgoingDuoCall = resources.getString(duo.getOutgoingCallTypeText()); + outgoingDuoCall = resources.getString(duo.getOutgoingCallTypeText()); } else { - mOutgoingDuoCall = mOutgoingVideoName; + outgoingDuoCall = outgoingVideoName; } } @@ -100,60 +100,60 @@ public class CallTypeHelper { case AppCompatConstants.CALLS_INCOMING_TYPE: if (isVideoCall) { if (isPulledCall) { - return mIncomingVideoPulledName; + return incomingVideoPulledName; } else { if (isDuoCall) { - return mIncomingDuoCall; + return incomingDuoCall; } - return mIncomingVideoName; + return incomingVideoName; } } else { if (isPulledCall) { - return mIncomingPulledName; + return incomingPulledName; } else { - return mIncomingName; + return incomingName; } } case AppCompatConstants.CALLS_OUTGOING_TYPE: if (isVideoCall) { if (isPulledCall) { - return mOutgoingVideoPulledName; + return outgoingVideoPulledName; } else { if (isDuoCall) { - return mOutgoingDuoCall; + return outgoingDuoCall; } - return mOutgoingVideoName; + return outgoingVideoName; } } else { if (isPulledCall) { - return mOutgoingPulledName; + return outgoingPulledName; } else { - return mOutgoingName; + return outgoingName; } } case AppCompatConstants.CALLS_MISSED_TYPE: if (isVideoCall) { - return mMissedVideoName; + return missedVideoName; } else { - return mMissedName; + return missedName; } case AppCompatConstants.CALLS_VOICEMAIL_TYPE: - return mVoicemailName; + return voicemailName; case AppCompatConstants.CALLS_REJECTED_TYPE: - return mRejectedName; + return rejectedName; case AppCompatConstants.CALLS_BLOCKED_TYPE: - return mBlockedName; + return blockedName; case AppCompatConstants.CALLS_ANSWERED_EXTERNALLY_TYPE: - return mAnsweredElsewhereName; + return answeredElsewhereName; default: - return mMissedName; + return missedName; } } } diff --git a/java/com/android/dialer/calllogutils/CallTypeIconsView.java b/java/com/android/dialer/calllogutils/CallTypeIconsView.java index 0c28a9728..c7840c5ca 100644 --- a/java/com/android/dialer/calllogutils/CallTypeIconsView.java +++ b/java/com/android/dialer/calllogutils/CallTypeIconsView.java @@ -43,14 +43,14 @@ public class CallTypeIconsView extends View { private final boolean useLargeIcons; - private static Resources sResources; - private static Resources sLargeResouces; - private List mCallTypes = new ArrayList<>(3); - private boolean mShowVideo; - private boolean mShowHd; - private boolean mShowWifi; - private int mWidth; - private int mHeight; + private static Resources resources; + private static Resources largeResouces; + private List callTypes = new ArrayList<>(3); + private boolean showVideo; + private boolean showHd; + private boolean showWifi; + private int width; + private int height; public CallTypeIconsView(Context context) { this(context, null); @@ -62,27 +62,27 @@ public class CallTypeIconsView extends View { context.getTheme().obtainStyledAttributes(attrs, R.styleable.CallTypeIconsView, 0, 0); useLargeIcons = typedArray.getBoolean(R.styleable.CallTypeIconsView_useLargeIcons, false); typedArray.recycle(); - if (sResources == null) { - sResources = new Resources(context, false); + if (resources == null) { + resources = new Resources(context, false); } - if (sLargeResouces == null && useLargeIcons) { - sLargeResouces = new Resources(context, true); + if (largeResouces == null && useLargeIcons) { + largeResouces = new Resources(context, true); } } public void clear() { - mCallTypes.clear(); - mWidth = 0; - mHeight = 0; + callTypes.clear(); + width = 0; + height = 0; invalidate(); } public void add(int callType) { - mCallTypes.add(callType); + callTypes.add(callType); final Drawable drawable = getCallTypeDrawable(callType); - mWidth += drawable.getIntrinsicWidth() + sResources.iconMargin; - mHeight = Math.max(mHeight, drawable.getIntrinsicWidth()); + width += drawable.getIntrinsicWidth() + resources.iconMargin; + height = Math.max(height, drawable.getIntrinsicWidth()); invalidate(); } @@ -92,10 +92,10 @@ public class CallTypeIconsView extends View { * @param showVideo True where the video icon should be shown. */ public void setShowVideo(boolean showVideo) { - mShowVideo = showVideo; + this.showVideo = showVideo; if (showVideo) { - mWidth += sResources.videoCall.getIntrinsicWidth() + sResources.iconMargin; - mHeight = Math.max(mHeight, sResources.videoCall.getIntrinsicHeight()); + width += resources.videoCall.getIntrinsicWidth() + resources.iconMargin; + height = Math.max(height, resources.videoCall.getIntrinsicHeight()); invalidate(); } } @@ -106,42 +106,42 @@ public class CallTypeIconsView extends View { * @return True if the video icon should be shown. */ public boolean isVideoShown() { - return mShowVideo; + return showVideo; } public void setShowHd(boolean showHd) { - mShowHd = showHd; + this.showHd = showHd; if (showHd) { - mWidth += sResources.hdCall.getIntrinsicWidth() + sResources.iconMargin; - mHeight = Math.max(mHeight, sResources.hdCall.getIntrinsicHeight()); + width += resources.hdCall.getIntrinsicWidth() + resources.iconMargin; + height = Math.max(height, resources.hdCall.getIntrinsicHeight()); invalidate(); } } @VisibleForTesting public boolean isHdShown() { - return mShowHd; + return showHd; } public void setShowWifi(boolean showWifi) { - mShowWifi = showWifi; + this.showWifi = showWifi; if (showWifi) { - mWidth += sResources.wifiCall.getIntrinsicWidth() + sResources.iconMargin; - mHeight = Math.max(mHeight, sResources.wifiCall.getIntrinsicHeight()); + width += resources.wifiCall.getIntrinsicWidth() + resources.iconMargin; + height = Math.max(height, resources.wifiCall.getIntrinsicHeight()); invalidate(); } } public int getCount() { - return mCallTypes.size(); + return callTypes.size(); } public int getCallType(int index) { - return mCallTypes.get(index); + return callTypes.get(index); } private Drawable getCallTypeDrawable(int callType) { - Resources resources = useLargeIcons ? sLargeResouces : sResources; + Resources resources = useLargeIcons ? largeResouces : CallTypeIconsView.resources; switch (callType) { case AppCompatConstants.CALLS_INCOMING_TYPE: case AppCompatConstants.CALLS_ANSWERED_EXTERNALLY_TYPE: @@ -165,17 +165,17 @@ public class CallTypeIconsView extends View { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { - setMeasuredDimension(mWidth, mHeight); + setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { - Resources resources = useLargeIcons ? sLargeResouces : sResources; + Resources resources = useLargeIcons ? largeResouces : CallTypeIconsView.resources; int left = 0; // If we are using large icons, we should only show one icon (video, hd or call type) with // priority give to HD or Video. So we skip the call type icon if we plan to show them. - if (!useLargeIcons || !(mShowHd || mShowVideo || mShowWifi)) { - for (Integer callType : mCallTypes) { + if (!useLargeIcons || !(showHd || showVideo || showWifi)) { + for (Integer callType : callTypes) { final Drawable drawable = getCallTypeDrawable(callType); final int right = left + drawable.getIntrinsicWidth(); drawable.setBounds(left, 0, right, drawable.getIntrinsicHeight()); @@ -185,15 +185,15 @@ public class CallTypeIconsView extends View { } // If showing the video call icon, draw it scaled appropriately. - if (mShowVideo) { + if (showVideo) { left = addDrawable(canvas, resources.videoCall, left) + resources.iconMargin; } // If showing HD call icon, draw it scaled appropriately. - if (mShowHd) { + if (showHd) { left = addDrawable(canvas, resources.hdCall, left) + resources.iconMargin; } // If showing HD call icon, draw it scaled appropriately. - if (mShowWifi) { + if (showWifi) { left = addDrawable(canvas, resources.wifiCall, left) + resources.iconMargin; } } diff --git a/java/com/android/dialer/common/concurrent/AsyncTaskExecutors.java b/java/com/android/dialer/common/concurrent/AsyncTaskExecutors.java index a25e9fbf5..5beae4de8 100644 --- a/java/com/android/dialer/common/concurrent/AsyncTaskExecutors.java +++ b/java/com/android/dialer/common/concurrent/AsyncTaskExecutors.java @@ -35,15 +35,15 @@ public final class AsyncTaskExecutors { * A single instance of the {@link AsyncTaskExecutorFactory}, to which we delegate if it is * non-null, for injecting when testing. */ - private static AsyncTaskExecutorFactory mInjectedAsyncTaskExecutorFactory = null; + private static AsyncTaskExecutorFactory injectedAsyncTaskExecutorFactory = null; /** * Creates an AsyncTaskExecutor that submits tasks to run with {@link AsyncTask#SERIAL_EXECUTOR}. */ public static AsyncTaskExecutor createAsyncTaskExecutor() { synchronized (AsyncTaskExecutors.class) { - if (mInjectedAsyncTaskExecutorFactory != null) { - return mInjectedAsyncTaskExecutorFactory.createAsyncTaskExeuctor(); + if (injectedAsyncTaskExecutorFactory != null) { + return injectedAsyncTaskExecutorFactory.createAsyncTaskExeuctor(); } return new SimpleAsyncTaskExecutor(AsyncTask.SERIAL_EXECUTOR); } @@ -55,8 +55,8 @@ public final class AsyncTaskExecutors { */ public static AsyncTaskExecutor createThreadPoolExecutor() { synchronized (AsyncTaskExecutors.class) { - if (mInjectedAsyncTaskExecutorFactory != null) { - return mInjectedAsyncTaskExecutorFactory.createAsyncTaskExeuctor(); + if (injectedAsyncTaskExecutorFactory != null) { + return injectedAsyncTaskExecutorFactory.createAsyncTaskExeuctor(); } return new SimpleAsyncTaskExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -64,7 +64,7 @@ public final class AsyncTaskExecutors { public static void setFactoryForTest(AsyncTaskExecutorFactory factory) { synchronized (AsyncTaskExecutors.class) { - mInjectedAsyncTaskExecutorFactory = factory; + injectedAsyncTaskExecutorFactory = factory; } } @@ -76,17 +76,17 @@ public final class AsyncTaskExecutors { static class SimpleAsyncTaskExecutor implements AsyncTaskExecutor { - private final Executor mExecutor; + private final Executor executor; public SimpleAsyncTaskExecutor(Executor executor) { - mExecutor = executor; + this.executor = executor; } @Override @MainThread public AsyncTask submit(Object identifer, AsyncTask task, T... params) { Assert.isMainThread(); - return task.executeOnExecutor(mExecutor, params); + return task.executeOnExecutor(executor, params); } } } diff --git a/java/com/android/dialer/compat/PathInterpolatorCompat.java b/java/com/android/dialer/compat/PathInterpolatorCompat.java index 7139bc4af..d0d410d7b 100644 --- a/java/com/android/dialer/compat/PathInterpolatorCompat.java +++ b/java/com/android/dialer/compat/PathInterpolatorCompat.java @@ -37,8 +37,8 @@ public class PathInterpolatorCompat { /** Governs the accuracy of the approximation of the {@link Path}. */ private static final float PRECISION = 0.002f; - private final float[] mX; - private final float[] mY; + private final float[] x; + private final float[] y; public PathInterpolatorBase(Path path) { final PathMeasure pathMeasure = new PathMeasure(path, false /* forceClosed */); @@ -46,16 +46,16 @@ public class PathInterpolatorCompat { final float pathLength = pathMeasure.getLength(); final int numPoints = (int) (pathLength / PRECISION) + 1; - mX = new float[numPoints]; - mY = new float[numPoints]; + x = new float[numPoints]; + y = new float[numPoints]; final float[] position = new float[2]; for (int i = 0; i < numPoints; ++i) { final float distance = (i * pathLength) / (numPoints - 1); pathMeasure.getPosTan(distance, position, null /* tangent */); - mX[i] = position[0]; - mY[i] = position[1]; + x[i] = position[0]; + y[i] = position[1]; } } @@ -93,26 +93,26 @@ public class PathInterpolatorCompat { // Do a binary search for the correct x to interpolate between. int startIndex = 0; - int endIndex = mX.length - 1; + int endIndex = x.length - 1; while (endIndex - startIndex > 1) { int midIndex = (startIndex + endIndex) / 2; - if (t < mX[midIndex]) { + if (t < x[midIndex]) { endIndex = midIndex; } else { startIndex = midIndex; } } - final float xRange = mX[endIndex] - mX[startIndex]; + final float xRange = x[endIndex] - x[startIndex]; if (xRange == 0) { - return mY[startIndex]; + return y[startIndex]; } - final float tInRange = t - mX[startIndex]; + final float tInRange = t - x[startIndex]; final float fraction = tInRange / xRange; - final float startY = mY[startIndex]; - final float endY = mY[endIndex]; + final float startY = y[startIndex]; + final float endY = y[endIndex]; return startY + (fraction * (endY - startY)); } diff --git a/java/com/android/dialer/contactphoto/ContactPhotoManager.java b/java/com/android/dialer/contactphoto/ContactPhotoManager.java index 459837936..353c1ee33 100644 --- a/java/com/android/dialer/contactphoto/ContactPhotoManager.java +++ b/java/com/android/dialer/contactphoto/ContactPhotoManager.java @@ -57,7 +57,7 @@ public abstract class ContactPhotoManager implements ComponentCallbacks2 { private static final String DEFAULT_IMAGE_URI_SCHEME = "defaultimage"; private static final Uri DEFAULT_IMAGE_URI = Uri.parse(DEFAULT_IMAGE_URI_SCHEME + "://"); public static final DefaultImageProvider DEFAULT_AVATAR = new LetterTileDefaultImageProvider(); - private static ContactPhotoManager sInstance; + private static ContactPhotoManager instance; /** * Given a {@link DefaultImageRequest}, returns an Uri that can be used to request a letter tile @@ -179,15 +179,15 @@ public abstract class ContactPhotoManager implements ComponentCallbacks2 { } public static ContactPhotoManager getInstance(Context context) { - if (sInstance == null) { + if (instance == null) { Context applicationContext = context.getApplicationContext(); - sInstance = createContactPhotoManager(applicationContext); - applicationContext.registerComponentCallbacks(sInstance); + instance = createContactPhotoManager(applicationContext); + applicationContext.registerComponentCallbacks(instance); if (PermissionsUtil.hasContactsReadPermissions(context)) { - sInstance.preloadPhotosInBackground(); + instance.preloadPhotosInBackground(); } } - return sInstance; + return instance; } public static synchronized ContactPhotoManager createContactPhotoManager(Context context) { @@ -196,7 +196,7 @@ public abstract class ContactPhotoManager implements ComponentCallbacks2 { @VisibleForTesting public static void injectContactPhotoManagerForTesting(ContactPhotoManager photoManager) { - sInstance = photoManager; + instance = photoManager; } protected boolean isDefaultImageUri(Uri uri) { diff --git a/java/com/android/dialer/contactphoto/ContactPhotoManagerImpl.java b/java/com/android/dialer/contactphoto/ContactPhotoManagerImpl.java index 5dbdf5e48..edeeb78d6 100644 --- a/java/com/android/dialer/contactphoto/ContactPhotoManagerImpl.java +++ b/java/com/android/dialer/contactphoto/ContactPhotoManagerImpl.java @@ -95,57 +95,57 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { * Dummy object used to indicate that a bitmap for a given key could not be stored in the cache. */ private static final BitmapHolder BITMAP_UNAVAILABLE; - /** Cache size for {@link #mBitmapHolderCache} for devices with "large" RAM. */ + /** Cache size for {@link #bitmapHolderCache} for devices with "large" RAM. */ private static final int HOLDER_CACHE_SIZE = 2000000; - /** Cache size for {@link #mBitmapCache} for devices with "large" RAM. */ + /** Cache size for {@link #bitmapCache} for devices with "large" RAM. */ private static final int BITMAP_CACHE_SIZE = 36864 * 48; // 1728K /** Height/width of a thumbnail image */ - private static int mThumbnailSize; + private static int thumbnailSize; static { BITMAP_UNAVAILABLE = new BitmapHolder(new byte[0], 0); BITMAP_UNAVAILABLE.bitmapRef = new SoftReference(null); } - private final Context mContext; + private final Context context; /** * An LRU cache for bitmap holders. The cache contains bytes for photos just as they come from the * database. Each holder has a soft reference to the actual bitmap. */ - private final LruCache mBitmapHolderCache; + private final LruCache bitmapHolderCache; /** Cache size threshold at which bitmaps will not be preloaded. */ - private final int mBitmapHolderCacheRedZoneBytes; + private final int bitmapHolderCacheRedZoneBytes; /** * Level 2 LRU cache for bitmaps. This is a smaller cache that holds the most recently used * bitmaps to save time on decoding them from bytes (the bytes are stored in {@link - * #mBitmapHolderCache}. + * #bitmapHolderCache}. */ - private final LruCache mBitmapCache; + private final LruCache bitmapCache; /** * A map from ImageView to the corresponding photo ID or uri, encapsulated in a request. The * request may swapped out before the photo loading request is started. */ - private final ConcurrentHashMap mPendingRequests = + private final ConcurrentHashMap pendingRequests = new ConcurrentHashMap(); /** Handler for messages sent to the UI thread. */ - private final Handler mMainThreadHandler = new Handler(this); + private final Handler mainThreadHandler = new Handler(this); /** For debug: How many times we had to reload cached photo for a stale entry */ - private final AtomicInteger mStaleCacheOverwrite = new AtomicInteger(); + private final AtomicInteger staleCacheOverwrite = new AtomicInteger(); /** For debug: How many times we had to reload cached photo for a fresh entry. Should be 0. */ - private final AtomicInteger mFreshCacheOverwrite = new AtomicInteger(); - /** {@code true} if ALL entries in {@link #mBitmapHolderCache} are NOT fresh. */ - private volatile boolean mBitmapHolderCacheAllUnfresh = true; + private final AtomicInteger freshCacheOverwrite = new AtomicInteger(); + /** {@code true} if ALL entries in {@link #bitmapHolderCache} are NOT fresh. */ + private volatile boolean bitmapHolderCacheAllUnfresh = true; /** Thread responsible for loading photos from the database. Created upon the first request. */ - private LoaderThread mLoaderThread; + private LoaderThread loaderThread; /** A gate to make sure we only send one instance of MESSAGE_PHOTOS_NEEDED at a time. */ - private boolean mLoadingRequested; + private boolean loadingRequested; /** Flag indicating if the image loading is paused. */ - private boolean mPaused; + private boolean paused; /** The user agent string to use when loading URI based photos. */ - private String mUserAgent; + private String userAgent; public ContactPhotoManagerImpl(Context context) { - mContext = context; + this.context = context; final ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)); @@ -153,7 +153,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { final float cacheSizeAdjustment = (am.isLowRamDevice()) ? 0.5f : 1.0f; final int bitmapCacheSize = (int) (cacheSizeAdjustment * BITMAP_CACHE_SIZE); - mBitmapCache = + bitmapCache = new LruCache(bitmapCacheSize) { @Override protected int sizeOf(Object key, Bitmap value) { @@ -169,7 +169,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } }; final int holderCacheSize = (int) (cacheSizeAdjustment * HOLDER_CACHE_SIZE); - mBitmapHolderCache = + bitmapHolderCache = new LruCache(holderCacheSize) { @Override protected int sizeOf(Object key, BitmapHolder value) { @@ -184,22 +184,22 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } } }; - mBitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75); + bitmapHolderCacheRedZoneBytes = (int) (holderCacheSize * 0.75); LogUtil.i( "ContactPhotoManagerImpl.ContactPhotoManagerImpl", "cache adj: " + cacheSizeAdjustment); if (DEBUG) { LogUtil.d( "ContactPhotoManagerImpl.ContactPhotoManagerImpl", - "Cache size: " + btk(mBitmapHolderCache.maxSize()) + " + " + btk(mBitmapCache.maxSize())); + "Cache size: " + btk(bitmapHolderCache.maxSize()) + " + " + btk(bitmapCache.maxSize())); } - mThumbnailSize = + thumbnailSize = context.getResources().getDimensionPixelSize(R.dimen.contact_browser_list_item_photo_size); // Get a user agent string to use for URI photo requests. - mUserAgent = Constants.get().getUserAgent(context); - if (mUserAgent == null) { - mUserAgent = ""; + userAgent = Constants.get().getUserAgent(context); + if (userAgent == null) { + userAgent = ""; } } @@ -221,7 +221,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { /** * If necessary, decodes bytes stored in the holder to Bitmap. As long as the bitmap is held - * either by {@link #mBitmapCache} or by a soft reference in the holder, it will not be necessary + * either by {@link #bitmapCache} or by a soft reference in the holder, it will not be necessary * to decode the bitmap. */ private static void inflateBitmap(BitmapHolder holder, int requestedExtent) { @@ -256,7 +256,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { // The smaller dimension of a scaled bitmap can range from anywhere from 0 to just // below twice the length of a thumbnail image due to the way we calculate the optimal // sample size. - if (height != width && Math.min(height, width) <= mThumbnailSize * 2) { + if (height != width && Math.min(height, width) <= thumbnailSize * 2) { final int dimension = Math.min(height, width); bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension); } @@ -306,7 +306,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { int rawBytes = 0; int bitmapBytes = 0; int numBitmaps = 0; - for (BitmapHolder h : mBitmapHolderCache.snapshot().values()) { + for (BitmapHolder h : bitmapHolderCache.snapshot().values()) { numHolders++; if (h.bytes != null) { rawBytes += h.bytes.length; @@ -336,17 +336,17 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { LogUtil.d( "ContactPhotoManagerImpl.dumpStats", "L1 Stats: " - + mBitmapHolderCache.toString() + + bitmapHolderCache.toString() + ", overwrite: fresh=" - + mFreshCacheOverwrite.get() + + freshCacheOverwrite.get() + " stale=" - + mStaleCacheOverwrite.get()); + + staleCacheOverwrite.get()); } { int numBitmaps = 0; int bitmapBytes = 0; - for (Bitmap b : mBitmapCache.snapshot().values()) { + for (Bitmap b : bitmapCache.snapshot().values()) { numBitmaps++; bitmapBytes += b.getByteCount(); } @@ -377,7 +377,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { @Override public void preloadPhotosInBackground() { ensureLoaderThread(); - mLoaderThread.requestPreloading(); + loaderThread.requestPreloading(); } @Override @@ -391,7 +391,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { if (photoId == 0) { // No photo is needed defaultProvider.applyDefaultImage(view, -1, darkTheme, defaultImageRequest); - mPendingRequests.remove(view); + pendingRequests.remove(view); } else { if (DEBUG) { LogUtil.d("ContactPhotoManagerImpl.loadThumbnail", "loadPhoto request: " + photoId); @@ -413,7 +413,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { if (photoUri == null) { // No photo is needed defaultProvider.applyDefaultImage(view, requestedExtent, darkTheme, defaultImageRequest); - mPendingRequests.remove(view); + pendingRequests.remove(view); } else { if (DEBUG) { LogUtil.d("ContactPhotoManagerImpl.loadPhoto", "loadPhoto request: " + photoUri); @@ -445,10 +445,10 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { private void loadPhotoByIdOrUri(ImageView view, Request request) { boolean loaded = loadCachedPhoto(view, request, false); if (loaded) { - mPendingRequests.remove(view); + pendingRequests.remove(view); } else { - mPendingRequests.put(view, request); - if (!mPaused) { + pendingRequests.put(view, request); + if (!paused) { // Send a request to start loading photos requestLoading(); } @@ -458,7 +458,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { @Override public void removePhoto(ImageView view) { view.setImageDrawable(null); - mPendingRequests.remove(view); + pendingRequests.remove(view); } /** @@ -468,10 +468,10 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { @Override public void cancelPendingRequests(View fragmentRootView) { if (fragmentRootView == null) { - mPendingRequests.clear(); + pendingRequests.clear(); return; } - final Iterator> iterator = mPendingRequests.entrySet().iterator(); + final Iterator> iterator = pendingRequests.entrySet().iterator(); while (iterator.hasNext()) { final ImageView imageView = iterator.next().getKey(); // If an ImageView is orphaned (currently scrap) or a child of fragmentRootView, then @@ -484,7 +484,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { @Override public void refreshCache() { - if (mBitmapHolderCacheAllUnfresh) { + if (bitmapHolderCacheAllUnfresh) { if (DEBUG) { LogUtil.d("ContactPhotoManagerImpl.refreshCache", "refreshCache -- no fresh entries."); } @@ -493,8 +493,8 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { if (DEBUG) { LogUtil.d("ContactPhotoManagerImpl.refreshCache", "refreshCache"); } - mBitmapHolderCacheAllUnfresh = true; - for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) { + bitmapHolderCacheAllUnfresh = true; + for (BitmapHolder holder : bitmapHolderCache.snapshot().values()) { if (holder != BITMAP_UNAVAILABLE) { holder.fresh = false; } @@ -508,21 +508,21 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { */ @UiThread private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) { - BitmapHolder holder = mBitmapHolderCache.get(request.getKey()); + BitmapHolder holder = bitmapHolderCache.get(request.getKey()); if (holder == null) { // The bitmap has not been loaded ==> show default avatar - request.applyDefaultImage(view, request.mIsCircular); + request.applyDefaultImage(view, request.isCircular); return false; } if (holder.bytes == null) { - request.applyDefaultImage(view, request.mIsCircular); + request.applyDefaultImage(view, request.isCircular); return holder.fresh; } Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get(); if (cachedBitmap == null) { - request.applyDefaultImage(view, request.mIsCircular); + request.applyDefaultImage(view, request.isCircular); return false; } @@ -538,18 +538,18 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } else { layers[0] = previousDrawable; } - layers[1] = getDrawableForBitmap(mContext.getResources(), cachedBitmap, request); + layers[1] = getDrawableForBitmap(context.getResources(), cachedBitmap, request); TransitionDrawable drawable = new TransitionDrawable(layers); view.setImageDrawable(drawable); drawable.startTransition(FADE_TRANSITION_DURATION); } else { - view.setImageDrawable(getDrawableForBitmap(mContext.getResources(), cachedBitmap, request)); + view.setImageDrawable(getDrawableForBitmap(context.getResources(), cachedBitmap, request)); } // Put the bitmap in the LRU cache. But only do this for images that are small enough // (we require that at least six of those can be cached at the same time) - if (cachedBitmap.getByteCount() < mBitmapCache.maxSize() / 6) { - mBitmapCache.put(request.getKey(), cachedBitmap); + if (cachedBitmap.getByteCount() < bitmapCache.maxSize() / 6) { + bitmapCache.put(request.getKey(), cachedBitmap); } // Soften the reference @@ -563,7 +563,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { * specified request. */ private Drawable getDrawableForBitmap(Resources resources, Bitmap bitmap, Request request) { - if (request.mIsCircular) { + if (request.isCircular) { final RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(resources, bitmap); drawable.setAntiAlias(true); drawable.setCornerRadius(drawable.getIntrinsicHeight() / 2); @@ -577,23 +577,23 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { if (DEBUG) { LogUtil.d("ContactPhotoManagerImpl.clear", "clear"); } - mPendingRequests.clear(); - mBitmapHolderCache.evictAll(); - mBitmapCache.evictAll(); + pendingRequests.clear(); + bitmapHolderCache.evictAll(); + bitmapCache.evictAll(); } @Override public void pause() { - mPaused = true; + paused = true; } @Override public void resume() { - mPaused = false; + paused = false; if (DEBUG) { dumpStats(); } - if (!mPendingRequests.isEmpty()) { + if (!pendingRequests.isEmpty()) { requestLoading(); } } @@ -604,9 +604,9 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { * photos before any of those requests are executed. This allows us to load images in bulk. */ private void requestLoading() { - if (!mLoadingRequested) { - mLoadingRequested = true; - mMainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING); + if (!loadingRequested) { + loadingRequested = true; + mainThreadHandler.sendEmptyMessage(MESSAGE_REQUEST_LOADING); } } @@ -616,17 +616,17 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { switch (msg.what) { case MESSAGE_REQUEST_LOADING: { - mLoadingRequested = false; - if (!mPaused) { + loadingRequested = false; + if (!paused) { ensureLoaderThread(); - mLoaderThread.requestLoading(); + loaderThread.requestLoading(); } return true; } case MESSAGE_PHOTOS_LOADED: { - if (!mPaused) { + if (!paused) { processLoadedImages(); } if (DEBUG) { @@ -640,9 +640,9 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } public void ensureLoaderThread() { - if (mLoaderThread == null) { - mLoaderThread = new LoaderThread(mContext.getContentResolver()); - mLoaderThread.start(); + if (loaderThread == null) { + loaderThread = new LoaderThread(context.getContentResolver()); + loaderThread.start(); } } @@ -651,7 +651,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { * haven't been loaded, sends another request for image loading. */ private void processLoadedImages() { - final Iterator> iterator = mPendingRequests.entrySet().iterator(); + final Iterator> iterator = pendingRequests.entrySet().iterator(); while (iterator.hasNext()) { final Entry entry = iterator.next(); // TODO: Temporarily disable contact photo fading in, until issues with @@ -664,17 +664,17 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { softenCache(); - if (!mPendingRequests.isEmpty()) { + if (!pendingRequests.isEmpty()) { requestLoading(); } } /** * Removes strong references to loaded bitmaps to allow them to be garbage collected if needed. - * Some of the bitmaps will still be retained by {@link #mBitmapCache}. + * Some of the bitmaps will still be retained by {@link #bitmapCache}. */ private void softenCache() { - for (BitmapHolder holder : mBitmapHolderCache.snapshot().values()) { + for (BitmapHolder holder : bitmapHolderCache.snapshot().values()) { holder.bitmap = null; } } @@ -682,15 +682,15 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { /** Stores the supplied bitmap in cache. */ private void cacheBitmap(Object key, byte[] bytes, boolean preloading, int requestedExtent) { if (DEBUG) { - BitmapHolder prev = mBitmapHolderCache.get(key); + BitmapHolder prev = bitmapHolderCache.get(key); if (prev != null && prev.bytes != null) { LogUtil.d( "ContactPhotoManagerImpl.cacheBitmap", "overwriting cache: key=" + key + (prev.fresh ? " FRESH" : " stale")); if (prev.fresh) { - mFreshCacheOverwrite.incrementAndGet(); + freshCacheOverwrite.incrementAndGet(); } else { - mStaleCacheOverwrite.incrementAndGet(); + staleCacheOverwrite.incrementAndGet(); } } LogUtil.d( @@ -707,16 +707,16 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } if (bytes != null) { - mBitmapHolderCache.put(key, holder); - if (mBitmapHolderCache.get(key) != holder) { + bitmapHolderCache.put(key, holder); + if (bitmapHolderCache.get(key) != holder) { LogUtil.w("ContactPhotoManagerImpl.cacheBitmap", "bitmap too big to fit in cache."); - mBitmapHolderCache.put(key, BITMAP_UNAVAILABLE); + bitmapHolderCache.put(key, BITMAP_UNAVAILABLE); } } else { - mBitmapHolderCache.put(key, BITMAP_UNAVAILABLE); + bitmapHolderCache.put(key, BITMAP_UNAVAILABLE); } - mBitmapHolderCacheAllUnfresh = false; + bitmapHolderCacheAllUnfresh = false; } /** @@ -739,10 +739,10 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { * concurrent change, we will need to check the map again once loading * is complete. */ - Iterator iterator = mPendingRequests.values().iterator(); + Iterator iterator = pendingRequests.values().iterator(); while (iterator.hasNext()) { Request request = iterator.next(); - final BitmapHolder holder = mBitmapHolderCache.get(request.getKey()); + final BitmapHolder holder = bitmapHolderCache.get(request.getKey()); if (holder == BITMAP_UNAVAILABLE) { continue; } @@ -759,14 +759,14 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { uris.add(request); } else { photoIds.add(request.getId()); - photoIdsAsStrings.add(String.valueOf(request.mId)); + photoIdsAsStrings.add(String.valueOf(request.id)); } } } } if (jpegsDecoded) { - mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); + mainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); } } @@ -794,13 +794,13 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { */ private static final class Request { - private final long mId; - private final Uri mUri; - private final boolean mDarkTheme; - private final int mRequestedExtent; - private final DefaultImageProvider mDefaultProvider; + private final long id; + private final Uri uri; + private final boolean darkTheme; + private final int requestedExtent; + private final DefaultImageProvider defaultProvider; /** Whether or not the contact photo is to be displayed as a circle */ - private final boolean mIsCircular; + private final boolean isCircular; private Request( long id, @@ -809,12 +809,12 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { boolean darkTheme, boolean isCircular, DefaultImageProvider defaultProvider) { - mId = id; - mUri = uri; - mDarkTheme = darkTheme; - mIsCircular = isCircular; - mRequestedExtent = requestedExtent; - mDefaultProvider = defaultProvider; + this.id = id; + this.uri = uri; + this.darkTheme = darkTheme; + this.isCircular = isCircular; + this.requestedExtent = requestedExtent; + this.defaultProvider = defaultProvider; } public static Request createFromThumbnailId( @@ -833,28 +833,28 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } public boolean isUriRequest() { - return mUri != null; + return uri != null; } public Uri getUri() { - return mUri; + return uri; } public long getId() { - return mId; + return id; } public int getRequestedExtent() { - return mRequestedExtent; + return requestedExtent; } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int) (mId ^ (mId >>> 32)); - result = prime * result + mRequestedExtent; - result = prime * result + ((mUri == null) ? 0 : mUri.hashCode()); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + requestedExtent; + result = prime * result + ((uri == null) ? 0 : uri.hashCode()); return result; } @@ -870,13 +870,13 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { return false; } final Request that = (Request) obj; - if (mId != that.mId) { + if (id != that.id) { return false; } - if (mRequestedExtent != that.mRequestedExtent) { + if (requestedExtent != that.requestedExtent) { return false; } - if (!UriUtils.areEqual(mUri, that.mUri)) { + if (!UriUtils.areEqual(uri, that.uri)) { return false; } // Don't compare equality of mDarkTheme because it is only used in the default contact @@ -887,7 +887,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } public Object getKey() { - return mUri == null ? mId : mUri; + return uri == null ? id : uri; } /** @@ -903,16 +903,16 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { if (isCircular) { request = - ContactPhotoManager.isBusinessContactUri(mUri) + ContactPhotoManager.isBusinessContactUri(uri) ? DefaultImageRequest.EMPTY_CIRCULAR_BUSINESS_IMAGE_REQUEST : DefaultImageRequest.EMPTY_CIRCULAR_DEFAULT_IMAGE_REQUEST; } else { request = - ContactPhotoManager.isBusinessContactUri(mUri) + ContactPhotoManager.isBusinessContactUri(uri) ? DefaultImageRequest.EMPTY_DEFAULT_BUSINESS_IMAGE_REQUEST : DefaultImageRequest.EMPTY_DEFAULT_IMAGE_REQUEST; } - mDefaultProvider.applyDefaultImage(view, mRequestedExtent, mDarkTheme, request); + defaultProvider.applyDefaultImage(view, requestedExtent, darkTheme, request); } } @@ -938,24 +938,24 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { private static final int PRELOAD_STATUS_NOT_STARTED = 0; private static final int PRELOAD_STATUS_IN_PROGRESS = 1; private static final int PRELOAD_STATUS_DONE = 2; - private final ContentResolver mResolver; - private final StringBuilder mStringBuilder = new StringBuilder(); - private final Set mPhotoIds = new HashSet<>(); - private final Set mPhotoIdsAsStrings = new HashSet<>(); - private final Set mPhotoUris = new HashSet<>(); - private final List mPreloadPhotoIds = new ArrayList<>(); - private Handler mLoaderThreadHandler; - private byte[] mBuffer; - private int mPreloadStatus = PRELOAD_STATUS_NOT_STARTED; + private final ContentResolver resolver; + private final StringBuilder stringBuilder = new StringBuilder(); + private final Set photoIds = new HashSet<>(); + private final Set photoIdsAsStrings = new HashSet<>(); + private final Set photoUris = new HashSet<>(); + private final List preloadPhotoIds = new ArrayList<>(); + private Handler loaderThreadHandler; + private byte[] buffer; + private int preloadStatus = PRELOAD_STATUS_NOT_STARTED; public LoaderThread(ContentResolver resolver) { super(LOADER_THREAD_NAME); - mResolver = resolver; + this.resolver = resolver; } public void ensureHandler() { - if (mLoaderThreadHandler == null) { - mLoaderThreadHandler = new Handler(getLooper(), this); + if (loaderThreadHandler == null) { + loaderThreadHandler = new Handler(getLooper(), this); } } @@ -966,16 +966,16 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { *

If preloading is already complete, does nothing. */ public void requestPreloading() { - if (mPreloadStatus == PRELOAD_STATUS_DONE) { + if (preloadStatus == PRELOAD_STATUS_DONE) { return; } ensureHandler(); - if (mLoaderThreadHandler.hasMessages(MESSAGE_LOAD_PHOTOS)) { + if (loaderThreadHandler.hasMessages(MESSAGE_LOAD_PHOTOS)) { return; } - mLoaderThreadHandler.sendEmptyMessageDelayed(MESSAGE_PRELOAD_PHOTOS, PHOTO_PRELOAD_DELAY); + loaderThreadHandler.sendEmptyMessageDelayed(MESSAGE_PRELOAD_PHOTOS, PHOTO_PRELOAD_DELAY); } /** @@ -984,8 +984,8 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { */ public void requestLoading() { ensureHandler(); - mLoaderThreadHandler.removeMessages(MESSAGE_PRELOAD_PHOTOS); - mLoaderThreadHandler.sendEmptyMessage(MESSAGE_LOAD_PHOTOS); + loaderThreadHandler.removeMessages(MESSAGE_PRELOAD_PHOTOS); + loaderThreadHandler.sendEmptyMessage(MESSAGE_LOAD_PHOTOS); } /** @@ -1012,53 +1012,53 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { */ @WorkerThread private void preloadPhotosInBackground() { - if (!PermissionsUtil.hasPermission(mContext, android.Manifest.permission.READ_CONTACTS)) { + if (!PermissionsUtil.hasPermission(context, android.Manifest.permission.READ_CONTACTS)) { return; } - if (mPreloadStatus == PRELOAD_STATUS_DONE) { + if (preloadStatus == PRELOAD_STATUS_DONE) { return; } - if (mPreloadStatus == PRELOAD_STATUS_NOT_STARTED) { + if (preloadStatus == PRELOAD_STATUS_NOT_STARTED) { queryPhotosForPreload(); - if (mPreloadPhotoIds.isEmpty()) { - mPreloadStatus = PRELOAD_STATUS_DONE; + if (preloadPhotoIds.isEmpty()) { + preloadStatus = PRELOAD_STATUS_DONE; } else { - mPreloadStatus = PRELOAD_STATUS_IN_PROGRESS; + preloadStatus = PRELOAD_STATUS_IN_PROGRESS; } requestPreloading(); return; } - if (mBitmapHolderCache.size() > mBitmapHolderCacheRedZoneBytes) { - mPreloadStatus = PRELOAD_STATUS_DONE; + if (bitmapHolderCache.size() > bitmapHolderCacheRedZoneBytes) { + preloadStatus = PRELOAD_STATUS_DONE; return; } - mPhotoIds.clear(); - mPhotoIdsAsStrings.clear(); + photoIds.clear(); + photoIdsAsStrings.clear(); int count = 0; - int preloadSize = mPreloadPhotoIds.size(); - while (preloadSize > 0 && mPhotoIds.size() < PRELOAD_BATCH) { + int preloadSize = preloadPhotoIds.size(); + while (preloadSize > 0 && photoIds.size() < PRELOAD_BATCH) { preloadSize--; count++; - Long photoId = mPreloadPhotoIds.get(preloadSize); - mPhotoIds.add(photoId); - mPhotoIdsAsStrings.add(photoId.toString()); - mPreloadPhotoIds.remove(preloadSize); + Long photoId = preloadPhotoIds.get(preloadSize); + photoIds.add(photoId); + photoIdsAsStrings.add(photoId.toString()); + preloadPhotoIds.remove(preloadSize); } loadThumbnails(true); if (preloadSize == 0) { - mPreloadStatus = PRELOAD_STATUS_DONE; + preloadStatus = PRELOAD_STATUS_DONE; } LogUtil.v( "ContactPhotoManagerImpl.preloadPhotosInBackground", - "preloaded " + count + " photos. cached bytes: " + mBitmapHolderCache.size()); + "preloaded " + count + " photos. cached bytes: " + bitmapHolderCache.size()); requestPreloading(); } @@ -1076,7 +1076,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { ContactsContract.LIMIT_PARAM_KEY, String.valueOf(MAX_PHOTOS_TO_PRELOAD)) .build(); cursor = - mResolver.query( + resolver.query( uri, new String[] {Contacts.PHOTO_ID}, Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + "!=0", @@ -1087,7 +1087,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { while (cursor.moveToNext()) { // Insert them in reverse order, because we will be taking // them from the end of the list for loading. - mPreloadPhotoIds.add(0, cursor.getLong(0)); + preloadPhotoIds.add(0, cursor.getLong(0)); } } } finally { @@ -1099,10 +1099,10 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { @WorkerThread private void loadPhotosInBackground() { - if (!PermissionsUtil.hasPermission(mContext, android.Manifest.permission.READ_CONTACTS)) { + if (!PermissionsUtil.hasPermission(context, android.Manifest.permission.READ_CONTACTS)) { return; } - obtainPhotoIdsAndUrisToLoad(mPhotoIds, mPhotoIdsAsStrings, mPhotoUris); + obtainPhotoIdsAndUrisToLoad(photoIds, photoIdsAsStrings, photoUris); loadThumbnails(false); loadUriBasedPhotos(); requestPreloading(); @@ -1111,44 +1111,44 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { /** Loads thumbnail photos with ids */ @WorkerThread private void loadThumbnails(boolean preloading) { - if (mPhotoIds.isEmpty()) { + if (photoIds.isEmpty()) { return; } // Remove loaded photos from the preload queue: we don't want // the preloading process to load them again. - if (!preloading && mPreloadStatus == PRELOAD_STATUS_IN_PROGRESS) { - for (Long id : mPhotoIds) { - mPreloadPhotoIds.remove(id); + if (!preloading && preloadStatus == PRELOAD_STATUS_IN_PROGRESS) { + for (Long id : photoIds) { + preloadPhotoIds.remove(id); } - if (mPreloadPhotoIds.isEmpty()) { - mPreloadStatus = PRELOAD_STATUS_DONE; + if (preloadPhotoIds.isEmpty()) { + preloadStatus = PRELOAD_STATUS_DONE; } } - mStringBuilder.setLength(0); - mStringBuilder.append(Photo._ID + " IN("); - for (int i = 0; i < mPhotoIds.size(); i++) { + stringBuilder.setLength(0); + stringBuilder.append(Photo._ID + " IN("); + for (int i = 0; i < photoIds.size(); i++) { if (i != 0) { - mStringBuilder.append(','); + stringBuilder.append(','); } - mStringBuilder.append('?'); + stringBuilder.append('?'); } - mStringBuilder.append(')'); + stringBuilder.append(')'); Cursor cursor = null; try { if (DEBUG) { LogUtil.d( "ContactPhotoManagerImpl.loadThumbnails", - "loading " + TextUtils.join(",", mPhotoIdsAsStrings)); + "loading " + TextUtils.join(",", photoIdsAsStrings)); } cursor = - mResolver.query( + resolver.query( Data.CONTENT_URI, COLUMNS, - mStringBuilder.toString(), - mPhotoIdsAsStrings.toArray(EMPTY_STRING_ARRAY), + stringBuilder.toString(), + photoIdsAsStrings.toArray(EMPTY_STRING_ARRAY), null); if (cursor != null) { @@ -1156,7 +1156,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { Long id = cursor.getLong(0); byte[] bytes = cursor.getBlob(1); cacheBitmap(id, bytes, preloading, -1); - mPhotoIds.remove(id); + photoIds.remove(id); } } } finally { @@ -1166,12 +1166,12 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } // Remaining photos were not found in the contacts database (but might be in profile). - for (Long id : mPhotoIds) { + for (Long id : photoIds) { if (ContactsContract.isProfileId(id)) { Cursor profileCursor = null; try { profileCursor = - mResolver.query( + resolver.query( ContentUris.withAppendedId(Data.CONTENT_URI, id), COLUMNS, null, null, null); if (profileCursor != null && profileCursor.moveToFirst()) { cacheBitmap(profileCursor.getLong(0), profileCursor.getBlob(1), preloading, -1); @@ -1190,7 +1190,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { } } - mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); + mainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); } /** @@ -1199,7 +1199,7 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { */ @WorkerThread private void loadUriBasedPhotos() { - for (Request uriRequest : mPhotoUris) { + for (Request uriRequest : photoUris) { // Keep the original URI and use this to key into the cache. Failure to do so will // result in an image being continually reloaded into cache if the original URI // has a contact type encodedFragment (eg nearby places business photo URLs). @@ -1209,8 +1209,8 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { // a business photo -- there is no need to pass this on to the server. Uri uri = ContactPhotoManager.removeContactType(originalUri); - if (mBuffer == null) { - mBuffer = new byte[BUFFER_SIZE]; + if (buffer == null) { + buffer = new byte[BUFFER_SIZE]; } try { if (DEBUG) { @@ -1225,8 +1225,8 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { (HttpURLConnection) new URL(uri.toString()).openConnection(); // Include the user agent if it is specified. - if (!TextUtils.isEmpty(mUserAgent)) { - connection.setRequestProperty("User-Agent", mUserAgent); + if (!TextUtils.isEmpty(userAgent)) { + connection.setRequestProperty("User-Agent", userAgent); } try { is = connection.getInputStream(); @@ -1238,20 +1238,20 @@ class ContactPhotoManagerImpl extends ContactPhotoManager implements Callback { TrafficStats.clearThreadStatsTag(); } } else { - is = mResolver.openInputStream(uri); + is = resolver.openInputStream(uri); } if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int size; - while ((size = is.read(mBuffer)) != -1) { - baos.write(mBuffer, 0, size); + while ((size = is.read(buffer)) != -1) { + baos.write(buffer, 0, size); } } finally { is.close(); } cacheBitmap(originalUri, baos.toByteArray(), false, uriRequest.getRequestedExtent()); - mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); + mainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED); } else { LogUtil.v("ContactPhotoManagerImpl.loadUriBasedPhotos", "cannot load photo " + uri); cacheBitmap(originalUri, null, false, uriRequest.getRequestedExtent()); diff --git a/java/com/android/dialer/database/CallLogQueryHandler.java b/java/com/android/dialer/database/CallLogQueryHandler.java index 35250d668..1aa125184 100644 --- a/java/com/android/dialer/database/CallLogQueryHandler.java +++ b/java/com/android/dialer/database/CallLogQueryHandler.java @@ -66,10 +66,10 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { /** The token for the query to fetch the number of missed calls. */ private static final int QUERY_MISSED_CALLS_UNREAD_COUNT_TOKEN = 59; - private final int mLogLimit; - private final WeakReference mListener; + private final int logLimit; + private final WeakReference listener; - private final Context mContext; + private final Context context; public CallLogQueryHandler(Context context, ContentResolver contentResolver, Listener listener) { this(context, contentResolver, listener, -1); @@ -78,9 +78,9 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { public CallLogQueryHandler( Context context, ContentResolver contentResolver, Listener listener, int limit) { super(contentResolver); - mContext = context.getApplicationContext(); - mListener = new WeakReference<>(listener); - mLogLimit = limit; + this.context = context.getApplicationContext(); + this.listener = new WeakReference<>(listener); + logLimit = limit; } @Override @@ -97,7 +97,7 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { */ public void fetchCalls(int callType, long newerThan) { cancelFetch(); - if (PermissionsUtil.hasPhonePermissions(mContext)) { + if (PermissionsUtil.hasPhonePermissions(context)) { fetchCalls(QUERY_CALLLOG_TOKEN, callType, false /* newOnly */, newerThan); } else { updateAdapterData(null); @@ -108,11 +108,11 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { StringBuilder where = new StringBuilder(); List selectionArgs = new ArrayList<>(); - VoicemailComponent.get(mContext) + VoicemailComponent.get(context) .getVoicemailClient() - .appendOmtpVoicemailStatusSelectionClause(mContext, where, selectionArgs); + .appendOmtpVoicemailStatusSelectionClause(context, where, selectionArgs); - if (TelecomUtil.hasReadWriteVoicemailPermissions(mContext)) { + if (TelecomUtil.hasReadWriteVoicemailPermissions(context)) { startQuery( QUERY_VOICEMAIL_STATUS_TOKEN, null, @@ -125,15 +125,15 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { } public void fetchVoicemailUnreadCount() { - if (TelecomUtil.hasReadWriteVoicemailPermissions(mContext)) { + if (TelecomUtil.hasReadWriteVoicemailPermissions(context)) { // Only count voicemails that have not been read and have not been deleted. StringBuilder where = new StringBuilder(Voicemails.IS_READ + "=0" + " AND " + Voicemails.DELETED + "=0 "); List selectionArgs = new ArrayList<>(); - VoicemailComponent.get(mContext) + VoicemailComponent.get(context) .getVoicemailClient() - .appendOmtpVoicemailSelectionClause(mContext, where, selectionArgs); + .appendOmtpVoicemailSelectionClause(context, where, selectionArgs); startQuery( QUERY_VOICEMAIL_UNREAD_COUNT_TOKEN, @@ -178,9 +178,9 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { } if (callType == Calls.VOICEMAIL_TYPE) { - VoicemailComponent.get(mContext) + VoicemailComponent.get(context) .getVoicemailClient() - .appendOmtpVoicemailSelectionClause(mContext, where, selectionArgs); + .appendOmtpVoicemailSelectionClause(context, where, selectionArgs); } else { // Filter out all Duo entries other than video calls where @@ -197,10 +197,10 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { .append(")"); } - final int limit = (mLogLimit == -1) ? NUM_LOGS_TO_DISPLAY : mLogLimit; + final int limit = (logLimit == -1) ? NUM_LOGS_TO_DISPLAY : logLimit; final String selection = where.length() > 0 ? where.toString() : null; Uri uri = - TelecomUtil.getCallLogUri(mContext) + TelecomUtil.getCallLogUri(context) .buildUpon() .appendQueryParameter(Calls.LIMIT_PARAM_KEY, Integer.toString(limit)) .build(); @@ -221,7 +221,7 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { /** Updates all missed calls to mark them as read. */ public void markMissedCallsAsRead() { - if (!PermissionsUtil.hasPhonePermissions(mContext)) { + if (!PermissionsUtil.hasPhonePermissions(context)) { return; } @@ -239,7 +239,7 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { /** Fetch all missed calls received since last time the tab was opened. */ public void fetchMissedCallsUnreadCount() { - if (!PermissionsUtil.hasPhonePermissions(mContext)) { + if (!PermissionsUtil.hasPhonePermissions(context)) { return; } @@ -286,7 +286,7 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { * listener took ownership of the cursor. */ private boolean updateAdapterData(Cursor cursor) { - final Listener listener = mListener.get(); + final Listener listener = this.listener.get(); return listener != null && listener.onCallsFetched(cursor); } @@ -303,21 +303,21 @@ public class CallLogQueryHandler extends NoNullCursorAsyncQueryHandler { } private void updateVoicemailStatus(Cursor statusCursor) { - final Listener listener = mListener.get(); + final Listener listener = this.listener.get(); if (listener != null) { listener.onVoicemailStatusFetched(statusCursor); } } private void updateVoicemailUnreadCount(Cursor statusCursor) { - final Listener listener = mListener.get(); + final Listener listener = this.listener.get(); if (listener != null) { listener.onVoicemailUnreadCountFetched(statusCursor); } } private void updateMissedCallsUnreadCount(Cursor statusCursor) { - final Listener listener = mListener.get(); + final Listener listener = this.listener.get(); if (listener != null) { listener.onMissedCallsUnreadCountFetched(statusCursor); } diff --git a/java/com/android/dialer/database/DialerDatabaseHelper.java b/java/com/android/dialer/database/DialerDatabaseHelper.java index 3fb87304b..d12b4e8bd 100644 --- a/java/com/android/dialer/database/DialerDatabaseHelper.java +++ b/java/com/android/dialer/database/DialerDatabaseHelper.java @@ -78,16 +78,16 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_VERSION_PROPERTY = "database_version"; private static final int MAX_ENTRIES = 20; - private final Context mContext; - private boolean mIsTestInstance = false; + private final Context context; + private boolean isTestInstance = false; protected DialerDatabaseHelper(Context context, String databaseName, int dbVersion) { super(context, databaseName, null, dbVersion); - mContext = Objects.requireNonNull(context, "Context must not be null"); + this.context = Objects.requireNonNull(context, "Context must not be null"); } public void setIsTestInstance(boolean isTestInstance) { - mIsTestInstance = isTestInstance; + this.isTestInstance = isTestInstance; } /** @@ -188,7 +188,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { + ");"); setProperty(db, DATABASE_VERSION_PROPERTY, String.valueOf(DATABASE_VERSION)); - if (!mIsTestInstance) { + if (!isTestInstance) { resetSmartDialLastUpdatedTime(); } } @@ -325,7 +325,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { private void resetSmartDialLastUpdatedTime() { final SharedPreferences databaseLastUpdateSharedPref = - mContext.getSharedPreferences(DATABASE_LAST_CREATED_SHARED_PREF, Context.MODE_PRIVATE); + context.getSharedPreferences(DATABASE_LAST_CREATED_SHARED_PREF, Context.MODE_PRIVATE); final SharedPreferences.Editor editor = databaseLastUpdateSharedPref.edit(); editor.putLong(LAST_UPDATED_MILLIS, 0); editor.apply(); @@ -333,8 +333,8 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { /** Starts the database upgrade process in the background. */ public void startSmartDialUpdateThread() { - if (PermissionsUtil.hasContactsReadPermissions(mContext)) { - DialerExecutorComponent.get(mContext) + if (PermissionsUtil.hasContactsReadPermissions(context)) { + DialerExecutorComponent.get(context) .dialerExecutorFactory() .createNonUiTaskBuilder(new UpdateSmartDialWorker()) .build() @@ -373,7 +373,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { } private Cursor getDeletedContactCursor(String lastUpdateMillis) { - return mContext + return context .getContentResolver() .query( DeleteContactQuery.URI, @@ -517,7 +517,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { final String displayName = updatedContactCursor.getString(PhoneQuery.PHONE_DISPLAY_NAME); if (displayName == null) { - insert.bindString(5, mContext.getResources().getString(R.string.missing_name)); + insert.bindString(5, context.getResources().getString(R.string.missing_name)); } else { insert.bindString(5, displayName); } @@ -535,7 +535,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { insert.executeInsert(); final String contactPhoneNumber = updatedContactCursor.getString(PhoneQuery.PHONE_NUMBER); final ArrayList numberPrefixes = - SmartDialPrefix.parseToNumberTokens(mContext, contactPhoneNumber); + SmartDialPrefix.parseToNumberTokens(context, contactPhoneNumber); for (String numberPrefix : numberPrefixes) { numberInsert.bindLong(1, updatedContactCursor.getLong(PhoneQuery.PHONE_CONTACT_ID)); @@ -578,7 +578,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { while (nameCursor.moveToNext()) { /** Computes a list of prefixes of a given contact name. */ final ArrayList namePrefixes = - SmartDialPrefix.generateNamePrefixes(mContext, nameCursor.getString(columnIndexName)); + SmartDialPrefix.generateNamePrefixes(context, nameCursor.getString(columnIndexName)); for (String namePrefix : namePrefixes) { insert.bindLong(1, nameCursor.getLong(columnIndexContactId)); @@ -611,7 +611,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { /** Gets the last update time on the database. */ final SharedPreferences databaseLastUpdateSharedPref = - mContext.getSharedPreferences(DATABASE_LAST_CREATED_SHARED_PREF, Context.MODE_PRIVATE); + context.getSharedPreferences(DATABASE_LAST_CREATED_SHARED_PREF, Context.MODE_PRIVATE); final String lastUpdateMillis = String.valueOf(databaseLastUpdateSharedPref.getLong(LAST_UPDATED_MILLIS, 0)); @@ -644,7 +644,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { * up in updatedPhoneCursor (since all of its phone numbers have been deleted). */ final Cursor updatedContactCursor = - mContext + context .getContentResolver() .query( UpdatedContactQuery.URI, @@ -673,7 +673,7 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { * update time. */ final Cursor updatedPhoneCursor = - mContext + context .getContentResolver() .query( PhoneQuery.URI, @@ -804,8 +804,8 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { // Notify content observers that smart dial database has been updated. Intent intent = new Intent(ACTION_SMART_DIAL_UPDATED); - intent.setPackage(mContext.getPackageName()); - mContext.sendBroadcast(intent); + intent.setPackage(context.getPackageName()); + context.sendBroadcast(intent); } /** @@ -912,9 +912,9 @@ public class DialerDatabaseHelper extends SQLiteOpenHelper { /** * If the contact has either the name or number that matches the query, add to the result. */ - final boolean nameMatches = nameMatcher.matches(mContext, displayName); + final boolean nameMatches = nameMatcher.matches(context, displayName); final boolean numberMatches = - (nameMatcher.matchesNumber(mContext, phoneNumber, query) != null); + (nameMatcher.matchesNumber(context, phoneNumber, query) != null); if (nameMatches || numberMatches) { /** If a contact has not been added, add it to the result and the hash set. */ duplicates.add(contactMatch); diff --git a/java/com/android/dialer/dialpadview/DialpadFragment.java b/java/com/android/dialer/dialpadview/DialpadFragment.java index 4673d9eca..0418009d7 100644 --- a/java/com/android/dialer/dialpadview/DialpadFragment.java +++ b/java/com/android/dialer/dialpadview/DialpadFragment.java @@ -137,45 +137,45 @@ public class DialpadFragment extends Fragment private static Optional currentCountryIsoForTesting = Optional.absent(); - private final Object mToneGeneratorLock = new Object(); + private final Object toneGeneratorLock = new Object(); /** Set of dialpad keys that are currently being pressed */ - private final HashSet mPressedDialpadKeys = new HashSet<>(12); + private final HashSet pressedDialpadKeys = new HashSet<>(12); - private OnDialpadQueryChangedListener mDialpadQueryListener; - private DialpadView mDialpadView; - private EditText mDigits; - private int mDialpadSlideInDuration; + private OnDialpadQueryChangedListener dialpadQueryListener; + private DialpadView dialpadView; + private EditText digits; + private int dialpadSlideInDuration; /** Remembers if we need to clear digits field when the screen is completely gone. */ - private boolean mClearDigitsOnStop; - - private View mOverflowMenuButton; - private PopupMenu mOverflowPopupMenu; - private View mDelete; - private ToneGenerator mToneGenerator; - private FloatingActionButtonController mFloatingActionButtonController; - private FloatingActionButton mFloatingActionButton; - private ListView mDialpadChooser; - private DialpadChooserAdapter mDialpadChooserAdapter; + private boolean clearDigitsOnStop; + + private View overflowMenuButton; + private PopupMenu overflowPopupMenu; + private View delete; + private ToneGenerator toneGenerator; + private FloatingActionButtonController floatingActionButtonController; + private FloatingActionButton floatingActionButton; + private ListView dialpadChooser; + private DialpadChooserAdapter dialpadChooserAdapter; /** Regular expression prohibiting manual phone call. Can be empty, which means "no rule". */ - private String mProhibitedPhoneNumberRegexp; + private String prohibitedPhoneNumberRegexp; - private PseudoEmergencyAnimator mPseudoEmergencyAnimator; - private String mLastNumberDialed = EMPTY_NUMBER; + private PseudoEmergencyAnimator pseudoEmergencyAnimator; + private String lastNumberDialed = EMPTY_NUMBER; // determines if we want to playback local DTMF tones. - private boolean mDTMFToneEnabled; - private CallStateReceiver mCallStateReceiver; - private boolean mWasEmptyBeforeTextChange; + private boolean dTMFToneEnabled; + private CallStateReceiver callStateReceiver; + private boolean wasEmptyBeforeTextChange; /** * This field is set to true while processing an incoming DIAL intent, in order to make sure that * SpecialCharSequenceMgr actions can be triggered by user input but *not* by a tel: URI passed by * some other app. It will be set to false when all digits are cleared. */ - private boolean mDigitsFilledByIntent; + private boolean digitsFilledByIntent; - private boolean mStartedFromNewIntent = false; - private boolean mFirstLaunch = false; - private boolean mAnimate = false; + private boolean startedFromNewIntent = false; + private boolean firstLaunch = false; + private boolean animate = false; private DialerExecutor initPhoneNumberFormattingTextWatcherExecutor; @@ -283,16 +283,16 @@ public class DialpadFragment extends Fragment @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { - mWasEmptyBeforeTextChange = TextUtils.isEmpty(s); + wasEmptyBeforeTextChange = TextUtils.isEmpty(s); } @Override public void onTextChanged(CharSequence input, int start, int before, int changeCount) { - if (mWasEmptyBeforeTextChange != TextUtils.isEmpty(input)) { + if (wasEmptyBeforeTextChange != TextUtils.isEmpty(input)) { final Activity activity = getActivity(); if (activity != null) { activity.invalidateOptionsMenu(); - updateMenuOverflowButton(mWasEmptyBeforeTextChange); + updateMenuOverflowButton(wasEmptyBeforeTextChange); } } @@ -305,19 +305,19 @@ public class DialpadFragment extends Fragment // When DTMF dialpad buttons are being pressed, we delay SpecialCharSequenceMgr sequence, // since some of SpecialCharSequenceMgr's behavior is too abrupt for the "touch-down" // behavior. - if (!mDigitsFilledByIntent - && SpecialCharSequenceMgr.handleChars(getActivity(), input.toString(), mDigits)) { + if (!digitsFilledByIntent + && SpecialCharSequenceMgr.handleChars(getActivity(), input.toString(), digits)) { // A special sequence was entered, clear the digits - mDigits.getText().clear(); + digits.getText().clear(); } if (isDigitsEmpty()) { - mDigitsFilledByIntent = false; - mDigits.setCursorVisible(false); + digitsFilledByIntent = false; + digits.setCursorVisible(false); } - if (mDialpadQueryListener != null) { - mDialpadQueryListener.onDialpadQueryChanged(mDigits.getText().toString()); + if (dialpadQueryListener != null) { + dialpadQueryListener.onDialpadQueryChanged(digits.getText().toString()); } updateDeleteButtonEnabledState(); @@ -329,22 +329,22 @@ public class DialpadFragment extends Fragment LogUtil.enterBlock("DialpadFragment.onCreate"); super.onCreate(state); - mFirstLaunch = state == null; + firstLaunch = state == null; - mProhibitedPhoneNumberRegexp = + prohibitedPhoneNumberRegexp = getResources().getString(R.string.config_prohibited_phone_number_regexp); if (state != null) { - mDigitsFilledByIntent = state.getBoolean(PREF_DIGITS_FILLED_BY_INTENT); + digitsFilledByIntent = state.getBoolean(PREF_DIGITS_FILLED_BY_INTENT); } - mDialpadSlideInDuration = getResources().getInteger(R.integer.dialpad_slide_in_duration); + dialpadSlideInDuration = getResources().getInteger(R.integer.dialpad_slide_in_duration); - if (mCallStateReceiver == null) { + if (callStateReceiver == null) { IntentFilter callStateIntentFilter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED); - mCallStateReceiver = new CallStateReceiver(); - getActivity().registerReceiver(mCallStateReceiver, callStateIntentFilter); + callStateReceiver = new CallStateReceiver(); + getActivity().registerReceiver(callStateReceiver, callStateIntentFilter); } initPhoneNumberFormattingTextWatcherExecutor = @@ -354,7 +354,7 @@ public class DialpadFragment extends Fragment getFragmentManager(), "DialpadFragment.initPhoneNumberFormattingTextWatcher", new InitPhoneNumberFormattingTextWatcherWorker()) - .onSuccess(watcher -> mDialpadView.getDigits().addTextChangedListener(watcher)) + .onSuccess(watcher -> dialpadView.getDigits().addTextChangedListener(watcher)) .build(); Trace.endSection(); } @@ -372,15 +372,15 @@ public class DialpadFragment extends Fragment Trace.beginSection(TAG + " setup views"); - mDialpadView = fragmentView.findViewById(R.id.dialpad_view); - mDialpadView.setCanDigitsBeEdited(true); - mDigits = mDialpadView.getDigits(); - mDigits.setKeyListener(UnicodeDialerKeyListener.INSTANCE); - mDigits.setOnClickListener(this); - mDigits.setOnKeyListener(this); - mDigits.setOnLongClickListener(this); - mDigits.addTextChangedListener(this); - mDigits.setElegantTextHeight(false); + dialpadView = fragmentView.findViewById(R.id.dialpad_view); + dialpadView.setCanDigitsBeEdited(true); + digits = dialpadView.getDigits(); + digits.setKeyListener(UnicodeDialerKeyListener.INSTANCE); + digits.setOnClickListener(this); + digits.setOnKeyListener(this); + digits.setOnLongClickListener(this); + digits.addTextChangedListener(this); + digits.setElegantTextHeight(false); initPhoneNumberFormattingTextWatcherExecutor.executeSerial(getCurrentCountryIso()); @@ -390,11 +390,11 @@ public class DialpadFragment extends Fragment configureKeypadListeners(fragmentView); } - mDelete = mDialpadView.getDeleteButton(); + delete = dialpadView.getDeleteButton(); - if (mDelete != null) { - mDelete.setOnClickListener(this); - mDelete.setOnLongClickListener(this); + if (delete != null) { + delete.setOnClickListener(this); + delete.setOnLongClickListener(this); } fragmentView @@ -411,16 +411,16 @@ public class DialpadFragment extends Fragment return false; }); - mDigits.setCursorVisible(false); + digits.setCursorVisible(false); // Set up the "dialpad chooser" UI; see showDialpadChooser(). - mDialpadChooser = fragmentView.findViewById(R.id.dialpadChooser); - mDialpadChooser.setOnItemClickListener(this); + dialpadChooser = fragmentView.findViewById(R.id.dialpadChooser); + dialpadChooser.setOnItemClickListener(this); - mFloatingActionButton = fragmentView.findViewById(R.id.dialpad_floating_action_button); - mFloatingActionButton.setOnClickListener(this); - mFloatingActionButtonController = - new FloatingActionButtonController(getActivity(), mFloatingActionButton); + floatingActionButton = fragmentView.findViewById(R.id.dialpad_floating_action_button); + floatingActionButton.setOnClickListener(this); + floatingActionButtonController = + new FloatingActionButtonController(getActivity(), floatingActionButton); Trace.endSection(); Trace.endSection(); return fragmentView; @@ -440,18 +440,18 @@ public class DialpadFragment extends Fragment } private boolean isLayoutReady() { - return mDigits != null; + return digits != null; } public EditText getDigitsWidget() { - return mDigits; + return digits; } - /** @return true when {@link #mDigits} is actually filled by the Intent. */ + /** @return true when {@link #digits} is actually filled by the Intent. */ private boolean fillDigitsIfNecessary(Intent intent) { // Only fills digits from an intent if it is a new intent. // Otherwise falls back to the previously used number. - if (!mFirstLaunch && !mStartedFromNewIntent) { + if (!firstLaunch && !startedFromNewIntent) { return false; } @@ -463,7 +463,7 @@ public class DialpadFragment extends Fragment // Put the requested number into the input area String data = uri.getSchemeSpecificPart(); // Remember it is filled via Intent. - mDigitsFilledByIntent = true; + digitsFilledByIntent = true; final String converted = PhoneNumberUtils.convertKeypadLettersToDigits( PhoneNumberUtils.replaceUnicodeDigits(data)); @@ -489,7 +489,7 @@ public class DialpadFragment extends Fragment try { if (c.moveToFirst()) { // Remember it is filled via Intent. - mDigitsFilledByIntent = true; + digitsFilledByIntent = true; // Put the number into the input area setFormattedDigits(c.getString(0), c.getString(1)); return true; @@ -550,7 +550,7 @@ public class DialpadFragment extends Fragment // i.e. User clicks a telephone link from gmail for example. // In this case, we want to show the dialpad with the phone number. boolean digitsFilled = fillDigitsIfNecessary(intent); - if (!(mStartedFromNewIntent && digitsFilled) && isPhoneInUse()) { + if (!(startedFromNewIntent && digitsFilled) && isPhoneInUse()) { // If there's already an active call, bring up an intermediate UI to // make the user confirm what they really want to do. LogUtil.i("DialpadFragment.configureScreenFromIntent", "Dialpad chooser mode"); @@ -565,7 +565,7 @@ public class DialpadFragment extends Fragment } public void setStartedFromNewIntent(boolean value) { - mStartedFromNewIntent = value; + startedFromNewIntent = value; } public void clearCallRateInformation() { @@ -573,14 +573,14 @@ public class DialpadFragment extends Fragment } public void setCallRateInformation(String countryName, String displayRate) { - mDialpadView.setCallRateInformation(countryName, displayRate); + dialpadView.setCallRateInformation(countryName, displayRate); } /** Sets formatted digits to digits field. */ private void setFormattedDigits(String data, String normalizedNumber) { final String formatted = getFormattedDigits(data, normalizedNumber, getCurrentCountryIso()); if (!TextUtils.isEmpty(formatted)) { - Editable digits = mDigits.getText(); + Editable digits = this.digits.getText(); digits.replace(0, digits.length(), formatted); // for some reason this isn't getting called in the digits.replace call above.. // but in any case, this will make sure the background drawable looks right @@ -623,21 +623,21 @@ public class DialpadFragment extends Fragment @Override public void onStart() { - LogUtil.i("DialpadFragment.onStart", "first launch: %b", mFirstLaunch); + LogUtil.i("DialpadFragment.onStart", "first launch: %b", firstLaunch); Trace.beginSection(TAG + " onStart"); super.onStart(); // if the mToneGenerator creation fails, just continue without it. It is // a local audio signal, and is not as important as the dtmf tone itself. final long start = System.currentTimeMillis(); - synchronized (mToneGeneratorLock) { - if (mToneGenerator == null) { + synchronized (toneGeneratorLock) { + if (toneGenerator == null) { try { - mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME); + toneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME); } catch (RuntimeException e) { LogUtil.e( "DialpadFragment.onStart", "Exception caught while creating local tone generator: " + e); - mToneGenerator = null; + toneGenerator = null; } } } @@ -659,11 +659,10 @@ public class DialpadFragment extends Fragment if (MotorolaUtils.isWifiCallingAvailable(getContext())) { iconId = R.drawable.ic_wifi_calling; } - mFloatingActionButtonController.changeIcon( + floatingActionButtonController.changeIcon( getContext(), iconId, res.getString(R.string.description_dial_button)); - mDialpadQueryListener = - FragmentUtils.getParentUnsafe(this, OnDialpadQueryChangedListener.class); + dialpadQueryListener = FragmentUtils.getParentUnsafe(this, OnDialpadQueryChangedListener.class); final StopWatch stopWatch = StopWatch.start("Dialpad.onResume"); @@ -676,14 +675,14 @@ public class DialpadFragment extends Fragment final ContentResolver contentResolver = getActivity().getContentResolver(); // retrieve the DTMF tone play back setting. - mDTMFToneEnabled = + dTMFToneEnabled = Settings.System.getInt(contentResolver, Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1; stopWatch.lap("dtwd"); stopWatch.lap("hptc"); - mPressedDialpadKeys.clear(); + pressedDialpadKeys.clear(); configureScreenFromIntent(getActivity().getIntent()); @@ -706,19 +705,19 @@ public class DialpadFragment extends Fragment // Populate the overflow menu in onResume instead of onCreate, so that if the SMS activity // is disabled while Dialer is paused, the "Send a text message" option can be correctly // removed when resumed. - mOverflowMenuButton = mDialpadView.getOverflowMenuButton(); - mOverflowPopupMenu = buildOptionsMenu(mOverflowMenuButton); - mOverflowMenuButton.setOnTouchListener(mOverflowPopupMenu.getDragToOpenListener()); - mOverflowMenuButton.setOnClickListener(this); - mOverflowMenuButton.setVisibility(isDigitsEmpty() ? View.INVISIBLE : View.VISIBLE); + overflowMenuButton = dialpadView.getOverflowMenuButton(); + overflowPopupMenu = buildOptionsMenu(overflowMenuButton); + overflowMenuButton.setOnTouchListener(overflowPopupMenu.getDragToOpenListener()); + overflowMenuButton.setOnClickListener(this); + overflowMenuButton.setVisibility(isDigitsEmpty() ? View.INVISIBLE : View.VISIBLE); - if (mFirstLaunch) { + if (firstLaunch) { // The onHiddenChanged callback does not get called the first time the fragment is // attached, so call it ourselves here. onHiddenChanged(false); } - mFirstLaunch = false; + firstLaunch = false; Trace.endSection(); } @@ -728,14 +727,14 @@ public class DialpadFragment extends Fragment // Make sure we don't leave this activity with a tone still playing. stopTone(); - mPressedDialpadKeys.clear(); + pressedDialpadKeys.clear(); // TODO: I wonder if we should not check if the AsyncTask that // lookup the last dialed number has completed. - mLastNumberDialed = EMPTY_NUMBER; // Since we are going to query again, free stale number. + lastNumberDialed = EMPTY_NUMBER; // Since we are going to query again, free stale number. SpecialCharSequenceMgr.cleanup(); - mOverflowPopupMenu.dismiss(); + overflowPopupMenu.dismiss(); } @Override @@ -743,15 +742,15 @@ public class DialpadFragment extends Fragment LogUtil.enterBlock("DialpadFragment.onStop"); super.onStop(); - synchronized (mToneGeneratorLock) { - if (mToneGenerator != null) { - mToneGenerator.release(); - mToneGenerator = null; + synchronized (toneGeneratorLock) { + if (toneGenerator != null) { + toneGenerator.release(); + toneGenerator = null; } } - if (mClearDigitsOnStop) { - mClearDigitsOnStop = false; + if (clearDigitsOnStop) { + clearDigitsOnStop = false; clearDialpad(); } } @@ -759,17 +758,17 @@ public class DialpadFragment extends Fragment @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - outState.putBoolean(PREF_DIGITS_FILLED_BY_INTENT, mDigitsFilledByIntent); + outState.putBoolean(PREF_DIGITS_FILLED_BY_INTENT, digitsFilledByIntent); } @Override public void onDestroy() { super.onDestroy(); - if (mPseudoEmergencyAnimator != null) { - mPseudoEmergencyAnimator.destroy(); - mPseudoEmergencyAnimator = null; + if (pseudoEmergencyAnimator != null) { + pseudoEmergencyAnimator.destroy(); + pseudoEmergencyAnimator = null; } - getActivity().unregisterReceiver(mCallStateReceiver); + getActivity().unregisterReceiver(callStateReceiver); } private void keyPressed(int keyCode) { @@ -819,12 +818,12 @@ public class DialpadFragment extends Fragment getView().performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY); KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); - mDigits.onKeyDown(keyCode, event); + digits.onKeyDown(keyCode, event); // If the cursor is at the end of the text we hide it. - final int length = mDigits.length(); - if (length == mDigits.getSelectionStart() && length == mDigits.getSelectionEnd()) { - mDigits.setCursorVisible(false); + final int length = digits.length(); + if (length == digits.getSelectionStart() && length == digits.getSelectionEnd()) { + digits.setCursorVisible(false); } } @@ -877,10 +876,10 @@ public class DialpadFragment extends Fragment LogUtil.e( "DialpadFragment.onPressed", "Unexpected onTouch(ACTION_DOWN) event from: " + view); } - mPressedDialpadKeys.add(view); + pressedDialpadKeys.add(view); } else { - mPressedDialpadKeys.remove(view); - if (mPressedDialpadKeys.isEmpty()) { + pressedDialpadKeys.remove(view); + if (pressedDialpadKeys.isEmpty()) { stopTone(); } } @@ -925,10 +924,10 @@ public class DialpadFragment extends Fragment keyPressed(KeyEvent.KEYCODE_DEL); } else if (resId == R.id.digits) { if (!isDigitsEmpty()) { - mDigits.setCursorVisible(true); + digits.setCursorVisible(true); } } else if (resId == R.id.dialpad_overflow) { - mOverflowPopupMenu.show(); + overflowPopupMenu.show(); } else { LogUtil.w("DialpadFragment.onClick", "Unexpected event from: " + view); } @@ -936,13 +935,13 @@ public class DialpadFragment extends Fragment @Override public boolean onLongClick(View view) { - final Editable digits = mDigits.getText(); + final Editable digits = this.digits.getText(); final int id = view.getId(); if (id == R.id.deleteButton) { digits.clear(); return true; } else if (id == R.id.one) { - if (isDigitsEmpty() || TextUtils.equals(mDigits.getText(), "1")) { + if (isDigitsEmpty() || TextUtils.equals(this.digits.getText(), "1")) { // We'll try to initiate voicemail and thus we want to remove irrelevant string. removePreviousDigitIfPossible('1'); @@ -981,7 +980,7 @@ public class DialpadFragment extends Fragment } return false; } else if (id == R.id.zero) { - if (mPressedDialpadKeys.contains(view)) { + if (pressedDialpadKeys.contains(view)) { // If the zero key is currently pressed, then the long press occurred by touch // (and not via other means like certain accessibility input methods). // Remove the '0' that was input when the key was first pressed. @@ -989,10 +988,10 @@ public class DialpadFragment extends Fragment } keyPressed(KeyEvent.KEYCODE_PLUS); stopTone(); - mPressedDialpadKeys.remove(view); + pressedDialpadKeys.remove(view); return true; } else if (id == R.id.digits) { - mDigits.setCursorVisible(true); + this.digits.setCursorVisible(true); return false; } return false; @@ -1006,10 +1005,10 @@ public class DialpadFragment extends Fragment * @param digit to remove from the digits view. */ private void removePreviousDigitIfPossible(char digit) { - final int currentPosition = mDigits.getSelectionStart(); - if (currentPosition > 0 && digit == mDigits.getText().charAt(currentPosition - 1)) { - mDigits.setSelection(currentPosition); - mDigits.getText().delete(currentPosition - 1, currentPosition); + final int currentPosition = digits.getSelectionStart(); + if (currentPosition > 0 && digit == digits.getText().charAt(currentPosition - 1)) { + digits.setSelection(currentPosition); + digits.getText().delete(currentPosition - 1, currentPosition); } } @@ -1044,14 +1043,14 @@ public class DialpadFragment extends Fragment PerformanceReport.recordClick(UiAction.Type.PRESS_CALL_BUTTON_WITHOUT_CALLING); handleDialButtonClickWithEmptyDigits(); } else { - final String number = mDigits.getText().toString(); + final String number = digits.getText().toString(); // "persist.radio.otaspdial" is a temporary hack needed for one carrier's automated // test equipment. // TODO: clean it up. if (number != null - && !TextUtils.isEmpty(mProhibitedPhoneNumberRegexp) - && number.matches(mProhibitedPhoneNumberRegexp)) { + && !TextUtils.isEmpty(prohibitedPhoneNumberRegexp) + && number.matches(prohibitedPhoneNumberRegexp)) { PerformanceReport.recordClick(UiAction.Type.PRESS_CALL_BUTTON_WITHOUT_CALLING); LogUtil.i( "DialpadFragment.handleDialButtonPressed", @@ -1072,8 +1071,8 @@ public class DialpadFragment extends Fragment } public void clearDialpad() { - if (mDigits != null) { - mDigits.getText().clear(); + if (digits != null) { + digits.getText().clear(); } } @@ -1086,13 +1085,13 @@ public class DialpadFragment extends Fragment // the redial feature. startActivity(newFlashIntent()); } else { - if (!TextUtils.isEmpty(mLastNumberDialed)) { + if (!TextUtils.isEmpty(lastNumberDialed)) { // Dialpad will be filled with last called number, // but we don't want to record it as user action PerformanceReport.setIgnoreActionOnce(UiAction.Type.TEXT_CHANGE_WITH_INPUT); // Recall the last number dialed. - mDigits.setText(mLastNumberDialed); + digits.setText(lastNumberDialed); // ...and move the cursor to the end of the digits string, // so you'll be able to delete digits using the Delete @@ -1102,7 +1101,7 @@ public class DialpadFragment extends Fragment // mLastNumberDialed.length(), since the EditText widget now // contains a *formatted* version of mLastNumberDialed (due to // mTextWatcher) and its length may have changed. - mDigits.setSelection(mDigits.getText().length()); + digits.setSelection(digits.getText().length()); } else { // There's no "last number dialed" or the // background query is still running. There's @@ -1135,7 +1134,7 @@ public class DialpadFragment extends Fragment */ private void playTone(int tone, int durationMs) { // if local tone playback is disabled, just return. - if (!mDTMFToneEnabled) { + if (!dTMFToneEnabled) { return; } @@ -1152,29 +1151,29 @@ public class DialpadFragment extends Fragment return; } - synchronized (mToneGeneratorLock) { - if (mToneGenerator == null) { + synchronized (toneGeneratorLock) { + if (toneGenerator == null) { LogUtil.w("DialpadFragment.playTone", "mToneGenerator == null, tone: " + tone); return; } // Start the new tone (will stop any playing tone) - mToneGenerator.startTone(tone, durationMs); + toneGenerator.startTone(tone, durationMs); } } /** Stop the tone if it is played. */ private void stopTone() { // if local tone playback is disabled, just return. - if (!mDTMFToneEnabled) { + if (!dTMFToneEnabled) { return; } - synchronized (mToneGeneratorLock) { - if (mToneGenerator == null) { + synchronized (toneGeneratorLock) { + if (toneGenerator == null) { LogUtil.w("DialpadFragment.stopTone", "mToneGenerator == null"); return; } - mToneGenerator.stopTone(); + toneGenerator.stopTone(); } } @@ -1202,48 +1201,48 @@ public class DialpadFragment extends Fragment if (enabled) { LogUtil.i("DialpadFragment.showDialpadChooser", "Showing dialpad chooser!"); - if (mDialpadView != null) { - mDialpadView.setVisibility(View.GONE); + if (dialpadView != null) { + dialpadView.setVisibility(View.GONE); } - if (mOverflowPopupMenu != null) { - mOverflowPopupMenu.dismiss(); + if (overflowPopupMenu != null) { + overflowPopupMenu.dismiss(); } - mFloatingActionButtonController.scaleOut(); - mDialpadChooser.setVisibility(View.VISIBLE); + floatingActionButtonController.scaleOut(); + dialpadChooser.setVisibility(View.VISIBLE); // Instantiate the DialpadChooserAdapter and hook it up to the // ListView. We do this only once. - if (mDialpadChooserAdapter == null) { - mDialpadChooserAdapter = new DialpadChooserAdapter(getActivity()); + if (dialpadChooserAdapter == null) { + dialpadChooserAdapter = new DialpadChooserAdapter(getActivity()); } - mDialpadChooser.setAdapter(mDialpadChooserAdapter); + dialpadChooser.setAdapter(dialpadChooserAdapter); } else { LogUtil.i("DialpadFragment.showDialpadChooser", "Displaying normal Dialer UI."); - if (mDialpadView != null) { + if (dialpadView != null) { LogUtil.i("DialpadFragment.showDialpadChooser", "mDialpadView not null"); - mDialpadView.setVisibility(View.VISIBLE); - mFloatingActionButtonController.scaleIn(); + dialpadView.setVisibility(View.VISIBLE); + floatingActionButtonController.scaleIn(); } else { LogUtil.i("DialpadFragment.showDialpadChooser", "mDialpadView null"); - mDigits.setVisibility(View.VISIBLE); + digits.setVisibility(View.VISIBLE); } // mFloatingActionButtonController must also be 'scaled in', in order to be visible after // 'scaleOut()' hidden method. - if (!mFloatingActionButtonController.isVisible()) { + if (!floatingActionButtonController.isVisible()) { // Just call 'scaleIn()' method if the mFloatingActionButtonController was not already // previously visible. - mFloatingActionButtonController.scaleIn(); + floatingActionButtonController.scaleIn(); } - mDialpadChooser.setVisibility(View.GONE); + dialpadChooser.setVisibility(View.GONE); } } /** @return true if we're currently showing the "dialpad chooser" UI. */ private boolean isDialpadChooserVisible() { - return mDialpadChooser.getVisibility() == View.VISIBLE; + return dialpadChooser.getVisibility() == View.VISIBLE; } /** Handle clicks from the dialpad chooser. */ @@ -1310,7 +1309,7 @@ public class DialpadFragment extends Fragment updateDialString(WAIT); return true; } else if (resId == R.id.menu_call_with_note) { - CallSubjectDialog.start(getActivity(), mDigits.getText().toString()); + CallSubjectDialog.start(getActivity(), digits.getText().toString()); hideAndClearDialpad(); return true; } else { @@ -1330,24 +1329,24 @@ public class DialpadFragment extends Fragment int selectionEnd; // SpannableStringBuilder editable_text = new SpannableStringBuilder(mDigits.getText()); - int anchor = mDigits.getSelectionStart(); - int point = mDigits.getSelectionEnd(); + int anchor = this.digits.getSelectionStart(); + int point = this.digits.getSelectionEnd(); selectionStart = Math.min(anchor, point); selectionEnd = Math.max(anchor, point); if (selectionStart == -1) { - selectionStart = selectionEnd = mDigits.length(); + selectionStart = selectionEnd = this.digits.length(); } - Editable digits = mDigits.getText(); + Editable digits = this.digits.getText(); if (canAddDigit(digits, selectionStart, selectionEnd, newDigit)) { digits.replace(selectionStart, selectionEnd, Character.toString(newDigit)); if (selectionStart != selectionEnd) { // Unselect: back to a regular cursor, just pass the character inserted. - mDigits.setSelection(selectionStart + 1); + this.digits.setSelection(selectionStart + 1); } } } @@ -1358,7 +1357,7 @@ public class DialpadFragment extends Fragment return; } final boolean digitsNotEmpty = !isDigitsEmpty(); - mDelete.setEnabled(digitsNotEmpty); + delete.setEnabled(digitsNotEmpty); } /** @@ -1369,11 +1368,11 @@ public class DialpadFragment extends Fragment * @param transitionIn True if transitioning in, False if transitioning out */ private void updateMenuOverflowButton(boolean transitionIn) { - mOverflowMenuButton = mDialpadView.getOverflowMenuButton(); + overflowMenuButton = dialpadView.getOverflowMenuButton(); if (transitionIn) { - AnimUtils.fadeIn(mOverflowMenuButton, AnimUtils.DEFAULT_DURATION); + AnimUtils.fadeIn(overflowMenuButton, AnimUtils.DEFAULT_DURATION); } else { - AnimUtils.fadeOut(mOverflowMenuButton, AnimUtils.DEFAULT_DURATION); + AnimUtils.fadeOut(overflowMenuButton, AnimUtils.DEFAULT_DURATION); } } @@ -1406,7 +1405,7 @@ public class DialpadFragment extends Fragment /** @return true if the widget with the phone number digits is empty. */ private boolean isDigitsEmpty() { - return mDigits.length() == 0; + return digits.length() == 0; } /** @@ -1415,7 +1414,7 @@ public class DialpadFragment extends Fragment * yet. */ private void queryLastOutgoingCall() { - mLastNumberDialed = EMPTY_NUMBER; + lastNumberDialed = EMPTY_NUMBER; if (!PermissionsUtil.hasCallLogReadPermissions(getContext())) { return; } @@ -1429,7 +1428,7 @@ public class DialpadFragment extends Fragment if (getActivity() == null) { return; } - mLastNumberDialed = number; + lastNumberDialed = number; updateDeleteButtonEnabledState(); }); } @@ -1447,30 +1446,30 @@ public class DialpadFragment extends Fragment return; } if (!hidden && !isDialpadChooserVisible()) { - if (mAnimate) { - mDialpadView.animateShow(); + if (animate) { + dialpadView.animateShow(); } ThreadUtil.getUiThreadHandler() .postDelayed( () -> { if (!isDialpadChooserVisible()) { - mFloatingActionButtonController.scaleIn(); + floatingActionButtonController.scaleIn(); } }, - mAnimate ? mDialpadSlideInDuration : 0); + animate ? dialpadSlideInDuration : 0); FragmentUtils.getParentUnsafe(this, DialpadListener.class).onDialpadShown(); - mDigits.requestFocus(); + digits.requestFocus(); } else if (hidden) { - mFloatingActionButtonController.scaleOut(); + floatingActionButtonController.scaleOut(); } } public boolean getAnimate() { - return mAnimate; + return animate; } public void setAnimate(boolean value) { - mAnimate = value; + animate = value; } public void setYFraction(float yFraction) { @@ -1478,21 +1477,21 @@ public class DialpadFragment extends Fragment } public int getDialpadHeight() { - if (mDialpadView == null) { + if (dialpadView == null) { return 0; } - return mDialpadView.getHeight(); + return dialpadView.getHeight(); } public void process_quote_emergency_unquote(String query) { if (PseudoEmergencyAnimator.PSEUDO_EMERGENCY_NUMBER.equals(query)) { - if (mPseudoEmergencyAnimator == null) { - mPseudoEmergencyAnimator = + if (pseudoEmergencyAnimator == null) { + pseudoEmergencyAnimator = new PseudoEmergencyAnimator( new PseudoEmergencyAnimator.ViewProvider() { @Override public View getFab() { - return mFloatingActionButton; + return floatingActionButton; } @Override @@ -1501,10 +1500,10 @@ public class DialpadFragment extends Fragment } }); } - mPseudoEmergencyAnimator.start(); + pseudoEmergencyAnimator.start(); } else { - if (mPseudoEmergencyAnimator != null) { - mPseudoEmergencyAnimator.end(); + if (pseudoEmergencyAnimator != null) { + pseudoEmergencyAnimator.end(); } } } @@ -1561,8 +1560,8 @@ public class DialpadFragment extends Fragment private static final String ARG_TITLE_RES_ID = "argTitleResId"; private static final String ARG_MESSAGE_RES_ID = "argMessageResId"; - private int mTitleResId; - private int mMessageResId; + private int titleResId; + private int messageResId; public static ErrorDialogFragment newInstance(int messageResId) { return newInstance(0, messageResId); @@ -1580,18 +1579,18 @@ public class DialpadFragment extends Fragment @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mTitleResId = getArguments().getInt(ARG_TITLE_RES_ID); - mMessageResId = getArguments().getInt(ARG_MESSAGE_RES_ID); + titleResId = getArguments().getInt(ARG_TITLE_RES_ID); + messageResId = getArguments().getInt(ARG_MESSAGE_RES_ID); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - if (mTitleResId != 0) { - builder.setTitle(mTitleResId); + if (titleResId != 0) { + builder.setTitle(titleResId); } - if (mMessageResId != 0) { - builder.setMessage(mMessageResId); + if (messageResId != 0) { + builder.setMessage(messageResId); } builder.setPositiveButton(android.R.string.ok, (dialog, which) -> dismiss()); return builder.create(); @@ -1609,18 +1608,18 @@ public class DialpadFragment extends Fragment static final int DIALPAD_CHOICE_RETURN_TO_CALL = 102; static final int DIALPAD_CHOICE_ADD_NEW_CALL = 103; private static final int NUM_ITEMS = 3; - private LayoutInflater mInflater; - private ChoiceItem[] mChoiceItems = new ChoiceItem[NUM_ITEMS]; + private LayoutInflater inflater; + private ChoiceItem[] choiceItems = new ChoiceItem[NUM_ITEMS]; DialpadChooserAdapter(Context context) { // Cache the LayoutInflate to avoid asking for a new one each time. - mInflater = LayoutInflater.from(context); + inflater = LayoutInflater.from(context); // Initialize the possible choices. // TODO: could this be specified entirely in XML? // - "Use touch tone keypad" - mChoiceItems[0] = + choiceItems[0] = new ChoiceItem( context.getString(R.string.dialer_useDtmfDialpad), BitmapFactory.decodeResource( @@ -1628,7 +1627,7 @@ public class DialpadFragment extends Fragment DIALPAD_CHOICE_USE_DTMF_DIALPAD); // - "Return to call in progress" - mChoiceItems[1] = + choiceItems[1] = new ChoiceItem( context.getString(R.string.dialer_returnToInCallScreen), BitmapFactory.decodeResource( @@ -1636,7 +1635,7 @@ public class DialpadFragment extends Fragment DIALPAD_CHOICE_RETURN_TO_CALL); // - "Add call" - mChoiceItems[2] = + choiceItems[2] = new ChoiceItem( context.getString(R.string.dialer_addAnotherCall), BitmapFactory.decodeResource( @@ -1652,7 +1651,7 @@ public class DialpadFragment extends Fragment /** Return the ChoiceItem for a given position. */ @Override public Object getItem(int position) { - return mChoiceItems[position]; + return choiceItems[position]; } /** Return a unique ID for each possible choice. */ @@ -1667,14 +1666,14 @@ public class DialpadFragment extends Fragment // When convertView is non-null, we can reuse it (there's no need // to reinflate it.) if (convertView == null) { - convertView = mInflater.inflate(R.layout.dialpad_chooser_list_item, null); + convertView = inflater.inflate(R.layout.dialpad_chooser_list_item, null); } TextView text = convertView.findViewById(R.id.text); - text.setText(mChoiceItems[position].text); + text.setText(choiceItems[position].text); ImageView icon = convertView.findViewById(R.id.icon); - icon.setImageBitmap(mChoiceItems[position].icon); + icon.setImageBitmap(choiceItems[position].icon); return convertView; } diff --git a/java/com/android/dialer/dialpadview/DialpadKeyButton.java b/java/com/android/dialer/dialpadview/DialpadKeyButton.java index 0c842ebb5..84aca14f2 100644 --- a/java/com/android/dialer/dialpadview/DialpadKeyButton.java +++ b/java/com/android/dialer/dialpadview/DialpadKeyButton.java @@ -49,30 +49,30 @@ public class DialpadKeyButton extends FrameLayout { private static final int LONG_HOVER_TIMEOUT = ViewConfiguration.getLongPressTimeout() * 2; /** Accessibility manager instance used to check touch exploration state. */ - private AccessibilityManager mAccessibilityManager; + private AccessibilityManager accessibilityManager; /** Bounds used to filter HOVER_EXIT events. */ - private RectF mHoverBounds = new RectF(); + private RectF hoverBounds = new RectF(); /** Whether this view is currently in the long-hover state. */ - private boolean mLongHovered; + private boolean longHovered; /** Alternate content description for long-hover state. */ - private CharSequence mLongHoverContentDesc; + private CharSequence longHoverContentDesc; /** Backup of standard content description. Used for accessibility. */ - private CharSequence mBackupContentDesc; + private CharSequence backupContentDesc; /** Backup of clickable property. Used for accessibility. */ - private boolean mWasClickable; + private boolean wasClickable; /** Backup of long-clickable property. Used for accessibility. */ - private boolean mWasLongClickable; + private boolean wasLongClickable; /** Runnable used to trigger long-click mode for accessibility. */ - private Runnable mLongHoverRunnable; + private Runnable longHoverRunnable; - private OnPressedListener mOnPressedListener; + private OnPressedListener onPressedListener; public DialpadKeyButton(Context context, AttributeSet attrs) { super(context, attrs); @@ -85,26 +85,26 @@ public class DialpadKeyButton extends FrameLayout { } public void setOnPressedListener(OnPressedListener onPressedListener) { - mOnPressedListener = onPressedListener; + this.onPressedListener = onPressedListener; } private void initForAccessibility(Context context) { - mAccessibilityManager = + accessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); } public void setLongHoverContentDescription(CharSequence contentDescription) { - mLongHoverContentDesc = contentDescription; + longHoverContentDesc = contentDescription; - if (mLongHovered) { - super.setContentDescription(mLongHoverContentDesc); + if (longHovered) { + super.setContentDescription(longHoverContentDesc); } } @Override public void setContentDescription(CharSequence contentDescription) { - if (mLongHovered) { - mBackupContentDesc = contentDescription; + if (longHovered) { + backupContentDesc = contentDescription; } else { super.setContentDescription(contentDescription); } @@ -113,8 +113,8 @@ public class DialpadKeyButton extends FrameLayout { @Override public void setPressed(boolean pressed) { super.setPressed(pressed); - if (mOnPressedListener != null) { - mOnPressedListener.onPressed(this, pressed); + if (onPressedListener != null) { + onPressedListener.onPressed(this, pressed); } } @@ -122,10 +122,10 @@ public class DialpadKeyButton extends FrameLayout { public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); - mHoverBounds.left = getPaddingLeft(); - mHoverBounds.right = w - getPaddingRight(); - mHoverBounds.top = getPaddingTop(); - mHoverBounds.bottom = h - getPaddingBottom(); + hoverBounds.left = getPaddingLeft(); + hoverBounds.right = w - getPaddingRight(); + hoverBounds.top = getPaddingTop(); + hoverBounds.bottom = h - getPaddingBottom(); } @Override @@ -142,37 +142,37 @@ public class DialpadKeyButton extends FrameLayout { public boolean onHoverEvent(MotionEvent event) { // When touch exploration is turned on, lifting a finger while inside // the button's hover target bounds should perform a click action. - if (mAccessibilityManager.isEnabled() && mAccessibilityManager.isTouchExplorationEnabled()) { + if (accessibilityManager.isEnabled() && accessibilityManager.isTouchExplorationEnabled()) { switch (event.getActionMasked()) { case MotionEvent.ACTION_HOVER_ENTER: // Lift-to-type temporarily disables double-tap activation. - mWasClickable = isClickable(); - mWasLongClickable = isLongClickable(); - if (mWasLongClickable && mLongHoverContentDesc != null) { - if (mLongHoverRunnable == null) { - mLongHoverRunnable = + wasClickable = isClickable(); + wasLongClickable = isLongClickable(); + if (wasLongClickable && longHoverContentDesc != null) { + if (longHoverRunnable == null) { + longHoverRunnable = new Runnable() { @Override public void run() { setLongHovered(true); - announceForAccessibility(mLongHoverContentDesc); + announceForAccessibility(longHoverContentDesc); } }; } - postDelayed(mLongHoverRunnable, LONG_HOVER_TIMEOUT); + postDelayed(longHoverRunnable, LONG_HOVER_TIMEOUT); } setClickable(false); setLongClickable(false); break; case MotionEvent.ACTION_HOVER_EXIT: - if (mHoverBounds.contains(event.getX(), event.getY())) { + if (hoverBounds.contains(event.getX(), event.getY())) { simulateClickForAccessibility(); } cancelLongHover(); - setClickable(mWasClickable); - setLongClickable(mWasLongClickable); + setClickable(wasClickable); + setLongClickable(wasLongClickable); break; default: // No-op break; @@ -202,22 +202,22 @@ public class DialpadKeyButton extends FrameLayout { } private void setLongHovered(boolean enabled) { - if (mLongHovered != enabled) { - mLongHovered = enabled; + if (longHovered != enabled) { + longHovered = enabled; // Switch between normal and alternate description, if available. if (enabled) { - mBackupContentDesc = getContentDescription(); - super.setContentDescription(mLongHoverContentDesc); + backupContentDesc = getContentDescription(); + super.setContentDescription(longHoverContentDesc); } else { - super.setContentDescription(mBackupContentDesc); + super.setContentDescription(backupContentDesc); } } } private void cancelLongHover() { - if (mLongHoverRunnable != null) { - removeCallbacks(mLongHoverRunnable); + if (longHoverRunnable != null) { + removeCallbacks(longHoverRunnable); } setLongHovered(false); } diff --git a/java/com/android/dialer/dialpadview/DialpadTextView.java b/java/com/android/dialer/dialpadview/DialpadTextView.java index b1eee4b9c..9607195cd 100644 --- a/java/com/android/dialer/dialpadview/DialpadTextView.java +++ b/java/com/android/dialer/dialpadview/DialpadTextView.java @@ -33,8 +33,8 @@ import android.widget.TextView; */ public class DialpadTextView extends TextView { - private Rect mTextBounds = new Rect(); - private String mTextStr; + private Rect textBounds = new Rect(); + private String textStr; public DialpadTextView(Context context, AttributeSet attrs) { super(context, attrs); @@ -51,7 +51,7 @@ public class DialpadTextView extends TextView { // The text bounds values are relative and can be negative,, so rather than specifying a // standard origin such as 0, 0, we need to use negative of the left/top bounds. // For example, the bounds may be: Left: 11, Right: 37, Top: -77, Bottom: 0 - canvas.drawText(mTextStr, -mTextBounds.left, -mTextBounds.top, paint); + canvas.drawText(textStr, -textBounds.left, -textBounds.top, paint); } /** @@ -61,11 +61,11 @@ public class DialpadTextView extends TextView { @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); - mTextStr = getText().toString(); - getPaint().getTextBounds(mTextStr, 0, mTextStr.length(), mTextBounds); + textStr = getText().toString(); + getPaint().getTextBounds(textStr, 0, textStr.length(), textBounds); - int width = resolveSize(mTextBounds.width(), widthMeasureSpec); - int height = resolveSize(mTextBounds.height(), heightMeasureSpec); + int width = resolveSize(textBounds.width(), widthMeasureSpec); + int height = resolveSize(textBounds.height(), heightMeasureSpec); setMeasuredDimension(width, height); } } diff --git a/java/com/android/dialer/dialpadview/DialpadView.java b/java/com/android/dialer/dialpadview/DialpadView.java index 7b95ba7ea..58ba233bd 100644 --- a/java/com/android/dialer/dialpadview/DialpadView.java +++ b/java/com/android/dialer/dialpadview/DialpadView.java @@ -73,21 +73,21 @@ public class DialpadView extends LinearLayout { R.id.pound }; - private final AttributeSet mAttributeSet; - private final ColorStateList mRippleColor; - private final OnPreDrawListenerForKeyLayoutAdjust mOnPreDrawListenerForKeyLayoutAdjust; - private final String[] mPrimaryLettersMapping; - private final String[] mSecondaryLettersMapping; - private final boolean mIsRtl; // whether the dialpad is shown in a right-to-left locale - private final int mTranslateDistance; - - private EditText mDigits; - private ImageButton mDelete; - private View mOverflowMenuButton; - private ViewGroup mRateContainer; - private TextView mIldCountry; - private TextView mIldRate; - private boolean mIsLandscapeMode; + private final AttributeSet attributeSet; + private final ColorStateList rippleColor; + private final OnPreDrawListenerForKeyLayoutAdjust onPreDrawListenerForKeyLayoutAdjust; + private final String[] primaryLettersMapping; + private final String[] secondaryLettersMapping; + private final boolean isRtl; // whether the dialpad is shown in a right-to-left locale + private final int translateDistance; + + private EditText digits; + private ImageButton delete; + private View overflowMenuButton; + private ViewGroup rateContainer; + private TextView ildCountry; + private TextView ildRate; + private boolean isLandscapeMode; public DialpadView(Context context) { this(context, null); @@ -99,27 +99,27 @@ public class DialpadView extends LinearLayout { public DialpadView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - mAttributeSet = attrs; + attributeSet = attrs; TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Dialpad); - mRippleColor = a.getColorStateList(R.styleable.Dialpad_dialpad_key_button_touch_tint); + rippleColor = a.getColorStateList(R.styleable.Dialpad_dialpad_key_button_touch_tint); a.recycle(); - mTranslateDistance = + translateDistance = getResources().getDimensionPixelSize(R.dimen.dialpad_key_button_translate_y); - mIsRtl = + isRtl = TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL; - mPrimaryLettersMapping = DialpadCharMappings.getDefaultKeyToCharsMap(); - mSecondaryLettersMapping = DialpadCharMappings.getKeyToCharsMap(context); + primaryLettersMapping = DialpadCharMappings.getDefaultKeyToCharsMap(); + secondaryLettersMapping = DialpadCharMappings.getKeyToCharsMap(context); - mOnPreDrawListenerForKeyLayoutAdjust = new OnPreDrawListenerForKeyLayoutAdjust(); + onPreDrawListenerForKeyLayoutAdjust = new OnPreDrawListenerForKeyLayoutAdjust(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); - getViewTreeObserver().removeOnPreDrawListener(mOnPreDrawListenerForKeyLayoutAdjust); + getViewTreeObserver().removeOnPreDrawListener(onPreDrawListenerForKeyLayoutAdjust); } @Override @@ -129,28 +129,28 @@ public class DialpadView extends LinearLayout { // The orientation obtained at this point should be used as the only truth for DialpadView as we // observed inconsistency between configurations obtained here and in // OnPreDrawListenerForKeyLayoutAdjust under rare circumstances. - mIsLandscapeMode = + isLandscapeMode = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE); setupKeypad(); - mDigits = (EditText) findViewById(R.id.digits); - mDelete = (ImageButton) findViewById(R.id.deleteButton); - mOverflowMenuButton = findViewById(R.id.dialpad_overflow); - mRateContainer = (ViewGroup) findViewById(R.id.rate_container); - mIldCountry = (TextView) mRateContainer.findViewById(R.id.ild_country); - mIldRate = (TextView) mRateContainer.findViewById(R.id.ild_rate); + digits = (EditText) findViewById(R.id.digits); + delete = (ImageButton) findViewById(R.id.deleteButton); + overflowMenuButton = findViewById(R.id.dialpad_overflow); + rateContainer = (ViewGroup) findViewById(R.id.rate_container); + ildCountry = (TextView) rateContainer.findViewById(R.id.ild_country); + ildRate = (TextView) rateContainer.findViewById(R.id.ild_rate); AccessibilityManager accessibilityManager = (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (accessibilityManager.isEnabled()) { // The text view must be selected to send accessibility events. - mDigits.setSelected(true); + digits.setSelected(true); } // As OnPreDrawListenerForKeyLayoutAdjust makes changes to LayoutParams, it is added here to // ensure it can only be triggered after the layout is inflated. - getViewTreeObserver().removeOnPreDrawListener(mOnPreDrawListenerForKeyLayoutAdjust); - getViewTreeObserver().addOnPreDrawListener(mOnPreDrawListenerForKeyLayoutAdjust); + getViewTreeObserver().removeOnPreDrawListener(onPreDrawListenerForKeyLayoutAdjust); + getViewTreeObserver().addOnPreDrawListener(onPreDrawListenerForKeyLayoutAdjust); } private void setupKeypad() { @@ -174,7 +174,7 @@ public class DialpadView extends LinearLayout { // The content description is used for Talkback key presses. The number is // separated by a "," to introduce a slight delay. Convert letters into a verbatim // span so that they are read as letters instead of as one word. - String letters = mPrimaryLettersMapping[i]; + String letters = primaryLettersMapping[i]; Spannable spannable = Spannable.Factory.getInstance().newSpannable(numberString + "," + letters); spannable.setSpan( @@ -187,8 +187,8 @@ public class DialpadView extends LinearLayout { final RippleDrawable rippleBackground = (RippleDrawable) getContext().getDrawable(R.drawable.btn_dialpad_key); - if (mRippleColor != null) { - rippleBackground.setColor(mRippleColor); + if (rippleColor != null) { + rippleBackground.setColor(rippleColor); } numberView.setText(numberString); @@ -200,20 +200,20 @@ public class DialpadView extends LinearLayout { TextView secondaryLettersView = (TextView) dialpadKey.findViewById(R.id.dialpad_key_secondary_letters); if (primaryLettersView != null) { - primaryLettersView.setText(mPrimaryLettersMapping[i]); + primaryLettersView.setText(primaryLettersMapping[i]); } if (primaryLettersView != null && secondaryLettersView != null) { - if (mSecondaryLettersMapping == null) { + if (secondaryLettersMapping == null) { secondaryLettersView.setVisibility(View.GONE); } else { secondaryLettersView.setVisibility(View.VISIBLE); - secondaryLettersView.setText(mSecondaryLettersMapping[i]); + secondaryLettersView.setText(secondaryLettersMapping[i]); // Adjust the font size of the letters if a secondary alphabet is available. TypedArray a = getContext() .getTheme() - .obtainStyledAttributes(mAttributeSet, R.styleable.Dialpad, 0, 0); + .obtainStyledAttributes(attributeSet, R.styleable.Dialpad, 0, 0); int textSize = a.getDimensionPixelSize( R.styleable.Dialpad_dialpad_key_letters_size_for_dual_alphabets, 0); @@ -260,12 +260,12 @@ public class DialpadView extends LinearLayout { public void setCallRateInformation(String countryName, String displayRate) { if (TextUtils.isEmpty(countryName) && TextUtils.isEmpty(displayRate)) { - mRateContainer.setVisibility(View.GONE); + rateContainer.setVisibility(View.GONE); return; } - mRateContainer.setVisibility(View.VISIBLE); - mIldCountry.setText(countryName); - mIldRate.setText(displayRate); + rateContainer.setVisibility(View.VISIBLE); + ildCountry.setText(countryName); + ildRate.setText(displayRate); } /** @@ -288,14 +288,14 @@ public class DialpadView extends LinearLayout { final DialpadKeyButton dialpadKey = (DialpadKeyButton) findViewById(BUTTON_IDS[i]); ViewPropertyAnimator animator = dialpadKey.animate(); - if (mIsLandscapeMode) { + if (isLandscapeMode) { // Landscape orientation requires translation along the X axis. // For RTL locales, ensure we translate negative on the X axis. - dialpadKey.setTranslationX((mIsRtl ? -1 : 1) * mTranslateDistance); + dialpadKey.setTranslationX((isRtl ? -1 : 1) * translateDistance); animator.translationX(0); } else { // Portrait orientation requires translation along the Y axis. - dialpadKey.setTranslationY(mTranslateDistance); + dialpadKey.setTranslationY(translateDistance); animator.translationY(0); } animator @@ -308,15 +308,15 @@ public class DialpadView extends LinearLayout { } public EditText getDigits() { - return mDigits; + return digits; } public ImageButton getDeleteButton() { - return mDelete; + return delete; } public View getOverflowMenuButton() { - return mOverflowMenuButton; + return overflowMenuButton; } /** @@ -327,8 +327,8 @@ public class DialpadView extends LinearLayout { * @return The animation delay. */ private int getKeyButtonAnimationDelay(int buttonId) { - if (mIsLandscapeMode) { - if (mIsRtl) { + if (isLandscapeMode) { + if (isRtl) { if (buttonId == R.id.three) { return KEY_FRAME_DURATION * 1; } else if (buttonId == R.id.six) { @@ -415,8 +415,8 @@ public class DialpadView extends LinearLayout { * @return The animation duration. */ private int getKeyButtonAnimationDuration(int buttonId) { - if (mIsLandscapeMode) { - if (mIsRtl) { + if (isLandscapeMode) { + if (isRtl) { if (buttonId == R.id.one || buttonId == R.id.four || buttonId == R.id.seven @@ -528,7 +528,7 @@ public class DialpadView extends LinearLayout { } private boolean shouldAdjustKeySizes() { - return mIsLandscapeMode ? shouldAdjustKeyWidths() : shouldAdjustDigitKeyHeights(); + return isLandscapeMode ? shouldAdjustKeyWidths() : shouldAdjustDigitKeyHeights(); } /** @@ -536,7 +536,7 @@ public class DialpadView extends LinearLayout { * device is in landscape mode. */ private boolean shouldAdjustKeyWidths() { - Assert.checkState(mIsLandscapeMode); + Assert.checkState(isLandscapeMode); DialpadKeyButton dialpadKeyButton = (DialpadKeyButton) findViewById(BUTTON_IDS[0]); LinearLayout keyLayout = @@ -559,7 +559,7 @@ public class DialpadView extends LinearLayout { * called when the device is in portrait mode. */ private boolean shouldAdjustDigitKeyHeights() { - Assert.checkState(!mIsLandscapeMode); + Assert.checkState(!isLandscapeMode); DialpadKeyButton dialpadKey = (DialpadKeyButton) findViewById(BUTTON_IDS[0]); LinearLayout keyLayout = (LinearLayout) dialpadKey.findViewById(R.id.dialpad_key_layout); @@ -579,7 +579,7 @@ public class DialpadView extends LinearLayout { } private void adjustKeySizes() { - if (mIsLandscapeMode) { + if (isLandscapeMode) { adjustKeyWidths(); } else { adjustDigitKeyHeights(); @@ -597,7 +597,7 @@ public class DialpadView extends LinearLayout { * LinearLayout#setLayoutParams(ViewGroup.LayoutParams)}. */ private void adjustDigitKeyHeights() { - Assert.checkState(!mIsLandscapeMode); + Assert.checkState(!isLandscapeMode); int maxHeight = 0; @@ -641,7 +641,7 @@ public class DialpadView extends LinearLayout { * View#setLayoutParams(ViewGroup.LayoutParams)}. */ private void adjustKeyWidths() { - Assert.checkState(mIsLandscapeMode); + Assert.checkState(isLandscapeMode); int maxWidth = 0; for (int buttonId : BUTTON_IDS) { diff --git a/java/com/android/dialer/dialpadview/PseudoEmergencyAnimator.java b/java/com/android/dialer/dialpadview/PseudoEmergencyAnimator.java index 16bdd24c1..f3442e6e3 100644 --- a/java/com/android/dialer/dialpadview/PseudoEmergencyAnimator.java +++ b/java/com/android/dialer/dialpadview/PseudoEmergencyAnimator.java @@ -35,40 +35,40 @@ public class PseudoEmergencyAnimator { private static final int VIBRATE_LENGTH_MILLIS = 200; private static final int ITERATION_LENGTH_MILLIS = 1000; private static final int ANIMATION_ITERATION_COUNT = 6; - private ViewProvider mViewProvider; - private ValueAnimator mPseudoEmergencyColorAnimator; + private ViewProvider viewProvider; + private ValueAnimator pseudoEmergencyColorAnimator; PseudoEmergencyAnimator(ViewProvider viewProvider) { - mViewProvider = viewProvider; + this.viewProvider = viewProvider; } public void destroy() { end(); - mViewProvider = null; + viewProvider = null; } public void start() { - if (mPseudoEmergencyColorAnimator == null) { + if (pseudoEmergencyColorAnimator == null) { Integer colorFrom = Color.BLUE; Integer colorTo = Color.RED; - mPseudoEmergencyColorAnimator = + pseudoEmergencyColorAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo); - mPseudoEmergencyColorAnimator.addUpdateListener( + pseudoEmergencyColorAnimator.addUpdateListener( animator -> { try { int color = (int) animator.getAnimatedValue(); ColorFilter colorFilter = new LightingColorFilter(Color.BLACK, color); - if (mViewProvider.getFab() != null) { - mViewProvider.getFab().getBackground().setColorFilter(colorFilter); + if (viewProvider.getFab() != null) { + viewProvider.getFab().getBackground().setColorFilter(colorFilter); } } catch (Exception e) { animator.cancel(); } }); - mPseudoEmergencyColorAnimator.addListener( + pseudoEmergencyColorAnimator.addListener( new AnimatorListener() { @Override public void onAnimationCancel(Animator animation) {} @@ -88,8 +88,8 @@ public class PseudoEmergencyAnimator { @Override public void onAnimationEnd(Animator animation) { try { - if (mViewProvider.getFab() != null) { - mViewProvider.getFab().getBackground().clearColorFilter(); + if (viewProvider.getFab() != null) { + viewProvider.getFab().getBackground().clearColorFilter(); } new Handler() @@ -108,23 +108,23 @@ public class PseudoEmergencyAnimator { } }); - mPseudoEmergencyColorAnimator.setDuration(VIBRATE_LENGTH_MILLIS); - mPseudoEmergencyColorAnimator.setRepeatMode(ValueAnimator.REVERSE); - mPseudoEmergencyColorAnimator.setRepeatCount(ANIMATION_ITERATION_COUNT); + pseudoEmergencyColorAnimator.setDuration(VIBRATE_LENGTH_MILLIS); + pseudoEmergencyColorAnimator.setRepeatMode(ValueAnimator.REVERSE); + pseudoEmergencyColorAnimator.setRepeatCount(ANIMATION_ITERATION_COUNT); } - if (!mPseudoEmergencyColorAnimator.isStarted()) { - mPseudoEmergencyColorAnimator.start(); + if (!pseudoEmergencyColorAnimator.isStarted()) { + pseudoEmergencyColorAnimator.start(); } } public void end() { - if (mPseudoEmergencyColorAnimator != null && mPseudoEmergencyColorAnimator.isStarted()) { - mPseudoEmergencyColorAnimator.end(); + if (pseudoEmergencyColorAnimator != null && pseudoEmergencyColorAnimator.isStarted()) { + pseudoEmergencyColorAnimator.end(); } } private void vibrate(long milliseconds) { - Context context = mViewProvider.getContext(); + Context context = viewProvider.getContext(); if (context != null) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); if (vibrator != null) { diff --git a/java/com/android/dialer/dialpadview/SpecialCharSequenceMgr.java b/java/com/android/dialer/dialpadview/SpecialCharSequenceMgr.java index 7ff0d084a..e6d405ccf 100644 --- a/java/com/android/dialer/dialpadview/SpecialCharSequenceMgr.java +++ b/java/com/android/dialer/dialpadview/SpecialCharSequenceMgr.java @@ -92,7 +92,7 @@ public class SpecialCharSequenceMgr { * Phone side doesn't have this functionality. Fundamental fix would be to have one shared * implementation and resolve this corner case more gracefully. */ - private static QueryHandler sPreviousAdnQueryHandler; + private static QueryHandler previousAdnQueryHandler; /** This class is never instantiated. */ private SpecialCharSequenceMgr() {} @@ -124,9 +124,9 @@ public class SpecialCharSequenceMgr { public static void cleanup() { Assert.isMainThread(); - if (sPreviousAdnQueryHandler != null) { - sPreviousAdnQueryHandler.cancel(); - sPreviousAdnQueryHandler = null; + if (previousAdnQueryHandler != null) { + previousAdnQueryHandler.cancel(); + previousAdnQueryHandler = null; } } @@ -255,11 +255,11 @@ public class SpecialCharSequenceMgr { null, null); - if (sPreviousAdnQueryHandler != null) { + if (previousAdnQueryHandler != null) { // It is harmless to call cancel() even after the handler's gone. - sPreviousAdnQueryHandler.cancel(); + previousAdnQueryHandler.cancel(); } - sPreviousAdnQueryHandler = handler; + previousAdnQueryHandler = handler; } static boolean handlePinEntry(final Context context, final String input) { @@ -343,40 +343,40 @@ public class SpecialCharSequenceMgr { public static class HandleAdnEntryAccountSelectedCallback extends SelectPhoneAccountListener { - private final Context mContext; - private final QueryHandler mQueryHandler; - private final SimContactQueryCookie mCookie; + private final Context context; + private final QueryHandler queryHandler; + private final SimContactQueryCookie cookie; public HandleAdnEntryAccountSelectedCallback( Context context, QueryHandler queryHandler, SimContactQueryCookie cookie) { - mContext = context; - mQueryHandler = queryHandler; - mCookie = cookie; + this.context = context; + this.queryHandler = queryHandler; + this.cookie = cookie; } @Override public void onPhoneAccountSelected( PhoneAccountHandle selectedAccountHandle, boolean setDefault, @Nullable String callId) { - Uri uri = TelecomUtil.getAdnUriForPhoneAccount(mContext, selectedAccountHandle); - handleAdnQuery(mQueryHandler, mCookie, uri); + Uri uri = TelecomUtil.getAdnUriForPhoneAccount(context, selectedAccountHandle); + handleAdnQuery(queryHandler, cookie, uri); // TODO: Show error dialog if result isn't valid. } } public static class HandleMmiAccountSelectedCallback extends SelectPhoneAccountListener { - private final Context mContext; - private final String mInput; + private final Context context; + private final String input; public HandleMmiAccountSelectedCallback(Context context, String input) { - mContext = context.getApplicationContext(); - mInput = input; + this.context = context.getApplicationContext(); + this.input = input; } @Override public void onPhoneAccountSelected( PhoneAccountHandle selectedAccountHandle, boolean setDefault, @Nullable String callId) { - TelecomUtil.handleMmi(mContext, mInput, selectedAccountHandle); + TelecomUtil.handleMmi(context, input, selectedAccountHandle); } } @@ -393,16 +393,16 @@ public class SpecialCharSequenceMgr { public int contactNum; // Used to identify the query request. - private int mToken; - private QueryHandler mHandler; + private int token; + private QueryHandler handler; // The text field we're going to update private EditText textField; public SimContactQueryCookie(int number, QueryHandler handler, int token) { contactNum = number; - mHandler = handler; - mToken = token; + this.handler = handler; + this.token = token; } /** Synchronized getter for the EditText. */ @@ -431,7 +431,7 @@ public class SpecialCharSequenceMgr { textField = null; // Cancel the operation if possible. - mHandler.cancelOperation(mToken); + handler.cancelOperation(token); } } @@ -442,7 +442,7 @@ public class SpecialCharSequenceMgr { */ private static class QueryHandler extends NoNullCursorAsyncQueryHandler { - private boolean mCanceled; + private boolean canceled; public QueryHandler(ContentResolver cr) { super(cr); @@ -452,8 +452,8 @@ public class SpecialCharSequenceMgr { @Override protected void onNotNullableQueryComplete(int token, Object cookie, Cursor c) { try { - sPreviousAdnQueryHandler = null; - if (mCanceled) { + previousAdnQueryHandler = null; + if (canceled) { return; } @@ -488,7 +488,7 @@ public class SpecialCharSequenceMgr { } public void cancel() { - mCanceled = true; + canceled = true; // Ask AsyncQueryHandler to cancel the whole request. This will fail when the query is // already started. cancelOperation(ADN_QUERY_TOKEN); diff --git a/java/com/android/dialer/interactions/PhoneNumberInteraction.java b/java/com/android/dialer/interactions/PhoneNumberInteraction.java index 5a6c34607..27ade1905 100644 --- a/java/com/android/dialer/interactions/PhoneNumberInteraction.java +++ b/java/com/android/dialer/interactions/PhoneNumberInteraction.java @@ -113,12 +113,12 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { + Data.DATA1 + " NOT NULL"; private static final int UNKNOWN_CONTACT_ID = -1; - private final Context mContext; - private final int mInteractionType; - private final CallSpecificAppData mCallSpecificAppData; - private long mContactId = UNKNOWN_CONTACT_ID; - private CursorLoader mLoader; - private boolean mIsVideoCall; + private final Context context; + private final int interactionType; + private final CallSpecificAppData callSpecificAppData; + private long contactId = UNKNOWN_CONTACT_ID; + private CursorLoader loader; + private boolean isVideoCall; /** Error codes for interactions. */ @Retention(RetentionPolicy.SOURCE) @@ -161,10 +161,10 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { int interactionType, boolean isVideoCall, CallSpecificAppData callSpecificAppData) { - mContext = context; - mInteractionType = interactionType; - mCallSpecificAppData = callSpecificAppData; - mIsVideoCall = isVideoCall; + this.context = context; + this.interactionType = interactionType; + this.callSpecificAppData = callSpecificAppData; + this.isVideoCall = isVideoCall; Assert.checkArgument(context instanceof InteractionErrorListener); Assert.checkArgument(context instanceof DisambigDialogDismissedListener); @@ -213,7 +213,7 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { private void performAction(String phoneNumber) { PhoneNumberInteraction.performAction( - mContext, phoneNumber, mInteractionType, mIsVideoCall, mCallSpecificAppData); + context, phoneNumber, interactionType, isVideoCall, callSpecificAppData); } /** @@ -225,27 +225,27 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { // It's possible for a shortcut to have been created, and then permissions revoked. To avoid a // crash when the user tries to use such a shortcut, check for this condition and ask the user // for the permission. - if (!PermissionsUtil.hasPhonePermissions(mContext)) { + if (!PermissionsUtil.hasPhonePermissions(context)) { LogUtil.i("PhoneNumberInteraction.startInteraction", "Need phone permission: CALL_PHONE"); ActivityCompat.requestPermissions( - (Activity) mContext, new String[] {permission.CALL_PHONE}, REQUEST_CALL_PHONE); + (Activity) context, new String[] {permission.CALL_PHONE}, REQUEST_CALL_PHONE); return; } String[] deniedContactsPermissions = PermissionsUtil.getPermissionsCurrentlyDenied( - mContext, PermissionsUtil.allContactsGroupPermissionsUsedInDialer); + context, PermissionsUtil.allContactsGroupPermissionsUsedInDialer); if (deniedContactsPermissions.length > 0) { LogUtil.i( "PhoneNumberInteraction.startInteraction", "Need contact permissions: " + Arrays.toString(deniedContactsPermissions)); ActivityCompat.requestPermissions( - (Activity) mContext, deniedContactsPermissions, REQUEST_READ_CONTACTS); + (Activity) context, deniedContactsPermissions, REQUEST_READ_CONTACTS); return; } - if (mLoader != null) { - mLoader.reset(); + if (loader != null) { + loader.reset(); } final Uri queryUri; final String inputUriAsString = uri.toString(); @@ -262,11 +262,11 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { "Input Uri must be contact Uri or data Uri (input: \"" + uri + "\")"); } - mLoader = + loader = new CursorLoader( - mContext, queryUri, PHONE_NUMBER_PROJECTION, PHONE_NUMBER_SELECTION, null, null); - mLoader.registerListener(0, this); - mLoader.startLoading(); + context, queryUri, PHONE_NUMBER_PROJECTION, PHONE_NUMBER_SELECTION, null, null); + loader.registerListener(0, this); + loader.startLoading(); } @Override @@ -295,8 +295,8 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { int phoneLabelColumn = cursor.getColumnIndexOrThrow(Phone.LABEL); int phoneMimeTpeColumn = cursor.getColumnIndexOrThrow(Phone.MIMETYPE); do { - if (mContactId == UNKNOWN_CONTACT_ID) { - mContactId = cursor.getLong(contactIdColumn); + if (contactId == UNKNOWN_CONTACT_ID) { + contactId = cursor.getLong(contactIdColumn); } if (cursor.getInt(isSuperPrimaryColumn) != 0) { @@ -325,7 +325,7 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { return; } - Collapser.collapseList(phoneList, mContext); + Collapser.collapseList(phoneList, context); if (phoneList.size() == 0) { interactionError(InteractionErrorCode.CONTACT_HAS_NO_NUMBER); } else if (phoneList.size() == 1) { @@ -342,22 +342,22 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { private void interactionError(@InteractionErrorCode int interactionErrorCode) { // mContext is really the activity -- see ctor docs. - ((InteractionErrorListener) mContext).interactionError(interactionErrorCode); + ((InteractionErrorListener) context).interactionError(interactionErrorCode); } private boolean isSafeToCommitTransactions() { - return !(mContext instanceof TransactionSafeActivity) - || ((TransactionSafeActivity) mContext).isSafeToCommitTransactions(); + return !(context instanceof TransactionSafeActivity) + || ((TransactionSafeActivity) context).isSafeToCommitTransactions(); } @VisibleForTesting /* package */ CursorLoader getLoader() { - return mLoader; + return loader; } private void showDisambiguationDialog(ArrayList phoneList) { // TODO(a bug): don't leak the activity - final Activity activity = (Activity) mContext; + final Activity activity = (Activity) context; if (activity.isFinishing()) { LogUtil.i("PhoneNumberInteraction.showDisambiguationDialog", "activity finishing"); return; @@ -373,9 +373,9 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { PhoneDisambiguationDialogFragment.show( activity.getFragmentManager(), phoneList, - mInteractionType, - mIsVideoCall, - mCallSpecificAppData); + interactionType, + isVideoCall, + callSpecificAppData); } catch (IllegalStateException e) { // ignore to be safe. Shouldn't happen because we checked the // activity wasn't destroyed, but to be safe. @@ -456,11 +456,11 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { /** A list adapter that populates the list of contact's phone numbers. */ private static class PhoneItemAdapter extends ArrayAdapter { - private final int mInteractionType; + private final int interactionType; PhoneItemAdapter(Context context, List list, int interactionType) { super(context, R.layout.phone_disambig_item, android.R.id.text2, list); - mInteractionType = interactionType; + this.interactionType = interactionType; } @Override @@ -472,7 +472,7 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { final TextView typeView = (TextView) view.findViewById(android.R.id.text1); CharSequence value = ContactDisplayUtils.getLabelForCallOrSms( - (int) item.type, item.label, mInteractionType, getContext()); + (int) item.type, item.label, interactionType, getContext()); typeView.setText(value); return view; @@ -498,11 +498,11 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { private static final String ARG_INTERACTION_TYPE = "interactionType"; private static final String ARG_IS_VIDEO_CALL = "is_video_call"; - private int mInteractionType; - private ListAdapter mPhonesAdapter; - private List mPhoneList; - private CallSpecificAppData mCallSpecificAppData; - private boolean mIsVideoCall; + private int interactionType; + private ListAdapter phonesAdapter; + private List phoneList; + private CallSpecificAppData callSpecificAppData; + private boolean isVideoCall; public PhoneDisambiguationDialogFragment() { super(); @@ -529,19 +529,19 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { final Activity activity = getActivity(); Assert.checkState(activity instanceof DisambigDialogDismissedListener); - mPhoneList = getArguments().getParcelableArrayList(ARG_PHONE_LIST); - mInteractionType = getArguments().getInt(ARG_INTERACTION_TYPE); - mIsVideoCall = getArguments().getBoolean(ARG_IS_VIDEO_CALL); - mCallSpecificAppData = CallIntentParser.getCallSpecificAppData(getArguments()); + phoneList = getArguments().getParcelableArrayList(ARG_PHONE_LIST); + interactionType = getArguments().getInt(ARG_INTERACTION_TYPE); + isVideoCall = getArguments().getBoolean(ARG_IS_VIDEO_CALL); + callSpecificAppData = CallIntentParser.getCallSpecificAppData(getArguments()); - mPhonesAdapter = new PhoneItemAdapter(activity, mPhoneList, mInteractionType); + phonesAdapter = new PhoneItemAdapter(activity, phoneList, interactionType); final LayoutInflater inflater = activity.getLayoutInflater(); @SuppressLint("InflateParams") // Allowed since dialog view is not available yet final View setPrimaryView = inflater.inflate(R.layout.set_primary_checkbox, null); return new AlertDialog.Builder(activity) - .setAdapter(mPhonesAdapter, this) + .setAdapter(phonesAdapter, this) .setTitle( - mInteractionType == ContactDisplayUtils.INTERACTION_SMS + interactionType == ContactDisplayUtils.INTERACTION_SMS ? R.string.sms_disambig_title : R.string.call_disambig_title) .setView(setPrimaryView) @@ -555,11 +555,11 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { return; } final AlertDialog alertDialog = (AlertDialog) dialog; - if (mPhoneList.size() > which && which >= 0) { - final PhoneItem phoneItem = mPhoneList.get(which); + if (phoneList.size() > which && which >= 0) { + final PhoneItem phoneItem = phoneList.get(which); final CheckBox checkBox = (CheckBox) alertDialog.findViewById(R.id.setPrimary); if (checkBox.isChecked()) { - if (mCallSpecificAppData.getCallInitiationType() == CallInitiationType.Type.SPEED_DIAL) { + if (callSpecificAppData.getCallInitiationType() == CallInitiationType.Type.SPEED_DIAL) { Logger.get(getContext()) .logInteraction( InteractionEvent.Type.SPEED_DIAL_SET_DEFAULT_NUMBER_FOR_AMBIGUOUS_CONTACT); @@ -572,7 +572,7 @@ public class PhoneNumberInteraction implements OnLoadCompleteListener { } PhoneNumberInteraction.performAction( - activity, phoneItem.phoneNumber, mInteractionType, mIsVideoCall, mCallSpecificAppData); + activity, phoneItem.phoneNumber, interactionType, isVideoCall, callSpecificAppData); } else { dialog.dismiss(); } diff --git a/java/com/android/dialer/lettertile/LetterTileDrawable.java b/java/com/android/dialer/lettertile/LetterTileDrawable.java index c8b75c5a9..b747c4f4c 100644 --- a/java/com/android/dialer/lettertile/LetterTileDrawable.java +++ b/java/com/android/dialer/lettertile/LetterTileDrawable.java @@ -88,53 +88,53 @@ public class LetterTileDrawable extends Drawable { private static final float VECTOR_ICON_SCALE = 0.7f; /** Reusable components to avoid new allocations */ - private final Paint mPaint = new Paint(); + private final Paint paint = new Paint(); - private final Rect mRect = new Rect(); - private final char[] mFirstChar = new char[1]; + private final Rect rect = new Rect(); + private final char[] firstChar = new char[1]; /** Letter tile */ - @NonNull private final TypedArray mColors; + @NonNull private final TypedArray colors; - private final int mSpamColor; - private final int mDefaultColor; - private final int mTileFontColor; - private final float mLetterToTileRatio; - @NonNull private final Drawable mDefaultPersonAvatar; - @NonNull private final Drawable mDefaultBusinessAvatar; - @NonNull private final Drawable mDefaultVoicemailAvatar; - @NonNull private final Drawable mDefaultSpamAvatar; - @NonNull private final Drawable mDefaultConferenceAvatar; + private final int spamColor; + private final int defaultColor; + private final int tileFontColor; + private final float letterToTileRatio; + @NonNull private final Drawable defaultPersonAvatar; + @NonNull private final Drawable defaultBusinessAvatar; + @NonNull private final Drawable defaultVoicemailAvatar; + @NonNull private final Drawable defaultSpamAvatar; + @NonNull private final Drawable defaultConferenceAvatar; - @ContactType private int mContactType = TYPE_DEFAULT; - private float mScale = 1.0f; - private float mOffset = 0.0f; - private boolean mIsCircle = false; + @ContactType private int contactType = TYPE_DEFAULT; + private float scale = 1.0f; + private float offset = 0.0f; + private boolean isCircle = false; - private int mColor; - private Character mLetter = null; + private int color; + private Character letter = null; - private String mDisplayName; + private String displayName; public LetterTileDrawable(final Resources res) { - mColors = res.obtainTypedArray(R.array.letter_tile_colors); - mSpamColor = res.getColor(R.color.spam_contact_background); - mDefaultColor = res.getColor(R.color.letter_tile_default_color); - mTileFontColor = res.getColor(R.color.letter_tile_font_color); - mLetterToTileRatio = res.getFraction(R.dimen.letter_to_tile_ratio, 1, 1); - mDefaultPersonAvatar = + colors = res.obtainTypedArray(R.array.letter_tile_colors); + spamColor = res.getColor(R.color.spam_contact_background); + defaultColor = res.getColor(R.color.letter_tile_default_color); + tileFontColor = res.getColor(R.color.letter_tile_font_color); + letterToTileRatio = res.getFraction(R.dimen.letter_to_tile_ratio, 1, 1); + defaultPersonAvatar = res.getDrawable(R.drawable.product_logo_avatar_anonymous_white_color_120, null); - mDefaultBusinessAvatar = res.getDrawable(R.drawable.quantum_ic_business_vd_theme_24, null); - mDefaultVoicemailAvatar = res.getDrawable(R.drawable.quantum_ic_voicemail_vd_theme_24, null); - mDefaultSpamAvatar = res.getDrawable(R.drawable.quantum_ic_report_vd_theme_24, null); - mDefaultConferenceAvatar = res.getDrawable(R.drawable.quantum_ic_group_vd_theme_24, null); - - mPaint.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); - mPaint.setTextAlign(Align.CENTER); - mPaint.setAntiAlias(true); - mPaint.setFilterBitmap(true); - mPaint.setDither(true); - mColor = mDefaultColor; + defaultBusinessAvatar = res.getDrawable(R.drawable.quantum_ic_business_vd_theme_24, null); + defaultVoicemailAvatar = res.getDrawable(R.drawable.quantum_ic_voicemail_vd_theme_24, null); + defaultSpamAvatar = res.getDrawable(R.drawable.quantum_ic_report_vd_theme_24, null); + defaultConferenceAvatar = res.getDrawable(R.drawable.quantum_ic_group_vd_theme_24, null); + + paint.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); + paint.setTextAlign(Align.CENTER); + paint.setAntiAlias(true); + paint.setFilterBitmap(true); + paint.setDither(true); + color = defaultColor; } private Rect getScaledBounds(float scale, float offset) { @@ -155,21 +155,21 @@ public class LetterTileDrawable extends Drawable { private Drawable getDrawableForContactType(int contactType) { switch (contactType) { case TYPE_BUSINESS: - mScale = VECTOR_ICON_SCALE; - return mDefaultBusinessAvatar; + scale = VECTOR_ICON_SCALE; + return defaultBusinessAvatar; case TYPE_VOICEMAIL: - mScale = VECTOR_ICON_SCALE; - return mDefaultVoicemailAvatar; + scale = VECTOR_ICON_SCALE; + return defaultVoicemailAvatar; case TYPE_SPAM: - mScale = VECTOR_ICON_SCALE; - return mDefaultSpamAvatar; + scale = VECTOR_ICON_SCALE; + return defaultSpamAvatar; case TYPE_CONFERENCE: - mScale = VECTOR_ICON_SCALE; - return mDefaultConferenceAvatar; + scale = VECTOR_ICON_SCALE; + return defaultConferenceAvatar; case TYPE_PERSON: case TYPE_GENERIC_AVATAR: default: - return mDefaultPersonAvatar; + return defaultPersonAvatar; } } @@ -197,88 +197,88 @@ public class LetterTileDrawable extends Drawable { private void drawLetterTile(final Canvas canvas) { // Draw background color. - mPaint.setColor(mColor); + paint.setColor(color); final Rect bounds = getBounds(); final int minDimension = Math.min(bounds.width(), bounds.height()); - if (mIsCircle) { - canvas.drawCircle(bounds.centerX(), bounds.centerY(), minDimension / 2, mPaint); + if (isCircle) { + canvas.drawCircle(bounds.centerX(), bounds.centerY(), minDimension / 2, paint); } else { - canvas.drawRect(bounds, mPaint); + canvas.drawRect(bounds, paint); } // Draw letter/digit only if the first character is an english letter or there's a override - if (mLetter != null) { + if (letter != null) { // Draw letter or digit. - mFirstChar[0] = mLetter; + firstChar[0] = letter; // Scale text by canvas bounds and user selected scaling factor - mPaint.setTextSize(mScale * mLetterToTileRatio * minDimension); - mPaint.getTextBounds(mFirstChar, 0, 1, mRect); - mPaint.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL)); - mPaint.setColor(mTileFontColor); - mPaint.setAlpha(ALPHA); + paint.setTextSize(scale * letterToTileRatio * minDimension); + paint.getTextBounds(firstChar, 0, 1, rect); + paint.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL)); + paint.setColor(tileFontColor); + paint.setAlpha(ALPHA); // Draw the letter in the canvas, vertically shifted up or down by the user-defined // offset canvas.drawText( - mFirstChar, + firstChar, 0, 1, bounds.centerX(), - bounds.centerY() + mOffset * bounds.height() - mRect.exactCenterY(), - mPaint); + bounds.centerY() + offset * bounds.height() - rect.exactCenterY(), + paint); } else { // Draw the default image if there is no letter/digit to be drawn - Drawable drawable = getDrawableForContactType(mContactType); + Drawable drawable = getDrawableForContactType(contactType); if (drawable == null) { throw Assert.createIllegalStateFailException( - "Unable to find drawable for contact type " + mContactType); + "Unable to find drawable for contact type " + contactType); } - drawable.setBounds(getScaledBounds(mScale, mOffset)); - drawable.setAlpha(drawable == mDefaultSpamAvatar ? SPAM_ALPHA : ALPHA); + drawable.setBounds(getScaledBounds(scale, offset)); + drawable.setAlpha(drawable == defaultSpamAvatar ? SPAM_ALPHA : ALPHA); drawable.draw(canvas); } } public int getColor() { - return mColor; + return color; } public LetterTileDrawable setColor(int color) { - mColor = color; + this.color = color; return this; } /** Returns a deterministic color based on the provided contact identifier string. */ private int pickColor(final String identifier) { - if (mContactType == TYPE_SPAM) { - return mSpamColor; + if (contactType == TYPE_SPAM) { + return spamColor; } - if (mContactType == TYPE_VOICEMAIL - || mContactType == TYPE_BUSINESS + if (contactType == TYPE_VOICEMAIL + || contactType == TYPE_BUSINESS || TextUtils.isEmpty(identifier)) { - return mDefaultColor; + return defaultColor; } // String.hashCode() implementation is not supposed to change across java versions, so // this should guarantee the same email address always maps to the same color. // The email should already have been normalized by the ContactRequest. - final int color = Math.abs(identifier.hashCode()) % mColors.length(); - return mColors.getColor(color, mDefaultColor); + final int color = Math.abs(identifier.hashCode()) % colors.length(); + return colors.getColor(color, defaultColor); } @Override public void setAlpha(final int alpha) { - mPaint.setAlpha(alpha); + paint.setAlpha(alpha); } @Override public void setColorFilter(final ColorFilter cf) { - mPaint.setColorFilter(cf); + paint.setColorFilter(cf); } @Override @@ -288,7 +288,7 @@ public class LetterTileDrawable extends Drawable { @Override public void getOutline(Outline outline) { - if (mIsCircle) { + if (isCircle) { outline.setOval(getBounds()); } else { outline.setRect(getBounds()); @@ -304,7 +304,7 @@ public class LetterTileDrawable extends Drawable { * from a scale of 0 to 2.0f. The default is 1.0f. */ public LetterTileDrawable setScale(float scale) { - mScale = scale; + this.scale = scale; return this; } @@ -320,47 +320,47 @@ public class LetterTileDrawable extends Drawable { */ public LetterTileDrawable setOffset(float offset) { Assert.checkArgument(offset >= -0.5f && offset <= 0.5f); - mOffset = offset; + this.offset = offset; return this; } public LetterTileDrawable setLetter(Character letter) { - mLetter = letter; + this.letter = letter; return this; } public Character getLetter() { - return this.mLetter; + return this.letter; } private LetterTileDrawable setLetterAndColorFromContactDetails( final String displayName, final String identifier) { if (!TextUtils.isEmpty(displayName) && isEnglishLetter(displayName.charAt(0))) { - mLetter = Character.toUpperCase(displayName.charAt(0)); + letter = Character.toUpperCase(displayName.charAt(0)); } else { - mLetter = null; + letter = null; } - mColor = pickColor(identifier); + color = pickColor(identifier); return this; } private LetterTileDrawable setContactType(@ContactType int contactType) { - mContactType = contactType; + this.contactType = contactType; return this; } @ContactType public int getContactType() { - return this.mContactType; + return this.contactType; } public LetterTileDrawable setIsCircular(boolean isCircle) { - mIsCircle = isCircle; + this.isCircle = isCircle; return this; } public boolean tileIsCircular() { - return this.mIsCircle; + return this.isCircle; } /** @@ -391,11 +391,11 @@ public class LetterTileDrawable extends Drawable { */ if (contactType == TYPE_DEFAULT && ((displayName == null && identifierForTileColor == null) - || (displayName != null && displayName.equals(mDisplayName)))) { + || (displayName != null && displayName.equals(this.displayName)))) { return this; } - this.mDisplayName = displayName; + this.displayName = displayName; setContactType(contactType); // Special contact types receive default color and no letter tile, but special iconography. diff --git a/java/com/android/dialer/location/CountryDetector.java b/java/com/android/dialer/location/CountryDetector.java index 110cf4502..5c5ed9c84 100644 --- a/java/com/android/dialer/location/CountryDetector.java +++ b/java/com/android/dialer/location/CountryDetector.java @@ -72,7 +72,7 @@ public class CountryDetector { // exceedingly rare event that the device does not have a default locale set for some reason. private static final String DEFAULT_COUNTRY_ISO = "US"; - @VisibleForTesting public static CountryDetector sInstance; + @VisibleForTesting public static CountryDetector instance; private final TelephonyManager telephonyManager; private final LocaleProvider localeProvider; @@ -121,9 +121,9 @@ public class CountryDetector { /** @return the single instance of the {@link CountryDetector} */ public static synchronized CountryDetector getInstance(Context context) { - if (sInstance == null) { + if (instance == null) { Context appContext = context.getApplicationContext(); - sInstance = + instance = new CountryDetector( appContext, (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE), @@ -131,7 +131,7 @@ public class CountryDetector { Locale::getDefault, new Geocoder(appContext)); } - return sInstance; + return instance; } public String getCurrentCountryIso() { diff --git a/java/com/android/dialer/phonenumbercache/ContactInfoHelper.java b/java/com/android/dialer/phonenumbercache/ContactInfoHelper.java index 1fd2bffd9..04226552d 100644 --- a/java/com/android/dialer/phonenumbercache/ContactInfoHelper.java +++ b/java/com/android/dialer/phonenumbercache/ContactInfoHelper.java @@ -60,14 +60,14 @@ public class ContactInfoHelper { private static final String TAG = ContactInfoHelper.class.getSimpleName(); - private final Context mContext; - private final String mCurrentCountryIso; - private final CachedNumberLookupService mCachedNumberLookupService; + private final Context context; + private final String currentCountryIso; + private final CachedNumberLookupService cachedNumberLookupService; public ContactInfoHelper(Context context, String currentCountryIso) { - mContext = context; - mCurrentCountryIso = currentCountryIso; - mCachedNumberLookupService = PhoneNumberCache.get(mContext).getCachedNumberLookupService(); + this.context = context; + this.currentCountryIso = currentCountryIso; + cachedNumberLookupService = PhoneNumberCache.get(this.context).getCachedNumberLookupService(); } /** @@ -277,8 +277,8 @@ public class ContactInfoHelper { * empty contact info for the number. */ public ContactInfo lookupNumberInRemoteDirectory(String number, String countryIso) { - if (mCachedNumberLookupService != null) { - List remoteDirectories = getRemoteDirectories(mContext); + if (cachedNumberLookupService != null) { + List remoteDirectories = getRemoteDirectories(context); for (long directoryId : remoteDirectories) { ContactInfo contactInfo = lookupNumber(number, countryIso, directoryId); if (hasName(contactInfo)) { @@ -332,13 +332,13 @@ public class ContactInfoHelper { LogUtil.d("ContactInfoHelper.lookupContactFromUri", "uri is null"); return null; } - if (!PermissionsUtil.hasContactsReadPermissions(mContext)) { + if (!PermissionsUtil.hasContactsReadPermissions(context)) { LogUtil.d("ContactInfoHelper.lookupContactFromUri", "no contact permission, return empty"); return ContactInfo.EMPTY; } try (Cursor phoneLookupCursor = - mContext + context .getContentResolver() .query( uri, @@ -368,7 +368,7 @@ public class ContactInfoHelper { String lookupKey = phoneLookupCursor.getString(PhoneQuery.LOOKUP_KEY); ContactInfo contactInfo = createPhoneLookupContactInfo(phoneLookupCursor, lookupKey); - fillAdditionalContactInfo(mContext, contactInfo); + fillAdditionalContactInfo(context, contactInfo); return contactInfo; } } @@ -442,9 +442,9 @@ public class ContactInfoHelper { // Contact found in the extended directory specified by directoryId info.sourceType = ContactSource.Type.SOURCE_TYPE_EXTENDED; } - } else if (mCachedNumberLookupService != null) { + } else if (cachedNumberLookupService != null) { CachedContactInfo cacheInfo = - mCachedNumberLookupService.lookupCachedContactFromNumber(mContext, number); + cachedNumberLookupService.lookupCachedContactFromNumber(context, number); if (cacheInfo != null) { if (!cacheInfo.getContactInfo().isBadData) { info = cacheInfo.getContactInfo(); @@ -474,7 +474,7 @@ public class ContactInfoHelper { return number; } if (TextUtils.isEmpty(countryIso)) { - countryIso = mCurrentCountryIso; + countryIso = currentCountryIso; } return PhoneNumberUtils.formatNumber(number, normalizedNumber, countryIso); } @@ -489,7 +489,7 @@ public class ContactInfoHelper { */ public void updateCallLogContactInfo( String number, String countryIso, ContactInfo updatedInfo, ContactInfo callLogInfo) { - if (!PermissionsUtil.hasPermission(mContext, android.Manifest.permission.WRITE_CALL_LOG)) { + if (!PermissionsUtil.hasPermission(context, android.Manifest.permission.WRITE_CALL_LOG)) { return; } @@ -572,18 +572,18 @@ public class ContactInfoHelper { try { if (countryIso == null) { - mContext + context .getContentResolver() .update( - TelecomUtil.getCallLogUri(mContext), + TelecomUtil.getCallLogUri(context), values, Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " IS NULL", new String[] {number}); } else { - mContext + context .getContentResolver() .update( - TelecomUtil.getCallLogUri(mContext), + TelecomUtil.getCallLogUri(context), values, Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " = ?", new String[] {number, countryIso}); @@ -594,11 +594,11 @@ public class ContactInfoHelper { } public void updateCachedNumberLookupService(ContactInfo updatedInfo) { - if (mCachedNumberLookupService != null) { + if (cachedNumberLookupService != null) { if (hasName(updatedInfo)) { CachedContactInfo cachedContactInfo = - mCachedNumberLookupService.buildCachedContactInfo(updatedInfo); - mCachedNumberLookupService.addContact(mContext, cachedContactInfo); + cachedNumberLookupService.buildCachedContactInfo(updatedInfo); + cachedNumberLookupService.addContact(context, cachedContactInfo); } } } @@ -607,10 +607,10 @@ public class ContactInfoHelper { * Given a contact's sourceType, return true if the contact is a business * * @param sourceType sourceType of the contact. This is usually populated by {@link - * #mCachedNumberLookupService}. + * #cachedNumberLookupService}. */ public boolean isBusiness(ContactSource.Type sourceType) { - return mCachedNumberLookupService != null && mCachedNumberLookupService.isBusiness(sourceType); + return cachedNumberLookupService != null && cachedNumberLookupService.isBusiness(sourceType); } /** @@ -622,8 +622,8 @@ public class ContactInfoHelper { * @return true if contacts from this source can be marked with an invalid caller id */ public boolean canReportAsInvalid(ContactSource.Type sourceType, String objectId) { - return mCachedNumberLookupService != null - && mCachedNumberLookupService.canReportAsInvalid(sourceType, objectId); + return cachedNumberLookupService != null + && cachedNumberLookupService.canReportAsInvalid(sourceType, objectId); } /** @@ -634,14 +634,14 @@ public class ContactInfoHelper { public void updateFromCequintCallerId( @Nullable CequintCallerIdManager cequintCallerIdManager, ContactInfo info, String number) { Assert.isWorkerThread(); - if (!CequintCallerIdManager.isCequintCallerIdEnabled(mContext)) { + if (!CequintCallerIdManager.isCequintCallerIdEnabled(context)) { return; } if (cequintCallerIdManager == null) { return; } CequintCallerIdContact cequintCallerIdContact = - cequintCallerIdManager.getCequintCallerIdContact(mContext, number); + cequintCallerIdManager.getCequintCallerIdContact(context, number); if (cequintCallerIdContact == null) { return; } diff --git a/java/com/android/dialer/smartdial/SmartDialCursorLoader.java b/java/com/android/dialer/smartdial/SmartDialCursorLoader.java index f6bc9325a..f2e41b22b 100644 --- a/java/com/android/dialer/smartdial/SmartDialCursorLoader.java +++ b/java/com/android/dialer/smartdial/SmartDialCursorLoader.java @@ -35,18 +35,18 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { private static final String TAG = "SmartDialCursorLoader"; private static final boolean DEBUG = false; - private final Context mContext; + private final Context context; - private Cursor mCursor; + private Cursor cursor; - private String mQuery; - private SmartDialNameMatcher mNameMatcher; + private String query; + private SmartDialNameMatcher nameMatcher; - private boolean mShowEmptyListForNullQuery = true; + private boolean showEmptyListForNullQuery = true; public SmartDialCursorLoader(Context context) { super(context); - mContext = context; + this.context = context; } /** @@ -58,11 +58,11 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { if (DEBUG) { LogUtil.v(TAG, "Configure new query to be " + query); } - mQuery = SmartDialNameMatcher.normalizeNumber(mContext, query); + this.query = SmartDialNameMatcher.normalizeNumber(context, query); /** Constructs a name matcher object for matching names. */ - mNameMatcher = new SmartDialNameMatcher(mQuery); - mNameMatcher.setShouldMatchEmptyQuery(!mShowEmptyListForNullQuery); + nameMatcher = new SmartDialNameMatcher(this.query); + nameMatcher.setShouldMatchEmptyQuery(!showEmptyListForNullQuery); } /** @@ -73,18 +73,18 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { @Override public Cursor loadInBackground() { if (DEBUG) { - LogUtil.v(TAG, "Load in background " + mQuery); + LogUtil.v(TAG, "Load in background " + query); } - if (!PermissionsUtil.hasContactsReadPermissions(mContext)) { + if (!PermissionsUtil.hasContactsReadPermissions(context)) { return new MatrixCursor(PhoneQuery.PROJECTION_PRIMARY); } /** Loads results from the database helper. */ final DialerDatabaseHelper dialerDatabaseHelper = - Database.get(mContext).getDatabaseHelper(mContext); + Database.get(context).getDatabaseHelper(context); final ArrayList allMatches = - dialerDatabaseHelper.getLooseMatches(mQuery, mNameMatcher); + dialerDatabaseHelper.getLooseMatches(query, nameMatcher); if (DEBUG) { LogUtil.v(TAG, "Loaded matches " + allMatches.size()); @@ -115,8 +115,8 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { } /** Hold a reference to the old data so it doesn't get garbage collected. */ - Cursor oldCursor = mCursor; - mCursor = cursor; + Cursor oldCursor = this.cursor; + this.cursor = cursor; if (isStarted()) { /** If the Loader is in a started state, deliver the results to the client. */ @@ -131,11 +131,11 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { @Override protected void onStartLoading() { - if (mCursor != null) { + if (cursor != null) { /** Deliver any previously loaded data immediately. */ - deliverResult(mCursor); + deliverResult(cursor); } - if (mCursor == null) { + if (cursor == null) { /** Force loads every time as our results change with queries. */ forceLoad(); } @@ -153,9 +153,9 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { onStopLoading(); /** Release all previously saved query results. */ - if (mCursor != null) { - releaseResources(mCursor); - mCursor = null; + if (cursor != null) { + releaseResources(cursor); + cursor = null; } } @@ -174,9 +174,9 @@ public class SmartDialCursorLoader extends AsyncTaskLoader { } public void setShowEmptyListForNullQuery(boolean show) { - mShowEmptyListForNullQuery = show; - if (mNameMatcher != null) { - mNameMatcher.setShouldMatchEmptyQuery(!show); + showEmptyListForNullQuery = show; + if (nameMatcher != null) { + nameMatcher.setShouldMatchEmptyQuery(!show); } } } diff --git a/java/com/android/dialer/smartdial/util/SmartDialNameMatcher.java b/java/com/android/dialer/smartdial/util/SmartDialNameMatcher.java index 725c88c57..601962292 100644 --- a/java/com/android/dialer/smartdial/util/SmartDialNameMatcher.java +++ b/java/com/android/dialer/smartdial/util/SmartDialNameMatcher.java @@ -38,14 +38,14 @@ public class SmartDialNameMatcher { // positives private static final int INITIAL_LENGTH_LIMIT = 1; - private final ArrayList mMatchPositions = new ArrayList<>(); - private String mQuery; + private final ArrayList matchPositions = new ArrayList<>(); + private String query; // Controls whether to treat an empty query as a match (with anything). - private boolean mShouldMatchEmptyQuery = false; + private boolean shouldMatchEmptyQuery = false; public SmartDialNameMatcher(String query) { - mQuery = query; + this.query = query; } /** @@ -112,7 +112,7 @@ public class SmartDialNameMatcher { @Nullable public SmartDialMatchPosition matchesNumber(Context context, String phoneNumber, String query) { if (TextUtils.isEmpty(phoneNumber)) { - return mShouldMatchEmptyQuery ? new SmartDialMatchPosition(0, 0) : null; + return shouldMatchEmptyQuery ? new SmartDialMatchPosition(0, 0) : null; } StringBuilder builder = new StringBuilder(); constructEmptyMask(builder, phoneNumber.length()); @@ -148,7 +148,7 @@ public class SmartDialNameMatcher { * with the matching positions otherwise */ public SmartDialMatchPosition matchesNumber(Context context, String phoneNumber) { - return matchesNumber(context, phoneNumber, mQuery); + return matchesNumber(context, phoneNumber, query); } /** @@ -164,7 +164,7 @@ public class SmartDialNameMatcher { private SmartDialMatchPosition matchesNumberWithOffset( Context context, String phoneNumber, String query, int offset) { if (TextUtils.isEmpty(phoneNumber) || TextUtils.isEmpty(query)) { - return mShouldMatchEmptyQuery ? new SmartDialMatchPosition(offset, offset) : null; + return shouldMatchEmptyQuery ? new SmartDialMatchPosition(offset, offset) : null; } int queryAt = 0; int numberAt = offset; @@ -406,25 +406,25 @@ public class SmartDialNameMatcher { * match positions (multiple matches correspond to initial matches). */ public boolean matches(Context context, String displayName) { - mMatchPositions.clear(); - return matchesCombination(context, displayName, mQuery, mMatchPositions); + matchPositions.clear(); + return matchesCombination(context, displayName, query, matchPositions); } public ArrayList getMatchPositions() { // Return a clone of mMatchPositions so that the caller can use it without // worrying about it changing - return new ArrayList<>(mMatchPositions); + return new ArrayList<>(matchPositions); } public String getQuery() { - return mQuery; + return query; } public void setQuery(String query) { - mQuery = query; + this.query = query; } public void setShouldMatchEmptyQuery(boolean matches) { - mShouldMatchEmptyQuery = matches; + shouldMatchEmptyQuery = matches; } } diff --git a/java/com/android/dialer/smartdial/util/SmartDialPrefix.java b/java/com/android/dialer/smartdial/util/SmartDialPrefix.java index 9af411913..7fef8814c 100644 --- a/java/com/android/dialer/smartdial/util/SmartDialPrefix.java +++ b/java/com/android/dialer/smartdial/util/SmartDialPrefix.java @@ -54,38 +54,38 @@ public class SmartDialPrefix { private static final String PREF_USER_SIM_COUNTRY_CODE_DEFAULT = null; - private static String sUserSimCountryCode = PREF_USER_SIM_COUNTRY_CODE_DEFAULT; + private static String userSimCountryCode = PREF_USER_SIM_COUNTRY_CODE_DEFAULT; /** Indicates whether user is in NANP regions. */ - private static boolean sUserInNanpRegion = false; + private static boolean userInNanpRegion = false; /** Set of country names that use NANP code. */ - private static Set sNanpCountries = null; + private static Set nanpCountries = null; /** Set of supported country codes in front of the phone number. */ - private static Set sCountryCodes = null; + private static Set countryCodes = null; - private static boolean sNanpInitialized = false; + private static boolean nanpInitialized = false; /** Initializes the Nanp settings, and finds out whether user is in a NANP region. */ public static void initializeNanpSettings(Context context) { final TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager != null) { - sUserSimCountryCode = manager.getSimCountryIso(); + userSimCountryCode = manager.getSimCountryIso(); } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); - if (sUserSimCountryCode != null) { + if (userSimCountryCode != null) { /** Updates shared preferences with the latest country obtained from getSimCountryIso. */ - prefs.edit().putString(PREF_USER_SIM_COUNTRY_CODE, sUserSimCountryCode).apply(); + prefs.edit().putString(PREF_USER_SIM_COUNTRY_CODE, userSimCountryCode).apply(); } else { /** Uses previously stored country code if loading fails. */ - sUserSimCountryCode = + userSimCountryCode = prefs.getString(PREF_USER_SIM_COUNTRY_CODE, PREF_USER_SIM_COUNTRY_CODE_DEFAULT); } /** Queries the NANP country list to find out whether user is in a NANP region. */ - sUserInNanpRegion = isCountryNanp(sUserSimCountryCode); - sNanpInitialized = true; + userInNanpRegion = isCountryNanp(userSimCountryCode); + nanpInitialized = true; } /** @@ -255,7 +255,7 @@ public class SmartDialPrefix { */ if ((normalizedNumber.length() == 11) && (normalizedNumber.charAt(0) == '1') - && (sUserInNanpRegion)) { + && (userInNanpRegion)) { countryCode = "1"; countryCodeOffset = number.indexOf(normalizedNumber.charAt(1)); if (countryCodeOffset == -1) { @@ -265,7 +265,7 @@ public class SmartDialPrefix { } /** If user is in NANP region, finds out whether a number is in NANP format. */ - if (sUserInNanpRegion) { + if (userInNanpRegion) { String areaCode = ""; if (countryCode.equals("") && normalizedNumber.length() == 10) { /** @@ -292,10 +292,10 @@ public class SmartDialPrefix { /** Checkes whether a country code is valid. */ private static boolean isValidCountryCode(String countryCode) { - if (sCountryCodes == null) { - sCountryCodes = initCountryCodes(); + if (countryCodes == null) { + countryCodes = initCountryCodes(); } - return sCountryCodes.contains(countryCode); + return countryCodes.contains(countryCode); } private static Set initCountryCodes() { @@ -531,10 +531,10 @@ public class SmartDialPrefix { if (TextUtils.isEmpty(country)) { return false; } - if (sNanpCountries == null) { - sNanpCountries = initNanpCountries(); + if (nanpCountries == null) { + nanpCountries = initNanpCountries(); } - return sNanpCountries.contains(country.toUpperCase()); + return nanpCountries.contains(country.toUpperCase()); } private static Set initNanpCountries() { @@ -572,13 +572,13 @@ public class SmartDialPrefix { * @return Whether user is in Nanp region. */ public static boolean getUserInNanpRegion() { - return sUserInNanpRegion; + return userInNanpRegion; } /** Explicitly setting the user Nanp to the given boolean */ @VisibleForTesting public static void setUserInNanpRegion(boolean userInNanpRegion) { - sUserInNanpRegion = userInNanpRegion; + SmartDialPrefix.userInNanpRegion = userInNanpRegion; } /** Class to record phone number parsing information. */ diff --git a/java/com/android/dialer/telecom/TelecomUtil.java b/java/com/android/dialer/telecom/TelecomUtil.java index c64a50231..f79ca8607 100644 --- a/java/com/android/dialer/telecom/TelecomUtil.java +++ b/java/com/android/dialer/telecom/TelecomUtil.java @@ -52,7 +52,7 @@ import java.util.concurrent.ConcurrentHashMap; public abstract class TelecomUtil { private static final String TAG = "TelecomUtil"; - private static boolean sWarningLogged = false; + private static boolean warningLogged = false; private static TelecomUtilImpl instance = new TelecomUtilImpl(); @@ -326,12 +326,12 @@ public abstract class TelecomUtil { TextUtils.equals( context.getPackageName(), getTelecomManager(context).getDefaultDialerPackage()); if (result) { - sWarningLogged = false; + warningLogged = false; } else { - if (!sWarningLogged) { + if (!warningLogged) { // Log only once to prevent spam. LogUtil.w(TAG, "Dialer is not currently set to be default dialer"); - sWarningLogged = true; + warningLogged = true; } } return result; diff --git a/java/com/android/dialer/util/ExpirableCache.java b/java/com/android/dialer/util/ExpirableCache.java index 2778a572c..a1b0afd74 100644 --- a/java/com/android/dialer/util/ExpirableCache.java +++ b/java/com/android/dialer/util/ExpirableCache.java @@ -98,13 +98,13 @@ public class ExpirableCache { * * @see ExpirableCache.CachedValue#isExpired() */ - private final AtomicInteger mGeneration; + private final AtomicInteger generation; /** The underlying cache used to stored the cached values. */ - private LruCache> mCache; + private LruCache> cache; private ExpirableCache(LruCache> cache) { - mCache = cache; - mGeneration = new AtomicInteger(0); + this.cache = cache; + generation = new AtomicInteger(0); } /** @@ -147,7 +147,7 @@ public class ExpirableCache { * @param key the key to look up */ public CachedValue getCachedValue(K key) { - return mCache.get(key); + return cache.get(key); } /** @@ -190,7 +190,7 @@ public class ExpirableCache { * @param value the value to associate with the key */ public void put(K key, V value) { - mCache.put(key, newCachedValue(value)); + cache.put(key, newCachedValue(value)); } /** @@ -201,7 +201,7 @@ public class ExpirableCache { *

Expiring the items in the cache does not imply they will be evicted. */ public void expireAll() { - mGeneration.incrementAndGet(); + generation.incrementAndGet(); } /** @@ -210,7 +210,7 @@ public class ExpirableCache { *

Implementation of {@link LruCache#create(K)} can use this method to create a new entry. */ public CachedValue newCachedValue(V value) { - return new GenerationalCachedValue(value, mGeneration); + return new GenerationalCachedValue(value, generation); } /** @@ -239,31 +239,31 @@ public class ExpirableCache { private static class GenerationalCachedValue implements ExpirableCache.CachedValue { /** The value stored in the cache. */ - public final V mValue; + public final V value; /** The generation at which the value was added to the cache. */ - private final int mGeneration; + private final int generation; /** The atomic integer storing the current generation of the cache it belongs to. */ - private final AtomicInteger mCacheGeneration; + private final AtomicInteger cacheGeneration; /** * @param cacheGeneration the atomic integer storing the generation of the cache in which this * value will be stored */ public GenerationalCachedValue(V value, AtomicInteger cacheGeneration) { - mValue = value; - mCacheGeneration = cacheGeneration; + this.value = value; + this.cacheGeneration = cacheGeneration; // Snapshot the current generation. - mGeneration = mCacheGeneration.get(); + generation = this.cacheGeneration.get(); } @Override public V getValue() { - return mValue; + return value; } @Override public boolean isExpired() { - return mGeneration != mCacheGeneration.get(); + return generation != cacheGeneration.get(); } } } diff --git a/java/com/android/dialer/util/TouchPointManager.java b/java/com/android/dialer/util/TouchPointManager.java index 0bd7371cc..ad5b00776 100644 --- a/java/com/android/dialer/util/TouchPointManager.java +++ b/java/com/android/dialer/util/TouchPointManager.java @@ -27,23 +27,23 @@ public class TouchPointManager { public static final String TOUCH_POINT = "touchPoint"; - private static TouchPointManager sInstance = new TouchPointManager(); + private static TouchPointManager instance = new TouchPointManager(); - private Point mPoint = new Point(); + private Point point = new Point(); /** Private constructor. Instance should only be acquired through getRunningInstance(). */ private TouchPointManager() {} public static TouchPointManager getInstance() { - return sInstance; + return instance; } public Point getPoint() { - return mPoint; + return point; } public void setPoint(int x, int y) { - mPoint.set(x, y); + point.set(x, y); } /** @@ -55,6 +55,6 @@ public class TouchPointManager { * (0,0). */ public boolean hasValidPoint() { - return mPoint.x != 0 || mPoint.y != 0; + return point.x != 0 || point.y != 0; } } diff --git a/java/com/android/dialer/util/TransactionSafeActivity.java b/java/com/android/dialer/util/TransactionSafeActivity.java index 9b5e92ba8..aa472493b 100644 --- a/java/com/android/dialer/util/TransactionSafeActivity.java +++ b/java/com/android/dialer/util/TransactionSafeActivity.java @@ -25,30 +25,30 @@ import android.support.v7.app.AppCompatActivity; */ public abstract class TransactionSafeActivity extends AppCompatActivity { - private boolean mIsSafeToCommitTransactions; + private boolean isSafeToCommitTransactions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override protected void onStart() { super.onStart(); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override protected void onResume() { super.onResume(); - mIsSafeToCommitTransactions = true; + isSafeToCommitTransactions = true; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - mIsSafeToCommitTransactions = false; + isSafeToCommitTransactions = false; } /** @@ -59,6 +59,6 @@ public abstract class TransactionSafeActivity extends AppCompatActivity { * outState)} (if that method is overridden), so the flag is properly set. */ public boolean isSafeToCommitTransactions() { - return mIsSafeToCommitTransactions; + return isSafeToCommitTransactions; } } diff --git a/java/com/android/dialer/voicemail/settings/VoicemailChangePinActivity.java b/java/com/android/dialer/voicemail/settings/VoicemailChangePinActivity.java index 13ca5b724..4e22fb335 100644 --- a/java/com/android/dialer/voicemail/settings/VoicemailChangePinActivity.java +++ b/java/com/android/dialer/voicemail/settings/VoicemailChangePinActivity.java @@ -71,8 +71,8 @@ public class VoicemailChangePinActivity extends Activity private static final int MESSAGE_HANDLE_RESULT = 1; - private PhoneAccountHandle mPhoneAccountHandle; - private PinChanger mPinChanger; + private PhoneAccountHandle phoneAccountHandle; + private PinChanger pinChanger; private static class ChangePinParams { PinChanger pinChanger; @@ -81,25 +81,25 @@ public class VoicemailChangePinActivity extends Activity String newPin; } - private DialerExecutor mChangePinExecutor; + private DialerExecutor changePinExecutor; - private int mPinMinLength; - private int mPinMaxLength; + private int pinMinLength; + private int pinMaxLength; - private State mUiState = State.Initial; - private String mOldPin; - private String mFirstPin; + private State uiState = State.Initial; + private String oldPin; + private String firstPin; - private ProgressDialog mProgressDialog; + private ProgressDialog progressDialog; - private TextView mHeaderText; - private TextView mHintText; - private TextView mErrorText; - private EditText mPinEntry; - private Button mCancelButton; - private Button mNextButton; + private TextView headerText; + private TextView hintText; + private TextView errorText; + private EditText pinEntry; + private Button cancelButton; + private Button nextButton; - private Handler mHandler = new ChangePinHandler(new WeakReference<>(this)); + private Handler handler = new ChangePinHandler(new WeakReference<>(this)); private enum State { /** @@ -116,9 +116,9 @@ public class VoicemailChangePinActivity extends Activity @Override public void onEnter(VoicemailChangePinActivity activity) { activity.setHeader(R.string.change_pin_enter_old_pin_header); - activity.mHintText.setText(R.string.change_pin_enter_old_pin_hint); - activity.mNextButton.setText(R.string.change_pin_continue_label); - activity.mErrorText.setText(null); + activity.hintText.setText(R.string.change_pin_enter_old_pin_hint); + activity.nextButton.setText(R.string.change_pin_continue_label); + activity.errorText.setText(null); } @Override @@ -128,7 +128,7 @@ public class VoicemailChangePinActivity extends Activity @Override public void handleNext(VoicemailChangePinActivity activity) { - activity.mOldPin = activity.getCurrentPasswordInput(); + activity.oldPin = activity.getCurrentPasswordInput(); activity.verifyOldPin(); } @@ -139,7 +139,7 @@ public class VoicemailChangePinActivity extends Activity } else { CharSequence message = activity.getChangePinResultMessage(result); activity.showError(message); - activity.mPinEntry.setText(""); + activity.pinEntry.setText(""); } } }, @@ -179,7 +179,7 @@ public class VoicemailChangePinActivity extends Activity // through other means, or the generated pin is invalid // Wipe the default old PIN so the old PIN input box will be shown to the user // on the next time. - activity.mPinChanger.setScrambledPin(null); + activity.pinChanger.setScrambledPin(null); activity.updateState(State.EnterOldPin); } } @@ -196,13 +196,13 @@ public class VoicemailChangePinActivity extends Activity EnterNewPin { @Override public void onEnter(VoicemailChangePinActivity activity) { - activity.mHeaderText.setText(R.string.change_pin_enter_new_pin_header); - activity.mNextButton.setText(R.string.change_pin_continue_label); - activity.mHintText.setText( + activity.headerText.setText(R.string.change_pin_enter_new_pin_header); + activity.nextButton.setText(R.string.change_pin_continue_label); + activity.hintText.setText( activity.getString( R.string.change_pin_enter_new_pin_hint, - activity.mPinMinLength, - activity.mPinMaxLength)); + activity.pinMinLength, + activity.pinMaxLength)); } @Override @@ -214,10 +214,10 @@ public class VoicemailChangePinActivity extends Activity } CharSequence error = activity.validatePassword(password); if (error != null) { - activity.mErrorText.setText(error); + activity.errorText.setText(error); activity.setNextEnabled(false); } else { - activity.mErrorText.setText(null); + activity.errorText.setText(null); activity.setNextEnabled(true); } } @@ -230,7 +230,7 @@ public class VoicemailChangePinActivity extends Activity activity.showError(errorMsg); return; } - activity.mFirstPin = activity.getCurrentPasswordInput(); + activity.firstPin = activity.getCurrentPasswordInput(); activity.updateState(State.ConfirmNewPin); } }, @@ -242,9 +242,9 @@ public class VoicemailChangePinActivity extends Activity ConfirmNewPin { @Override public void onEnter(VoicemailChangePinActivity activity) { - activity.mHeaderText.setText(R.string.change_pin_confirm_pin_header); - activity.mHintText.setText(null); - activity.mNextButton.setText(R.string.change_pin_ok_label); + activity.headerText.setText(R.string.change_pin_confirm_pin_header); + activity.hintText.setText(null); + activity.nextButton.setText(R.string.change_pin_ok_label); } @Override @@ -253,12 +253,12 @@ public class VoicemailChangePinActivity extends Activity activity.setNextEnabled(false); return; } - if (activity.getCurrentPasswordInput().equals(activity.mFirstPin)) { + if (activity.getCurrentPasswordInput().equals(activity.firstPin)) { activity.setNextEnabled(true); - activity.mErrorText.setText(null); + activity.errorText.setText(null); } else { activity.setNextEnabled(false); - activity.mErrorText.setText(R.string.change_pin_confirm_pins_dont_match); + activity.errorText.setText(R.string.change_pin_confirm_pins_dont_match); } } @@ -268,7 +268,7 @@ public class VoicemailChangePinActivity extends Activity // If the PIN change succeeded we no longer know what the old (current) PIN is. // Wipe the default old PIN so the old PIN input box will be shown to the user // on the next time. - activity.mPinChanger.setScrambledPin(null); + activity.pinChanger.setScrambledPin(null); activity.finish(); Logger.get(activity).logImpression(DialerImpression.Type.VVM_CHANGE_PIN_COMPLETED); @@ -291,7 +291,7 @@ public class VoicemailChangePinActivity extends Activity @Override public void handleNext(VoicemailChangePinActivity activity) { - activity.processPinChange(activity.mOldPin, activity.mFirstPin); + activity.processPinChange(activity.oldPin, activity.firstPin); } }; @@ -328,12 +328,11 @@ public class VoicemailChangePinActivity extends Activity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - mPhoneAccountHandle = - getIntent().getParcelableExtra(VoicemailClient.PARAM_PHONE_ACCOUNT_HANDLE); - mPinChanger = + phoneAccountHandle = getIntent().getParcelableExtra(VoicemailClient.PARAM_PHONE_ACCOUNT_HANDLE); + pinChanger = VoicemailComponent.get(this) .getVoicemailClient() - .createPinChanger(getApplicationContext(), mPhoneAccountHandle); + .createPinChanger(getApplicationContext(), phoneAccountHandle); setContentView(R.layout.voicemail_change_pin); setTitle(R.string.change_pin_title); @@ -341,23 +340,23 @@ public class VoicemailChangePinActivity extends Activity View view = findViewById(android.R.id.content); - mCancelButton = (Button) view.findViewById(R.id.cancel_button); - mCancelButton.setOnClickListener(this); - mNextButton = (Button) view.findViewById(R.id.next_button); - mNextButton.setOnClickListener(this); + cancelButton = (Button) view.findViewById(R.id.cancel_button); + cancelButton.setOnClickListener(this); + nextButton = (Button) view.findViewById(R.id.next_button); + nextButton.setOnClickListener(this); - mPinEntry = (EditText) view.findViewById(R.id.pin_entry); - mPinEntry.setOnEditorActionListener(this); - mPinEntry.addTextChangedListener(this); - if (mPinMaxLength != 0) { - mPinEntry.setFilters(new InputFilter[] {new LengthFilter(mPinMaxLength)}); + pinEntry = (EditText) view.findViewById(R.id.pin_entry); + pinEntry.setOnEditorActionListener(this); + pinEntry.addTextChangedListener(this); + if (pinMaxLength != 0) { + pinEntry.setFilters(new InputFilter[] {new LengthFilter(pinMaxLength)}); } - mHeaderText = (TextView) view.findViewById(R.id.headerText); - mHintText = (TextView) view.findViewById(R.id.hintText); - mErrorText = (TextView) view.findViewById(R.id.errorText); + headerText = (TextView) view.findViewById(R.id.headerText); + hintText = (TextView) view.findViewById(R.id.hintText); + errorText = (TextView) view.findViewById(R.id.errorText); - mChangePinExecutor = + changePinExecutor = DialerExecutorComponent.get(this) .dialerExecutorFactory() .createUiTaskBuilder(getFragmentManager(), "changePin", new ChangePinWorker()) @@ -365,8 +364,8 @@ public class VoicemailChangePinActivity extends Activity .onFailure((tr) -> sendResult(PinChanger.CHANGE_PIN_SYSTEM_ERROR)) .build(); - if (isPinScrambled(this, mPhoneAccountHandle)) { - mOldPin = mPinChanger.getScrambledPin(); + if (isPinScrambled(this, phoneAccountHandle)) { + oldPin = pinChanger.getScrambledPin(); updateState(State.VerifyOldPin); } else { updateState(State.EnterOldPin); @@ -375,22 +374,22 @@ public class VoicemailChangePinActivity extends Activity /** Extracts the pin length requirement sent by the server with a STATUS SMS. */ private void readPinLength() { - PinSpecification pinSpecification = mPinChanger.getPinSpecification(); - mPinMinLength = pinSpecification.minLength; - mPinMaxLength = pinSpecification.maxLength; + PinSpecification pinSpecification = pinChanger.getPinSpecification(); + pinMinLength = pinSpecification.minLength; + pinMaxLength = pinSpecification.maxLength; } @Override public void onResume() { super.onResume(); - updateState(mUiState); + updateState(uiState); } public void handleNext() { - if (mPinEntry.length() == 0) { + if (pinEntry.length() == 0) { return; } - mUiState.handleNext(this); + uiState.handleNext(this); } @Override @@ -413,7 +412,7 @@ public class VoicemailChangePinActivity extends Activity @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { - if (!mNextButton.isEnabled()) { + if (!nextButton.isEnabled()) { return true; } // Check if this was the result of hitting the enter or "done" key @@ -428,7 +427,7 @@ public class VoicemailChangePinActivity extends Activity @Override public void afterTextChanged(Editable s) { - mUiState.onInputChanged(this); + uiState.onInputChanged(this); } @Override @@ -454,18 +453,18 @@ public class VoicemailChangePinActivity extends Activity } private String getCurrentPasswordInput() { - return mPinEntry.getText().toString(); + return pinEntry.getText().toString(); } private void updateState(State state) { - State previousState = mUiState; - mUiState = state; + State previousState = uiState; + uiState = state; if (previousState != state) { previousState.onLeave(this); - mPinEntry.setText(""); - mUiState.onEnter(this); + pinEntry.setText(""); + uiState.onEnter(this); } - mUiState.onInputChanged(this); + uiState.onInputChanged(this); } /** @@ -475,21 +474,21 @@ public class VoicemailChangePinActivity extends Activity * @return error message to show to user or null if password is OK */ private CharSequence validatePassword(String password) { - if (mPinMinLength == 0 && mPinMaxLength == 0) { + if (pinMinLength == 0 && pinMaxLength == 0) { // Invalid length requirement is sent by the server, just accept anything and let the // server decide. return null; } - if (password.length() < mPinMinLength) { + if (password.length() < pinMinLength) { return getString(R.string.vm_change_pin_error_too_short); } return null; } private void setHeader(int text) { - mHeaderText.setText(text); - mPinEntry.setContentDescription(mHeaderText.getText()); + headerText.setText(text); + pinEntry.setContentDescription(headerText.getText()); } /** @@ -517,11 +516,11 @@ public class VoicemailChangePinActivity extends Activity } private void verifyOldPin() { - processPinChange(mOldPin, mOldPin); + processPinChange(oldPin, oldPin); } private void setNextEnabled(boolean enabled) { - mNextButton.setEnabled(enabled); + nextButton.setEnabled(enabled); } private void showError(CharSequence message) { @@ -538,30 +537,30 @@ public class VoicemailChangePinActivity extends Activity /** Asynchronous call to change the PIN on the server. */ private void processPinChange(String oldPin, String newPin) { - mProgressDialog = new ProgressDialog(this); - mProgressDialog.setCancelable(false); - mProgressDialog.setMessage(getString(R.string.vm_change_pin_progress_message)); - mProgressDialog.show(); + progressDialog = new ProgressDialog(this); + progressDialog.setCancelable(false); + progressDialog.setMessage(getString(R.string.vm_change_pin_progress_message)); + progressDialog.show(); ChangePinParams params = new ChangePinParams(); - params.pinChanger = mPinChanger; - params.phoneAccountHandle = mPhoneAccountHandle; + params.pinChanger = pinChanger; + params.phoneAccountHandle = phoneAccountHandle; params.oldPin = oldPin; params.newPin = newPin; - mChangePinExecutor.executeSerial(params); + changePinExecutor.executeSerial(params); } private void sendResult(@ChangePinResult int result) { LogUtil.i(TAG, "Change PIN result: " + result); - if (mProgressDialog.isShowing() + if (progressDialog.isShowing() && !VoicemailChangePinActivity.this.isDestroyed() && !VoicemailChangePinActivity.this.isFinishing()) { - mProgressDialog.dismiss(); + progressDialog.dismiss(); } else { LogUtil.i(TAG, "Dialog not visible, not dismissing"); } - mHandler.obtainMessage(MESSAGE_HANDLE_RESULT, result, 0).sendToTarget(); + handler.obtainMessage(MESSAGE_HANDLE_RESULT, result, 0).sendToTarget(); } private static class ChangePinHandler extends Handler { @@ -579,7 +578,7 @@ public class VoicemailChangePinActivity extends Activity return; } if (message.what == MESSAGE_HANDLE_RESULT) { - activity.mUiState.handleResult(activity, message.arg1); + activity.uiState.handleResult(activity, message.arg1); } } } diff --git a/java/com/android/dialer/voicemailstatus/VisualVoicemailEnabledChecker.java b/java/com/android/dialer/voicemailstatus/VisualVoicemailEnabledChecker.java index 3f519ad82..8010e025e 100644 --- a/java/com/android/dialer/voicemailstatus/VisualVoicemailEnabledChecker.java +++ b/java/com/android/dialer/voicemailstatus/VisualVoicemailEnabledChecker.java @@ -42,17 +42,17 @@ public class VisualVoicemailEnabledChecker implements CallLogQueryHandler.Listen public static final String PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER = "has_active_voicemail_provider"; - private SharedPreferences mPrefs; - private boolean mHasActiveVoicemailProvider; - private CallLogQueryHandler mCallLogQueryHandler; - private Context mContext; - private Callback mCallback; + private SharedPreferences prefs; + private boolean hasActiveVoicemailProvider; + private CallLogQueryHandler callLogQueryHandler; + private Context context; + private Callback callback; public VisualVoicemailEnabledChecker(Context context, @Nullable Callback callback) { - mContext = context; - mCallback = callback; - mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); - mHasActiveVoicemailProvider = mPrefs.getBoolean(PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, false); + this.context = context; + this.callback = callback; + prefs = PreferenceManager.getDefaultSharedPreferences(this.context); + hasActiveVoicemailProvider = prefs.getBoolean(PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, false); } /** @@ -60,7 +60,7 @@ public class VisualVoicemailEnabledChecker implements CallLogQueryHandler.Listen * result. */ public boolean isVisualVoicemailEnabled() { - return mHasActiveVoicemailProvider; + return hasActiveVoicemailProvider; } /** @@ -68,22 +68,22 @@ public class VisualVoicemailEnabledChecker implements CallLogQueryHandler.Listen * has changed, Callback.onVisualVoicemailEnabledStatusChanged() will be called. */ public void asyncUpdate() { - mCallLogQueryHandler = new CallLogQueryHandler(mContext, mContext.getContentResolver(), this); - mCallLogQueryHandler.fetchVoicemailStatus(); + callLogQueryHandler = new CallLogQueryHandler(context, context.getContentResolver(), this); + callLogQueryHandler.fetchVoicemailStatus(); } @Override public void onVoicemailStatusFetched(Cursor statusCursor) { boolean hasActiveVoicemailProvider = VoicemailStatusHelper.getNumberActivityVoicemailSources(statusCursor) > 0; - if (hasActiveVoicemailProvider != mHasActiveVoicemailProvider) { - mHasActiveVoicemailProvider = hasActiveVoicemailProvider; - mPrefs + if (hasActiveVoicemailProvider != this.hasActiveVoicemailProvider) { + this.hasActiveVoicemailProvider = hasActiveVoicemailProvider; + prefs .edit() - .putBoolean(PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, mHasActiveVoicemailProvider) + .putBoolean(PREF_KEY_HAS_ACTIVE_VOICEMAIL_PROVIDER, this.hasActiveVoicemailProvider) .apply(); - if (mCallback != null) { - mCallback.onVisualVoicemailEnabledStatusChanged(mHasActiveVoicemailProvider); + if (callback != null) { + callback.onVisualVoicemailEnabledStatusChanged(this.hasActiveVoicemailProvider); } } } diff --git a/java/com/android/dialer/widget/EmptyContentView.java b/java/com/android/dialer/widget/EmptyContentView.java index a76ab98d6..5c2e4d501 100644 --- a/java/com/android/dialer/widget/EmptyContentView.java +++ b/java/com/android/dialer/widget/EmptyContentView.java @@ -35,10 +35,10 @@ public class EmptyContentView extends LinearLayout implements View.OnClickListen public static final int NO_LABEL = 0; public static final int NO_IMAGE = 0; - private ImageView mImageView; - private TextView mDescriptionView; - private TextView mActionView; - private OnEmptyViewActionButtonClickedListener mOnActionButtonClickedListener; + private ImageView imageView; + private TextView descriptionView; + private TextView actionView; + private OnEmptyViewActionButtonClickedListener onActionButtonClickedListener; private @StringRes int actionLabel; @@ -60,40 +60,40 @@ public class EmptyContentView extends LinearLayout implements View.OnClickListen // Don't let touches fall through the empty view. setClickable(true); - mImageView = (ImageView) findViewById(R.id.empty_list_view_image); - mDescriptionView = (TextView) findViewById(R.id.empty_list_view_message); - mActionView = (TextView) findViewById(R.id.empty_list_view_action); - mActionView.setOnClickListener(this); + imageView = (ImageView) findViewById(R.id.empty_list_view_image); + descriptionView = (TextView) findViewById(R.id.empty_list_view_message); + actionView = (TextView) findViewById(R.id.empty_list_view_action); + actionView.setOnClickListener(this); } public void setDescription(int resourceId) { if (resourceId == NO_LABEL) { - mDescriptionView.setText(null); - mDescriptionView.setVisibility(View.GONE); + descriptionView.setText(null); + descriptionView.setVisibility(View.GONE); } else { - mDescriptionView.setText(resourceId); - mDescriptionView.setVisibility(View.VISIBLE); + descriptionView.setText(resourceId); + descriptionView.setVisibility(View.VISIBLE); } } public void setImage(int resourceId) { if (resourceId == NO_LABEL) { - mImageView.setImageDrawable(null); - mImageView.setVisibility(View.GONE); + imageView.setImageDrawable(null); + imageView.setVisibility(View.GONE); } else { - mImageView.setImageResource(resourceId); - mImageView.setVisibility(View.VISIBLE); + imageView.setImageResource(resourceId); + imageView.setVisibility(View.VISIBLE); } } public void setActionLabel(@StringRes int resourceId) { actionLabel = resourceId; if (resourceId == NO_LABEL) { - mActionView.setText(null); - mActionView.setVisibility(View.GONE); + actionView.setText(null); + actionView.setVisibility(View.GONE); } else { - mActionView.setText(resourceId); - mActionView.setVisibility(View.VISIBLE); + actionView.setText(resourceId); + actionView.setVisibility(View.VISIBLE); } } @@ -102,19 +102,19 @@ public class EmptyContentView extends LinearLayout implements View.OnClickListen } public boolean isShowingContent() { - return mImageView.getVisibility() == View.VISIBLE - || mDescriptionView.getVisibility() == View.VISIBLE - || mActionView.getVisibility() == View.VISIBLE; + return imageView.getVisibility() == View.VISIBLE + || descriptionView.getVisibility() == View.VISIBLE + || actionView.getVisibility() == View.VISIBLE; } public void setActionClickedListener(OnEmptyViewActionButtonClickedListener listener) { - mOnActionButtonClickedListener = listener; + onActionButtonClickedListener = listener; } @Override public void onClick(View v) { - if (mOnActionButtonClickedListener != null) { - mOnActionButtonClickedListener.onEmptyViewActionButtonClicked(); + if (onActionButtonClickedListener != null) { + onActionButtonClickedListener.onEmptyViewActionButtonClicked(); } } diff --git a/java/com/android/dialer/widget/FloatingActionButtonController.java b/java/com/android/dialer/widget/FloatingActionButtonController.java index 1f9923dca..c89c1a8ce 100644 --- a/java/com/android/dialer/widget/FloatingActionButtonController.java +++ b/java/com/android/dialer/widget/FloatingActionButtonController.java @@ -36,24 +36,24 @@ public class FloatingActionButtonController { public static final int ALIGN_QUARTER_END = 1; public static final int ALIGN_END = 2; - private final int mAnimationDuration; - private final int mFloatingActionButtonWidth; - private final int mFloatingActionButtonMarginRight; - private final FloatingActionButton mFab; - private final Interpolator mFabInterpolator; - private int mFabIconId = -1; - private int mScreenWidth; + private final int animationDuration; + private final int floatingActionButtonWidth; + private final int floatingActionButtonMarginRight; + private final FloatingActionButton fab; + private final Interpolator fabInterpolator; + private int fabIconId = -1; + private int screenWidth; public FloatingActionButtonController(Activity activity, FloatingActionButton fab) { Resources resources = activity.getResources(); - mFabInterpolator = + fabInterpolator = AnimationUtils.loadInterpolator(activity, android.R.interpolator.fast_out_slow_in); - mFloatingActionButtonWidth = + floatingActionButtonWidth = resources.getDimensionPixelSize(R.dimen.floating_action_button_width); - mFloatingActionButtonMarginRight = + floatingActionButtonMarginRight = resources.getDimensionPixelOffset(R.dimen.floating_action_button_margin_right); - mAnimationDuration = resources.getInteger(R.integer.floating_action_button_animation_duration); - mFab = fab; + animationDuration = resources.getInteger(R.integer.floating_action_button_animation_duration); + this.fab = fab; } /** @@ -63,12 +63,12 @@ public class FloatingActionButtonController { * @param screenWidth The width of the screen in pixels. */ public void setScreenWidth(int screenWidth) { - mScreenWidth = screenWidth; + this.screenWidth = screenWidth; } /** @see FloatingActionButton#isShown() */ public boolean isVisible() { - return mFab.isShown(); + return fab.isShown(); } /** @@ -86,14 +86,14 @@ public class FloatingActionButtonController { } public void changeIcon(Context context, @DrawableRes int iconId, String description) { - if (this.mFabIconId != iconId) { - mFab.setImageResource(iconId); - mFab.setImageTintList( + if (this.fabIconId != iconId) { + fab.setImageResource(iconId); + fab.setImageTintList( ColorStateList.valueOf(context.getResources().getColor(android.R.color.white))); - this.mFabIconId = iconId; + this.fabIconId = iconId; } - if (!mFab.getContentDescription().equals(description)) { - mFab.setContentDescription(description); + if (!fab.getContentDescription().equals(description)) { + fab.setContentDescription(description); } } @@ -105,7 +105,7 @@ public class FloatingActionButtonController { public void onPageScrolled(float positionOffset) { // As the page is scrolling, if we're on the first tab, update the FAB position so it // moves along with it. - mFab.setTranslationX(positionOffset * getTranslationXForAlignment(ALIGN_END)); + fab.setTranslationX(positionOffset * getTranslationXForAlignment(ALIGN_END)); } /** @@ -127,38 +127,38 @@ public class FloatingActionButtonController { * @param animate Whether or not to animate the transition. */ private void align(int align, int offsetX, int offsetY, boolean animate) { - if (mScreenWidth == 0) { + if (screenWidth == 0) { return; } int translationX = getTranslationXForAlignment(align); // Skip animation if container is not shown; animation causes container to show again. - if (animate && mFab.isShown()) { - mFab.animate() + if (animate && fab.isShown()) { + fab.animate() .translationX(translationX + offsetX) .translationY(offsetY) - .setInterpolator(mFabInterpolator) - .setDuration(mAnimationDuration) + .setInterpolator(fabInterpolator) + .setDuration(animationDuration) .start(); } else { - mFab.setTranslationX(translationX + offsetX); - mFab.setTranslationY(offsetY); + fab.setTranslationX(translationX + offsetX); + fab.setTranslationY(offsetY); } } /** @see FloatingActionButton#show() */ public void scaleIn() { - mFab.show(); + fab.show(); } /** @see FloatingActionButton#hide() */ public void scaleOut() { - mFab.hide(); + fab.hide(); } public void scaleOut(OnVisibilityChangedListener listener) { - mFab.hide(listener); + fab.hide(listener); } /** @@ -176,12 +176,11 @@ public class FloatingActionButtonController { return 0; case ALIGN_QUARTER_END: // Moves the FAB a quarter of the screen width. - result = mScreenWidth / 4; + result = screenWidth / 4; break; case ALIGN_END: // Moves the FAB half the screen width. Same as aligning right with a marginRight. - result = - mScreenWidth / 2 - mFloatingActionButtonWidth / 2 - mFloatingActionButtonMarginRight; + result = screenWidth / 2 - floatingActionButtonWidth / 2 - floatingActionButtonMarginRight; break; default: throw Assert.createIllegalStateFailException("Invalid alignment value: " + align); @@ -193,6 +192,6 @@ public class FloatingActionButtonController { } private boolean isLayoutRtl() { - return mFab.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; + return fab.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; } } diff --git a/java/com/android/dialer/widget/ResizingTextEditText.java b/java/com/android/dialer/widget/ResizingTextEditText.java index fb894bd14..16b755241 100644 --- a/java/com/android/dialer/widget/ResizingTextEditText.java +++ b/java/com/android/dialer/widget/ResizingTextEditText.java @@ -25,27 +25,27 @@ import com.android.dialer.util.ViewUtil; /** EditText which resizes dynamically with respect to text length. */ public class ResizingTextEditText extends EditText { - private final int mOriginalTextSize; - private final int mMinTextSize; + private final int originalTextSize; + private final int minTextSize; public ResizingTextEditText(Context context, AttributeSet attrs) { super(context, attrs); - mOriginalTextSize = (int) getTextSize(); + originalTextSize = (int) getTextSize(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ResizingText); - mMinTextSize = - (int) a.getDimension(R.styleable.ResizingText_resizing_text_min_size, mOriginalTextSize); + minTextSize = + (int) a.getDimension(R.styleable.ResizingText_resizing_text_min_size, originalTextSize); a.recycle(); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); - ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize); + ViewUtil.resizeText(this, originalTextSize, minTextSize); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); - ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize); + ViewUtil.resizeText(this, originalTextSize, minTextSize); } } diff --git a/java/com/android/dialer/widget/ResizingTextTextView.java b/java/com/android/dialer/widget/ResizingTextTextView.java index 9b624414d..100b2ca29 100644 --- a/java/com/android/dialer/widget/ResizingTextTextView.java +++ b/java/com/android/dialer/widget/ResizingTextTextView.java @@ -25,27 +25,27 @@ import com.android.dialer.util.ViewUtil; /** TextView which resizes dynamically with respect to text length. */ public class ResizingTextTextView extends TextView { - private final int mOriginalTextSize; - private final int mMinTextSize; + private final int originalTextSize; + private final int minTextSize; public ResizingTextTextView(Context context, AttributeSet attrs) { super(context, attrs); - mOriginalTextSize = (int) getTextSize(); + originalTextSize = (int) getTextSize(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ResizingText); - mMinTextSize = - (int) a.getDimension(R.styleable.ResizingText_resizing_text_min_size, mOriginalTextSize); + minTextSize = + (int) a.getDimension(R.styleable.ResizingText_resizing_text_min_size, originalTextSize); a.recycle(); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { super.onTextChanged(text, start, lengthBefore, lengthAfter); - ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize); + ViewUtil.resizeText(this, originalTextSize, minTextSize); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); - ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize); + ViewUtil.resizeText(this, originalTextSize, minTextSize); } } -- cgit v1.2.3