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 +- .../android/incallui/AccelerometerListener.java | 65 +- java/com/android/incallui/CallButtonPresenter.java | 231 ++++---- java/com/android/incallui/CallCardPresenter.java | 428 ++++++------- java/com/android/incallui/CallerInfo.java | 20 +- .../com/android/incallui/CallerInfoAsyncQuery.java | 98 +-- .../incallui/ConferenceManagerFragment.java | 24 +- .../incallui/ConferenceParticipantListAdapter.java | 114 ++-- java/com/android/incallui/ContactInfoCache.java | 154 ++--- .../incallui/ContactsPreferencesFactory.java | 12 +- java/com/android/incallui/DialpadFragment.java | 96 +-- java/com/android/incallui/DialpadPresenter.java | 16 +- .../com/android/incallui/ExternalCallNotifier.java | 98 +-- java/com/android/incallui/InCallCameraManager.java | 46 +- .../incallui/InCallOrientationEventListener.java | 26 +- java/com/android/incallui/InCallPresenter.java | 632 ++++++++++---------- .../incallui/InCallUIMaterialColorMapUtils.java | 20 +- .../android/incallui/PostCharDialogFragment.java | 24 +- java/com/android/incallui/ProximitySensor.java | 128 ++-- java/com/android/incallui/StatusBarNotifier.java | 209 ++++--- .../incallui/TransactionSafeFragmentActivity.java | 12 +- java/com/android/incallui/VideoCallPresenter.java | 276 +++++---- .../com/android/incallui/VideoPauseController.java | 90 +-- .../answer/impl/FixedAspectSurfaceView.java | 8 +- .../answer/impl/affordance/SwipeButtonHelper.java | 6 +- .../answer/impl/affordance/SwipeButtonView.java | 6 +- .../impl/classifier/AccelerationClassifier.java | 16 +- .../answer/impl/classifier/AnglesClassifier.java | 131 ++-- .../answer/impl/classifier/Classifier.java | 2 +- .../answer/impl/classifier/ClassifierData.java | 36 +- .../impl/classifier/EndPointLengthClassifier.java | 2 +- .../impl/classifier/EndPointRatioClassifier.java | 2 +- .../answer/impl/classifier/FalsingManager.java | 52 +- .../answer/impl/classifier/HistoryEvaluator.java | 25 +- .../classifier/HumanInteractionClassifier.java | 66 +-- .../impl/classifier/PointerCountClassifier.java | 10 +- .../impl/classifier/ProximityClassifier.java | 36 +- .../impl/classifier/SpeedAnglesClassifier.java | 88 +-- .../incallui/answer/impl/classifier/Stroke.java | 34 +- .../answer/impl/utils/FlingAnimationUtils.java | 56 +- java/com/android/incallui/baseui/BaseFragment.java | 14 +- java/com/android/incallui/baseui/Presenter.java | 8 +- java/com/android/incallui/call/CallList.java | 130 ++-- java/com/android/incallui/call/DialerCall.java | 395 ++++++------ .../android/incallui/call/ExternalCallList.java | 32 +- .../call/InCallVideoCallCallbackNotifier.java | 14 +- java/com/android/incallui/call/TelecomAdapter.java | 40 +- .../calllocation/impl/DownloadMapImageTask.java | 8 +- .../incallui/calllocation/impl/HttpFetcher.java | 12 +- .../calllocation/impl/LocationPresenter.java | 24 +- .../calllocation/impl/ReverseGeocodeTask.java | 8 +- .../incallui/latencyreport/LatencyReport.java | 76 +-- .../incallui/ringtone/DialerRingtoneManager.java | 24 +- .../incallui/ringtone/InCallTonePlayer.java | 36 +- java/com/android/newbubble/NewCheckableButton.java | 10 +- .../RoundedRectRevealOutlineProvider.java | 40 +- .../com/android/voicemail/impl/ActivationTask.java | 18 +- java/com/android/voicemail/impl/Assert.java | 12 +- java/com/android/voicemail/impl/OmtpEvents.java | 20 +- .../voicemail/impl/OmtpVvmCarrierConfigHelper.java | 142 ++--- .../voicemail/impl/TelephonyVvmConfigManager.java | 16 +- java/com/android/voicemail/impl/Voicemail.java | 192 +++--- .../android/voicemail/impl/VoicemailStatus.java | 46 +- java/com/android/voicemail/impl/VvmLog.java | 32 +- .../voicemail/impl/VvmPhoneStateListener.java | 48 +- .../impl/fetch/FetchVoicemailReceiver.java | 58 +- .../impl/fetch/VoicemailFetchedCallback.java | 34 +- .../android/voicemail/impl/imap/ImapHelper.java | 137 +++-- .../voicemail/impl/imap/VoicemailPayload.java | 12 +- java/com/android/voicemail/impl/mail/Address.java | 60 +- .../android/voicemail/impl/mail/Base64Body.java | 16 +- java/com/android/voicemail/impl/mail/BodyPart.java | 4 +- .../impl/mail/FixedLengthInputStream.java | 28 +- .../android/voicemail/impl/mail/MailTransport.java | 126 ++-- java/com/android/voicemail/impl/mail/Message.java | 22 +- .../voicemail/impl/mail/MessagingException.java | 16 +- .../com/android/voicemail/impl/mail/Multipart.java | 24 +- .../android/voicemail/impl/mail/PackedString.java | 34 +- .../voicemail/impl/mail/PeekableInputStream.java | 37 +- .../android/voicemail/impl/mail/TempDirectory.java | 8 +- .../impl/mail/internet/BinaryTempFileBody.java | 16 +- .../voicemail/impl/mail/internet/MimeBodyPart.java | 46 +- .../voicemail/impl/mail/internet/MimeHeader.java | 20 +- .../voicemail/impl/mail/internet/MimeMessage.java | 150 ++--- .../impl/mail/internet/MimeMultipart.java | 42 +- .../voicemail/impl/mail/internet/TextBody.java | 10 +- .../voicemail/impl/mail/store/ImapConnection.java | 116 ++-- .../voicemail/impl/mail/store/ImapFolder.java | 100 ++-- .../voicemail/impl/mail/store/ImapStore.java | 78 +-- .../impl/mail/store/imap/DigestMd5Utils.java | 48 +- .../impl/mail/store/imap/ImapElement.java | 8 +- .../voicemail/impl/mail/store/imap/ImapList.java | 22 +- .../impl/mail/store/imap/ImapMemoryLiteral.java | 18 +- .../impl/mail/store/imap/ImapResponse.java | 22 +- .../impl/mail/store/imap/ImapResponseParser.java | 50 +- .../impl/mail/store/imap/ImapSimpleString.java | 12 +- .../voicemail/impl/mail/store/imap/ImapString.java | 20 +- .../impl/mail/store/imap/ImapTempFileLiteral.java | 20 +- .../impl/mail/utility/CountingOutputStream.java | 16 +- .../voicemail/impl/mail/utils/LogUtils.java | 12 +- .../voicemail/impl/protocol/Vvm3Subscriber.java | 68 +-- .../voicemail/impl/scheduling/BaseTask.java | 76 +-- .../impl/scheduling/MinimalIntervalPolicy.java | 22 +- .../voicemail/impl/scheduling/PostponePolicy.java | 16 +- .../voicemail/impl/scheduling/RetryPolicy.java | 59 +- .../voicemail/impl/sms/OmtpMessageReceiver.java | 18 +- .../voicemail/impl/sms/OmtpMessageSender.java | 21 +- .../impl/sms/OmtpStandardMessageSender.java | 28 +- .../android/voicemail/impl/sms/StatusMessage.java | 104 ++-- .../voicemail/impl/sms/StatusSmsFetcher.java | 29 +- .../android/voicemail/impl/sms/SyncMessage.java | 56 +- .../voicemail/impl/sync/OmtpVvmSyncService.java | 76 +-- .../android/voicemail/impl/sync/SyncOneTask.java | 14 +- java/com/android/voicemail/impl/sync/SyncTask.java | 14 +- .../impl/sync/VoicemailStatusQueryHelper.java | 16 +- .../voicemail/impl/sync/VoicemailsQueryHelper.java | 38 +- .../voicemail/impl/sync/VvmNetworkRequest.java | 20 +- .../impl/sync/VvmNetworkRequestCallback.java | 72 ++- .../voicemail/impl/utils/IndentingPrintWriter.java | 64 +- 219 files changed, 8051 insertions(+), 8093 deletions(-) (limited to 'java/com/android') 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); } } diff --git a/java/com/android/incallui/AccelerometerListener.java b/java/com/android/incallui/AccelerometerListener.java index 01f884354..92e62b098 100644 --- a/java/com/android/incallui/AccelerometerListener.java +++ b/java/com/android/incallui/AccelerometerListener.java @@ -23,7 +23,7 @@ import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Handler; import android.os.Message; -import android.util.Log; +import com.android.dialer.common.LogUtil; /** * This class is used to listen to the accelerometer to monitor the orientation of the phone. The @@ -42,40 +42,40 @@ public class AccelerometerListener { private static final int VERTICAL_DEBOUNCE = 100; private static final int HORIZONTAL_DEBOUNCE = 500; private static final double VERTICAL_ANGLE = 50.0; - private SensorManager mSensorManager; - private Sensor mSensor; + private SensorManager sensorManager; + private Sensor sensor; // mOrientation is the orientation value most recently reported to the client. - private int mOrientation; + private int orientation; // mPendingOrientation is the latest orientation computed based on the sensor value. // This is sent to the client after a rebounce delay, at which point it is copied to // mOrientation. - private int mPendingOrientation; - private OrientationListener mListener; - Handler mHandler = + private int pendingOrientation; + private OrientationListener listener; + Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case ORIENTATION_CHANGED: synchronized (this) { - mOrientation = mPendingOrientation; + orientation = pendingOrientation; if (DEBUG) { - Log.d( + LogUtil.d( TAG, "orientation: " - + (mOrientation == ORIENTATION_HORIZONTAL + + (orientation == ORIENTATION_HORIZONTAL ? "horizontal" - : (mOrientation == ORIENTATION_VERTICAL ? "vertical" : "unknown"))); + : (orientation == ORIENTATION_VERTICAL ? "vertical" : "unknown"))); } - if (mListener != null) { - mListener.orientationChanged(mOrientation); + if (listener != null) { + listener.orientationChanged(orientation); } } break; } } }; - SensorEventListener mSensorListener = + SensorEventListener sensorListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { @@ -89,34 +89,33 @@ public class AccelerometerListener { }; public AccelerometerListener(Context context) { - mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); } public void setListener(OrientationListener listener) { - mListener = listener; + this.listener = listener; } public void enable(boolean enable) { if (DEBUG) { - Log.d(TAG, "enable(" + enable + ")"); + LogUtil.d(TAG, "enable(" + enable + ")"); } synchronized (this) { if (enable) { - mOrientation = ORIENTATION_UNKNOWN; - mPendingOrientation = ORIENTATION_UNKNOWN; - mSensorManager.registerListener( - mSensorListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL); + orientation = ORIENTATION_UNKNOWN; + pendingOrientation = ORIENTATION_UNKNOWN; + sensorManager.registerListener(sensorListener, sensor, SensorManager.SENSOR_DELAY_NORMAL); } else { - mSensorManager.unregisterListener(mSensorListener); - mHandler.removeMessages(ORIENTATION_CHANGED); + sensorManager.unregisterListener(sensorListener); + handler.removeMessages(ORIENTATION_CHANGED); } } } private void setOrientation(int orientation) { synchronized (this) { - if (mPendingOrientation == orientation) { + if (pendingOrientation == orientation) { // Pending orientation has not changed, so do nothing. return; } @@ -124,26 +123,26 @@ public class AccelerometerListener { // Cancel any pending messages. // We will either start a new timer or cancel alltogether // if the orientation has not changed. - mHandler.removeMessages(ORIENTATION_CHANGED); + handler.removeMessages(ORIENTATION_CHANGED); - if (mOrientation != orientation) { + if (this.orientation != orientation) { // Set timer to send an event if the orientation has changed since its // previously reported value. - mPendingOrientation = orientation; - final Message m = mHandler.obtainMessage(ORIENTATION_CHANGED); + pendingOrientation = orientation; + final Message m = handler.obtainMessage(ORIENTATION_CHANGED); // set delay to our debounce timeout int delay = (orientation == ORIENTATION_VERTICAL ? VERTICAL_DEBOUNCE : HORIZONTAL_DEBOUNCE); - mHandler.sendMessageDelayed(m, delay); + handler.sendMessageDelayed(m, delay); } else { // no message is pending - mPendingOrientation = ORIENTATION_UNKNOWN; + pendingOrientation = ORIENTATION_UNKNOWN; } } } private void onSensorEvent(double x, double y, double z) { if (VDEBUG) { - Log.d(TAG, "onSensorEvent(" + x + ", " + y + ", " + z + ")"); + LogUtil.d(TAG, "onSensorEvent(" + x + ", " + y + ", " + z + ")"); } // If some values are exactly zero, then likely the sensor is not powered up yet. @@ -161,7 +160,7 @@ public class AccelerometerListener { final int orientation = (angle > VERTICAL_ANGLE ? ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL); if (VDEBUG) { - Log.d(TAG, "angle: " + angle + " orientation: " + orientation); + LogUtil.d(TAG, "angle: " + angle + " orientation: " + orientation); } setOrientation(orientation); } diff --git a/java/com/android/incallui/CallButtonPresenter.java b/java/com/android/incallui/CallButtonPresenter.java index c20642b59..88aeaf581 100644 --- a/java/com/android/incallui/CallButtonPresenter.java +++ b/java/com/android/incallui/CallButtonPresenter.java @@ -62,22 +62,22 @@ public class CallButtonPresenter private static final String KEY_AUTOMATICALLY_MUTED = "incall_key_automatically_muted"; private static final String KEY_PREVIOUS_MUTE_STATE = "incall_key_previous_mute_state"; - private final Context mContext; - private InCallButtonUi mInCallButtonUi; - private DialerCall mCall; - private boolean mAutomaticallyMuted = false; - private boolean mPreviousMuteState = false; + private final Context context; + private InCallButtonUi inCallButtonUi; + private DialerCall call; + private boolean automaticallyMuted = false; + private boolean previousMuteState = false; private boolean isInCallButtonUiReady; - private PhoneAccountHandle mOtherAccount; + private PhoneAccountHandle otherAccount; public CallButtonPresenter(Context context) { - mContext = context.getApplicationContext(); + this.context = context.getApplicationContext(); } @Override public void onInCallButtonUiReady(InCallButtonUi ui) { Assert.checkState(!isInCallButtonUiReady); - mInCallButtonUi = ui; + inCallButtonUi = ui; AudioModeProvider.getInstance().addListener(this); // register for call state changes last @@ -96,7 +96,7 @@ public class CallButtonPresenter @Override public void onInCallButtonUiUnready() { Assert.checkState(isInCallButtonUiReady); - mInCallButtonUi = null; + inCallButtonUi = null; InCallPresenter.getInstance().removeListener(this); AudioModeProvider.getInstance().removeListener(this); InCallPresenter.getInstance().removeIncomingCallListener(this); @@ -110,16 +110,16 @@ public class CallButtonPresenter public void onStateChange(InCallState oldState, InCallState newState, CallList callList) { Trace.beginSection("CallButtonPresenter.onStateChange"); if (newState == InCallState.OUTGOING) { - mCall = callList.getOutgoingCall(); + call = callList.getOutgoingCall(); } else if (newState == InCallState.INCALL) { - mCall = callList.getActiveOrBackgroundCall(); + call = callList.getActiveOrBackgroundCall(); // When connected to voice mail, automatically shows the dialpad. // (On previous releases we showed it when in-call shows up, before waiting for // OUTGOING. We may want to do that once we start showing "Voice mail" label on // the dialpad too.) - if (oldState == InCallState.OUTGOING && mCall != null) { - if (mCall.isVoiceMailNumber() && getActivity() != null) { + if (oldState == InCallState.OUTGOING && call != null) { + if (call.isVoiceMailNumber() && getActivity() != null) { getActivity().showDialpadFragment(true /* show */, true /* animate */); } } @@ -127,11 +127,11 @@ public class CallButtonPresenter if (getActivity() != null) { getActivity().showDialpadFragment(false /* show */, true /* animate */); } - mCall = callList.getIncomingCall(); + call = callList.getIncomingCall(); } else { - mCall = null; + call = null; } - updateUi(newState, mCall); + updateUi(newState, call); Trace.endSection(); } @@ -146,7 +146,7 @@ public class CallButtonPresenter @Override public void onDetailsChanged(DialerCall call, android.telecom.Call.Details details) { // Only update if the changes are for the currently active call - if (mInCallButtonUi != null && call != null && call.equals(mCall)) { + if (inCallButtonUi != null && call != null && call.equals(this.call)) { updateButtonsState(call); } } @@ -158,15 +158,15 @@ public class CallButtonPresenter @Override public void onCanAddCallChanged(boolean canAddCall) { - if (mInCallButtonUi != null && mCall != null) { - updateButtonsState(mCall); + if (inCallButtonUi != null && call != null) { + updateButtonsState(call); } } @Override public void onAudioStateChanged(CallAudioState audioState) { - if (mInCallButtonUi != null) { - mInCallButtonUi.setAudioState(audioState); + if (inCallButtonUi != null) { + inCallButtonUi.setAudioState(audioState); } } @@ -192,25 +192,25 @@ public class CallButtonPresenter // It's clear the UI is wrong, so update the supported mode once again. LogUtil.e( "CallButtonPresenter", "toggling speakerphone not allowed when bluetooth supported."); - mInCallButtonUi.setAudioState(audioState); + inCallButtonUi.setAudioState(audioState); return; } int newRoute; if (audioState.getRoute() == CallAudioState.ROUTE_SPEAKER) { newRoute = CallAudioState.ROUTE_WIRED_OR_EARPIECE; - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_SCREEN_TURN_ON_WIRED_OR_EARPIECE, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); } else { newRoute = CallAudioState.ROUTE_SPEAKER; - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_SCREEN_TURN_ON_SPEAKERPHONE, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); } setAudioRoute(newRoute); @@ -221,61 +221,61 @@ public class CallButtonPresenter LogUtil.i( "CallButtonPresenter", "turning on mute: %s, clicked by user: %s", checked, clickedByUser); if (clickedByUser) { - Logger.get(mContext) + Logger.get(context) .logCallImpression( checked ? DialerImpression.Type.IN_CALL_SCREEN_TURN_ON_MUTE : DialerImpression.Type.IN_CALL_SCREEN_TURN_OFF_MUTE, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); } TelecomAdapter.getInstance().mute(checked); } @Override public void holdClicked(boolean checked) { - if (mCall == null) { + if (call == null) { return; } if (checked) { - LogUtil.i("CallButtonPresenter", "putting the call on hold: " + mCall); - mCall.hold(); + LogUtil.i("CallButtonPresenter", "putting the call on hold: " + call); + call.hold(); } else { - LogUtil.i("CallButtonPresenter", "removing the call from hold: " + mCall); - mCall.unhold(); + LogUtil.i("CallButtonPresenter", "removing the call from hold: " + call); + call.unhold(); } } @Override public void swapClicked() { - if (mCall == null) { + if (call == null) { return; } - LogUtil.i("CallButtonPresenter", "swapping the call: " + mCall); - TelecomAdapter.getInstance().swap(mCall.getId()); + LogUtil.i("CallButtonPresenter", "swapping the call: " + call); + TelecomAdapter.getInstance().swap(call.getId()); } @Override public void mergeClicked() { - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_MERGE_BUTTON_PRESSED, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); - TelecomAdapter.getInstance().merge(mCall.getId()); + call.getUniqueCallId(), + call.getTimeAddedMs()); + TelecomAdapter.getInstance().merge(call.getId()); } @Override public void addCallClicked() { - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_ADD_CALL_BUTTON_PRESSED, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); // Automatically mute the current call - mAutomaticallyMuted = true; - mPreviousMuteState = AudioModeProvider.getInstance().getAudioState().isMuted(); + automaticallyMuted = true; + previousMuteState = AudioModeProvider.getInstance().getAudioState().isMuted(); // Simulate a click on the mute button muteClicked(true /* checked */, false /* clickedByUser */); TelecomAdapter.getInstance().addCall(); @@ -283,11 +283,11 @@ public class CallButtonPresenter @Override public void showDialpadClicked(boolean checked) { - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_SHOW_DIALPAD_BUTTON_PRESSED, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); LogUtil.v("CallButtonPresenter", "show dialpad " + String.valueOf(checked)); getActivity().showDialpadFragment(checked /* show */, true /* animate */); } @@ -295,25 +295,25 @@ public class CallButtonPresenter @Override public void changeToVideoClicked() { LogUtil.enterBlock("CallButtonPresenter.changeToVideoClicked"); - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.VIDEO_CALL_UPGRADE_REQUESTED, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); - mCall.getVideoTech().upgradeToVideo(mContext); + call.getUniqueCallId(), + call.getTimeAddedMs()); + call.getVideoTech().upgradeToVideo(context); } @Override public void onEndCallClicked() { - LogUtil.i("CallButtonPresenter.onEndCallClicked", "call: " + mCall); - if (mCall != null) { - mCall.disconnect(); + LogUtil.i("CallButtonPresenter.onEndCallClicked", "call: " + call); + if (call != null) { + call.disconnect(); } } @Override public void showAudioRouteSelector() { - mInCallButtonUi.showAudioRouteSelector(); + inCallButtonUi.showAudioRouteSelector(); } @Override @@ -323,9 +323,9 @@ public class CallButtonPresenter SwapSimWorker worker = new SwapSimWorker( getContext(), - mCall, + call, InCallPresenter.getInstance().getCallList(), - mOtherAccount, + otherAccount, InCallPresenter.getInstance().acquireInCallUiLock("swapSim")); DialerExecutorComponent.get(getContext()) .dialerExecutorFactory() @@ -348,14 +348,14 @@ public class CallButtonPresenter @Override public void toggleCameraClicked() { LogUtil.i("CallButtonPresenter.toggleCameraClicked", ""); - if (mCall == null) { + if (call == null) { return; } - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_SCREEN_SWAP_CAMERA, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); switchCameraClicked( !InCallPresenter.getInstance().getInCallCameraManager().isUsingFrontFacingCamera()); } @@ -370,25 +370,25 @@ public class CallButtonPresenter public void pauseVideoClicked(boolean pause) { LogUtil.i("CallButtonPresenter.pauseVideoClicked", "%s", pause ? "pause" : "unpause"); - Logger.get(mContext) + Logger.get(context) .logCallImpression( pause ? DialerImpression.Type.IN_CALL_SCREEN_TURN_OFF_VIDEO : DialerImpression.Type.IN_CALL_SCREEN_TURN_ON_VIDEO, - mCall.getUniqueCallId(), - mCall.getTimeAddedMs()); + call.getUniqueCallId(), + call.getTimeAddedMs()); if (pause) { - mCall.getVideoTech().setCamera(null); - mCall.getVideoTech().stopTransmission(); + call.getVideoTech().setCamera(null); + call.getVideoTech().stopTransmission(); } else { updateCamera( InCallPresenter.getInstance().getInCallCameraManager().isUsingFrontFacingCamera()); - mCall.getVideoTech().resumeTransmission(mContext); + call.getVideoTech().resumeTransmission(context); } - mInCallButtonUi.setVideoPaused(pause); - mInCallButtonUi.enableButton(InCallButtonIds.BUTTON_PAUSE_VIDEO, false); + inCallButtonUi.setVideoPaused(pause); + inCallButtonUi.enableButton(InCallButtonIds.BUTTON_PAUSE_VIDEO, false); } private void updateCamera(boolean useFrontFacingCamera) { @@ -401,26 +401,26 @@ public class CallButtonPresenter cameraManager.isUsingFrontFacingCamera() ? CameraDirection.CAMERA_DIRECTION_FRONT_FACING : CameraDirection.CAMERA_DIRECTION_BACK_FACING; - mCall.setCameraDir(cameraDir); - mCall.getVideoTech().setCamera(cameraId); + call.setCameraDir(cameraDir); + call.getVideoTech().setCamera(cameraId); } } private void updateUi(InCallState state, DialerCall call) { LogUtil.v("CallButtonPresenter", "updating call UI for call: %s", call); - if (mInCallButtonUi == null) { + if (inCallButtonUi == null) { return; } if (call != null) { - mInCallButtonUi.updateInCallButtonUiColors( + inCallButtonUi.updateInCallButtonUiColors( InCallPresenter.getInstance().getThemeColorManager().getSecondaryColor()); } final boolean isEnabled = state.isConnectingOrConnected() && !state.isIncoming() && call != null; - mInCallButtonUi.setEnabled(isEnabled); + inCallButtonUi.setEnabled(isEnabled); if (call == null) { return; @@ -451,53 +451,53 @@ public class CallButtonPresenter final boolean isCallOnHold = call.getState() == DialerCall.State.ONHOLD; final boolean showAddCall = - TelecomAdapter.getInstance().canAddCall() && UserManagerCompat.isUserUnlocked(mContext); + TelecomAdapter.getInstance().canAddCall() && UserManagerCompat.isUserUnlocked(context); final boolean showMerge = call.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE); final boolean showUpgradeToVideo = !isVideo && (hasVideoCallCapabilities(call)); final boolean showDowngradeToAudio = isVideo && isDowngradeToAudioSupported(call); final boolean showMute = call.can(android.telecom.Call.Details.CAPABILITY_MUTE); final boolean hasCameraPermission = - isVideo && VideoUtils.hasCameraPermissionAndShownPrivacyToast(mContext); + isVideo && VideoUtils.hasCameraPermissionAndShownPrivacyToast(context); // Disabling local video doesn't seem to work when dialing. See a bug. final boolean showPauseVideo = isVideo && call.getState() != DialerCall.State.DIALING && call.getState() != DialerCall.State.CONNECTING; - mOtherAccount = TelecomUtil.getOtherAccount(getContext(), call.getAccountHandle()); + otherAccount = TelecomUtil.getOtherAccount(getContext(), call.getAccountHandle()); boolean showSwapSim = - mOtherAccount != null + otherAccount != null && !call.isVoiceMailNumber() && DialerCall.State.isDialing(call.getState()) // Most devices cannot make calls on 2 SIMs at the same time. && InCallPresenter.getInstance().getCallList().getAllCalls().size() == 1; - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_AUDIO, true); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_SWAP, showSwap); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_HOLD, showHold); - mInCallButtonUi.setHold(isCallOnHold); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_MUTE, showMute); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_SWAP_SIM, showSwapSim); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_ADD_CALL, true); - mInCallButtonUi.enableButton(InCallButtonIds.BUTTON_ADD_CALL, showAddCall); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_UPGRADE_TO_VIDEO, showUpgradeToVideo); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_DOWNGRADE_TO_AUDIO, showDowngradeToAudio); - mInCallButtonUi.showButton( + inCallButtonUi.showButton(InCallButtonIds.BUTTON_AUDIO, true); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_SWAP, showSwap); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_HOLD, showHold); + inCallButtonUi.setHold(isCallOnHold); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_MUTE, showMute); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_SWAP_SIM, showSwapSim); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_ADD_CALL, true); + inCallButtonUi.enableButton(InCallButtonIds.BUTTON_ADD_CALL, showAddCall); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_UPGRADE_TO_VIDEO, showUpgradeToVideo); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_DOWNGRADE_TO_AUDIO, showDowngradeToAudio); + inCallButtonUi.showButton( InCallButtonIds.BUTTON_SWITCH_CAMERA, isVideo && hasCameraPermission && call.getVideoTech().isTransmitting()); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_PAUSE_VIDEO, showPauseVideo); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_PAUSE_VIDEO, showPauseVideo); if (isVideo) { - mInCallButtonUi.setVideoPaused(!call.getVideoTech().isTransmitting() || !hasCameraPermission); + inCallButtonUi.setVideoPaused(!call.getVideoTech().isTransmitting() || !hasCameraPermission); } - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_DIALPAD, true); - mInCallButtonUi.showButton(InCallButtonIds.BUTTON_MERGE, showMerge); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_DIALPAD, true); + inCallButtonUi.showButton(InCallButtonIds.BUTTON_MERGE, showMerge); - mInCallButtonUi.updateButtonStates(); + inCallButtonUi.updateButtonStates(); } private boolean hasVideoCallCapabilities(DialerCall call) { - return call.getVideoTech().isAvailable(mContext); + return call.getVideoTech().isAvailable(context); } /** @@ -516,52 +516,51 @@ public class CallButtonPresenter @Override public void refreshMuteState() { // Restore the previous mute state - if (mAutomaticallyMuted - && AudioModeProvider.getInstance().getAudioState().isMuted() != mPreviousMuteState) { - if (mInCallButtonUi == null) { + if (automaticallyMuted + && AudioModeProvider.getInstance().getAudioState().isMuted() != previousMuteState) { + if (inCallButtonUi == null) { return; } - muteClicked(mPreviousMuteState, false /* clickedByUser */); + muteClicked(previousMuteState, false /* clickedByUser */); } - mAutomaticallyMuted = false; + automaticallyMuted = false; } @Override public void onSaveInstanceState(Bundle outState) { - outState.putBoolean(KEY_AUTOMATICALLY_MUTED, mAutomaticallyMuted); - outState.putBoolean(KEY_PREVIOUS_MUTE_STATE, mPreviousMuteState); + outState.putBoolean(KEY_AUTOMATICALLY_MUTED, automaticallyMuted); + outState.putBoolean(KEY_PREVIOUS_MUTE_STATE, previousMuteState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { - mAutomaticallyMuted = - savedInstanceState.getBoolean(KEY_AUTOMATICALLY_MUTED, mAutomaticallyMuted); - mPreviousMuteState = savedInstanceState.getBoolean(KEY_PREVIOUS_MUTE_STATE, mPreviousMuteState); + automaticallyMuted = savedInstanceState.getBoolean(KEY_AUTOMATICALLY_MUTED, automaticallyMuted); + previousMuteState = savedInstanceState.getBoolean(KEY_PREVIOUS_MUTE_STATE, previousMuteState); } @Override public void onCameraPermissionGranted() { - if (mCall != null) { - updateButtonsState(mCall); + if (call != null) { + updateButtonsState(call); } } @Override public void onActiveCameraSelectionChanged(boolean isUsingFrontFacingCamera) { - if (mInCallButtonUi == null) { + if (inCallButtonUi == null) { return; } - mInCallButtonUi.setCameraSwitched(!isUsingFrontFacingCamera); + inCallButtonUi.setCameraSwitched(!isUsingFrontFacingCamera); } @Override public Context getContext() { - return mContext; + return context; } private InCallActivity getActivity() { - if (mInCallButtonUi != null) { - Fragment fragment = mInCallButtonUi.getInCallButtonUiFragment(); + if (inCallButtonUi != null) { + Fragment fragment = inCallButtonUi.getInCallButtonUiFragment(); if (fragment != null) { return (InCallActivity) fragment.getActivity(); } diff --git a/java/com/android/incallui/CallCardPresenter.java b/java/com/android/incallui/CallCardPresenter.java index eb5221669..67473d75e 100644 --- a/java/com/android/incallui/CallCardPresenter.java +++ b/java/com/android/incallui/CallCardPresenter.java @@ -113,16 +113,16 @@ public class CallCardPresenter private static final long CONFIG_MIN_BATTERY_PERCENT_FOR_EMERGENCY_LOCATION_DEFAULT = 10; - private final Context mContext; + private final Context context; private final Handler handler = new Handler(); - private DialerCall mPrimary; - private DialerCall mSecondary; - private ContactCacheEntry mPrimaryContactInfo; - private ContactCacheEntry mSecondaryContactInfo; - @Nullable private ContactsPreferences mContactsPreferences; - private boolean mIsFullscreen = false; - private InCallScreen mInCallScreen; + private DialerCall primary; + private DialerCall secondary; + private ContactCacheEntry primaryContactInfo; + private ContactCacheEntry secondaryContactInfo; + @Nullable private ContactsPreferences contactsPreferences; + private boolean isFullscreen = false; + private InCallScreen inCallScreen; private boolean isInCallScreenReady; private boolean shouldSendAccessibilityEvent; @@ -131,7 +131,7 @@ public class CallCardPresenter new Runnable() { @Override public void run() { - shouldSendAccessibilityEvent = !sendAccessibilityEvent(mContext, getUi()); + shouldSendAccessibilityEvent = !sendAccessibilityEvent(context, getUi()); LogUtil.i( "CallCardPresenter.sendAccessibilityEventRunnable", "still should send: %b", @@ -144,8 +144,8 @@ public class CallCardPresenter public CallCardPresenter(Context context) { LogUtil.i("CallCardPresenter.constructor", null); - mContext = Assert.isNotNull(context).getApplicationContext(); - callLocation = CallLocationComponent.get(mContext).getCallLocation(); + this.context = Assert.isNotNull(context).getApplicationContext(); + callLocation = CallLocationComponent.get(this.context).getCallLocation(); } private static boolean hasCallSubject(DialerCall call) { @@ -160,18 +160,18 @@ public class CallCardPresenter @Override public void onInCallScreenDelegateInit(InCallScreen inCallScreen) { Assert.isNotNull(inCallScreen); - mInCallScreen = inCallScreen; - mContactsPreferences = ContactsPreferencesFactory.newContactsPreferences(mContext); + this.inCallScreen = inCallScreen; + contactsPreferences = ContactsPreferencesFactory.newContactsPreferences(context); // Call may be null if disconnect happened already. DialerCall call = CallList.getInstance().getFirstCall(); if (call != null) { - mPrimary = call; - if (shouldShowNoteSentToast(mPrimary)) { - mInCallScreen.showNoteSentToast(); + primary = call; + if (shouldShowNoteSentToast(primary)) { + this.inCallScreen.showNoteSentToast(); } call.addListener(this); - addCallFeedbackListener(mContext); + addCallFeedbackListener(context); // start processing lookups right away. if (!call.isConferenceCall()) { startContactInfoSearch(call, true, call.getState() == DialerCall.State.INCOMING); @@ -187,12 +187,12 @@ public class CallCardPresenter public void onInCallScreenReady() { LogUtil.i("CallCardPresenter.onInCallScreenReady", null); Assert.checkState(!isInCallScreenReady); - if (mContactsPreferences != null) { - mContactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); + if (contactsPreferences != null) { + contactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); } // Contact search may have completed before ui is ready. - if (mPrimaryContactInfo != null) { + if (primaryContactInfo != null) { updatePrimaryDisplayInfo(); } @@ -204,24 +204,24 @@ public class CallCardPresenter isInCallScreenReady = true; // Log location impressions - if (isOutgoingEmergencyCall(mPrimary)) { - Logger.get(mContext).logImpression(DialerImpression.Type.EMERGENCY_NEW_EMERGENCY_CALL); - } else if (isIncomingEmergencyCall(mPrimary) || isIncomingEmergencyCall(mSecondary)) { - Logger.get(mContext).logImpression(DialerImpression.Type.EMERGENCY_CALLBACK); + if (isOutgoingEmergencyCall(primary)) { + Logger.get(context).logImpression(DialerImpression.Type.EMERGENCY_NEW_EMERGENCY_CALL); + } else if (isIncomingEmergencyCall(primary) || isIncomingEmergencyCall(secondary)) { + Logger.get(context).logImpression(DialerImpression.Type.EMERGENCY_CALLBACK); } // Showing the location may have been skipped if the UI wasn't ready during previous layout. if (shouldShowLocation()) { - mInCallScreen.showLocationUi(getLocationFragment()); + inCallScreen.showLocationUi(getLocationFragment()); // Log location impressions if (!hasLocationPermission()) { - Logger.get(mContext).logImpression(DialerImpression.Type.EMERGENCY_NO_LOCATION_PERMISSION); + Logger.get(context).logImpression(DialerImpression.Type.EMERGENCY_NO_LOCATION_PERMISSION); } else if (isBatteryTooLowForEmergencyLocation()) { - Logger.get(mContext) + Logger.get(context) .logImpression(DialerImpression.Type.EMERGENCY_BATTERY_TOO_LOW_TO_GET_LOCATION); - } else if (!callLocation.canGetLocation(mContext)) { - Logger.get(mContext).logImpression(DialerImpression.Type.EMERGENCY_CANT_GET_LOCATION); + } else if (!callLocation.canGetLocation(context)) { + Logger.get(context).logImpression(DialerImpression.Type.EMERGENCY_CANT_GET_LOCATION); } } } @@ -236,15 +236,15 @@ public class CallCardPresenter InCallPresenter.getInstance().removeIncomingCallListener(this); InCallPresenter.getInstance().removeDetailsListener(this); InCallPresenter.getInstance().removeInCallEventListener(this); - if (mPrimary != null) { - mPrimary.removeListener(this); + if (primary != null) { + primary.removeListener(this); } callLocation.close(); - mPrimary = null; - mPrimaryContactInfo = null; - mSecondaryContactInfo = null; + primary = null; + primaryContactInfo = null; + secondaryContactInfo = null; isInCallScreenReady = false; } @@ -258,7 +258,7 @@ public class CallCardPresenter public void onStateChange(InCallState oldState, InCallState newState, CallList callList) { Trace.beginSection("CallCardPresenter.onStateChange"); LogUtil.v("CallCardPresenter.onStateChange", "oldState: %s, newState: %s", oldState, newState); - if (mInCallScreen == null) { + if (inCallScreen == null) { Trace.endSection(); return; } @@ -286,22 +286,23 @@ public class CallCardPresenter LogUtil.v("CallCardPresenter.onStateChange", "secondary call: " + secondary); final boolean primaryChanged = - !(DialerCall.areSame(mPrimary, primary) && DialerCall.areSameNumber(mPrimary, primary)); + !(DialerCall.areSame(this.primary, primary) + && DialerCall.areSameNumber(this.primary, primary)); final boolean secondaryChanged = - !(DialerCall.areSame(mSecondary, secondary) - && DialerCall.areSameNumber(mSecondary, secondary)); + !(DialerCall.areSame(this.secondary, secondary) + && DialerCall.areSameNumber(this.secondary, secondary)); - mSecondary = secondary; - DialerCall previousPrimary = mPrimary; - mPrimary = primary; + this.secondary = secondary; + DialerCall previousPrimary = this.primary; + this.primary = primary; - if (mPrimary != null) { - InCallPresenter.getInstance().onForegroundCallChanged(mPrimary); - mInCallScreen.updateInCallScreenColors(); + if (this.primary != null) { + InCallPresenter.getInstance().onForegroundCallChanged(this.primary); + inCallScreen.updateInCallScreenColors(); } if (primaryChanged && shouldShowNoteSentToast(primary)) { - mInCallScreen.showNoteSentToast(); + inCallScreen.showNoteSentToast(); } // Refresh primary call information if either: @@ -312,38 +313,38 @@ public class CallCardPresenter if (previousPrimary != null) { previousPrimary.removeListener(this); } - mPrimary.addListener(this); + this.primary.addListener(this); - mPrimaryContactInfo = + primaryContactInfo = ContactInfoCache.buildCacheEntryFromCall( - mContext, mPrimary, mPrimary.getState() == DialerCall.State.INCOMING); + context, this.primary, this.primary.getState() == DialerCall.State.INCOMING); updatePrimaryDisplayInfo(); - maybeStartSearch(mPrimary, true); + maybeStartSearch(this.primary, true); } - if (previousPrimary != null && mPrimary == null) { + if (previousPrimary != null && this.primary == null) { previousPrimary.removeListener(this); } if (secondaryChanged) { - if (mSecondary == null) { + if (this.secondary == null) { // Secondary call may have ended. Update the ui. - mSecondaryContactInfo = null; + secondaryContactInfo = null; updateSecondaryDisplayInfo(); } else { // secondary call has changed - mSecondaryContactInfo = + secondaryContactInfo = ContactInfoCache.buildCacheEntryFromCall( - mContext, mSecondary, mSecondary.getState() == DialerCall.State.INCOMING); + context, this.secondary, this.secondary.getState() == DialerCall.State.INCOMING); updateSecondaryDisplayInfo(); - maybeStartSearch(mSecondary, false); + maybeStartSearch(this.secondary, false); } } // Set the call state int callState = DialerCall.State.IDLE; - if (mPrimary != null) { - callState = mPrimary.getState(); + if (this.primary != null) { + callState = this.primary.getState(); updatePrimaryCallState(); } else { getUi().setCallState(PrimaryCallState.createEmptyPrimaryCallState()); @@ -354,7 +355,7 @@ public class CallCardPresenter // Hide the end call button instantly if we're receiving an incoming call. getUi() .setEndCallButtonEnabled( - shouldShowEndCallButton(mPrimary, callState), + shouldShowEndCallButton(this.primary, callState), callState != DialerCall.State.INCOMING /* animate */); maybeSendAccessibilityEvent(oldState, newState, primaryChanged); @@ -399,7 +400,7 @@ public class CallCardPresenter public void onDialerCallChildNumberChange() { LogUtil.v("CallCardPresenter.onDialerCallChildNumberChange", ""); - if (mPrimary == null) { + if (primary == null) { return; } updatePrimaryDisplayInfo(); @@ -410,7 +411,7 @@ public class CallCardPresenter public void onDialerCallLastForwardedNumberChange() { LogUtil.v("CallCardPresenter.onDialerCallLastForwardedNumberChange", ""); - if (mPrimary == null) { + if (primary == null) { return; } updatePrimaryDisplayInfo(); @@ -425,78 +426,78 @@ public class CallCardPresenter public void onDialerCallSessionModificationStateChange() { LogUtil.enterBlock("CallCardPresenter.onDialerCallSessionModificationStateChange"); - if (mPrimary == null) { + if (primary == null) { return; } getUi() .setEndCallButtonEnabled( - mPrimary.getVideoTech().getSessionModificationState() + primary.getVideoTech().getSessionModificationState() != SessionModificationState.RECEIVED_UPGRADE_TO_VIDEO_REQUEST, true /* shouldAnimate */); updatePrimaryCallState(); } private boolean shouldRefreshPrimaryInfo(boolean primaryChanged) { - if (mPrimary == null) { + if (primary == null) { return false; } return primaryChanged - || mInCallScreen.isManageConferenceVisible() != shouldShowManageConference(); + || inCallScreen.isManageConferenceVisible() != shouldShowManageConference(); } private void updatePrimaryCallState() { - if (getUi() != null && mPrimary != null) { + if (getUi() != null && primary != null) { boolean isWorkCall = - mPrimary.hasProperty(PROPERTY_ENTERPRISE_CALL) - || (mPrimaryContactInfo != null - && mPrimaryContactInfo.userType == ContactsUtils.USER_TYPE_WORK); + primary.hasProperty(PROPERTY_ENTERPRISE_CALL) + || (primaryContactInfo != null + && primaryContactInfo.userType == ContactsUtils.USER_TYPE_WORK); boolean isHdAudioCall = - isPrimaryCallActive() && mPrimary.hasProperty(Details.PROPERTY_HIGH_DEF_AUDIO); + isPrimaryCallActive() && primary.hasProperty(Details.PROPERTY_HIGH_DEF_AUDIO); boolean isAttemptingHdAudioCall = !isHdAudioCall - && !mPrimary.hasProperty(DialerCall.PROPERTY_CODEC_KNOWN) - && MotorolaUtils.shouldBlinkHdIconWhenConnectingCall(mContext); + && !primary.hasProperty(DialerCall.PROPERTY_CODEC_KNOWN) + && MotorolaUtils.shouldBlinkHdIconWhenConnectingCall(context); - boolean isBusiness = mPrimaryContactInfo != null && mPrimaryContactInfo.isBusiness; + boolean isBusiness = primaryContactInfo != null && primaryContactInfo.isBusiness; // Check for video state change and update the visibility of the contact photo. The contact // photo is hidden when the incoming video surface is shown. // The contact photo visibility can also change in setPrimary(). boolean shouldShowContactPhoto = - !VideoCallPresenter.showIncomingVideo(mPrimary.getVideoState(), mPrimary.getState()); + !VideoCallPresenter.showIncomingVideo(primary.getVideoState(), primary.getState()); getUi() .setCallState( new PrimaryCallState( - mPrimary.getState(), - mPrimary.isVideoCall(), - mPrimary.getVideoTech().getSessionModificationState(), - mPrimary.getDisconnectCause(), + primary.getState(), + primary.isVideoCall(), + primary.getVideoTech().getSessionModificationState(), + primary.getDisconnectCause(), getConnectionLabel(), getCallStateIcon(), getGatewayNumber(), - shouldShowCallSubject(mPrimary) ? mPrimary.getCallSubject() : null, + shouldShowCallSubject(primary) ? primary.getCallSubject() : null, PhoneNumberHelper.formatNumber( - mPrimary.getCallbackNumber(), mPrimary.getSimCountryIso()), - mPrimary.hasProperty(Details.PROPERTY_WIFI), - mPrimary.isConferenceCall() - && !mPrimary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE), + primary.getCallbackNumber(), primary.getSimCountryIso()), + primary.hasProperty(Details.PROPERTY_WIFI), + primary.isConferenceCall() + && !primary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE), isWorkCall, isAttemptingHdAudioCall, isHdAudioCall, - !TextUtils.isEmpty(mPrimary.getLastForwardedNumber()), + !TextUtils.isEmpty(primary.getLastForwardedNumber()), shouldShowContactPhoto, - mPrimary.getConnectTimeMillis(), - mPrimary.isVoiceMailNumber(), - mPrimary.isRemotelyHeld(), + primary.getConnectTimeMillis(), + primary.isVoiceMailNumber(), + primary.isRemotelyHeld(), isBusiness, supports2ndCallOnHold(), getSwapToSecondaryButtonState(), - mPrimary.isAssistedDialed(), + primary.isAssistedDialed(), null, - mPrimary.getAssistedDialingExtras())); + primary.getAssistedDialingExtras())); InCallActivity activity = - (InCallActivity) (mInCallScreen.getInCallScreenFragment().getActivity()); + (InCallActivity) (inCallScreen.getInCallScreenFragment().getActivity()); if (activity != null) { activity.onPrimaryCallStateChanged(); } @@ -504,10 +505,10 @@ public class CallCardPresenter } private @ButtonState int getSwapToSecondaryButtonState() { - if (mSecondary == null) { + if (secondary == null) { return ButtonState.NOT_SUPPORT; } - if (mPrimary.getState() == State.ACTIVE) { + if (primary.getState() == State.ACTIVE) { return ButtonState.ENABLED; } return ButtonState.DISABLED; @@ -525,12 +526,11 @@ public class CallCardPresenter * @return {@code True} if the manage conference button should be visible. */ private boolean shouldShowManageConference() { - if (mPrimary == null) { + if (primary == null) { return false; } - return mPrimary.can(android.telecom.Call.Details.CAPABILITY_MANAGE_CONFERENCE) - && !mIsFullscreen; + return primary.can(android.telecom.Call.Details.CAPABILITY_MANAGE_CONFERENCE) && !isFullscreen; } private boolean supports2ndCallOnHold() { @@ -544,19 +544,19 @@ public class CallCardPresenter @Override public void onCallStateButtonClicked() { - Intent broadcastIntent = Bindings.get(mContext).getCallStateButtonBroadcastIntent(mContext); + Intent broadcastIntent = Bindings.get(context).getCallStateButtonBroadcastIntent(context); if (broadcastIntent != null) { LogUtil.v( "CallCardPresenter.onCallStateButtonClicked", "sending call state button broadcast: " + broadcastIntent); - mContext.sendBroadcast(broadcastIntent, Manifest.permission.READ_PHONE_STATE); + context.sendBroadcast(broadcastIntent, Manifest.permission.READ_PHONE_STATE); } } @Override public void onManageConferenceClicked() { InCallActivity activity = - (InCallActivity) (mInCallScreen.getInCallScreenFragment().getActivity()); + (InCallActivity) (inCallScreen.getInCallScreenFragment().getActivity()); activity.showConferenceFragment(true); } @@ -575,15 +575,15 @@ public class CallCardPresenter /** Starts a query for more contact data for the save primary and secondary calls. */ private void startContactInfoSearch( final DialerCall call, final boolean isPrimary, boolean isIncoming) { - final ContactInfoCache cache = ContactInfoCache.getInstance(mContext); + final ContactInfoCache cache = ContactInfoCache.getInstance(context); cache.findInfo(call, isIncoming, new ContactLookupCallback(this, isPrimary)); } private void onContactInfoComplete(String callId, ContactCacheEntry entry, boolean isPrimary) { final boolean entryMatchesExistingCall = - (isPrimary && mPrimary != null && TextUtils.equals(callId, mPrimary.getId())) - || (!isPrimary && mSecondary != null && TextUtils.equals(callId, mSecondary.getId())); + (isPrimary && primary != null && TextUtils.equals(callId, primary.getId())) + || (!isPrimary && secondary != null && TextUtils.equals(callId, secondary.getId())); if (entryMatchesExistingCall) { updateContactEntry(entry, isPrimary); } else { @@ -597,7 +597,7 @@ public class CallCardPresenter call.getLogState().contactLookupResult = entry.contactLookupResult; } if (entry.lookupUri != null) { - CallerInfoUtils.sendViewNotification(mContext, entry.lookupUri); + CallerInfoUtils.sendViewNotification(context, entry.lookupUri); } } @@ -607,9 +607,9 @@ public class CallCardPresenter } if (entry.photo != null) { - if (mPrimary != null && callId.equals(mPrimary.getId())) { + if (primary != null && callId.equals(primary.getId())) { updateContactEntry(entry, true /* isPrimary */); - } else if (mSecondary != null && callId.equals(mSecondary.getId())) { + } else if (secondary != null && callId.equals(secondary.getId())) { updateContactEntry(entry, false /* isPrimary */); } } @@ -617,10 +617,10 @@ public class CallCardPresenter private void updateContactEntry(ContactCacheEntry entry, boolean isPrimary) { if (isPrimary) { - mPrimaryContactInfo = entry; + primaryContactInfo = entry; updatePrimaryDisplayInfo(); } else { - mSecondaryContactInfo = entry; + secondaryContactInfo = entry; updateSecondaryDisplayInfo(); } } @@ -674,7 +674,7 @@ public class CallCardPresenter } private void updatePrimaryDisplayInfo() { - if (mInCallScreen == null) { + if (inCallScreen == null) { // TODO: May also occur if search result comes back after ui is destroyed. Look into // removing that case completely. LogUtil.v( @@ -683,35 +683,35 @@ public class CallCardPresenter return; } - if (mPrimary == null) { + if (primary == null) { // Clear the primary display info. - mInCallScreen.setPrimary(PrimaryInfo.createEmptyPrimaryInfo()); + inCallScreen.setPrimary(PrimaryInfo.createEmptyPrimaryInfo()); return; } // Hide the contact photo if we are in a video call and the incoming video surface is // showing. boolean showContactPhoto = - !VideoCallPresenter.showIncomingVideo(mPrimary.getVideoState(), mPrimary.getState()); + !VideoCallPresenter.showIncomingVideo(primary.getVideoState(), primary.getState()); // DialerCall placed through a work phone account. - boolean hasWorkCallProperty = mPrimary.hasProperty(PROPERTY_ENTERPRISE_CALL); + boolean hasWorkCallProperty = primary.hasProperty(PROPERTY_ENTERPRISE_CALL); MultimediaData multimediaData = null; - if (mPrimary.getEnrichedCallSession() != null) { - multimediaData = mPrimary.getEnrichedCallSession().getMultimediaData(); + if (primary.getEnrichedCallSession() != null) { + multimediaData = primary.getEnrichedCallSession().getMultimediaData(); } - if (mPrimary.isConferenceCall()) { + if (primary.isConferenceCall()) { LogUtil.v( "CallCardPresenter.updatePrimaryDisplayInfo", "update primary display info for conference call."); - mInCallScreen.setPrimary( + inCallScreen.setPrimary( new PrimaryInfo( null /* number */, CallerInfoUtils.getConferenceString( - mContext, mPrimary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)), + context, primary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)), false /* nameIsNumber */, null /* location */, null /* label */, @@ -727,63 +727,63 @@ public class CallCardPresenter null /* contactInfoLookupKey */, null /* enrichedCallMultimediaData */, true /* showInCallButtonGrid */, - mPrimary.getNumberPresentation())); - } else if (mPrimaryContactInfo != null) { + primary.getNumberPresentation())); + } else if (primaryContactInfo != null) { LogUtil.v( "CallCardPresenter.updatePrimaryDisplayInfo", - "update primary display info for " + mPrimaryContactInfo); + "update primary display info for " + primaryContactInfo); - String name = getNameForCall(mPrimaryContactInfo); + String name = getNameForCall(primaryContactInfo); String number; - boolean isChildNumberShown = !TextUtils.isEmpty(mPrimary.getChildNumber()); - boolean isForwardedNumberShown = !TextUtils.isEmpty(mPrimary.getLastForwardedNumber()); - boolean isCallSubjectShown = shouldShowCallSubject(mPrimary); + boolean isChildNumberShown = !TextUtils.isEmpty(primary.getChildNumber()); + boolean isForwardedNumberShown = !TextUtils.isEmpty(primary.getLastForwardedNumber()); + boolean isCallSubjectShown = shouldShowCallSubject(primary); if (isCallSubjectShown) { number = null; } else if (isChildNumberShown) { - number = mContext.getString(R.string.child_number, mPrimary.getChildNumber()); + number = context.getString(R.string.child_number, primary.getChildNumber()); } else if (isForwardedNumberShown) { // Use last forwarded number instead of second line, if present. - number = mPrimary.getLastForwardedNumber(); + number = primary.getLastForwardedNumber(); } else { - number = mPrimaryContactInfo.number; + number = primaryContactInfo.number; } - boolean nameIsNumber = name != null && name.equals(mPrimaryContactInfo.number); + boolean nameIsNumber = name != null && name.equals(primaryContactInfo.number); // DialerCall with caller that is a work contact. - boolean isWorkContact = (mPrimaryContactInfo.userType == ContactsUtils.USER_TYPE_WORK); - mInCallScreen.setPrimary( + boolean isWorkContact = (primaryContactInfo.userType == ContactsUtils.USER_TYPE_WORK); + inCallScreen.setPrimary( new PrimaryInfo( number, - mPrimary.updateNameIfRestricted(name), + primary.updateNameIfRestricted(name), nameIsNumber, - shouldShowLocationAsLabel(nameIsNumber, mPrimaryContactInfo.shouldShowLocation) - ? mPrimaryContactInfo.location + shouldShowLocationAsLabel(nameIsNumber, primaryContactInfo.shouldShowLocation) + ? primaryContactInfo.location : null, - isChildNumberShown || isCallSubjectShown ? null : mPrimaryContactInfo.label, - mPrimaryContactInfo.photo, - mPrimaryContactInfo.photoType, - mPrimaryContactInfo.isSipCall, + isChildNumberShown || isCallSubjectShown ? null : primaryContactInfo.label, + primaryContactInfo.photo, + primaryContactInfo.photoType, + primaryContactInfo.isSipCall, showContactPhoto, hasWorkCallProperty || isWorkContact, - mPrimary.isSpam(), - mPrimaryContactInfo.isLocalContact(), - mPrimary.answeringDisconnectsForegroundVideoCall(), + primary.isSpam(), + primaryContactInfo.isLocalContact(), + primary.answeringDisconnectsForegroundVideoCall(), shouldShowLocation(), - mPrimaryContactInfo.lookupKey, + primaryContactInfo.lookupKey, multimediaData, true /* showInCallButtonGrid */, - mPrimary.getNumberPresentation())); + primary.getNumberPresentation())); } else { // Clear the primary display info. - mInCallScreen.setPrimary(PrimaryInfo.createEmptyPrimaryInfo()); + inCallScreen.setPrimary(PrimaryInfo.createEmptyPrimaryInfo()); } if (isInCallScreenReady) { - mInCallScreen.showLocationUi(getLocationFragment()); + inCallScreen.showLocationUi(getLocationFragment()); } else { LogUtil.i("CallCardPresenter.updatePrimaryDisplayInfo", "UI not ready, not showing location"); } @@ -805,11 +805,11 @@ public class CallCardPresenter return null; } LogUtil.i("CallCardPresenter.getLocationFragment", "returning location fragment"); - return callLocation.getLocationFragment(mContext); + return callLocation.getLocationFragment(context); } private boolean shouldShowLocation() { - if (!ConfigProviderBindings.get(mContext) + if (!ConfigProviderBindings.get(context) .getBoolean(CONFIG_ENABLE_EMERGENCY_LOCATION, CONFIG_ENABLE_EMERGENCY_LOCATION_DEFAULT)) { LogUtil.i("CallCardPresenter.getLocationFragment", "disabled by config."); return false; @@ -826,15 +826,15 @@ public class CallCardPresenter LogUtil.i("CallCardPresenter.getLocationFragment", "low battery."); return false; } - if (ActivityCompat.isInMultiWindowMode(mInCallScreen.getInCallScreenFragment().getActivity())) { + if (ActivityCompat.isInMultiWindowMode(inCallScreen.getInCallScreenFragment().getActivity())) { LogUtil.i("CallCardPresenter.getLocationFragment", "in multi-window mode"); return false; } - if (mPrimary.isVideoCall()) { + if (primary.isVideoCall()) { LogUtil.i("CallCardPresenter.getLocationFragment", "emergency video calls not supported"); return false; } - if (!callLocation.canGetLocation(mContext)) { + if (!callLocation.canGetLocation(context)) { LogUtil.i("CallCardPresenter.getLocationFragment", "can't get current location"); return false; } @@ -842,13 +842,13 @@ public class CallCardPresenter } private boolean isPotentialEmergencyCall() { - if (isOutgoingEmergencyCall(mPrimary)) { + if (isOutgoingEmergencyCall(primary)) { LogUtil.i("CallCardPresenter.shouldShowLocation", "new emergency call"); return true; - } else if (isIncomingEmergencyCall(mPrimary)) { + } else if (isIncomingEmergencyCall(primary)) { LogUtil.i("CallCardPresenter.shouldShowLocation", "potential emergency callback"); return true; - } else if (isIncomingEmergencyCall(mSecondary)) { + } else if (isIncomingEmergencyCall(secondary)) { LogUtil.i("CallCardPresenter.shouldShowLocation", "has potential emergency callback"); return true; } @@ -864,13 +864,13 @@ public class CallCardPresenter } private boolean hasLocationPermission() { - return ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) + return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } private boolean isBatteryTooLowForEmergencyLocation() { Intent batteryStatus = - mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); + context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) { @@ -881,7 +881,7 @@ public class CallCardPresenter int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPercent = (100f * level) / scale; long threshold = - ConfigProviderBindings.get(mContext) + ConfigProviderBindings.get(context) .getLong( CONFIG_MIN_BATTERY_PERCENT_FOR_EMERGENCY_LOCATION, CONFIG_MIN_BATTERY_PERCENT_FOR_EMERGENCY_LOCATION_DEFAULT); @@ -892,60 +892,60 @@ public class CallCardPresenter } private void updateSecondaryDisplayInfo() { - if (mInCallScreen == null) { + if (inCallScreen == null) { return; } - if (mSecondary == null) { + if (secondary == null) { // Clear the secondary display info. - mInCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(mIsFullscreen)); + inCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(isFullscreen)); return; } - if (mSecondary.isMergeInProcess()) { + if (secondary.isMergeInProcess()) { LogUtil.i( "CallCardPresenter.updateSecondaryDisplayInfo", "secondary call is merge in process, clearing info"); - mInCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(mIsFullscreen)); + inCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(isFullscreen)); return; } - if (mSecondary.isConferenceCall()) { - mInCallScreen.setSecondary( + if (secondary.isConferenceCall()) { + inCallScreen.setSecondary( new SecondaryInfo( true /* show */, CallerInfoUtils.getConferenceString( - mContext, mSecondary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)), + context, secondary.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)), false /* nameIsNumber */, null /* label */, - mSecondary.getCallProviderLabel(), + secondary.getCallProviderLabel(), true /* isConference */, - mSecondary.isVideoCall(), - mIsFullscreen)); - } else if (mSecondaryContactInfo != null) { - LogUtil.v("CallCardPresenter.updateSecondaryDisplayInfo", "" + mSecondaryContactInfo); - String name = getNameForCall(mSecondaryContactInfo); - boolean nameIsNumber = name != null && name.equals(mSecondaryContactInfo.number); - mInCallScreen.setSecondary( + secondary.isVideoCall(), + isFullscreen)); + } else if (secondaryContactInfo != null) { + LogUtil.v("CallCardPresenter.updateSecondaryDisplayInfo", "" + secondaryContactInfo); + String name = getNameForCall(secondaryContactInfo); + boolean nameIsNumber = name != null && name.equals(secondaryContactInfo.number); + inCallScreen.setSecondary( new SecondaryInfo( true /* show */, - mSecondary.updateNameIfRestricted(name), + secondary.updateNameIfRestricted(name), nameIsNumber, - mSecondaryContactInfo.label, - mSecondary.getCallProviderLabel(), + secondaryContactInfo.label, + secondary.getCallProviderLabel(), false /* isConference */, - mSecondary.isVideoCall(), - mIsFullscreen)); + secondary.isVideoCall(), + isFullscreen)); } else { // Clear the secondary display info. - mInCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(mIsFullscreen)); + inCallScreen.setSecondary(SecondaryInfo.createEmptySecondaryInfo(isFullscreen)); } } /** Returns the gateway number for any existing outgoing call. */ private String getGatewayNumber() { if (hasOutgoingGatewayCall()) { - return DialerCall.getNumberFromHandle(mPrimary.getGatewayInfo().getGatewayAddress()); + return DialerCall.getNumberFromHandle(primary.getGatewayInfo().getGatewayAddress()); } return null; } @@ -955,35 +955,35 @@ public class CallCardPresenter * "calling via [Account/Google Voice]" for outgoing calls. */ private String getConnectionLabel() { - if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_PHONE_STATE) + if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return null; } - StatusHints statusHints = mPrimary.getStatusHints(); + StatusHints statusHints = primary.getStatusHints(); if (statusHints != null && !TextUtils.isEmpty(statusHints.getLabel())) { return statusHints.getLabel().toString(); } if (hasOutgoingGatewayCall() && getUi() != null) { // Return the label for the gateway app on outgoing calls. - final PackageManager pm = mContext.getPackageManager(); + final PackageManager pm = context.getPackageManager(); try { ApplicationInfo info = - pm.getApplicationInfo(mPrimary.getGatewayInfo().getGatewayProviderPackageName(), 0); + pm.getApplicationInfo(primary.getGatewayInfo().getGatewayProviderPackageName(), 0); return pm.getApplicationLabel(info).toString(); } catch (PackageManager.NameNotFoundException e) { LogUtil.e("CallCardPresenter.getConnectionLabel", "gateway Application Not Found.", e); return null; } } - return mPrimary.getCallProviderLabel(); + return primary.getCallProviderLabel(); } private Drawable getCallStateIcon() { // Return connection icon if one exists. - StatusHints statusHints = mPrimary.getStatusHints(); + StatusHints statusHints = primary.getStatusHints(); if (statusHints != null && statusHints.getIcon() != null) { - Drawable icon = statusHints.getIcon().loadDrawable(mContext); + Drawable icon = statusHints.getIcon().loadDrawable(context); if (icon != null) { return icon; } @@ -998,19 +998,19 @@ public class CallCardPresenter // TODO: mPrimary can be null because this is called from updatePrimaryDisplayInfo which // is also called after a contact search completes (call is not present yet). Split the // UI update so it can receive independent updates. - if (mPrimary == null) { + if (primary == null) { return false; } - return DialerCall.State.isDialing(mPrimary.getState()) - && mPrimary.getGatewayInfo() != null - && !mPrimary.getGatewayInfo().isEmpty(); + return DialerCall.State.isDialing(primary.getState()) + && primary.getGatewayInfo() != null + && !primary.getGatewayInfo().isEmpty(); } /** Gets the name to display for the call. */ private String getNameForCall(ContactCacheEntry contactInfo) { String preferredName = ContactDisplayUtils.getPreferredDisplayName( - contactInfo.namePrimary, contactInfo.nameAlternative, mContactsPreferences); + contactInfo.namePrimary, contactInfo.nameAlternative, contactsPreferences); if (TextUtils.isEmpty(preferredName)) { return contactInfo.number; } @@ -1019,30 +1019,30 @@ public class CallCardPresenter @Override public void onSecondaryInfoClicked() { - if (mSecondary == null) { + if (secondary == null) { LogUtil.e( "CallCardPresenter.onSecondaryInfoClicked", "secondary info clicked but no secondary call."); return; } - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.IN_CALL_SWAP_SECONDARY_BUTTON_PRESSED, - mPrimary.getUniqueCallId(), - mPrimary.getTimeAddedMs()); + primary.getUniqueCallId(), + primary.getTimeAddedMs()); LogUtil.i( - "CallCardPresenter.onSecondaryInfoClicked", "swapping call to foreground: " + mSecondary); - mSecondary.unhold(); + "CallCardPresenter.onSecondaryInfoClicked", "swapping call to foreground: " + secondary); + secondary.unhold(); } @Override public void onEndCallClicked() { - LogUtil.i("CallCardPresenter.onEndCallClicked", "disconnecting call: " + mPrimary); - if (mPrimary != null) { - mPrimary.disconnect(); + LogUtil.i("CallCardPresenter.onEndCallClicked", "disconnecting call: " + primary); + if (primary != null) { + primary.disconnect(); } - PostCall.onDisconnectPressed(mContext); + PostCall.onDisconnectPressed(context); } /** @@ -1052,15 +1052,15 @@ public class CallCardPresenter */ @Override public void onFullscreenModeChanged(boolean isFullscreenMode) { - mIsFullscreen = isFullscreenMode; - if (mInCallScreen == null) { + isFullscreen = isFullscreenMode; + if (inCallScreen == null) { return; } maybeShowManageConferenceCallButton(); } private boolean isPrimaryCallActive() { - return mPrimary != null && mPrimary.getState() == DialerCall.State.ACTIVE; + return primary != null && primary.getState() == DialerCall.State.ACTIVE; } private boolean shouldShowEndCallButton(DialerCall primary, int callState) { @@ -1073,7 +1073,7 @@ public class CallCardPresenter || callState == DialerCall.State.INCOMING) { return false; } - if (mPrimary.getVideoTech().getSessionModificationState() + if (this.primary.getVideoTech().getSessionModificationState() == SessionModificationState.RECEIVED_UPGRADE_TO_VIDEO_REQUEST) { return false; } @@ -1128,11 +1128,11 @@ public class CallCardPresenter private void maybeSendAccessibilityEvent( InCallState oldState, final InCallState newState, boolean primaryChanged) { shouldSendAccessibilityEvent = false; - if (mContext == null) { + if (context == null) { return; } final AccessibilityManager am = - (AccessibilityManager) mContext.getSystemService(Context.ACCESSIBILITY_SERVICE); + (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE); if (!am.isEnabled()) { return; } @@ -1161,8 +1161,8 @@ public class CallCardPresenter } boolean isIncomingOrWaiting = - mPrimary.getState() == DialerCall.State.INCOMING - || mPrimary.getState() == DialerCall.State.CALL_WAITING; + primary.getState() == DialerCall.State.INCOMING + || primary.getState() == DialerCall.State.CALL_WAITING; return isIncomingOrWaiting && !TextUtils.isEmpty(call.getCallSubject()) && call.getNumberPresentation() == TelecomManager.PRESENTATION_ALLOWED @@ -1184,30 +1184,30 @@ public class CallCardPresenter } private InCallScreen getUi() { - return mInCallScreen; + return inCallScreen; } public static class ContactLookupCallback implements ContactInfoCacheCallback { - private final WeakReference mCallCardPresenter; - private final boolean mIsPrimary; + private final WeakReference callCardPresenter; + private final boolean isPrimary; public ContactLookupCallback(CallCardPresenter callCardPresenter, boolean isPrimary) { - mCallCardPresenter = new WeakReference(callCardPresenter); - mIsPrimary = isPrimary; + this.callCardPresenter = new WeakReference(callCardPresenter); + this.isPrimary = isPrimary; } @Override public void onContactInfoComplete(String callId, ContactCacheEntry entry) { - CallCardPresenter presenter = mCallCardPresenter.get(); + CallCardPresenter presenter = callCardPresenter.get(); if (presenter != null) { - presenter.onContactInfoComplete(callId, entry, mIsPrimary); + presenter.onContactInfoComplete(callId, entry, isPrimary); } } @Override public void onImageLoadComplete(String callId, ContactCacheEntry entry) { - CallCardPresenter presenter = mCallCardPresenter.get(); + CallCardPresenter presenter = callCardPresenter.get(); if (presenter != null) { presenter.onImageLoadComplete(callId, entry); } diff --git a/java/com/android/incallui/CallerInfo.java b/java/com/android/incallui/CallerInfo.java index d3b12c158..7a5002d0e 100644 --- a/java/com/android/incallui/CallerInfo.java +++ b/java/com/android/incallui/CallerInfo.java @@ -164,13 +164,13 @@ public class CallerInfo { public String countryIso; - private boolean mIsEmergency; - private boolean mIsVoiceMail; + private boolean isEmergency; + private boolean isVoiceMail; public CallerInfo() { // TODO: Move all the basic initialization here? - mIsEmergency = false; - mIsVoiceMail = false; + isEmergency = false; + isVoiceMail = false; userType = ContactsUtils.USER_TYPE_CURRENT; } @@ -467,12 +467,12 @@ public class CallerInfo { /** @return true if the caller info is an emergency number. */ public boolean isEmergencyNumber() { - return mIsEmergency; + return isEmergency; } /** @return true if the caller info is a voicemail number. */ public boolean isVoiceMailNumber() { - return mIsVoiceMail; + return isVoiceMail; } /** @@ -485,7 +485,7 @@ public class CallerInfo { name = context.getString(R.string.emergency_call_dialog_number_for_display); phoneNumber = null; - mIsEmergency = true; + isEmergency = true; return this; } @@ -497,7 +497,7 @@ public class CallerInfo { * @return this instance. */ /* package */ CallerInfo markAsVoiceMail(Context context) { - mIsVoiceMail = true; + isVoiceMail = true; try { // For voicemail calls, we display the voice mail tag @@ -565,8 +565,8 @@ public class CallerInfo { .append("\nshouldSendToVoicemail: " + shouldSendToVoicemail) .append("\ncachedPhoto: " + cachedPhoto) .append("\nisCachedPhotoCurrent: " + isCachedPhotoCurrent) - .append("\nemergency: " + mIsEmergency) - .append("\nvoicemail: " + mIsVoiceMail) + .append("\nemergency: " + isEmergency) + .append("\nvoicemail: " + isVoiceMail) .append("\nuserType: " + userType) .append(" }") .toString(); diff --git a/java/com/android/incallui/CallerInfoAsyncQuery.java b/java/com/android/incallui/CallerInfoAsyncQuery.java index f9d8da819..52ca8cafa 100644 --- a/java/com/android/incallui/CallerInfoAsyncQuery.java +++ b/java/com/android/incallui/CallerInfoAsyncQuery.java @@ -287,56 +287,56 @@ public class CallerInfoAsyncQuery { private static final class DirectoryQueryCompleteListenerFactory { - private final OnQueryCompleteListener mListener; - private final Context mContext; + private final OnQueryCompleteListener listener; + private final Context context; // Make sure listener to be called once and only once - private int mCount; - private boolean mIsListenerCalled; + private int count; + private boolean isListenerCalled; DirectoryQueryCompleteListenerFactory( Context context, int size, OnQueryCompleteListener listener) { - mCount = size; - mListener = listener; - mIsListenerCalled = false; - mContext = context; + count = size; + this.listener = listener; + isListenerCalled = false; + this.context = context; } private void onDirectoryQueryComplete( int token, Object cookie, CallerInfo ci, long directoryId) { boolean shouldCallListener = false; synchronized (this) { - mCount = mCount - 1; - if (!mIsListenerCalled && (ci.contactExists || mCount == 0)) { - mIsListenerCalled = true; + count = count - 1; + if (!isListenerCalled && (ci.contactExists || count == 0)) { + isListenerCalled = true; shouldCallListener = true; } } // Don't call callback in synchronized block because mListener.onQueryComplete may // take long time to complete - if (shouldCallListener && mListener != null) { + if (shouldCallListener && listener != null) { addCallerInfoIntoCache(ci, directoryId); - mListener.onQueryComplete(token, cookie, ci); + listener.onQueryComplete(token, cookie, ci); } } private void addCallerInfoIntoCache(CallerInfo ci, long directoryId) { CachedNumberLookupService cachedNumberLookupService = - PhoneNumberCache.get(mContext).getCachedNumberLookupService(); + PhoneNumberCache.get(context).getCachedNumberLookupService(); if (ci.contactExists && cachedNumberLookupService != null) { // 1. Cache caller info CachedContactInfo cachedContactInfo = CallerInfoUtils.buildCachedContactInfo(cachedNumberLookupService, ci); - String directoryLabel = mContext.getString(R.string.directory_search_label); + String directoryLabel = context.getString(R.string.directory_search_label); cachedContactInfo.setDirectorySource(directoryLabel, directoryId); - cachedNumberLookupService.addContact(mContext, cachedContactInfo); + cachedNumberLookupService.addContact(context, cachedContactInfo); // 2. Cache photo if (ci.contactDisplayPhotoUri != null && ci.normalizedNumber != null) { try (InputStream in = - mContext.getContentResolver().openInputStream(ci.contactDisplayPhotoUri)) { + context.getContentResolver().openInputStream(ci.contactDisplayPhotoUri)) { if (in != null) { - cachedNumberLookupService.addPhoto(mContext, ci.normalizedNumber, in); + cachedNumberLookupService.addPhoto(context, ci.normalizedNumber, in); } } catch (IOException e) { Log.e(LOG_TAG, "failed to fetch directory contact photo", e); @@ -351,22 +351,22 @@ public class CallerInfoAsyncQuery { private class DirectoryQueryCompleteListener implements OnQueryCompleteListener { - private final long mDirectoryId; + private final long directoryId; DirectoryQueryCompleteListener(long directoryId) { - mDirectoryId = directoryId; + this.directoryId = directoryId; } @Override public void onDataLoaded(int token, Object cookie, CallerInfo ci) { Log.d(LOG_TAG, "DirectoryQueryCompleteListener.onDataLoaded"); - mListener.onDataLoaded(token, cookie, ci); + listener.onDataLoaded(token, cookie, ci); } @Override public void onQueryComplete(int token, Object cookie, CallerInfo ci) { Log.d(LOG_TAG, "DirectoryQueryCompleteListener.onQueryComplete"); - onDirectoryQueryComplete(token, cookie, ci, mDirectoryId); + onDirectoryQueryComplete(token, cookie, ci, directoryId); } } } @@ -380,16 +380,16 @@ public class CallerInfoAsyncQuery { * with a new query event, and one with a end event, with 0 or more additional listeners in * between). */ - private Context mQueryContext; + private Context queryContext; - private Uri mQueryUri; - private CallerInfo mCallerInfo; + private Uri queryUri; + private CallerInfo callerInfo; /** Asynchronous query handler class for the contact / callerinfo object. */ private CallerInfoAsyncQueryHandler(Context context, Uri contactRef) { super(context.getContentResolver()); - this.mQueryContext = context; - this.mQueryUri = contactRef; + this.queryContext = context; + this.queryUri = contactRef; } @Override @@ -448,12 +448,12 @@ public class CallerInfoAsyncQuery { + cw.listener.getClass().toString() + " for token: " + token - + mCallerInfo); - cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo); + + callerInfo); + cw.listener.onQueryComplete(token, cw.cookie, callerInfo); } - mQueryContext = null; - mQueryUri = null; - mCallerInfo = null; + queryContext = null; + queryUri = null; + callerInfo = null; } void updateData(int token, Object cookie, Cursor cursor) { @@ -472,8 +472,8 @@ public class CallerInfoAsyncQuery { } // check the token and if needed, create the callerinfo object. - if (mCallerInfo == null) { - if ((mQueryContext == null) || (mQueryUri == null)) { + if (callerInfo == null) { + if ((queryContext == null) || (queryUri == null)) { throw new QueryPoolException( "Bad context or query uri, or CallerInfoAsyncQuery already released."); } @@ -486,20 +486,20 @@ public class CallerInfoAsyncQuery { if (cw.event == EVENT_EMERGENCY_NUMBER) { // Note we're setting the phone number here (refer to javadoc // comments at the top of CallerInfo class). - mCallerInfo = new CallerInfo().markAsEmergency(mQueryContext); + callerInfo = new CallerInfo().markAsEmergency(queryContext); } else if (cw.event == EVENT_VOICEMAIL_NUMBER) { - mCallerInfo = new CallerInfo().markAsVoiceMail(mQueryContext); + callerInfo = new CallerInfo().markAsVoiceMail(queryContext); } else { - mCallerInfo = CallerInfo.getCallerInfo(mQueryContext, mQueryUri, cursor); - Log.d(this, "==> Got mCallerInfo: " + mCallerInfo); + callerInfo = CallerInfo.getCallerInfo(queryContext, queryUri, cursor); + Log.d(this, "==> Got mCallerInfo: " + callerInfo); CallerInfo newCallerInfo = - CallerInfo.doSecondaryLookupIfNecessary(mQueryContext, cw.number, mCallerInfo); - if (newCallerInfo != mCallerInfo) { - mCallerInfo = newCallerInfo; - Log.d(this, "#####async contact look up with numeric username" + mCallerInfo); + CallerInfo.doSecondaryLookupIfNecessary(queryContext, cw.number, callerInfo); + if (newCallerInfo != callerInfo) { + callerInfo = newCallerInfo; + Log.d(this, "#####async contact look up with numeric username" + callerInfo); } - mCallerInfo.countryIso = cw.countryIso; + callerInfo.countryIso = cw.countryIso; // Final step: look up the geocoded description. if (ENABLE_UNKNOWN_NUMBER_GEO_DESCRIPTION) { @@ -514,25 +514,25 @@ public class CallerInfoAsyncQuery { // new parameter to CallerInfoAsyncQuery.startQuery() to force // the geoDescription field to be populated.) - if (TextUtils.isEmpty(mCallerInfo.name)) { + if (TextUtils.isEmpty(callerInfo.name)) { // Actually when no contacts match the incoming phone number, // the CallerInfo object is totally blank here (i.e. no name // *or* phoneNumber). So we need to pass in cw.number as // a fallback number. - mCallerInfo.updateGeoDescription(mQueryContext, cw.number); + callerInfo.updateGeoDescription(queryContext, cw.number); } } // Use the number entered by the user for display. if (!TextUtils.isEmpty(cw.number)) { - mCallerInfo.phoneNumber = cw.number; + callerInfo.phoneNumber = cw.number; } } Log.d(this, "constructing CallerInfo object for token: " + token); if (cw.listener != null) { - cw.listener.onDataLoaded(token, cw.cookie, mCallerInfo); + cw.listener.onDataLoaded(token, cw.cookie, callerInfo); } } @@ -598,14 +598,14 @@ public class CallerInfoAsyncQuery { switch (cw.event) { case EVENT_NEW_QUERY: - final ContentResolver resolver = mQueryContext.getContentResolver(); + final ContentResolver resolver = queryContext.getContentResolver(); // This should never happen. if (resolver == null) { Log.e(this, "Content Resolver is null!"); return; } - //start the sql command. + // start the sql command. Cursor cursor; try { cursor = diff --git a/java/com/android/incallui/ConferenceManagerFragment.java b/java/com/android/incallui/ConferenceManagerFragment.java index bd6cb850b..20625c43d 100644 --- a/java/com/android/incallui/ConferenceManagerFragment.java +++ b/java/com/android/incallui/ConferenceManagerFragment.java @@ -35,9 +35,9 @@ public class ConferenceManagerFragment extends BaseFragment implements ConferenceManagerPresenter.ConferenceManagerUi { - private ListView mConferenceParticipantList; - private ContactPhotoManager mContactPhotoManager; - private ConferenceParticipantListAdapter mConferenceParticipantListAdapter; + private ListView conferenceParticipantList; + private ContactPhotoManager contactPhotoManager; + private ConferenceParticipantListAdapter conferenceParticipantListAdapter; @Override public ConferenceManagerPresenter createPresenter() { @@ -62,8 +62,8 @@ public class ConferenceManagerFragment LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View parent = inflater.inflate(R.layout.conference_manager_fragment, container, false); - mConferenceParticipantList = (ListView) parent.findViewById(R.id.participantList); - mContactPhotoManager = ContactPhotoManager.getInstance(getActivity().getApplicationContext()); + conferenceParticipantList = (ListView) parent.findViewById(R.id.participantList); + contactPhotoManager = ContactPhotoManager.getInstance(getActivity().getApplicationContext()); return parent; } @@ -75,7 +75,7 @@ public class ConferenceManagerFragment getPresenter().init(calls); // Request focus on the list of participants for accessibility purposes. This ensures // that once the list of participants is shown, the first participant is announced. - mConferenceParticipantList.requestFocus(); + conferenceParticipantList.requestFocus(); } @Override @@ -90,17 +90,17 @@ public class ConferenceManagerFragment @Override public void update(List participants, boolean parentCanSeparate) { - if (mConferenceParticipantListAdapter == null) { - mConferenceParticipantListAdapter = - new ConferenceParticipantListAdapter(mConferenceParticipantList, mContactPhotoManager); + if (conferenceParticipantListAdapter == null) { + conferenceParticipantListAdapter = + new ConferenceParticipantListAdapter(conferenceParticipantList, contactPhotoManager); - mConferenceParticipantList.setAdapter(mConferenceParticipantListAdapter); + conferenceParticipantList.setAdapter(conferenceParticipantListAdapter); } - mConferenceParticipantListAdapter.updateParticipants(participants, parentCanSeparate); + conferenceParticipantListAdapter.updateParticipants(participants, parentCanSeparate); } @Override public void refreshCall(DialerCall call) { - mConferenceParticipantListAdapter.refreshCall(call); + conferenceParticipantListAdapter.refreshCall(call); } } diff --git a/java/com/android/incallui/ConferenceParticipantListAdapter.java b/java/com/android/incallui/ConferenceParticipantListAdapter.java index 66b6a97c1..d4579b1ed 100644 --- a/java/com/android/incallui/ConferenceParticipantListAdapter.java +++ b/java/com/android/incallui/ConferenceParticipantListAdapter.java @@ -55,15 +55,15 @@ import java.util.Set; public class ConferenceParticipantListAdapter extends BaseAdapter { /** The ListView containing the participant information. */ - private final ListView mListView; + private final ListView listView; /** Hashmap to make accessing participant info by call Id faster. */ - private final Map mParticipantsByCallId = new ArrayMap<>(); + private final Map participantsByCallId = new ArrayMap<>(); /** ContactsPreferences used to lookup displayName preferences */ - @Nullable private final ContactsPreferences mContactsPreferences; + @Nullable private final ContactsPreferences contactsPreferences; /** Contact photo manager to retrieve cached contact photo information. */ - private final ContactPhotoManager mContactPhotoManager; + private final ContactPhotoManager contactPhotoManager; /** Listener used to handle tap of the "disconnect' button for a participant. */ - private View.OnClickListener mDisconnectListener = + private View.OnClickListener disconnectListener = new View.OnClickListener() { @Override public void onClick(View view) { @@ -76,7 +76,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { } }; /** Listener used to handle tap of the "separate' button for a participant. */ - private View.OnClickListener mSeparateListener = + private View.OnClickListener separateListener = new View.OnClickListener() { @Override public void onClick(View view) { @@ -88,9 +88,9 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { } }; /** The conference participants to show in the ListView. */ - private List mConferenceParticipants = new ArrayList<>(); + private List conferenceParticipants = new ArrayList<>(); /** {@code True} if the conference parent supports separating calls from the conference. */ - private boolean mParentCanSeparate; + private boolean parentCanSeparate; /** * Creates an instance of the ConferenceParticipantListAdapter. @@ -101,9 +101,9 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { public ConferenceParticipantListAdapter( ListView listView, ContactPhotoManager contactPhotoManager) { - mListView = listView; - mContactsPreferences = ContactsPreferencesFactory.newContactsPreferences(getContext()); - mContactPhotoManager = contactPhotoManager; + this.listView = listView; + contactsPreferences = ContactsPreferencesFactory.newContactsPreferences(getContext()); + this.contactPhotoManager = contactPhotoManager; } /** @@ -115,11 +115,11 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { */ public void updateParticipants( List conferenceParticipants, boolean parentCanSeparate) { - if (mContactsPreferences != null) { - mContactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); - mContactsPreferences.refreshValue(ContactsPreferences.SORT_ORDER_KEY); + if (contactsPreferences != null) { + contactsPreferences.refreshValue(ContactsPreferences.DISPLAY_ORDER_KEY); + contactsPreferences.refreshValue(ContactsPreferences.SORT_ORDER_KEY); } - mParentCanSeparate = parentCanSeparate; + this.parentCanSeparate = parentCanSeparate; updateParticipantInfo(conferenceParticipants); } @@ -130,7 +130,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { */ @Override public int getCount() { - return mConferenceParticipants.size(); + return conferenceParticipants.size(); } /** @@ -141,7 +141,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { */ @Override public Object getItem(int position) { - return mConferenceParticipants.get(position); + return conferenceParticipants.get(position); } /** @@ -163,15 +163,15 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { public void refreshCall(DialerCall call) { String callId = call.getId(); - if (mParticipantsByCallId.containsKey(callId)) { - ParticipantInfo participantInfo = mParticipantsByCallId.get(callId); + if (participantsByCallId.containsKey(callId)) { + ParticipantInfo participantInfo = participantsByCallId.get(callId); participantInfo.setCall(call); refreshView(callId); } } private Context getContext() { - return mListView.getContext(); + return listView.getContext(); } /** @@ -181,14 +181,14 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { * @param callId The call id. */ private void refreshView(String callId) { - int first = mListView.getFirstVisiblePosition(); - int last = mListView.getLastVisiblePosition(); + int first = listView.getFirstVisiblePosition(); + int last = listView.getLastVisiblePosition(); for (int position = 0; position <= last - first; position++) { - View view = mListView.getChildAt(position); + View view = listView.getChildAt(position); String rowCallId = (String) view.getTag(); if (rowCallId.equals(callId)) { - getView(position + first, view, mListView); + getView(position + first, view, listView); break; } } @@ -212,7 +212,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { .inflate(R.layout.caller_in_conference, parent, false) : convertView; - ParticipantInfo participantInfo = mConferenceParticipants.get(position); + ParticipantInfo participantInfo = conferenceParticipants.get(position); DialerCall call = participantInfo.getCall(); ContactCacheEntry contactCache = participantInfo.getContactCacheEntry(); @@ -228,14 +228,14 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { } boolean thisRowCanSeparate = - mParentCanSeparate + parentCanSeparate && call.can(android.telecom.Call.Details.CAPABILITY_SEPARATE_FROM_CONFERENCE); boolean thisRowCanDisconnect = call.can(android.telecom.Call.Details.CAPABILITY_DISCONNECT_FROM_CONFERENCE); String name = ContactDisplayUtils.getPreferredDisplayName( - contactCache.namePrimary, contactCache.nameAlternative, mContactsPreferences); + contactCache.namePrimary, contactCache.nameAlternative, contactsPreferences); setCallerInfoForRow( result, @@ -262,8 +262,8 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { * @param entry The new contact info. */ /* package */ void updateContactInfo(String callId, ContactCacheEntry entry) { - if (mParticipantsByCallId.containsKey(callId)) { - ParticipantInfo participantInfo = mParticipantsByCallId.get(callId); + if (participantsByCallId.containsKey(callId)) { + ParticipantInfo participantInfo = participantsByCallId.get(callId); participantInfo.setContactCacheEntry(entry); participantInfo.setCacheLookupComplete(true); refreshView(callId); @@ -307,14 +307,14 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { endButton.setVisibility(thisRowCanDisconnect ? View.VISIBLE : View.GONE); if (thisRowCanDisconnect) { - endButton.setOnClickListener(mDisconnectListener); + endButton.setOnClickListener(disconnectListener); } else { endButton.setOnClickListener(null); } separateButton.setVisibility(thisRowCanSeparate ? View.VISIBLE : View.GONE); if (thisRowCanSeparate) { - separateButton.setOnClickListener(mSeparateListener); + separateButton.setOnClickListener(separateListener); } else { separateButton.setOnClickListener(null); } @@ -325,7 +325,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { ? null : new DefaultImageRequest(displayNameForImage, lookupKey, true /* isCircularPhoto */); - mContactPhotoManager.loadDirectoryPhoto(photoView, photoUri, false, true, imageRequest); + contactPhotoManager.loadDirectoryPhoto(photoView, photoUri, false, true, imageRequest); // set the caller name if (TextUtils.isEmpty(preferredName)) { @@ -404,26 +404,26 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { getContext(), call, call.getState() == DialerCall.State.INCOMING); } - if (mParticipantsByCallId.containsKey(callId)) { - ParticipantInfo participantInfo = mParticipantsByCallId.get(callId); + if (participantsByCallId.containsKey(callId)) { + ParticipantInfo participantInfo = participantsByCallId.get(callId); participantInfo.setCall(call); participantInfo.setContactCacheEntry(contactCache); } else { newParticipantAdded = true; ParticipantInfo participantInfo = new ParticipantInfo(call, contactCache); - mConferenceParticipants.add(participantInfo); - mParticipantsByCallId.put(call.getId(), participantInfo); + this.conferenceParticipants.add(participantInfo); + participantsByCallId.put(call.getId(), participantInfo); } } // Remove any participants that no longer exist. - Iterator> it = mParticipantsByCallId.entrySet().iterator(); + Iterator> it = participantsByCallId.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); String existingCallId = entry.getKey(); if (!newCallIds.contains(existingCallId)) { ParticipantInfo existingInfo = entry.getValue(); - mConferenceParticipants.remove(existingInfo); + this.conferenceParticipants.remove(existingInfo); it.remove(); } } @@ -438,7 +438,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { /** Sorts the participant list by contact name. */ private void sortParticipantList() { Collections.sort( - mConferenceParticipants, + conferenceParticipants, new Comparator() { @Override public int compare(ParticipantInfo p1, ParticipantInfo p2) { @@ -446,13 +446,13 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { ContactCacheEntry c1 = p1.getContactCacheEntry(); String p1Name = ContactDisplayUtils.getPreferredSortName( - c1.namePrimary, c1.nameAlternative, mContactsPreferences); + c1.namePrimary, c1.nameAlternative, contactsPreferences); p1Name = p1Name != null ? p1Name : ""; ContactCacheEntry c2 = p2.getContactCacheEntry(); String p2Name = ContactDisplayUtils.getPreferredSortName( - c2.namePrimary, c2.nameAlternative, mContactsPreferences); + c2.namePrimary, c2.nameAlternative, contactsPreferences); p2Name = p2Name != null ? p2Name : ""; return p1Name.compareToIgnoreCase(p2Name); @@ -472,10 +472,10 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { */ public static class ContactLookupCallback implements ContactInfoCache.ContactInfoCacheCallback { - private final WeakReference mListAdapter; + private final WeakReference listAdapter; public ContactLookupCallback(ConferenceParticipantListAdapter listAdapter) { - mListAdapter = new WeakReference<>(listAdapter); + this.listAdapter = new WeakReference<>(listAdapter); } /** @@ -507,7 +507,7 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { * @param entry The new contact information. */ private void update(String callId, ContactCacheEntry entry) { - ConferenceParticipantListAdapter listAdapter = mListAdapter.get(); + ConferenceParticipantListAdapter listAdapter = this.listAdapter.get(); if (listAdapter != null) { listAdapter.updateContactInfo(callId, entry); } @@ -520,51 +520,51 @@ public class ConferenceParticipantListAdapter extends BaseAdapter { */ private static class ParticipantInfo { - private DialerCall mCall; - private ContactCacheEntry mContactCacheEntry; - private boolean mCacheLookupComplete = false; + private DialerCall call; + private ContactCacheEntry contactCacheEntry; + private boolean cacheLookupComplete = false; public ParticipantInfo(DialerCall call, ContactCacheEntry contactCacheEntry) { - mCall = call; - mContactCacheEntry = contactCacheEntry; + this.call = call; + this.contactCacheEntry = contactCacheEntry; } public DialerCall getCall() { - return mCall; + return call; } public void setCall(DialerCall call) { - mCall = call; + this.call = call; } public ContactCacheEntry getContactCacheEntry() { - return mContactCacheEntry; + return contactCacheEntry; } public void setContactCacheEntry(ContactCacheEntry entry) { - mContactCacheEntry = entry; + contactCacheEntry = entry; } public boolean isCacheLookupComplete() { - return mCacheLookupComplete; + return cacheLookupComplete; } public void setCacheLookupComplete(boolean cacheLookupComplete) { - mCacheLookupComplete = cacheLookupComplete; + this.cacheLookupComplete = cacheLookupComplete; } @Override public boolean equals(Object o) { if (o instanceof ParticipantInfo) { ParticipantInfo p = (ParticipantInfo) o; - return Objects.equals(p.getCall().getId(), mCall.getId()); + return Objects.equals(p.getCall().getId(), call.getId()); } return false; } @Override public int hashCode() { - return mCall.getId().hashCode(); + return call.getId().hashCode(); } } } diff --git a/java/com/android/incallui/ContactInfoCache.java b/java/com/android/incallui/ContactInfoCache.java index 67a294f97..fbee743c6 100644 --- a/java/com/android/incallui/ContactInfoCache.java +++ b/java/com/android/incallui/ContactInfoCache.java @@ -78,14 +78,14 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private static final String TAG = ContactInfoCache.class.getSimpleName(); private static final int TOKEN_UPDATE_PHOTO_FOR_CALL_STATE = 0; - private static ContactInfoCache sCache = null; - private final Context mContext; - private final PhoneNumberService mPhoneNumberService; + private static ContactInfoCache cache = null; + private final Context context; + private final PhoneNumberService phoneNumberService; // Cache info map needs to be thread-safe since it could be modified by both main thread and // worker thread. - private final ConcurrentHashMap mInfoMap = new ConcurrentHashMap<>(); - private final Map> mCallBacks = new ArrayMap<>(); - private int mQueryId; + private final ConcurrentHashMap infoMap = new ConcurrentHashMap<>(); + private final Map> callBacks = new ArrayMap<>(); + private int queryId; private final DialerExecutor cachedNumberLookupExecutor; private static class CachedNumberLookupWorker implements Worker { @@ -123,10 +123,10 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private ContactInfoCache(Context context) { Trace.beginSection("ContactInfoCache constructor"); - mContext = context; - mPhoneNumberService = Bindings.get(context).newPhoneNumberService(context); + this.context = context; + phoneNumberService = Bindings.get(context).newPhoneNumberService(context); cachedNumberLookupExecutor = - DialerExecutorComponent.get(mContext) + DialerExecutorComponent.get(this.context) .dialerExecutorFactory() .createNonUiTaskBuilder(new CachedNumberLookupWorker()) .build(); @@ -134,10 +134,10 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } public static synchronized ContactInfoCache getInstance(Context mContext) { - if (sCache == null) { - sCache = new ContactInfoCache(mContext.getApplicationContext()); + if (cache == null) { + cache = new ContactInfoCache(mContext.getApplicationContext()); } - return sCache; + return cache; } static ContactCacheEntry buildCacheEntryFromCall( @@ -300,7 +300,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } ContactCacheEntry getInfo(String callId) { - return mInfoMap.get(callId); + return infoMap.get(callId); } private static final class CnapInformationWrapper { @@ -328,7 +328,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } if (cachedNumberLookupService == null || TextUtils.isEmpty(info.cnapName) - || mInfoMap.get(call.getId()) != null) { + || infoMap.get(call.getId()) != null) { return; } Log.i(TAG, "Found contact with CNAP name - inserting into cache"); @@ -355,8 +355,8 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { Trace.beginSection("prepare callback"); final String callId = call.getId(); - final ContactCacheEntry cacheEntry = mInfoMap.get(callId); - Set callBacks = mCallBacks.get(callId); + final ContactCacheEntry cacheEntry = infoMap.get(callId); + Set callBacks = this.callBacks.get(callId); // We need to force a new query if phone number has changed. boolean forceQuery = needForceQuery(call, cacheEntry); @@ -392,7 +392,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { // New lookup callBacks = new ArraySet<>(); callBacks.add(callback); - mCallBacks.put(callId, callBacks); + this.callBacks.put(callId, callBacks); } Trace.beginSection("prepare query"); @@ -402,11 +402,11 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { * such as those for voicemail and emergency call information, will not perform an additional * asynchronous query. */ - final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryId, callId); - mQueryId++; + final CallerInfoQueryToken queryToken = new CallerInfoQueryToken(queryId, callId); + queryId++; final CallerInfo callerInfo = CallerInfoUtils.getCallerInfoForCall( - mContext, + context, call, new DialerCallCookieWrapper(callId, call.getNumberPresentation(), call.getCnapName()), new FindInfoCallback(isIncoming, queryToken)); @@ -417,7 +417,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { // back. We should only update the queryId. Otherwise, we may see // flicker of the name and image (old cache -> new cache before query // -> new cache after query) - cacheEntry.queryId = queryToken.mQueryId; + cacheEntry.queryId = queryToken.queryId; Log.d(TAG, "There is an existing cache. Do not override until new query is back"); } else { ContactCacheEntry initialCacheEntry = @@ -441,20 +441,20 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { "updateCallerInfoInCacheOnAnyThread: callId = " + callId + "; queryId = " - + queryToken.mQueryId + + queryToken.queryId + "; didLocalLookup = " + didLocalLookup); - ContactCacheEntry existingCacheEntry = mInfoMap.get(callId); + ContactCacheEntry existingCacheEntry = infoMap.get(callId); Log.d(TAG, "Existing cacheEntry in hashMap " + existingCacheEntry); // Mark it as emergency/voicemail if the cache exists and was emergency/voicemail before the // number changed. if (existingCacheEntry != null) { if (existingCacheEntry.isEmergencyNumber) { - callerInfo.markAsEmergency(mContext); + callerInfo.markAsEmergency(context); } else if (existingCacheEntry.isVoicemailNumber) { - callerInfo.markAsVoiceMail(mContext); + callerInfo.markAsVoiceMail(context); } } @@ -466,8 +466,8 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } // We always replace the entry. The only exception is the same photo case. - ContactCacheEntry cacheEntry = buildEntry(mContext, callerInfo, presentationMode); - cacheEntry.queryId = queryToken.mQueryId; + ContactCacheEntry cacheEntry = buildEntry(context, callerInfo, presentationMode); + cacheEntry.queryId = queryToken.queryId; if (didLocalLookup) { if (cacheEntry.displayPhotoUri != null) { @@ -491,17 +491,17 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { cacheEntry.hasPendingQuery = true; ContactsAsyncHelper.startObtainPhotoAsync( TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, - mContext, + context, cacheEntry.displayPhotoUri, ContactInfoCache.this, queryToken); } Log.d(TAG, "put entry into map: " + cacheEntry); - mInfoMap.put(callId, cacheEntry); + infoMap.put(callId, cacheEntry); } else { // Don't overwrite if there is existing cache. Log.d(TAG, "put entry into map if not exists: " + cacheEntry); - mInfoMap.putIfAbsent(callId, cacheEntry); + infoMap.putIfAbsent(callId, cacheEntry); } Trace.endSection(); return cacheEntry; @@ -509,7 +509,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private void maybeUpdateFromCequintCallerId( CallerInfo callerInfo, String cnapName, boolean isIncoming) { - if (!CequintCallerIdManager.isCequintCallerIdEnabled(mContext)) { + if (!CequintCallerIdManager.isCequintCallerIdEnabled(context)) { return; } if (callerInfo.phoneNumber == null) { @@ -517,7 +517,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } CequintCallerIdContact cequintCallerIdContact = CequintCallerIdManager.getCequintCallerIdContactForInCall( - mContext, callerInfo.phoneNumber, cnapName, isIncoming); + context, callerInfo.phoneNumber, cnapName, isIncoming); if (cequintCallerIdContact == null) { return; @@ -553,8 +553,8 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { public void onImageLoaded(int token, Drawable photo, Bitmap photoIcon, Object cookie) { Assert.isWorkerThread(); CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie; - final String callId = myCookie.mCallId; - final int queryId = myCookie.mQueryId; + final String callId = myCookie.callId; + final int queryId = myCookie.queryId; if (!isWaitingForThisQuery(callId, queryId)) { return; } @@ -562,12 +562,12 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } private void loadImage(Drawable photo, Bitmap photoIcon, Object cookie) { - Log.d(TAG, "Image load complete with context: ", mContext); + Log.d(TAG, "Image load complete with context: ", context); // TODO: may be nice to update the image view again once the newer one // is available on contacts database. CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie; - final String callId = myCookie.mCallId; - ContactCacheEntry entry = mInfoMap.get(callId); + final String callId = myCookie.callId; + ContactCacheEntry entry = infoMap.get(callId); if (entry == null) { Log.e(TAG, "Image Load received for empty search entry."); @@ -584,7 +584,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { entry.photoType = ContactPhotoType.CONTACT; } else if (photoIcon != null) { Log.v(TAG, "photo icon: ", photoIcon); - entry.photo = new BitmapDrawable(mContext.getResources(), photoIcon); + entry.photo = new BitmapDrawable(context.getResources(), photoIcon); entry.photoType = ContactPhotoType.CONTACT; } else { Log.v(TAG, "unknown photo"); @@ -602,21 +602,21 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { public void onImageLoadComplete(int token, Drawable photo, Bitmap photoIcon, Object cookie) { Assert.isMainThread(); CallerInfoQueryToken myCookie = (CallerInfoQueryToken) cookie; - final String callId = myCookie.mCallId; - final int queryId = myCookie.mQueryId; + final String callId = myCookie.callId; + final int queryId = myCookie.queryId; if (!isWaitingForThisQuery(callId, queryId)) { return; } - sendImageNotifications(callId, mInfoMap.get(callId)); + sendImageNotifications(callId, infoMap.get(callId)); clearCallbacks(callId); } /** Blows away the stored cache values. */ public void clearCache() { - mInfoMap.clear(); - mCallBacks.clear(); - mQueryId = 0; + infoMap.clear(); + callBacks.clear(); + queryId = 0; } private ContactCacheEntry buildEntry(Context context, CallerInfo info, int presentation) { @@ -662,7 +662,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private void sendInfoNotifications(String callId, ContactCacheEntry entry) { Trace.beginSection("ContactInfoCache.sendInfoNotifications"); Assert.isMainThread(); - final Set callBacks = mCallBacks.get(callId); + final Set callBacks = this.callBacks.get(callId); if (callBacks != null) { for (ContactInfoCacheCallback callBack : callBacks) { callBack.onContactInfoComplete(callId, entry); @@ -675,7 +675,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private void sendImageNotifications(String callId, ContactCacheEntry entry) { Trace.beginSection("ContactInfoCache.sendImageNotifications"); Assert.isMainThread(); - final Set callBacks = mCallBacks.get(callId); + final Set callBacks = this.callBacks.get(callId); if (callBacks != null && entry.photo != null) { for (ContactInfoCacheCallback callBack : callBacks) { callBack.onImageLoadComplete(callId, entry); @@ -685,7 +685,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } private void clearCallbacks(String callId) { - mCallBacks.remove(callId); + callBacks.remove(callId); } /** Callback interface for the contact query. */ @@ -791,26 +791,26 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { private class FindInfoCallback implements OnQueryCompleteListener { - private final boolean mIsIncoming; - private final CallerInfoQueryToken mQueryToken; + private final boolean isIncoming; + private final CallerInfoQueryToken queryToken; FindInfoCallback(boolean isIncoming, CallerInfoQueryToken queryToken) { - mIsIncoming = isIncoming; - mQueryToken = queryToken; + this.isIncoming = isIncoming; + this.queryToken = queryToken; } @Override public void onDataLoaded(int token, Object cookie, CallerInfo ci) { Assert.isWorkerThread(); DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie; - if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) { + if (!isWaitingForThisQuery(cw.callId, queryToken.queryId)) { return; } long start = SystemClock.uptimeMillis(); - maybeUpdateFromCequintCallerId(ci, cw.cnapName, mIsIncoming); + maybeUpdateFromCequintCallerId(ci, cw.cnapName, isIncoming); long time = SystemClock.uptimeMillis() - start; Log.d(TAG, "Cequint Caller Id look up takes " + time + " ms."); - updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, mQueryToken); + updateCallerInfoInCacheOnAnyThread(cw.callId, cw.numberPresentation, ci, true, queryToken); } @Override @@ -819,11 +819,11 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { Assert.isMainThread(); DialerCallCookieWrapper cw = (DialerCallCookieWrapper) cookie; String callId = cw.callId; - if (!isWaitingForThisQuery(cw.callId, mQueryToken.mQueryId)) { + if (!isWaitingForThisQuery(cw.callId, queryToken.queryId)) { Trace.endSection(); return; } - ContactCacheEntry cacheEntry = mInfoMap.get(callId); + ContactCacheEntry cacheEntry = infoMap.get(callId); // This may happen only when InCallPresenter attempt to cleanup. if (cacheEntry == null) { Log.w(TAG, "Contact lookup done, but cache entry is not found."); @@ -834,12 +834,12 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { // Before issuing a request for more data from other services, we only check that the // contact wasn't found in the local DB. We don't check the if the cache entry already // has a name because we allow overriding cnap data with data from other services. - if (!callerInfo.contactExists && mPhoneNumberService != null) { + if (!callerInfo.contactExists && phoneNumberService != null) { Log.d(TAG, "Contact lookup. Local contacts miss, checking remote"); final PhoneNumberServiceListener listener = - new PhoneNumberServiceListener(callId, mQueryToken.mQueryId); + new PhoneNumberServiceListener(callId, queryToken.queryId); cacheEntry.hasPendingQuery = true; - mPhoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener, listener, mIsIncoming); + phoneNumberService.getPhoneNumberInfo(cacheEntry.number, listener, listener, isIncoming); } sendInfoNotifications(callId, cacheEntry); if (!cacheEntry.hasPendingQuery) { @@ -860,18 +860,18 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { class PhoneNumberServiceListener implements PhoneNumberService.NumberLookupListener, PhoneNumberService.ImageLookupListener { - private final String mCallId; - private final int mQueryIdOfRemoteLookup; + private final String callId; + private final int queryIdOfRemoteLookup; PhoneNumberServiceListener(String callId, int queryId) { - mCallId = callId; - mQueryIdOfRemoteLookup = queryId; + this.callId = callId; + queryIdOfRemoteLookup = queryId; } @Override public void onPhoneNumberInfoComplete(final PhoneNumberService.PhoneNumberInfo info) { Log.d(TAG, "PhoneNumberServiceListener.onPhoneNumberInfoComplete"); - if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) { + if (!isWaitingForThisQuery(callId, queryIdOfRemoteLookup)) { return; } @@ -879,7 +879,7 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { // so clear the callbacks and return. if (info == null) { Log.d(TAG, "Contact lookup done. Remote contact not found."); - clearCallbacks(mCallId); + clearCallbacks(callId); return; } ContactCacheEntry entry = new ContactCacheEntry(); @@ -892,10 +892,10 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { if (type == Phone.TYPE_CUSTOM) { entry.label = label; } else { - final CharSequence typeStr = Phone.getTypeLabel(mContext.getResources(), type, label); + final CharSequence typeStr = Phone.getTypeLabel(context.getResources(), type, label); entry.label = typeStr == null ? null : typeStr.toString(); } - final ContactCacheEntry oldEntry = mInfoMap.get(mCallId); + final ContactCacheEntry oldEntry = infoMap.get(callId); if (oldEntry != null) { // Location is only obtained from local lookup so persist // the value for remote lookups. Once we have a name this @@ -915,25 +915,25 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } Log.d(TAG, "put entry into map: " + entry); - mInfoMap.put(mCallId, entry); - sendInfoNotifications(mCallId, entry); + infoMap.put(callId, entry); + sendInfoNotifications(callId, entry); entry.hasPendingQuery = info.getImageUrl() != null; // If there is no image then we should not expect another callback. if (!entry.hasPendingQuery) { // We're done, so clear callbacks - clearCallbacks(mCallId); + clearCallbacks(callId); } } @Override public void onImageFetchComplete(Bitmap bitmap) { Log.d(TAG, "PhoneNumberServiceListener.onImageFetchComplete"); - if (!isWaitingForThisQuery(mCallId, mQueryIdOfRemoteLookup)) { + if (!isWaitingForThisQuery(callId, queryIdOfRemoteLookup)) { return; } - CallerInfoQueryToken queryToken = new CallerInfoQueryToken(mQueryIdOfRemoteLookup, mCallId); + CallerInfoQueryToken queryToken = new CallerInfoQueryToken(queryIdOfRemoteLookup, callId); loadImage(null, bitmap, queryToken); onImageLoadComplete(TOKEN_UPDATE_PHOTO_FOR_CALL_STATE, null, bitmap, queryToken); } @@ -961,18 +961,18 @@ public class ContactInfoCache implements OnImageLoadCompleteListener { } private static final class CallerInfoQueryToken { - final int mQueryId; - final String mCallId; + final int queryId; + final String callId; CallerInfoQueryToken(int queryId, String callId) { - mQueryId = queryId; - mCallId = callId; + this.queryId = queryId; + this.callId = callId; } } /** Check if the queryId in the cached map is the same as the one from query result. */ private boolean isWaitingForThisQuery(String callId, int queryId) { - final ContactCacheEntry existingCacheEntry = mInfoMap.get(callId); + final ContactCacheEntry existingCacheEntry = infoMap.get(callId); if (existingCacheEntry == null) { // This might happen if lookup on background thread comes back before the initial entry is // created. diff --git a/java/com/android/incallui/ContactsPreferencesFactory.java b/java/com/android/incallui/ContactsPreferencesFactory.java index 429de7bc9..a9a210963 100644 --- a/java/com/android/incallui/ContactsPreferencesFactory.java +++ b/java/com/android/incallui/ContactsPreferencesFactory.java @@ -24,8 +24,8 @@ import com.android.contacts.common.preference.ContactsPreferences; /** Factory class for {@link ContactsPreferences}. */ public class ContactsPreferencesFactory { - private static boolean sUseTestInstance; - private static ContactsPreferences sTestInstance; + private static boolean useTestInstance; + private static ContactsPreferences testInstance; /** * Creates a new {@link ContactsPreferences} object if possible. @@ -35,8 +35,8 @@ public class ContactsPreferencesFactory { */ @Nullable public static ContactsPreferences newContactsPreferences(Context context) { - if (sUseTestInstance) { - return sTestInstance; + if (useTestInstance) { + return testInstance; } if (UserManagerCompat.isUserUnlocked(context)) { return new ContactsPreferences(context); @@ -50,7 +50,7 @@ public class ContactsPreferencesFactory { * @param testInstance the instance to return. */ static void setTestInstance(ContactsPreferences testInstance) { - sUseTestInstance = true; - sTestInstance = testInstance; + useTestInstance = true; + ContactsPreferencesFactory.testInstance = testInstance; } } diff --git a/java/com/android/incallui/DialpadFragment.java b/java/com/android/incallui/DialpadFragment.java index b2aacf71d..c5b9d785f 100644 --- a/java/com/android/incallui/DialpadFragment.java +++ b/java/com/android/incallui/DialpadFragment.java @@ -45,26 +45,26 @@ public class DialpadFragment extends BaseFragment implements DialpadUi, OnKeyListener, OnClickListener, OnPressedListener { /** Hash Map to map a view id to a character */ - private static final Map mDisplayMap = new ArrayMap<>(); + private static final Map displayMap = new ArrayMap<>(); /** Set up the static maps */ static { // Map the buttons to the display characters - mDisplayMap.put(R.id.one, '1'); - mDisplayMap.put(R.id.two, '2'); - mDisplayMap.put(R.id.three, '3'); - mDisplayMap.put(R.id.four, '4'); - mDisplayMap.put(R.id.five, '5'); - mDisplayMap.put(R.id.six, '6'); - mDisplayMap.put(R.id.seven, '7'); - mDisplayMap.put(R.id.eight, '8'); - mDisplayMap.put(R.id.nine, '9'); - mDisplayMap.put(R.id.zero, '0'); - mDisplayMap.put(R.id.pound, '#'); - mDisplayMap.put(R.id.star, '*'); + displayMap.put(R.id.one, '1'); + displayMap.put(R.id.two, '2'); + displayMap.put(R.id.three, '3'); + displayMap.put(R.id.four, '4'); + displayMap.put(R.id.five, '5'); + displayMap.put(R.id.six, '6'); + displayMap.put(R.id.seven, '7'); + displayMap.put(R.id.eight, '8'); + displayMap.put(R.id.nine, '9'); + displayMap.put(R.id.zero, '0'); + displayMap.put(R.id.pound, '#'); + displayMap.put(R.id.star, '*'); } - private final int[] mButtonIds = + private final int[] buttonIds = new int[] { R.id.zero, R.id.one, @@ -79,11 +79,11 @@ public class DialpadFragment extends BaseFragment R.id.star, R.id.pound }; - private EditText mDtmfDialerField; + private EditText dtmfDialerField; // KeyListener used with the "dialpad digits" EditText widget. - private DtmfKeyListener mDtmfKeyListener; - private DialpadView mDialpadView; - private int mCurrentTextColor; + private DtmfKeyListener dtmfKeyListener; + private DialpadView dialpadView; + private int currentTextColor; @Override public void onClick(View v) { @@ -100,11 +100,11 @@ public class DialpadFragment extends BaseFragment if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) { int viewId = v.getId(); - if (mDisplayMap.containsKey(viewId)) { + if (displayMap.containsKey(viewId)) { switch (event.getAction()) { case KeyEvent.ACTION_DOWN: if (event.getRepeatCount() == 0) { - getPresenter().processDtmf(mDisplayMap.get(viewId)); + getPresenter().processDtmf(displayMap.get(viewId)); } break; case KeyEvent.ACTION_UP: @@ -135,21 +135,21 @@ public class DialpadFragment extends BaseFragment public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View parent = inflater.inflate(R.layout.incall_dialpad_fragment, container, false); - mDialpadView = (DialpadView) parent.findViewById(R.id.dialpad_view); - mDialpadView.setCanDigitsBeEdited(false); - mDialpadView.setBackgroundResource(R.color.incall_dialpad_background); - mDtmfDialerField = (EditText) parent.findViewById(R.id.digits); - if (mDtmfDialerField != null) { + dialpadView = (DialpadView) parent.findViewById(R.id.dialpad_view); + dialpadView.setCanDigitsBeEdited(false); + dialpadView.setBackgroundResource(R.color.incall_dialpad_background); + dtmfDialerField = (EditText) parent.findViewById(R.id.digits); + if (dtmfDialerField != null) { LogUtil.i("DialpadFragment.onCreateView", "creating dtmfKeyListener"); - mDtmfKeyListener = new DtmfKeyListener(getPresenter()); - mDtmfDialerField.setKeyListener(mDtmfKeyListener); + dtmfKeyListener = new DtmfKeyListener(getPresenter()); + dtmfDialerField.setKeyListener(dtmfKeyListener); // remove the long-press context menus that support // the edit (copy / paste / select) functions. - mDtmfDialerField.setLongClickable(false); - mDtmfDialerField.setElegantTextHeight(false); + dtmfDialerField.setLongClickable(false); + dtmfDialerField.setElegantTextHeight(false); configureKeypadListeners(); } - View backButton = mDialpadView.findViewById(R.id.dialpad_back); + View backButton = dialpadView.findViewById(R.id.dialpad_back); backButton.setVisibility(View.VISIBLE); backButton.setOnClickListener(this); @@ -165,22 +165,22 @@ public class DialpadFragment extends BaseFragment public void updateColors() { int textColor = InCallPresenter.getInstance().getThemeColorManager().getPrimaryColor(); - if (mCurrentTextColor == textColor) { + if (currentTextColor == textColor) { return; } DialpadKeyButton dialpadKey; - for (int i = 0; i < mButtonIds.length; i++) { - dialpadKey = (DialpadKeyButton) mDialpadView.findViewById(mButtonIds[i]); + for (int i = 0; i < buttonIds.length; i++) { + dialpadKey = (DialpadKeyButton) dialpadView.findViewById(buttonIds[i]); ((TextView) dialpadKey.findViewById(R.id.dialpad_key_number)).setTextColor(textColor); } - mCurrentTextColor = textColor; + currentTextColor = textColor; } @Override public void onDestroyView() { - mDtmfKeyListener = null; + dtmfKeyListener = null; super.onDestroyView(); } @@ -190,7 +190,7 @@ public class DialpadFragment extends BaseFragment * @return String containing current Dialpad EditText text. */ public String getDtmfText() { - return mDtmfDialerField.getText().toString(); + return dtmfDialerField.getText().toString(); } /** @@ -199,7 +199,7 @@ public class DialpadFragment extends BaseFragment * @param text Text to set Dialpad EditText to. */ public void setDtmfText(String text) { - mDtmfDialerField.setText(PhoneNumberUtilsCompat.createTtsSpannable(text)); + dtmfDialerField.setText(PhoneNumberUtilsCompat.createTtsSpannable(text)); } /** Starts the slide up animation for the Dialpad keys when the Dialpad is revealed. */ @@ -210,7 +210,7 @@ public class DialpadFragment extends BaseFragment @Override public void appendDigitsToField(char digit) { - if (mDtmfDialerField != null) { + if (dtmfDialerField != null) { // TODO: maybe *don't* manually append this digit if // mDialpadDigits is focused and this key came from the HW // keyboard, since in that case the EditText field will @@ -220,15 +220,15 @@ public class DialpadFragment extends BaseFragment // *not* handle HW key presses. That seems to be more // complicated than just setting focusable="false" on it, // though.) - mDtmfDialerField.getText().append(digit); + dtmfDialerField.getText().append(digit); } } /** Called externally (from InCallScreen) to play a DTMF Tone. */ /* package */ boolean onDialerKeyDown(KeyEvent event) { Log.d(this, "Notifying dtmf key down."); - if (mDtmfKeyListener != null) { - return mDtmfKeyListener.onKeyDown(event); + if (dtmfKeyListener != null) { + return dtmfKeyListener.onKeyDown(event); } else { return false; } @@ -237,8 +237,8 @@ public class DialpadFragment extends BaseFragment /** Called externally (from InCallScreen) to cancel the last DTMF Tone played. */ public boolean onDialerKeyUp(KeyEvent event) { Log.d(this, "Notifying dtmf key up."); - if (mDtmfKeyListener != null) { - return mDtmfKeyListener.onKeyUp(event); + if (dtmfKeyListener != null) { + return dtmfKeyListener.onKeyUp(event); } else { return false; } @@ -246,8 +246,8 @@ public class DialpadFragment extends BaseFragment private void configureKeypadListeners() { DialpadKeyButton dialpadKey; - for (int i = 0; i < mButtonIds.length; i++) { - dialpadKey = (DialpadKeyButton) mDialpadView.findViewById(mButtonIds[i]); + for (int i = 0; i < buttonIds.length; i++) { + dialpadKey = (DialpadKeyButton) dialpadView.findViewById(buttonIds[i]); dialpadKey.setOnKeyListener(this); dialpadKey.setOnClickListener(this); dialpadKey.setOnPressedListener(this); @@ -256,11 +256,11 @@ public class DialpadFragment extends BaseFragment @Override public void onPressed(View view, boolean pressed) { - if (pressed && mDisplayMap.containsKey(view.getId())) { + if (pressed && displayMap.containsKey(view.getId())) { Logger.get(getContext()) .logImpression(DialerImpression.Type.IN_CALL_DIALPAD_NUMBER_BUTTON_PRESSED); - Log.d(this, "onPressed: " + pressed + " " + mDisplayMap.get(view.getId())); - getPresenter().processDtmf(mDisplayMap.get(view.getId())); + Log.d(this, "onPressed: " + pressed + " " + displayMap.get(view.getId())); + getPresenter().processDtmf(displayMap.get(view.getId())); } if (!pressed) { Log.d(this, "onPressed: " + pressed); diff --git a/java/com/android/incallui/DialpadPresenter.java b/java/com/android/incallui/DialpadPresenter.java index 002fefce7..e6fbdc22d 100644 --- a/java/com/android/incallui/DialpadPresenter.java +++ b/java/com/android/incallui/DialpadPresenter.java @@ -28,13 +28,13 @@ import com.android.incallui.call.TelecomAdapter; public class DialpadPresenter extends Presenter implements InCallPresenter.InCallStateListener { - private DialerCall mCall; + private DialerCall call; @Override public void onUiReady(DialpadUi ui) { super.onUiReady(ui); InCallPresenter.getInstance().addListener(this); - mCall = CallList.getInstance().getOutgoingOrActive(); + call = CallList.getInstance().getOutgoingOrActive(); } @Override @@ -48,8 +48,8 @@ public class DialpadPresenter extends Presenter InCallPresenter.InCallState oldState, InCallPresenter.InCallState newState, CallList callList) { - mCall = callList.getOutgoingOrActive(); - Log.d(this, "DialpadPresenter mCall = " + mCall); + call = callList.getOutgoingOrActive(); + Log.d(this, "DialpadPresenter mCall = " + call); } /** @@ -59,7 +59,7 @@ public class DialpadPresenter extends Presenter public final void processDtmf(char c) { Log.d(this, "Processing dtmf key " + c); // if it is a valid key, then update the display and send the dtmf tone. - if (PhoneNumberUtils.is12Key(c) && mCall != null) { + if (PhoneNumberUtils.is12Key(c) && call != null) { Log.d(this, "updating display and sending dtmf tone for '" + c + "'"); // Append this key to the "digits" widget. @@ -68,7 +68,7 @@ public class DialpadPresenter extends Presenter dialpadUi.appendDigitsToField(c); } // Plays the tone through Telecom. - TelecomAdapter.getInstance().playDtmfTone(mCall.getId(), c); + TelecomAdapter.getInstance().playDtmfTone(call.getId(), c); } else { Log.d(this, "ignoring dtmf request for '" + c + "'"); } @@ -76,9 +76,9 @@ public class DialpadPresenter extends Presenter /** Stops the local tone based on the phone type. */ public void stopDtmf() { - if (mCall != null) { + if (call != null) { Log.d(this, "stopping remote tone"); - TelecomAdapter.getInstance().stopDtmfTone(mCall.getId()); + TelecomAdapter.getInstance().stopDtmfTone(call.getId()); } } diff --git a/java/com/android/incallui/ExternalCallNotifier.java b/java/com/android/incallui/ExternalCallNotifier.java index 7915b85af..8c882d2a3 100644 --- a/java/com/android/incallui/ExternalCallNotifier.java +++ b/java/com/android/incallui/ExternalCallNotifier.java @@ -73,18 +73,18 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen */ private static final String GROUP_KEY = "ExternalCallGroup"; - private final Context mContext; - private final ContactInfoCache mContactInfoCache; - private Map mNotifications = new ArrayMap<>(); - private int mNextUniqueNotificationId; - private ContactsPreferences mContactsPreferences; + private final Context context; + private final ContactInfoCache contactInfoCache; + private Map notifications = new ArrayMap<>(); + private int nextUniqueNotificationId; + private ContactsPreferences contactsPreferences; /** Initializes a new instance of the external call notifier. */ public ExternalCallNotifier( @NonNull Context context, @NonNull ContactInfoCache contactInfoCache) { - mContext = context; - mContactsPreferences = ContactsPreferencesFactory.newContactsPreferences(mContext); - mContactInfoCache = contactInfoCache; + this.context = context; + contactsPreferences = ContactsPreferencesFactory.newContactsPreferences(this.context); + this.contactInfoCache = contactInfoCache; } /** @@ -94,9 +94,9 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen @Override public void onExternalCallAdded(android.telecom.Call call) { Log.i(this, "onExternalCallAdded " + call); - Assert.checkArgument(!mNotifications.containsKey(call)); - NotificationInfo info = new NotificationInfo(call, mNextUniqueNotificationId++); - mNotifications.put(call, info); + Assert.checkArgument(!notifications.containsKey(call)); + NotificationInfo info = new NotificationInfo(call, nextUniqueNotificationId++); + notifications.put(call, info); showNotifcation(info); } @@ -115,8 +115,8 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen /** Handles updates to an external call. */ @Override public void onExternalCallUpdated(Call call) { - Assert.checkArgument(mNotifications.containsKey(call)); - postNotification(mNotifications.get(call)); + Assert.checkArgument(notifications.containsKey(call)); + postNotification(notifications.get(call)); } @Override @@ -132,7 +132,7 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen */ @TargetApi(VERSION_CODES.N_MR1) public void pullExternalCall(int notificationId) { - for (NotificationInfo info : mNotifications.values()) { + for (NotificationInfo info : notifications.values()) { if (info.getNotificationId() == notificationId && CallCompat.canPullExternalCall(info.getCall())) { info.getCall().pullExternalCall(); @@ -153,13 +153,13 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen // call into the contacts provider for more data. DialerCall dialerCall = new DialerCall( - mContext, + context, new DialerCallDelegateStub(), info.getCall(), new LatencyReport(), false /* registerCallback */); - mContactInfoCache.findInfo( + contactInfoCache.findInfo( dialerCall, false /* isIncoming */, new ContactInfoCache.ContactInfoCacheCallback() { @@ -169,7 +169,7 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen // Ensure notification still exists as the external call could have been // removed during async contact info lookup. - if (mNotifications.containsKey(info.getCall())) { + if (notifications.containsKey(info.getCall())) { saveContactInfo(info, entry); } } @@ -179,7 +179,7 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen // Ensure notification still exists as the external call could have been // removed during async contact info lookup. - if (mNotifications.containsKey(info.getCall())) { + if (notifications.containsKey(info.getCall())) { savePhoto(info, entry); } } @@ -188,13 +188,13 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen /** Dismisses a notification for an external call. */ private void dismissNotification(Call call) { - Assert.checkArgument(mNotifications.containsKey(call)); + Assert.checkArgument(notifications.containsKey(call)); // This will also dismiss the group summary if there are no more external call notifications. DialerNotificationManager.cancel( - mContext, NOTIFICATION_TAG, mNotifications.get(call).getNotificationId()); + context, NOTIFICATION_TAG, notifications.get(call).getNotificationId()); - mNotifications.remove(call); + notifications.remove(call); } /** @@ -202,9 +202,9 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen * the updated notification to the notification manager. */ private void savePhoto(NotificationInfo info, ContactInfoCache.ContactCacheEntry entry) { - Bitmap largeIcon = getLargeIconToDisplay(mContext, entry, info.getCall()); + Bitmap largeIcon = getLargeIconToDisplay(context, entry, info.getCall()); if (largeIcon != null) { - largeIcon = getRoundedIcon(mContext, largeIcon); + largeIcon = getRoundedIcon(context, largeIcon); } info.setLargeIcon(largeIcon); postNotification(info); @@ -215,14 +215,14 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen * notification to the notification manager. */ private void saveContactInfo(NotificationInfo info, ContactInfoCache.ContactCacheEntry entry) { - info.setContentTitle(getContentTitle(mContext, mContactsPreferences, entry, info.getCall())); + info.setContentTitle(getContentTitle(context, contactsPreferences, entry, info.getCall())); info.setPersonReference(getPersonReference(entry, info.getCall())); postNotification(info); } /** Rebuild an existing or show a new notification given {@link NotificationInfo}. */ private void postNotification(NotificationInfo info) { - Notification.Builder builder = new Notification.Builder(mContext); + Notification.Builder builder = new Notification.Builder(context); // Set notification as ongoing since calls are long-running versus a point-in-time notice. builder.setOngoing(true); // Make the notification prioritized over the other normal notifications. @@ -232,14 +232,14 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen boolean isVideoCall = VideoProfile.isVideo(info.getCall().getDetails().getVideoState()); // Set the content ("Ongoing call on another device") builder.setContentText( - mContext.getString( + context.getString( isVideoCall ? R.string.notification_external_video_call : R.string.notification_external_call)); builder.setSmallIcon(R.drawable.quantum_ic_call_white_24); builder.setContentTitle(info.getContentTitle()); builder.setLargeIcon(info.getLargeIcon()); - builder.setColor(mContext.getResources().getColor(R.color.dialer_theme_color)); + builder.setColor(context.getResources().getColor(R.color.dialer_theme_color)); builder.addPerson(info.getPersonReference()); if (BuildCompat.isAtLeastO()) { builder.setChannelId(NotificationChannelId.DEFAULT); @@ -253,18 +253,18 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen new Intent( NotificationBroadcastReceiver.ACTION_PULL_EXTERNAL_CALL, null, - mContext, + context, NotificationBroadcastReceiver.class); intent.putExtra( NotificationBroadcastReceiver.EXTRA_NOTIFICATION_ID, info.getNotificationId()); builder.addAction( new Notification.Action.Builder( R.drawable.quantum_ic_call_white_24, - mContext.getString( + context.getString( isVideoCall ? R.string.notification_take_video_call : R.string.notification_take_call), - PendingIntent.getBroadcast(mContext, info.getNotificationId(), intent, 0)) + PendingIntent.getBroadcast(context, info.getNotificationId(), intent, 0)) .build()); } @@ -273,9 +273,9 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen * set their notification settings to 'hide sensitive content' {@see * Notification.Builder#setPublicVersion}. */ - Notification.Builder publicBuilder = new Notification.Builder(mContext); + Notification.Builder publicBuilder = new Notification.Builder(context); publicBuilder.setSmallIcon(R.drawable.quantum_ic_call_white_24); - publicBuilder.setColor(mContext.getResources().getColor(R.color.dialer_theme_color)); + publicBuilder.setColor(context.getResources().getColor(R.color.dialer_theme_color)); if (BuildCompat.isAtLeastO()) { publicBuilder.setChannelId(NotificationChannelId.DEFAULT); } @@ -284,9 +284,9 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen Notification notification = builder.build(); DialerNotificationManager.notify( - mContext, NOTIFICATION_TAG, info.getNotificationId(), notification); + context, NOTIFICATION_TAG, info.getNotificationId(), notification); - showGroupSummaryNotification(mContext); + showGroupSummaryNotification(context); } /** @@ -404,47 +404,47 @@ public class ExternalCallNotifier implements ExternalCallList.ExternalCallListen /** Represents a call and associated cached notification data. */ private static class NotificationInfo { - @NonNull private final Call mCall; - private final int mNotificationId; - @Nullable private String mContentTitle; - @Nullable private Bitmap mLargeIcon; - @Nullable private String mPersonReference; + @NonNull private final Call call; + private final int notificationId; + @Nullable private String contentTitle; + @Nullable private Bitmap largeIcon; + @Nullable private String personReference; public NotificationInfo(@NonNull Call call, int notificationId) { - mCall = call; - mNotificationId = notificationId; + this.call = call; + this.notificationId = notificationId; } public Call getCall() { - return mCall; + return call; } public int getNotificationId() { - return mNotificationId; + return notificationId; } public @Nullable String getContentTitle() { - return mContentTitle; + return contentTitle; } public void setContentTitle(@Nullable String contentTitle) { - mContentTitle = contentTitle; + this.contentTitle = contentTitle; } public @Nullable Bitmap getLargeIcon() { - return mLargeIcon; + return largeIcon; } public void setLargeIcon(@Nullable Bitmap largeIcon) { - mLargeIcon = largeIcon; + this.largeIcon = largeIcon; } public @Nullable String getPersonReference() { - return mPersonReference; + return personReference; } public void setPersonReference(@Nullable String personReference) { - mPersonReference = personReference; + this.personReference = personReference; } } diff --git a/java/com/android/incallui/InCallCameraManager.java b/java/com/android/incallui/InCallCameraManager.java index fdb422643..b5a8f91af 100644 --- a/java/com/android/incallui/InCallCameraManager.java +++ b/java/com/android/incallui/InCallCameraManager.java @@ -27,21 +27,21 @@ import java.util.concurrent.ConcurrentHashMap; /** Used to track which camera is used for outgoing video. */ public class InCallCameraManager { - private final Set mCameraSelectionListeners = + private final Set cameraSelectionListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); /** The camera ID for the front facing camera. */ - private String mFrontFacingCameraId; + private String frontFacingCameraId; /** The camera ID for the rear facing camera. */ - private String mRearFacingCameraId; + private String rearFacingCameraId; /** The currently active camera. */ - private boolean mUseFrontFacingCamera; + private boolean useFrontFacingCamera; /** * Indicates whether the list of cameras has been initialized yet. Initialization is delayed until * a video call is present. */ - private boolean mIsInitialized = false; + private boolean isInitialized = false; /** The context. */ - private Context mContext; + private Context context; /** * Initializes the InCall CameraManager. @@ -49,8 +49,8 @@ public class InCallCameraManager { * @param context The current context. */ public InCallCameraManager(Context context) { - mUseFrontFacingCamera = true; - mContext = context; + useFrontFacingCamera = true; + this.context = context; } /** @@ -59,9 +59,9 @@ public class InCallCameraManager { * @param useFrontFacingCamera {@code True} if the front facing camera is to be used. */ public void setUseFrontFacingCamera(boolean useFrontFacingCamera) { - mUseFrontFacingCamera = useFrontFacingCamera; - for (Listener listener : mCameraSelectionListeners) { - listener.onActiveCameraSelectionChanged(mUseFrontFacingCamera); + this.useFrontFacingCamera = useFrontFacingCamera; + for (Listener listener : cameraSelectionListeners) { + listener.onActiveCameraSelectionChanged(this.useFrontFacingCamera); } } @@ -71,7 +71,7 @@ public class InCallCameraManager { * @return {@code True} if the front facing camera is in use. */ public boolean isUsingFrontFacingCamera() { - return mUseFrontFacingCamera; + return useFrontFacingCamera; } /** @@ -80,18 +80,18 @@ public class InCallCameraManager { * @return The active camera ID. */ public String getActiveCameraId() { - maybeInitializeCameraList(mContext); + maybeInitializeCameraList(context); - if (mUseFrontFacingCamera) { - return mFrontFacingCameraId; + if (useFrontFacingCamera) { + return frontFacingCameraId; } else { - return mRearFacingCameraId; + return rearFacingCameraId; } } /** Calls when camera permission is granted by user. */ public void onCameraPermissionGranted() { - for (Listener listener : mCameraSelectionListeners) { + for (Listener listener : cameraSelectionListeners) { listener.onCameraPermissionGranted(); } } @@ -102,7 +102,7 @@ public class InCallCameraManager { * @param context The context. */ private void maybeInitializeCameraList(Context context) { - if (mIsInitialized || context == null) { + if (isInitialized || context == null) { return; } @@ -141,26 +141,26 @@ public class InCallCameraManager { if (c != null) { int facingCharacteristic = c.get(CameraCharacteristics.LENS_FACING); if (facingCharacteristic == CameraCharacteristics.LENS_FACING_FRONT) { - mFrontFacingCameraId = cameraIds[i]; + frontFacingCameraId = cameraIds[i]; } else if (facingCharacteristic == CameraCharacteristics.LENS_FACING_BACK) { - mRearFacingCameraId = cameraIds[i]; + rearFacingCameraId = cameraIds[i]; } } } - mIsInitialized = true; + isInitialized = true; Log.v(this, "initializeCameraList : done"); } public void addCameraSelectionListener(Listener listener) { if (listener != null) { - mCameraSelectionListeners.add(listener); + cameraSelectionListeners.add(listener); } } public void removeCameraSelectionListener(Listener listener) { if (listener != null) { - mCameraSelectionListeners.remove(listener); + cameraSelectionListeners.remove(listener); } } diff --git a/java/com/android/incallui/InCallOrientationEventListener.java b/java/com/android/incallui/InCallOrientationEventListener.java index 8aae6fb37..854bdd193 100644 --- a/java/com/android/incallui/InCallOrientationEventListener.java +++ b/java/com/android/incallui/InCallOrientationEventListener.java @@ -68,9 +68,9 @@ public class InCallOrientationEventListener extends OrientationEventListener { private static final int ROTATION_THRESHOLD = 10; /** Cache the current rotation of the device. */ - @ScreenOrientation private static int sCurrentOrientation = SCREEN_ORIENTATION_0; + @ScreenOrientation private static int currentOrientation = SCREEN_ORIENTATION_0; - private boolean mEnabled = false; + private boolean enabled = false; public InCallOrientationEventListener(Context context) { super(context); @@ -94,7 +94,7 @@ public class InCallOrientationEventListener extends OrientationEventListener { @ScreenOrientation public static int getCurrentOrientation() { - return sCurrentOrientation; + return currentOrientation; } /** @@ -114,14 +114,14 @@ public class InCallOrientationEventListener extends OrientationEventListener { final int orientation = toScreenOrientation(rotation); - if (orientation != SCREEN_ORIENTATION_UNKNOWN && sCurrentOrientation != orientation) { + if (orientation != SCREEN_ORIENTATION_UNKNOWN && currentOrientation != orientation) { LogUtil.i( "InCallOrientationEventListener.onOrientationChanged", "orientation: %d -> %d", - sCurrentOrientation, + currentOrientation, orientation); - sCurrentOrientation = orientation; - InCallPresenter.getInstance().onDeviceOrientationChange(sCurrentOrientation); + currentOrientation = orientation; + InCallPresenter.getInstance().onDeviceOrientationChange(currentOrientation); } } @@ -133,15 +133,15 @@ public class InCallOrientationEventListener extends OrientationEventListener { * changed. */ public void enable(boolean notifyDeviceOrientationChange) { - if (mEnabled) { + if (enabled) { Log.v(this, "enable: Orientation listener is already enabled. Ignoring..."); return; } super.enable(); - mEnabled = true; + enabled = true; if (notifyDeviceOrientationChange) { - InCallPresenter.getInstance().onDeviceOrientationChange(sCurrentOrientation); + InCallPresenter.getInstance().onDeviceOrientationChange(currentOrientation); } } @@ -154,18 +154,18 @@ public class InCallOrientationEventListener extends OrientationEventListener { /** Disables the OrientationEventListener. */ @Override public void disable() { - if (!mEnabled) { + if (!enabled) { Log.v(this, "enable: Orientation listener is already disabled. Ignoring..."); return; } - mEnabled = false; + enabled = false; super.disable(); } /** Returns true the OrientationEventListener is enabled, false otherwise. */ public boolean isEnabled() { - return mEnabled; + return enabled; } /** diff --git a/java/com/android/incallui/InCallPresenter.java b/java/com/android/incallui/InCallPresenter.java index 3debd704e..ae25f4dc1 100644 --- a/java/com/android/incallui/InCallPresenter.java +++ b/java/com/android/incallui/InCallPresenter.java @@ -93,53 +93,53 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud private static final Bundle EMPTY_EXTRAS = new Bundle(); - private static InCallPresenter sInCallPresenter; + private static InCallPresenter inCallPresenter; /** * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before * resizing, 1 means we only expect a single thread to access the map so make only a single shard */ - private final Set mListeners = + private final Set listeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private final List mIncomingCallListeners = new CopyOnWriteArrayList<>(); - private final Set mDetailsListeners = + private final List incomingCallListeners = new CopyOnWriteArrayList<>(); + private final Set detailsListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private final Set mCanAddCallListeners = + private final Set canAddCallListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private final Set mInCallUiListeners = + private final Set inCallUiListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private final Set mOrientationListeners = + private final Set orientationListeners = Collections.newSetFromMap( new ConcurrentHashMap(8, 0.9f, 1)); - private final Set mInCallEventListeners = + private final Set inCallEventListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private StatusBarNotifier mStatusBarNotifier; - private ExternalCallNotifier mExternalCallNotifier; - private ContactInfoCache mContactInfoCache; - private Context mContext; - private final OnCheckBlockedListener mOnCheckBlockedListener = + private StatusBarNotifier statusBarNotifier; + private ExternalCallNotifier externalCallNotifier; + private ContactInfoCache contactInfoCache; + private Context context; + private final OnCheckBlockedListener onCheckBlockedListener = new OnCheckBlockedListener() { @Override public void onCheckComplete(final Integer id) { if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) { // Silence the ringer now to prevent ringing and vibration before the call is // terminated when Telecom attempts to add it. - TelecomUtil.silenceRinger(mContext); + TelecomUtil.silenceRinger(context); } } }; - private CallList mCallList; - private ExternalCallList mExternalCallList; - private InCallActivity mInCallActivity; - private ManageConferenceActivity mManageConferenceActivity; - private final android.telecom.Call.Callback mCallCallback = + private CallList callList; + private ExternalCallList externalCallList; + private InCallActivity inCallActivity; + private ManageConferenceActivity manageConferenceActivity; + private final android.telecom.Call.Callback callCallback = new android.telecom.Call.Callback() { @Override public void onPostDialWait( android.telecom.Call telecomCall, String remainingPostDialSequence) { - final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall); + final DialerCall call = callList.getDialerCallFromTelecomCall(telecomCall); if (call == null) { LogUtil.w( "InCallPresenter.onPostDialWait", @@ -152,7 +152,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud @Override public void onDetailsChanged( android.telecom.Call telecomCall, android.telecom.Call.Details details) { - final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall); + final DialerCall call = callList.getDialerCallFromTelecomCall(telecomCall); if (call == null) { LogUtil.w( "InCallPresenter.onDetailsChanged", @@ -161,16 +161,16 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL) - && !mExternalCallList.isCallTracked(telecomCall)) { + && !externalCallList.isCallTracked(telecomCall)) { // A regular call became an external call so swap call lists. LogUtil.i("InCallPresenter.onDetailsChanged", "Call became external: " + telecomCall); - mCallList.onInternalCallMadeExternal(mContext, telecomCall); - mExternalCallList.onCallAdded(telecomCall); + callList.onInternalCallMadeExternal(context, telecomCall); + externalCallList.onCallAdded(telecomCall); return; } - for (InCallDetailsListener listener : mDetailsListeners) { + for (InCallDetailsListener listener : detailsListeners) { listener.onDetailsChanged(call, details); } } @@ -184,38 +184,38 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud onDetailsChanged(telecomCall, telecomCall.getDetails()); } }; - private InCallState mInCallState = InCallState.NO_CALLS; - private ProximitySensor mProximitySensor; - private final PseudoScreenState mPseudoScreenState = new PseudoScreenState(); - private boolean mServiceConnected; - private InCallCameraManager mInCallCameraManager; - private FilteredNumberAsyncQueryHandler mFilteredQueryHandler; - private CallList.Listener mSpamCallListListener; + private InCallState inCallState = InCallState.NO_CALLS; + private ProximitySensor proximitySensor; + private final PseudoScreenState pseudoScreenState = new PseudoScreenState(); + private boolean serviceConnected; + private InCallCameraManager inCallCameraManager; + private FilteredNumberAsyncQueryHandler filteredQueryHandler; + private CallList.Listener spamCallListListener; /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */ - private boolean mBoundAndWaitingForOutgoingCall; + private boolean boundAndWaitingForOutgoingCall; /** Determines if the InCall UI is in fullscreen mode or not. */ - private boolean mIsFullScreen = false; + private boolean isFullScreen = false; - private boolean mScreenTimeoutEnabled = true; + private boolean screenTimeoutEnabled = true; - private PhoneStateListener mPhoneStateListener = + private PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(int state, String incomingNumber) { if (state == TelephonyManager.CALL_STATE_RINGING) { - if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) { + if (FilteredNumbersUtil.hasRecentEmergencyCall(context)) { return; } // Check if the number is blocked, to silence the ringer. - String countryIso = GeoUtil.getCurrentCountryIso(mContext); - mFilteredQueryHandler.isBlockedNumber( - mOnCheckBlockedListener, incomingNumber, countryIso); + String countryIso = GeoUtil.getCurrentCountryIso(context); + filteredQueryHandler.isBlockedNumber( + onCheckBlockedListener, incomingNumber, countryIso); } } }; /** Whether or not InCallService is bound to Telecom. */ - private boolean mServiceBound = false; + private boolean serviceBound = false; /** * When configuration changes Android kills the current activity and starts a new one. The flag is @@ -223,11 +223,11 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * started), or if a new activity will be started right after the current one is destroyed, and * therefore no need in release all resources. */ - private boolean mIsChangingConfigurations = false; + private boolean isChangingConfigurations = false; - private boolean mAwaitingCallListUpdate = false; + private boolean awaitingCallListUpdate = false; - private ExternalCallList.ExternalCallListener mExternalCallListener = + private ExternalCallList.ExternalCallListener externalCallListener = new ExternalCallList.ExternalCallListener() { @Override @@ -236,8 +236,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud LatencyReport latencyReport = new LatencyReport(call); latencyReport.onCallBlockingDone(); // Note: External calls do not require spam checking. - mCallList.onCallAdded(mContext, call, latencyReport); - call.registerCallback(mCallCallback); + callList.onCallAdded(context, call, latencyReport); + call.registerCallback(callCallback); } @Override @@ -256,26 +256,26 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } }; - private ThemeColorManager mThemeColorManager; - private VideoSurfaceTexture mLocalVideoSurfaceTexture; - private VideoSurfaceTexture mRemoteVideoSurfaceTexture; + private ThemeColorManager themeColorManager; + private VideoSurfaceTexture localVideoSurfaceTexture; + private VideoSurfaceTexture remoteVideoSurfaceTexture; /** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */ @VisibleForTesting InCallPresenter() {} public static synchronized InCallPresenter getInstance() { - if (sInCallPresenter == null) { + if (inCallPresenter == null) { Trace.beginSection("InCallPresenter.Constructor"); - sInCallPresenter = new InCallPresenter(); + inCallPresenter = new InCallPresenter(); Trace.endSection(); } - return sInCallPresenter; + return inCallPresenter; } @VisibleForTesting public static synchronized void setInstanceForTesting(InCallPresenter inCallPresenter) { - sInCallPresenter = inCallPresenter; + InCallPresenter.inCallPresenter = inCallPresenter; } /** @@ -309,11 +309,11 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } public InCallState getInCallState() { - return mInCallState; + return inCallState; } public CallList getCallList() { - return mCallList; + return callList; } public void setUp( @@ -326,9 +326,9 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud ProximitySensor proximitySensor, FilteredNumberAsyncQueryHandler filteredNumberQueryHandler) { Trace.beginSection("InCallPresenter.setUp"); - if (mServiceConnected) { + if (serviceConnected) { LogUtil.i("InCallPresenter.setUp", "New service connection replacing existing one."); - if (context != mContext || callList != mCallList) { + if (context != this.context || callList != this.callList) { throw new IllegalStateException(); } Trace.endSection(); @@ -336,49 +336,49 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } Objects.requireNonNull(context); - mContext = context; + this.context = context; - mContactInfoCache = contactInfoCache; + this.contactInfoCache = contactInfoCache; - mStatusBarNotifier = statusBarNotifier; - mExternalCallNotifier = externalCallNotifier; - addListener(mStatusBarNotifier); - EnrichedCallComponent.get(mContext) + this.statusBarNotifier = statusBarNotifier; + this.externalCallNotifier = externalCallNotifier; + addListener(this.statusBarNotifier); + EnrichedCallComponent.get(this.context) .getEnrichedCallManager() - .registerStateChangedListener(mStatusBarNotifier); + .registerStateChangedListener(this.statusBarNotifier); - mProximitySensor = proximitySensor; - addListener(mProximitySensor); + this.proximitySensor = proximitySensor; + addListener(this.proximitySensor); - if (mThemeColorManager == null) { - mThemeColorManager = - new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources())); + if (themeColorManager == null) { + themeColorManager = + new ThemeColorManager(new InCallUIMaterialColorMapUtils(this.context.getResources())); } - mCallList = callList; - mExternalCallList = externalCallList; - externalCallList.addExternalCallListener(mExternalCallNotifier); - externalCallList.addExternalCallListener(mExternalCallListener); + this.callList = callList; + this.externalCallList = externalCallList; + externalCallList.addExternalCallListener(this.externalCallNotifier); + externalCallList.addExternalCallListener(externalCallListener); // This only gets called by the service so this is okay. - mServiceConnected = true; + serviceConnected = true; // The final thing we do in this set up is add ourselves as a listener to CallList. This // will kick off an update and the whole process can start. - mCallList.addListener(this); + this.callList.addListener(this); // Create spam call list listener and add it to the list of listeners - mSpamCallListListener = + spamCallListListener = new SpamCallListListener( context, DialerExecutorComponent.get(context).dialerExecutorFactory()); - mCallList.addListener(mSpamCallListListener); + this.callList.addListener(spamCallListListener); VideoPauseController.getInstance().setUp(this); - mFilteredQueryHandler = filteredNumberQueryHandler; - mContext + filteredQueryHandler = filteredNumberQueryHandler; + this.context .getSystemService(TelephonyManager.class) - .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); + .listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); AudioModeProvider.getInstance().addListener(this); @@ -395,13 +395,13 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud */ public void tearDown() { LogUtil.d("InCallPresenter.tearDown", "tearDown"); - mCallList.clearOnDisconnect(); + callList.clearOnDisconnect(); - mServiceConnected = false; + serviceConnected = false; - mContext + context .getSystemService(TelephonyManager.class) - .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); + .listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); attemptCleanup(); VideoPauseController.getInstance().tearDown(); @@ -409,12 +409,12 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } private void attemptFinishActivity() { - mScreenTimeoutEnabled = true; - final boolean doFinish = (mInCallActivity != null && isActivityStarted()); + screenTimeoutEnabled = true; + final boolean doFinish = (inCallActivity != null && isActivityStarted()); LogUtil.i("InCallPresenter.attemptFinishActivity", "Hide in call UI: " + doFinish); if (doFinish) { - mInCallActivity.setExcludeFromRecents(true); - mInCallActivity.finish(); + inCallActivity.setExcludeFromRecents(true); + inCallActivity.finish(); } } @@ -426,12 +426,12 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (inCallActivity == null) { throw new IllegalArgumentException("unregisterActivity cannot be called with null"); } - if (mInCallActivity == null) { + if (this.inCallActivity == null) { LogUtil.i( "InCallPresenter.unsetActivity", "No InCallActivity currently set, no need to unset."); return; } - if (mInCallActivity != inCallActivity) { + if (this.inCallActivity != inCallActivity) { LogUtil.w( "InCallPresenter.unsetActivity", "Second instance of InCallActivity is trying to unregister when another" @@ -451,8 +451,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud boolean doAttemptCleanup = false; if (inCallActivity != null) { - if (mInCallActivity == null) { - mContext = inCallActivity.getApplicationContext(); + if (this.inCallActivity == null) { + context = inCallActivity.getApplicationContext(); updateListeners = true; LogUtil.i("InCallPresenter.updateActivity", "UI Initialized"); } else { @@ -461,13 +461,13 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // this happens (like going to/from background) so we do not set updateListeners. } - mInCallActivity = inCallActivity; - mInCallActivity.setExcludeFromRecents(false); + this.inCallActivity = inCallActivity; + this.inCallActivity.setExcludeFromRecents(false); // By the time the UI finally comes up, the call may already be disconnected. // If that's the case, we may need to show an error dialog. - if (mCallList != null && mCallList.getDisconnectedCall() != null) { - showDialogOrToastForDisconnectedCall(mCallList.getDisconnectedCall()); + if (callList != null && callList.getDisconnectedCall() != null) { + showDialogOrToastForDisconnectedCall(callList.getDisconnectedCall()); } // When the UI comes up, we need to first check the in-call state. @@ -476,7 +476,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // If we dont have any calls, start tearing down the UI instead. // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after // it has been set. - if (mInCallState == InCallState.NO_CALLS) { + if (inCallState == InCallState.NO_CALLS) { LogUtil.i("InCallPresenter.updateActivity", "UI Initialized, but no calls left. Shut down"); attemptFinishActivity(); Trace.endSection(); @@ -485,7 +485,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } else { LogUtil.i("InCallPresenter.updateActivity", "UI Destroyed"); updateListeners = true; - mInCallActivity = null; + this.inCallActivity = null; // We attempt cleanup for the destroy case but only after we recalculate the state // to see if we need to come back up or stay shut down. This is why we do the @@ -509,7 +509,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // state here even if the service is disconnected since we may not have finished a state // transition while finish()ing. if (updateListeners) { - onCallListChange(mCallList); + onCallListChange(callList); } if (doAttemptCleanup) { @@ -520,7 +520,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public void setManageConferenceActivity( @Nullable ManageConferenceActivity manageConferenceActivity) { - mManageConferenceActivity = manageConferenceActivity; + this.manageConferenceActivity = manageConferenceActivity; } public void onBringToForeground(boolean showDialpad) { @@ -535,18 +535,18 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud maybeBlockCall(call, latencyReport); } else { if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) { - mExternalCallList.onCallAdded(call); + externalCallList.onCallAdded(call); } else { latencyReport.onCallBlockingDone(); - mCallList.onCallAdded(mContext, call, latencyReport); + callList.onCallAdded(context, call, latencyReport); } } // Since a call has been added we are no longer waiting for Telecom to send us a call. setBoundAndWaitingForOutgoingCall(false, null); - call.registerCallback(mCallCallback); + call.registerCallback(callCallback); // TODO(maxwelb): Return the future in recordPhoneLookupInfo and propagate. - PhoneLookupHistoryRecorder.recordPhoneLookupInfo(mContext.getApplicationContext(), call); + PhoneLookupHistoryRecorder.recordPhoneLookupInfo(context.getApplicationContext(), call); Trace.endSection(); } @@ -554,7 +554,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (call.getState() != android.telecom.Call.STATE_RINGING) { return false; } - if (!UserManagerCompat.isUserUnlocked(mContext)) { + if (!UserManagerCompat.isUserUnlocked(context)) { LogUtil.i( "InCallPresenter.shouldAttemptBlocking", "not attempting to block incoming call because user is locked"); @@ -566,7 +566,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud "Not attempting to block incoming emergency call"); return false; } - if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) { + if (FilteredNumbersUtil.hasRecentEmergencyCall(context)) { LogUtil.i( "InCallPresenter.shouldAttemptBlocking", "Not attempting to block incoming call due to recent emergency call"); @@ -575,7 +575,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) { return false; } - if (FilteredNumberCompat.useNewFiltering(mContext)) { + if (FilteredNumberCompat.useNewFiltering(context)) { LogUtil.i( "InCallPresenter.shouldAttemptBlocking", "not attempting to block incoming call because framework blocking is in use"); @@ -591,7 +591,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * call anyways. */ private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) { - final String countryIso = GeoUtil.getCurrentCountryIso(mContext); + final String countryIso = GeoUtil.getCurrentCountryIso(context); final String number = TelecomCallUtil.getNumber(call); final long timeAdded = System.currentTimeMillis(); @@ -609,7 +609,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public void run() { hasTimedOut.set(true); latencyReport.onCallBlockingDone(); - mCallList.onCallAdded(mContext, call, latencyReport); + callList.onCallAdded(context, call, latencyReport); } }; handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS); @@ -628,7 +628,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (id == null) { if (!hasTimedOut.get()) { latencyReport.onCallBlockingDone(); - mCallList.onCallAdded(mContext, call, latencyReport); + callList.onCallAdded(context, call, latencyReport); } } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) { LogUtil.d( @@ -637,68 +637,68 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud handler.removeCallbacks(runnable); latencyReport.onCallBlockingDone(); - mCallList.onCallAdded(mContext, call, latencyReport); + callList.onCallAdded(context, call, latencyReport); } } else { LogUtil.i( "InCallPresenter.onCheckComplete", "Rejecting incoming call from blocked number"); call.reject(false, null); - Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED); + Logger.get(context).logInteraction(InteractionEvent.Type.CALL_BLOCKED); /* * If mContext is null, then the InCallPresenter was torn down before the * block check had a chance to complete. The context is no longer valid, so * don't attempt to remove the call log entry. */ - if (mContext == null) { + if (context == null) { return; } // Register observer to update the call log. // BlockedNumberContentObserver will unregister after successful log or timeout. BlockedNumberContentObserver contentObserver = - new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded); + new BlockedNumberContentObserver(context, new Handler(), number, timeAdded); contentObserver.register(); } } }; - mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso); + filteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso); } public void onCallRemoved(android.telecom.Call call) { if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) { - mExternalCallList.onCallRemoved(call); + externalCallList.onCallRemoved(call); } else { - mCallList.onCallRemoved(mContext, call); - call.unregisterCallback(mCallCallback); + callList.onCallRemoved(context, call); + call.unregisterCallback(callCallback); } } public void onCanAddCallChanged(boolean canAddCall) { - for (CanAddCallListener listener : mCanAddCallListeners) { + for (CanAddCallListener listener : canAddCallListeners) { listener.onCanAddCallChanged(canAddCall); } } @Override public void onWiFiToLteHandover(DialerCall call) { - if (mInCallActivity != null) { - mInCallActivity.showToastForWiFiToLteHandover(call); + if (inCallActivity != null) { + inCallActivity.showToastForWiFiToLteHandover(call); } } @Override public void onHandoverToWifiFailed(DialerCall call) { - if (mInCallActivity != null) { - mInCallActivity.showDialogOrToastForWifiHandoverFailure(call); + if (inCallActivity != null) { + inCallActivity.showDialogOrToastForWifiHandoverFailure(call); } } @Override public void onInternationalCallOnWifi(@NonNull DialerCall call) { LogUtil.enterBlock("InCallPresenter.onInternationalCallOnWifi"); - if (mInCallActivity != null) { - mInCallActivity.showDialogForInternationalCallOnWifi(call); + if (inCallActivity != null) { + inCallActivity.showDialogForInternationalCallOnWifi(call); } } @@ -711,8 +711,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud @Override public void onCallListChange(CallList callList) { Trace.beginSection("InCallPresenter.onCallListChange"); - if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) { - mAwaitingCallListUpdate = true; + if (inCallActivity != null && inCallActivity.isInCallScreenAnimating()) { + awaitingCallListUpdate = true; Trace.endSection(); return; } @@ -721,10 +721,10 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud return; } - mAwaitingCallListUpdate = false; + awaitingCallListUpdate = false; InCallState newState = getPotentialStateFromCallList(callList); - InCallState oldState = mInCallState; + InCallState oldState = inCallState; LogUtil.d( "InCallPresenter.onCallListChange", "onCallListChange oldState= " + oldState + " newState=" + newState); @@ -740,7 +740,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud waitingForAccountCall.disconnect(); // The InCallActivity might be destroyed or not started yet at this point. if (isActivityStarted()) { - mInCallActivity.dismissPendingDialogs(); + inCallActivity.dismissPendingDialogs(); } } @@ -752,20 +752,20 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud LogUtil.i( "InCallPresenter.onCallListChange", "Phone switching state: " + oldState + " -> " + newState); - mInCallState = newState; + inCallState = newState; // notify listeners of new state - for (InCallStateListener listener : mListeners) { + for (InCallStateListener listener : listeners) { LogUtil.d( "InCallPresenter.onCallListChange", - "Notify " + listener + " of state " + mInCallState.toString()); - listener.onStateChange(oldState, mInCallState, callList); + "Notify " + listener + " of state " + inCallState.toString()); + listener.onStateChange(oldState, inCallState, callList); } if (isActivityStarted()) { final boolean hasCall = callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null; - mInCallActivity.dismissKeyguard(hasCall); + inCallActivity.dismissKeyguard(hasCall); } Trace.endSection(); } @@ -775,22 +775,22 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public void onIncomingCall(DialerCall call) { Trace.beginSection("InCallPresenter.onIncomingCall"); InCallState newState = startOrFinishUi(InCallState.INCOMING); - InCallState oldState = mInCallState; + InCallState oldState = inCallState; LogUtil.i( "InCallPresenter.onIncomingCall", "Phone switching state: " + oldState + " -> " + newState); - mInCallState = newState; + inCallState = newState; Trace.beginSection("listener.onIncomingCall"); - for (IncomingCallListener listener : mIncomingCallListeners) { - listener.onIncomingCall(oldState, mInCallState, call); + for (IncomingCallListener listener : incomingCallListeners) { + listener.onIncomingCall(oldState, inCallState, call); } Trace.endSection(); Trace.beginSection("onPrimaryCallStateChanged"); - if (mInCallActivity != null) { + if (inCallActivity != null) { // Re-evaluate which fragment is being shown. - mInCallActivity.onPrimaryCallStateChanged(); + inCallActivity.onPrimaryCallStateChanged(); } Trace.endSection(); Trace.endSection(); @@ -799,16 +799,16 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud @Override public void onUpgradeToVideo(DialerCall call) { if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState()) - && mInCallState == InCallPresenter.InCallState.INCOMING) { + && inCallState == InCallPresenter.InCallState.INCOMING) { LogUtil.i( "InCallPresenter.onUpgradeToVideo", "rejecting upgrade request due to existing incoming call"); call.getVideoTech().declineVideoRequest(); } - if (mInCallActivity != null) { + if (inCallActivity != null) { // Re-evaluate which fragment is being shown. - mInCallActivity.onPrimaryCallStateChanged(); + inCallActivity.onPrimaryCallStateChanged(); } } @@ -816,15 +816,15 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public void onSessionModificationStateChange(DialerCall call) { int newState = call.getVideoTech().getSessionModificationState(); LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState); - if (mProximitySensor == null) { + if (proximitySensor == null) { LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null"); return; } - mProximitySensor.setIsAttemptingVideoCall( + proximitySensor.setIsAttemptingVideoCall( call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest()); - if (mInCallActivity != null) { + if (inCallActivity != null) { // Re-evaluate which fragment is being shown. - mInCallActivity.onPrimaryCallStateChanged(); + inCallActivity.onPrimaryCallStateChanged(); } } @@ -837,21 +837,21 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud showDialogOrToastForDisconnectedCall(call); // We need to do the run the same code as onCallListChange. - onCallListChange(mCallList); + onCallListChange(callList); if (isActivityStarted()) { - mInCallActivity.dismissKeyguard(false); + inCallActivity.dismissKeyguard(false); } if (call.isEmergencyCall()) { - FilteredNumbersUtil.recordLastEmergencyCallTime(mContext); + FilteredNumbersUtil.recordLastEmergencyCallTime(context); } - if (!mCallList.hasLiveCall() + if (!callList.hasLiveCall() && !call.getLogState().isIncoming && !isSecretCode(call.getNumber()) && !call.isVoiceMailNumber()) { - PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis()); + PostCall.onCallDisconnected(context, call.getNumber(), call.getConnectTimeMillis()); } } @@ -884,7 +884,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } if (newState == InCallState.NO_CALLS) { - if (mBoundAndWaitingForOutgoingCall) { + if (boundAndWaitingForOutgoingCall) { return InCallState.PENDING_OUTGOING; } } @@ -893,98 +893,98 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } public boolean isBoundAndWaitingForOutgoingCall() { - return mBoundAndWaitingForOutgoingCall; + return boundAndWaitingForOutgoingCall; } public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) { LogUtil.i( "InCallPresenter.setBoundAndWaitingForOutgoingCall", "setBoundAndWaitingForOutgoingCall: " + isBound); - mBoundAndWaitingForOutgoingCall = isBound; - mThemeColorManager.setPendingPhoneAccountHandle(handle); - if (isBound && mInCallState == InCallState.NO_CALLS) { - mInCallState = InCallState.PENDING_OUTGOING; + boundAndWaitingForOutgoingCall = isBound; + themeColorManager.setPendingPhoneAccountHandle(handle); + if (isBound && inCallState == InCallState.NO_CALLS) { + inCallState = InCallState.PENDING_OUTGOING; } } public void onShrinkAnimationComplete() { - if (mAwaitingCallListUpdate) { - onCallListChange(mCallList); + if (awaitingCallListUpdate) { + onCallListChange(callList); } } public void addIncomingCallListener(IncomingCallListener listener) { Objects.requireNonNull(listener); - mIncomingCallListeners.add(listener); + incomingCallListeners.add(listener); } public void removeIncomingCallListener(IncomingCallListener listener) { if (listener != null) { - mIncomingCallListeners.remove(listener); + incomingCallListeners.remove(listener); } } public void addListener(InCallStateListener listener) { Objects.requireNonNull(listener); - mListeners.add(listener); + listeners.add(listener); } public void removeListener(InCallStateListener listener) { if (listener != null) { - mListeners.remove(listener); + listeners.remove(listener); } } public void addDetailsListener(InCallDetailsListener listener) { Objects.requireNonNull(listener); - mDetailsListeners.add(listener); + detailsListeners.add(listener); } public void removeDetailsListener(InCallDetailsListener listener) { if (listener != null) { - mDetailsListeners.remove(listener); + detailsListeners.remove(listener); } } public void addCanAddCallListener(CanAddCallListener listener) { Objects.requireNonNull(listener); - mCanAddCallListeners.add(listener); + canAddCallListeners.add(listener); } public void removeCanAddCallListener(CanAddCallListener listener) { if (listener != null) { - mCanAddCallListeners.remove(listener); + canAddCallListeners.remove(listener); } } public void addOrientationListener(InCallOrientationListener listener) { Objects.requireNonNull(listener); - mOrientationListeners.add(listener); + orientationListeners.add(listener); } public void removeOrientationListener(InCallOrientationListener listener) { if (listener != null) { - mOrientationListeners.remove(listener); + orientationListeners.remove(listener); } } public void addInCallEventListener(InCallEventListener listener) { Objects.requireNonNull(listener); - mInCallEventListeners.add(listener); + inCallEventListeners.add(listener); } public void removeInCallEventListener(InCallEventListener listener) { if (listener != null) { - mInCallEventListeners.remove(listener); + inCallEventListeners.remove(listener); } } public ProximitySensor getProximitySensor() { - return mProximitySensor; + return proximitySensor; } public PseudoScreenState getPseudoScreenState() { - return mPseudoScreenState; + return pseudoScreenState; } /** Returns true if the incall app is the foreground application. */ @@ -992,10 +992,10 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (!isActivityStarted()) { return false; } - if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) { + if (manageConferenceActivity != null && manageConferenceActivity.isVisible()) { return true; } - return mInCallActivity.isVisible(); + return inCallActivity.isVisible(); } /** @@ -1004,9 +1004,9 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * (not in foreground). */ public boolean isActivityStarted() { - return (mInCallActivity != null - && !mInCallActivity.isDestroyed() - && !mInCallActivity.isFinishing()); + return (inCallActivity != null + && !inCallActivity.isDestroyed() + && !inCallActivity.isFinishing()); } /** @@ -1015,7 +1015,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * @return {@code true} if the In-Call app is changing configuration. */ public boolean isChangingConfigurations() { - return mIsChangingConfigurations; + return isChangingConfigurations; } /** @@ -1024,54 +1024,54 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud */ /*package*/ void updateIsChangingConfigurations() { - mIsChangingConfigurations = false; - if (mInCallActivity != null) { - mIsChangingConfigurations = mInCallActivity.isChangingConfigurations(); + isChangingConfigurations = false; + if (inCallActivity != null) { + isChangingConfigurations = inCallActivity.isChangingConfigurations(); } LogUtil.v( "InCallPresenter.updateIsChangingConfigurations", - "updateIsChangingConfigurations = " + mIsChangingConfigurations); + "updateIsChangingConfigurations = " + isChangingConfigurations); } /** Called when the activity goes in/out of the foreground. */ public void onUiShowing(boolean showing) { // We need to update the notification bar when we leave the UI because that // could trigger it to show again. - if (mStatusBarNotifier != null) { - mStatusBarNotifier.updateNotification(); + if (statusBarNotifier != null) { + statusBarNotifier.updateNotification(); } - if (mProximitySensor != null) { - mProximitySensor.onInCallShowing(showing); + if (proximitySensor != null) { + proximitySensor.onInCallShowing(showing); } if (!showing) { updateIsChangingConfigurations(); } - for (InCallUiListener listener : mInCallUiListeners) { + for (InCallUiListener listener : inCallUiListeners) { listener.onUiShowing(showing); } - if (mInCallActivity != null) { + if (inCallActivity != null) { // Re-evaluate which fragment is being shown. - mInCallActivity.onPrimaryCallStateChanged(); + inCallActivity.onPrimaryCallStateChanged(); } } public void refreshUi() { - if (mInCallActivity != null) { + if (inCallActivity != null) { // Re-evaluate which fragment is being shown. - mInCallActivity.onPrimaryCallStateChanged(); + inCallActivity.onPrimaryCallStateChanged(); } } public void addInCallUiListener(InCallUiListener listener) { - mInCallUiListeners.add(listener); + inCallUiListeners.add(listener); } public boolean removeInCallUiListener(InCallUiListener listener) { - return mInCallUiListeners.remove(listener); + return inCallUiListeners.remove(listener); } /*package*/ @@ -1090,8 +1090,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud private void notifyVideoPauseController(boolean showing) { LogUtil.d( "InCallPresenter.notifyVideoPauseController", - "mIsChangingConfigurations=" + mIsChangingConfigurations); - if (!mIsChangingConfigurations) { + "mIsChangingConfigurations=" + isChangingConfigurations); + if (!isChangingConfigurations) { VideoPauseController.getInstance().onUiShowing(showing); } } @@ -1105,14 +1105,14 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // If the activity hadn't actually been started previously, yet there are still calls // present (e.g. a call was accepted by a bluetooth or wired headset), we want to // bring it up the UI regardless. - if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) { + if (!isShowingInCallUi() && inCallState != InCallState.NO_CALLS) { showInCall(showDialpad, false /* newOutgoingCall */); } } public void onPostDialCharWait(String callId, String chars) { if (isActivityStarted()) { - mInCallActivity.showDialogForPostCharWait(callId, chars); + inCallActivity.showDialogForPostCharWait(callId, chars); } } @@ -1129,7 +1129,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // of the Phone. /** INCOMING CALL */ - final CallList calls = mCallList; + final CallList calls = callList; final DialerCall incomingCall = calls.getIncomingCall(); LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall); @@ -1185,7 +1185,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud /** Clears the previous fullscreen state. */ public void clearFullscreen() { - mIsFullScreen = false; + isFullScreen = false; } /** @@ -1216,12 +1216,12 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud "setFullScreen overridden as dialpad is shown = " + isFullScreen); } - if (mIsFullScreen == isFullScreen && !force) { + if (this.isFullScreen == isFullScreen && !force) { LogUtil.v("InCallPresenter.setFullScreen", "setFullScreen ignored as already in that state."); return; } - mIsFullScreen = isFullScreen; - notifyFullscreenModeChange(mIsFullScreen); + this.isFullScreen = isFullScreen; + notifyFullscreenModeChange(this.isFullScreen); } /** @@ -1229,7 +1229,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * otherwise. */ public boolean isFullscreen() { - return mIsFullScreen; + return isFullScreen; } /** @@ -1238,7 +1238,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * @param isFullscreenMode {@code True} if entering full screen mode. */ public void notifyFullscreenModeChange(boolean isFullscreenMode) { - for (InCallEventListener listener : mInCallEventListeners) { + for (InCallEventListener listener : inCallEventListeners) { listener.onFullscreenModeChanged(isFullscreenMode); } } @@ -1254,8 +1254,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud setDisconnectCauseForMissingAccounts(call); } - mInCallActivity.showDialogOrToastForDisconnectedCall( - new DisconnectMessage(mInCallActivity, call)); + inCallActivity.showDialogOrToastForDisconnectedCall( + new DisconnectMessage(inCallActivity, call)); } /** @@ -1265,13 +1265,13 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud private InCallState startOrFinishUi(InCallState newState) { Trace.beginSection("InCallPresenter.startOrFinishUi"); LogUtil.d( - "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + mInCallState + " -> " + newState); + "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + inCallState + " -> " + newState); // TODO: Consider a proper state machine implementation // If the state isn't changing we have already done any starting/stopping of activities in // a previous pass...so lets cut out early - if (newState == mInCallState) { + if (newState == inCallState) { Trace.endSection(); return newState; } @@ -1318,14 +1318,14 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud // This is different from the incoming call sequence because we do not need to shock the // user with a top-level notification. Just show the call UI normally. boolean callCardFragmentVisible = - mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible(); + inCallActivity != null && inCallActivity.getCallCardFragmentVisible(); final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible; boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible; // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the // outgoing call process, so the UI should be brought up to show an error dialog. showCallUi |= - (InCallState.PENDING_OUTGOING == mInCallState + (InCallState.PENDING_OUTGOING == inCallState && InCallState.INCALL == newState && !isShowingInCallUi()); @@ -1340,19 +1340,19 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud showCallUi |= InCallState.PENDING_OUTGOING == newState && mainUiNotVisible - && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall()); + && isCallWithNoValidAccounts(callList.getPendingOutgoingCall()); // The only time that we have an instance of mInCallActivity and it isn't started is // when it is being destroyed. In that case, lets avoid bringing up another instance of // the activity. When it is finally destroyed, we double check if we should bring it back // up so we aren't going to lose anything by avoiding a second startup here. - boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted(); + boolean activityIsFinishing = inCallActivity != null && !isActivityStarted(); if (activityIsFinishing) { LogUtil.i( "InCallPresenter.startOrFinishUi", - "Undo the state change: " + newState + " -> " + mInCallState); + "Undo the state change: " + newState + " -> " + inCallState); Trace.endSection(); - return mInCallState; + return inCallState; } // We're about the bring up the in-call UI for outgoing and incoming call. If we still have @@ -1362,7 +1362,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING) && !showCallUi && isActivityStarted()) { - mInCallActivity.dismissPendingDialogs(); + inCallActivity.dismissPendingDialogs(); } if (showCallUi || showAccountPicker) { @@ -1371,7 +1371,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } else if (startIncomingCallSequence) { LogUtil.i("InCallPresenter.startOrFinishUi", "Start Full Screen in call UI"); - mStatusBarNotifier.updateNotification(); + statusBarNotifier.updateNotification(); } else if (newState == InCallState.NO_CALLS) { // The new state is the no calls state. Tear everything down. attemptFinishActivity(); @@ -1401,8 +1401,8 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud String scheme = call.getHandle().getScheme(); final String errorMsg = PhoneAccount.SCHEME_TEL.equals(scheme) - ? mContext.getString(R.string.callFailed_simError) - : mContext.getString(R.string.incall_error_supp_service_unknown); + ? context.getString(R.string.callFailed_simError) + : context.getString(R.string.incall_error_supp_service_unknown); DisconnectCause disconnectCause = new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg); call.setDisconnectCause(disconnectCause); @@ -1415,7 +1415,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * InCallPresenter or not. */ public boolean isReadyForTearDown() { - return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS; + return inCallActivity == null && !serviceConnected && inCallState == InCallState.NO_CALLS; } /** @@ -1427,53 +1427,53 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud cleanupSurfaces(); - mIsChangingConfigurations = false; + isChangingConfigurations = false; // blow away stale contact info so that we get fresh data on // the next set of calls - if (mContactInfoCache != null) { - mContactInfoCache.clearCache(); + if (contactInfoCache != null) { + contactInfoCache.clearCache(); } - mContactInfoCache = null; + contactInfoCache = null; - if (mProximitySensor != null) { - removeListener(mProximitySensor); - mProximitySensor.tearDown(); + if (proximitySensor != null) { + removeListener(proximitySensor); + proximitySensor.tearDown(); } - mProximitySensor = null; + proximitySensor = null; - if (mStatusBarNotifier != null) { - removeListener(mStatusBarNotifier); - EnrichedCallComponent.get(mContext) + if (statusBarNotifier != null) { + removeListener(statusBarNotifier); + EnrichedCallComponent.get(context) .getEnrichedCallManager() - .unregisterStateChangedListener(mStatusBarNotifier); + .unregisterStateChangedListener(statusBarNotifier); } - if (mExternalCallNotifier != null && mExternalCallList != null) { - mExternalCallList.removeExternalCallListener(mExternalCallNotifier); + if (externalCallNotifier != null && externalCallList != null) { + externalCallList.removeExternalCallListener(externalCallNotifier); } - mStatusBarNotifier = null; + statusBarNotifier = null; - if (mCallList != null) { - mCallList.removeListener(this); - mCallList.removeListener(mSpamCallListListener); + if (callList != null) { + callList.removeListener(this); + callList.removeListener(spamCallListListener); } - mCallList = null; - - mContext = null; - mInCallActivity = null; - mManageConferenceActivity = null; - - mListeners.clear(); - mIncomingCallListeners.clear(); - mDetailsListeners.clear(); - mCanAddCallListeners.clear(); - mOrientationListeners.clear(); - mInCallEventListeners.clear(); - mInCallUiListeners.clear(); - if (!mInCallUiLocks.isEmpty()) { - LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + mInCallUiLocks); - mInCallUiLocks.clear(); + callList = null; + + context = null; + inCallActivity = null; + manageConferenceActivity = null; + + listeners.clear(); + incomingCallListeners.clear(); + detailsListeners.clear(); + canAddCallListeners.clear(); + orientationListeners.clear(); + inCallEventListeners.clear(); + inCallUiListeners.clear(); + if (!inCallUiLocks.isEmpty()) { + LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + inCallUiLocks); + inCallUiLocks.clear(); } LogUtil.d("InCallPresenter.attemptCleanup", "finished"); } @@ -1481,26 +1481,25 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public void showInCall(boolean showDialpad, boolean newOutgoingCall) { LogUtil.i("InCallPresenter.showInCall", "Showing InCallActivity"); - mContext.startActivity( - InCallActivity.getIntent( - mContext, showDialpad, newOutgoingCall, false /* forFullScreen */)); + context.startActivity( + InCallActivity.getIntent(context, showDialpad, newOutgoingCall, false /* forFullScreen */)); } public void onServiceBind() { - mServiceBound = true; + serviceBound = true; } public void onServiceUnbind() { InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null); - mServiceBound = false; + serviceBound = false; } public boolean isServiceBound() { - return mServiceBound; + return serviceBound; } public void maybeStartRevealAnimation(Intent intent) { - if (intent == null || mInCallActivity != null) { + if (intent == null || inCallActivity != null) { return; } final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS); @@ -1521,9 +1520,9 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle); final Intent activityIntent = - InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */); + InCallActivity.getIntent(context, false, true, false /* forFullScreen */); activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint); - mContext.startActivity(activityIntent); + context.startActivity(activityIntent); } /** @@ -1533,11 +1532,11 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud */ public InCallCameraManager getInCallCameraManager() { synchronized (this) { - if (mInCallCameraManager == null) { - mInCallCameraManager = new InCallCameraManager(mContext); + if (inCallCameraManager == null) { + inCallCameraManager = new InCallCameraManager(context); } - return mInCallCameraManager; + return inCallCameraManager; } } @@ -1555,14 +1554,14 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud "InCallPresenter.onDeviceOrientationChange", "onDeviceOrientationChange: orientation= " + orientation); - if (mCallList != null) { - mCallList.notifyCallsOfDeviceRotation(orientation); + if (callList != null) { + callList.notifyCallsOfDeviceRotation(orientation); } else { LogUtil.w("InCallPresenter.onDeviceOrientationChange", "CallList is null."); } // Notify listeners of device orientation changed. - for (InCallOrientationListener listener : mOrientationListeners) { + for (InCallOrientationListener listener : orientationListeners) { listener.onDeviceOrientationChanged(orientation); } } @@ -1575,29 +1574,29 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * landscape. {@code false} if the in-call UI should be locked in portrait. */ public void setInCallAllowsOrientationChange(boolean allowOrientationChange) { - if (mInCallActivity == null) { + if (inCallActivity == null) { LogUtil.e( "InCallPresenter.setInCallAllowsOrientationChange", "InCallActivity is null. Can't set requested orientation."); return; } - mInCallActivity.setAllowOrientationChange(allowOrientationChange); + inCallActivity.setAllowOrientationChange(allowOrientationChange); } public void enableScreenTimeout(boolean enable) { LogUtil.v("InCallPresenter.enableScreenTimeout", "enableScreenTimeout: value=" + enable); - mScreenTimeoutEnabled = enable; + screenTimeoutEnabled = enable; applyScreenTimeout(); } private void applyScreenTimeout() { - if (mInCallActivity == null) { + if (inCallActivity == null) { LogUtil.e("InCallPresenter.applyScreenTimeout", "InCallActivity is null."); return; } - final Window window = mInCallActivity.getWindow(); - if (mScreenTimeoutEnabled) { + final Window window = inCallActivity.getWindow(); + if (screenTimeoutEnabled) { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); @@ -1611,11 +1610,11 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * be hidden. */ public void showConferenceCallManager(boolean show) { - if (mInCallActivity != null) { - mInCallActivity.showConferenceFragment(show); + if (inCallActivity != null) { + inCallActivity.showConferenceFragment(show); } - if (!show && mManageConferenceActivity != null) { - mManageConferenceActivity.finish(); + if (!show && manageConferenceActivity != null) { + manageConferenceActivity.finish(); } } @@ -1625,31 +1624,31 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud * @return {@code true} if the dialpad is visible, {@code false} otherwise. */ public boolean isDialpadVisible() { - if (mInCallActivity == null) { + if (inCallActivity == null) { return false; } - return mInCallActivity.isDialpadVisible(); + return inCallActivity.isDialpadVisible(); } public ThemeColorManager getThemeColorManager() { - return mThemeColorManager; + return themeColorManager; } @VisibleForTesting public void setThemeColorManager(ThemeColorManager themeColorManager) { - mThemeColorManager = themeColorManager; + this.themeColorManager = themeColorManager; } /** Called when the foreground call changes. */ public void onForegroundCallChanged(DialerCall newForegroundCall) { - mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall); - if (mInCallActivity != null) { - mInCallActivity.onForegroundCallChanged(newForegroundCall); + themeColorManager.onForegroundCallChanged(context, newForegroundCall); + if (inCallActivity != null) { + inCallActivity.onForegroundCallChanged(newForegroundCall); } } public InCallActivity getActivity() { - return mInCallActivity; + return inCallActivity; } /** Called when the UI begins, and starts the callstate callbacks if necessary. */ @@ -1657,7 +1656,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud if (inCallActivity == null) { throw new IllegalArgumentException("registerActivity cannot be called with null"); } - if (mInCallActivity != null && mInCallActivity != inCallActivity) { + if (this.inCallActivity != null && this.inCallActivity != inCallActivity) { LogUtil.w( "InCallPresenter.setActivity", "Setting a second activity before destroying the first."); } @@ -1665,47 +1664,46 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud } ExternalCallNotifier getExternalCallNotifier() { - return mExternalCallNotifier; + return externalCallNotifier; } VideoSurfaceTexture getLocalVideoSurfaceTexture() { - if (mLocalVideoSurfaceTexture == null) { + if (localVideoSurfaceTexture == null) { boolean isPixel2017 = false; - if (mContext != null) { - isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE); + if (context != null) { + isPixel2017 = context.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE); } - mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017); + localVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017); } - return mLocalVideoSurfaceTexture; + return localVideoSurfaceTexture; } VideoSurfaceTexture getRemoteVideoSurfaceTexture() { - if (mRemoteVideoSurfaceTexture == null) { + if (remoteVideoSurfaceTexture == null) { boolean isPixel2017 = false; - if (mContext != null) { - isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE); + if (context != null) { + isPixel2017 = context.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE); } - mRemoteVideoSurfaceTexture = - VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017); + remoteVideoSurfaceTexture = VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017); } - return mRemoteVideoSurfaceTexture; + return remoteVideoSurfaceTexture; } void cleanupSurfaces() { - if (mRemoteVideoSurfaceTexture != null) { - mRemoteVideoSurfaceTexture.setDoneWithSurface(); - mRemoteVideoSurfaceTexture = null; + if (remoteVideoSurfaceTexture != null) { + remoteVideoSurfaceTexture.setDoneWithSurface(); + remoteVideoSurfaceTexture = null; } - if (mLocalVideoSurfaceTexture != null) { - mLocalVideoSurfaceTexture.setDoneWithSurface(); - mLocalVideoSurfaceTexture = null; + if (localVideoSurfaceTexture != null) { + localVideoSurfaceTexture.setDoneWithSurface(); + localVideoSurfaceTexture = null; } } @Override public void onAudioStateChanged(CallAudioState audioState) { - if (mStatusBarNotifier != null) { - mStatusBarNotifier.updateNotification(); + if (statusBarNotifier != null) { + statusBarNotifier.updateNotification(); } } @@ -1804,7 +1802,7 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud public InCallUiLock acquireInCallUiLock(String tag) { Assert.isMainThread(); InCallUiLock lock = new InCallUiLockImpl(tag); - mInCallUiLocks.add(lock); + inCallUiLocks.add(lock); return lock; } @@ -1812,10 +1810,10 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud private void releaseInCallUiLock(InCallUiLock lock) { Assert.isMainThread(); LogUtil.i("InCallPresenter.releaseInCallUiLock", "releasing %s", lock); - mInCallUiLocks.remove(lock); - if (mInCallUiLocks.isEmpty()) { + inCallUiLocks.remove(lock); + if (inCallUiLocks.isEmpty()) { LogUtil.i("InCallPresenter.releaseInCallUiLock", "all locks released"); - if (mInCallState == InCallState.NO_CALLS) { + if (inCallState == InCallState.NO_CALLS) { LogUtil.i("InCallPresenter.releaseInCallUiLock", "no more calls, finishing UI"); attemptFinishActivity(); attemptCleanup(); @@ -1826,14 +1824,14 @@ public class InCallPresenter implements CallList.Listener, AudioModeProvider.Aud @MainThread public boolean isInCallUiLocked() { Assert.isMainThread(); - if (mInCallUiLocks.isEmpty()) { + if (inCallUiLocks.isEmpty()) { return false; } - for (InCallUiLock lock : mInCallUiLocks) { + for (InCallUiLock lock : inCallUiLocks) { LogUtil.i("InCallPresenter.isInCallUiLocked", "still locked by %s", lock); } return true; } - private final Set mInCallUiLocks = new ArraySet<>(); + private final Set inCallUiLocks = new ArraySet<>(); } diff --git a/java/com/android/incallui/InCallUIMaterialColorMapUtils.java b/java/com/android/incallui/InCallUIMaterialColorMapUtils.java index 7b06a5e39..945e9fb5a 100644 --- a/java/com/android/incallui/InCallUIMaterialColorMapUtils.java +++ b/java/com/android/incallui/InCallUIMaterialColorMapUtils.java @@ -23,15 +23,15 @@ import com.android.contacts.common.util.MaterialColorMapUtils; public class InCallUIMaterialColorMapUtils extends MaterialColorMapUtils { - private final TypedArray mPrimaryColors; - private final TypedArray mSecondaryColors; - private final Resources mResources; + private final TypedArray primaryColors; + private final TypedArray secondaryColors; + private final Resources resources; public InCallUIMaterialColorMapUtils(Resources resources) { super(resources); - mPrimaryColors = resources.obtainTypedArray(R.array.background_colors); - mSecondaryColors = resources.obtainTypedArray(R.array.background_colors_dark); - mResources = resources; + primaryColors = resources.obtainTypedArray(R.array.background_colors); + secondaryColors = resources.obtainTypedArray(R.array.background_colors_dark); + this.resources = resources; } /** @@ -52,12 +52,12 @@ public class InCallUIMaterialColorMapUtils extends MaterialColorMapUtils { @Override public MaterialPalette calculatePrimaryAndSecondaryColor(int color) { if (color == PhoneAccount.NO_HIGHLIGHT_COLOR) { - return getDefaultPrimaryAndSecondaryColors(mResources); + return getDefaultPrimaryAndSecondaryColors(resources); } - for (int i = 0; i < mPrimaryColors.length(); i++) { - if (mPrimaryColors.getColor(i, 0) == color) { - return new MaterialPalette(mPrimaryColors.getColor(i, 0), mSecondaryColors.getColor(i, 0)); + for (int i = 0; i < primaryColors.length(); i++) { + if (primaryColors.getColor(i, 0) == color) { + return new MaterialPalette(primaryColors.getColor(i, 0), secondaryColors.getColor(i, 0)); } } diff --git a/java/com/android/incallui/PostCharDialogFragment.java b/java/com/android/incallui/PostCharDialogFragment.java index a852f7683..4bcc68e33 100644 --- a/java/com/android/incallui/PostCharDialogFragment.java +++ b/java/com/android/incallui/PostCharDialogFragment.java @@ -32,28 +32,28 @@ public class PostCharDialogFragment extends DialogFragment { private static final String STATE_CALL_ID = "CALL_ID"; private static final String STATE_POST_CHARS = "POST_CHARS"; - private String mCallId; - private String mPostDialStr; + private String callId; + private String postDialStr; public PostCharDialogFragment() {} public PostCharDialogFragment(String callId, String postDialStr) { - mCallId = callId; - mPostDialStr = postDialStr; + this.callId = callId; + this.postDialStr = postDialStr; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); - if (mPostDialStr == null && savedInstanceState != null) { - mCallId = savedInstanceState.getString(STATE_CALL_ID); - mPostDialStr = savedInstanceState.getString(STATE_POST_CHARS); + if (postDialStr == null && savedInstanceState != null) { + callId = savedInstanceState.getString(STATE_CALL_ID); + postDialStr = savedInstanceState.getString(STATE_POST_CHARS); } final StringBuilder buf = new StringBuilder(); buf.append(getResources().getText(R.string.wait_prompt_str)); - buf.append(mPostDialStr); + buf.append(postDialStr); final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(buf.toString()); @@ -63,7 +63,7 @@ public class PostCharDialogFragment extends DialogFragment { new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { - TelecomAdapter.getInstance().postDialContinue(mCallId, true); + TelecomAdapter.getInstance().postDialContinue(callId, true); } }); builder.setNegativeButton( @@ -83,14 +83,14 @@ public class PostCharDialogFragment extends DialogFragment { public void onCancel(DialogInterface dialog) { super.onCancel(dialog); - TelecomAdapter.getInstance().postDialContinue(mCallId, false); + TelecomAdapter.getInstance().postDialContinue(callId, false); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - outState.putString(STATE_CALL_ID, mCallId); - outState.putString(STATE_POST_CHARS, mPostDialStr); + outState.putString(STATE_CALL_ID, callId); + outState.putString(STATE_POST_CHARS, postDialStr); } } diff --git a/java/com/android/incallui/ProximitySensor.java b/java/com/android/incallui/ProximitySensor.java index 123ca539f..f82b75d06 100644 --- a/java/com/android/incallui/ProximitySensor.java +++ b/java/com/android/incallui/ProximitySensor.java @@ -44,49 +44,49 @@ public class ProximitySensor private static final String TAG = ProximitySensor.class.getSimpleName(); - private final PowerManager mPowerManager; - private final PowerManager.WakeLock mProximityWakeLock; - private final AudioModeProvider mAudioModeProvider; - private final AccelerometerListener mAccelerometerListener; - private final ProximityDisplayListener mDisplayListener; - private int mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; - private boolean mUiShowing = false; - private boolean mIsPhoneOffhook = false; - private boolean mDialpadVisible; - private boolean mIsAttemptingVideoCall; - private boolean mIsVideoCall; + private final PowerManager powerManager; + private final PowerManager.WakeLock proximityWakeLock; + private final AudioModeProvider audioModeProvider; + private final AccelerometerListener accelerometerListener; + private final ProximityDisplayListener displayListener; + private int orientation = AccelerometerListener.ORIENTATION_UNKNOWN; + private boolean uiShowing = false; + private boolean isPhoneOffhook = false; + private boolean dialpadVisible; + private boolean isAttemptingVideoCall; + private boolean isVideoCall; public ProximitySensor( @NonNull Context context, @NonNull AudioModeProvider audioModeProvider, @NonNull AccelerometerListener accelerometerListener) { Trace.beginSection("ProximitySensor.Constructor"); - mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); - if (mPowerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { - mProximityWakeLock = - mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG); + powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); + if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) { + proximityWakeLock = + powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG); } else { LogUtil.i("ProximitySensor.constructor", "Device does not support proximity wake lock."); - mProximityWakeLock = null; + proximityWakeLock = null; } - mAccelerometerListener = accelerometerListener; - mAccelerometerListener.setListener(this); + this.accelerometerListener = accelerometerListener; + this.accelerometerListener.setListener(this); - mDisplayListener = + displayListener = new ProximityDisplayListener( (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE)); - mDisplayListener.register(); + displayListener.register(); - mAudioModeProvider = audioModeProvider; - mAudioModeProvider.addListener(this); + this.audioModeProvider = audioModeProvider; + this.audioModeProvider.addListener(this); Trace.endSection(); } public void tearDown() { - mAudioModeProvider.removeListener(this); + audioModeProvider.removeListener(this); - mAccelerometerListener.enable(false); - mDisplayListener.unregister(); + accelerometerListener.enable(false); + displayListener.unregister(); turnOffProximitySensor(true); } @@ -94,7 +94,7 @@ public class ProximitySensor /** Called to identify when the device is laid down flat. */ @Override public void orientationChanged(int orientation) { - mOrientation = orientation; + this.orientation = orientation; updateProximitySensorMode(); } @@ -113,12 +113,12 @@ public class ProximitySensor DialerCall activeCall = callList.getActiveCall(); boolean isVideoCall = activeCall != null && activeCall.isVideoCall(); - if (isOffhook != mIsPhoneOffhook || mIsVideoCall != isVideoCall) { - mIsPhoneOffhook = isOffhook; - mIsVideoCall = isVideoCall; + if (isOffhook != isPhoneOffhook || this.isVideoCall != isVideoCall) { + isPhoneOffhook = isOffhook; + this.isVideoCall = isVideoCall; - mOrientation = AccelerometerListener.ORIENTATION_UNKNOWN; - mAccelerometerListener.enable(mIsPhoneOffhook); + orientation = AccelerometerListener.ORIENTATION_UNKNOWN; + accelerometerListener.enable(isPhoneOffhook); updateProximitySensorMode(); } @@ -130,7 +130,7 @@ public class ProximitySensor } public void onDialpadVisible(boolean visible) { - mDialpadVisible = visible; + dialpadVisible = visible; updateProximitySensorMode(); } @@ -139,25 +139,25 @@ public class ProximitySensor "ProximitySensor.setIsAttemptingVideoCall", "isAttemptingVideoCall: %b", isAttemptingVideoCall); - mIsAttemptingVideoCall = isAttemptingVideoCall; + this.isAttemptingVideoCall = isAttemptingVideoCall; updateProximitySensorMode(); } /** Used to save when the UI goes in and out of the foreground. */ public void onInCallShowing(boolean showing) { if (showing) { - mUiShowing = true; + uiShowing = true; // We only consider the UI not showing for instances where another app took the foreground. // If we stopped showing because the screen is off, we still consider that showing. - } else if (mPowerManager.isScreenOn()) { - mUiShowing = false; + } else if (powerManager.isScreenOn()) { + uiShowing = false; } updateProximitySensorMode(); } void onDisplayStateChanged(boolean isDisplayOn) { LogUtil.i("ProximitySensor.onDisplayStateChanged", "isDisplayOn: %b", isDisplayOn); - mAccelerometerListener.enable(isDisplayOn); + accelerometerListener.enable(isDisplayOn); } /** @@ -167,14 +167,14 @@ public class ProximitySensor * replaced with the ProximityDisplayListener. */ public boolean isScreenReallyOff() { - return !mPowerManager.isScreenOn(); + return !powerManager.isScreenOn(); } private void turnOnProximitySensor() { - if (mProximityWakeLock != null) { - if (!mProximityWakeLock.isHeld()) { + if (proximityWakeLock != null) { + if (!proximityWakeLock.isHeld()) { LogUtil.i("ProximitySensor.turnOnProximitySensor", "acquiring wake lock"); - mProximityWakeLock.acquire(); + proximityWakeLock.acquire(); } else { LogUtil.i("ProximitySensor.turnOnProximitySensor", "wake lock already acquired"); } @@ -182,11 +182,11 @@ public class ProximitySensor } private void turnOffProximitySensor(boolean screenOnImmediately) { - if (mProximityWakeLock != null) { - if (mProximityWakeLock.isHeld()) { + if (proximityWakeLock != null) { + if (proximityWakeLock.isHeld()) { LogUtil.i("ProximitySensor.turnOffProximitySensor", "releasing wake lock"); int flags = (screenOnImmediately ? 0 : PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY); - mProximityWakeLock.release(flags); + proximityWakeLock.release(flags); } else { LogUtil.i("ProximitySensor.turnOffProximitySensor", "wake lock already released"); } @@ -210,39 +210,39 @@ public class ProximitySensor */ private synchronized void updateProximitySensorMode() { Trace.beginSection("ProximitySensor.updateProximitySensorMode"); - final int audioRoute = mAudioModeProvider.getAudioState().getRoute(); + final int audioRoute = audioModeProvider.getAudioState().getRoute(); boolean screenOnImmediately = (CallAudioState.ROUTE_WIRED_HEADSET == audioRoute || CallAudioState.ROUTE_SPEAKER == audioRoute || CallAudioState.ROUTE_BLUETOOTH == audioRoute - || mIsAttemptingVideoCall - || mIsVideoCall); + || isAttemptingVideoCall + || isVideoCall); // We do not keep the screen off when the user is outside in-call screen and we are // horizontal, but we do not force it on when we become horizontal until the // proximity sensor goes negative. - final boolean horizontal = (mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL); - screenOnImmediately |= !mUiShowing && horizontal; + final boolean horizontal = (orientation == AccelerometerListener.ORIENTATION_HORIZONTAL); + screenOnImmediately |= !uiShowing && horizontal; // We do not keep the screen off when dialpad is visible, we are horizontal, and // the in-call screen is being shown. // At that moment we're pretty sure users want to use it, instead of letting the // proximity sensor turn off the screen by their hands. - screenOnImmediately |= mDialpadVisible && horizontal; + screenOnImmediately |= dialpadVisible && horizontal; LogUtil.i( "ProximitySensor.updateProximitySensorMode", "screenOnImmediately: %b, dialPadVisible: %b, " + "offHook: %b, horizontal: %b, uiShowing: %b, audioRoute: %s", screenOnImmediately, - mDialpadVisible, - mIsPhoneOffhook, - mOrientation == AccelerometerListener.ORIENTATION_HORIZONTAL, - mUiShowing, + dialpadVisible, + isPhoneOffhook, + orientation == AccelerometerListener.ORIENTATION_HORIZONTAL, + uiShowing, CallAudioState.audioRouteToString(audioRoute)); - if (mIsPhoneOffhook && !screenOnImmediately) { + if (isPhoneOffhook && !screenOnImmediately) { LogUtil.v("ProximitySensor.updateProximitySensorMode", "turning on proximity sensor"); // Phone is in use! Arrange for the screen to turn off // automatically when the sensor detects a close object. @@ -263,19 +263,19 @@ public class ProximitySensor */ public class ProximityDisplayListener implements DisplayListener { - private DisplayManager mDisplayManager; - private boolean mIsDisplayOn = true; + private DisplayManager displayManager; + private boolean isDisplayOn = true; ProximityDisplayListener(DisplayManager displayManager) { - mDisplayManager = displayManager; + this.displayManager = displayManager; } void register() { - mDisplayManager.registerDisplayListener(this, null); + displayManager.registerDisplayListener(this, null); } void unregister() { - mDisplayManager.unregisterDisplayListener(this); + displayManager.unregisterDisplayListener(this); } @Override @@ -284,14 +284,14 @@ public class ProximitySensor @Override public void onDisplayChanged(int displayId) { if (displayId == Display.DEFAULT_DISPLAY) { - final Display display = mDisplayManager.getDisplay(displayId); + final Display display = displayManager.getDisplay(displayId); final boolean isDisplayOn = display.getState() != Display.STATE_OFF; // For call purposes, we assume that as long as the screen is not truly off, it is // considered on, even if it is in an unknown or low power idle state. - if (isDisplayOn != mIsDisplayOn) { - mIsDisplayOn = isDisplayOn; - onDisplayStateChanged(mIsDisplayOn); + if (isDisplayOn != this.isDisplayOn) { + this.isDisplayOn = isDisplayOn; + onDisplayStateChanged(this.isDisplayOn); } } } diff --git a/java/com/android/incallui/StatusBarNotifier.java b/java/com/android/incallui/StatusBarNotifier.java index 4da858fff..960fd14df 100644 --- a/java/com/android/incallui/StatusBarNotifier.java +++ b/java/com/android/incallui/StatusBarNotifier.java @@ -112,31 +112,31 @@ public class StatusBarNotifier private static final long[] VIBRATE_PATTERN = new long[] {0, 1000, 1000}; - private final Context mContext; - private final ContactInfoCache mContactInfoCache; - private final DialerRingtoneManager mDialerRingtoneManager; - @Nullable private ContactsPreferences mContactsPreferences; - private int mCurrentNotification = NOTIFICATION_NONE; - private int mCallState = DialerCall.State.INVALID; - private int mVideoState = VideoProfile.STATE_AUDIO_ONLY; - private int mSavedIcon = 0; - private String mSavedContent = null; - private Bitmap mSavedLargeIcon; - private String mSavedContentTitle; + private final Context context; + private final ContactInfoCache contactInfoCache; + private final DialerRingtoneManager dialerRingtoneManager; + @Nullable private ContactsPreferences contactsPreferences; + private int currentNotification = NOTIFICATION_NONE; + private int callState = DialerCall.State.INVALID; + private int videoState = VideoProfile.STATE_AUDIO_ONLY; + private int savedIcon = 0; + private String savedContent = null; + private Bitmap savedLargeIcon; + private String savedContentTitle; private CallAudioState savedCallAudioState; - private Uri mRingtone; - private StatusBarCallListener mStatusBarCallListener; + private Uri ringtone; + private StatusBarCallListener statusBarCallListener; public StatusBarNotifier(@NonNull Context context, @NonNull ContactInfoCache contactInfoCache) { Trace.beginSection("StatusBarNotifier.Constructor"); - mContext = Assert.isNotNull(context); - mContactsPreferences = ContactsPreferencesFactory.newContactsPreferences(mContext); - mContactInfoCache = contactInfoCache; - mDialerRingtoneManager = + this.context = Assert.isNotNull(context); + contactsPreferences = ContactsPreferencesFactory.newContactsPreferences(this.context); + this.contactInfoCache = contactInfoCache; + dialerRingtoneManager = new DialerRingtoneManager( new InCallTonePlayer(new ToneGeneratorFactory(), new PausableExecutorImpl()), CallList.getInstance()); - mCurrentNotification = NOTIFICATION_NONE; + currentNotification = NOTIFICATION_NONE; Trace.endSection(); } @@ -213,12 +213,12 @@ public class StatusBarNotifier * @see #updateInCallNotification() */ private void cancelNotification() { - if (mStatusBarCallListener != null) { + if (statusBarCallListener != null) { setStatusBarCallListener(null); } - if (mCurrentNotification != NOTIFICATION_NONE) { + if (currentNotification != NOTIFICATION_NONE) { TelecomAdapter.getInstance().stopForegroundNotification(); - mCurrentNotification = NOTIFICATION_NONE; + currentNotification = NOTIFICATION_NONE; } } @@ -253,7 +253,7 @@ public class StatusBarNotifier // This callback will always get called immediately and synchronously with whatever data // it has available, and may make a subsequent call later (same thread) if it had to // call into the contacts provider for more data. - mContactInfoCache.findInfo(call, isIncoming, this); + contactInfoCache.findInfo(call, isIncoming, this); Trace.endSection(); } @@ -278,7 +278,7 @@ public class StatusBarNotifier Trace.beginSection("read icon and strings"); // Check if data has changed; if nothing is different, don't issue another notification. final int iconResId = getIconToDisplay(call); - Bitmap largeIcon = getLargeIconToDisplay(mContext, contactInfo, call); + Bitmap largeIcon = getLargeIconToDisplay(context, contactInfo, call); final CharSequence content = getContentString(call, contactInfo.userType); final String contentTitle = getContentTitle(contactInfo, call); Trace.endSection(); @@ -290,7 +290,7 @@ public class StatusBarNotifier if (callState == DialerCall.State.INCOMING || callState == DialerCall.State.CALL_WAITING || isVideoUpgradeRequest) { - if (ConfigProviderBindings.get(mContext) + if (ConfigProviderBindings.get(context) .getBoolean("quiet_incoming_call_if_ui_showing", true)) { notificationType = InCallPresenter.getInstance().isShowingInCallUi() @@ -329,10 +329,10 @@ public class StatusBarNotifier // This builder is used for the notification shown when the device is locked and the user // has set their notification settings to 'hide sensitive content' // {@see Notification.Builder#setPublicVersion}. - Notification.Builder publicBuilder = new Notification.Builder(mContext); + Notification.Builder publicBuilder = new Notification.Builder(context); publicBuilder .setSmallIcon(iconResId) - .setColor(mContext.getResources().getColor(R.color.dialer_theme_color, mContext.getTheme())) + .setColor(context.getResources().getColor(R.color.dialer_theme_color, context.getTheme())) // Hide work call state for the lock screen notification .setContentTitle(getContentString(call, ContactsUtils.USER_TYPE_CURRENT)); setNotificationWhen(call, callState, publicBuilder); @@ -357,7 +357,7 @@ public class StatusBarNotifier builder.setCategory(Notification.CATEGORY_CALL); // This will be ignored on O+ and handled by the channel builder.setPriority(Notification.PRIORITY_MAX); - if (mCurrentNotification != NOTIFICATION_INCOMING_CALL) { + if (currentNotification != NOTIFICATION_INCOMING_CALL) { LogUtil.i( "StatusBarNotifier.buildAndSendNotification", "Canceling old notification so this one can be noisy"); @@ -403,20 +403,20 @@ public class StatusBarNotifier // Fire off the notification Notification notification = builder.build(); - if (mDialerRingtoneManager.shouldPlayRingtone(callState, contactInfo.contactRingtoneUri)) { + if (dialerRingtoneManager.shouldPlayRingtone(callState, contactInfo.contactRingtoneUri)) { notification.flags |= Notification.FLAG_INSISTENT; notification.sound = contactInfo.contactRingtoneUri; AudioAttributes.Builder audioAttributes = new AudioAttributes.Builder(); audioAttributes.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC); audioAttributes.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE); notification.audioAttributes = audioAttributes.build(); - if (mDialerRingtoneManager.shouldVibrate(mContext.getContentResolver())) { + if (dialerRingtoneManager.shouldVibrate(context.getContentResolver())) { notification.vibrate = VIBRATE_PATTERN; } } - if (mDialerRingtoneManager.shouldPlayCallWaitingTone(callState)) { + if (dialerRingtoneManager.shouldPlayCallWaitingTone(callState)) { LogUtil.v("StatusBarNotifier.buildAndSendNotification", "playing call waiting tone"); - mDialerRingtoneManager.playCallWaitingTone(); + dialerRingtoneManager.playCallWaitingTone(); } LogUtil.i( @@ -428,7 +428,7 @@ public class StatusBarNotifier Trace.endSection(); call.getLatencyReport().onNotificationShown(); - mCurrentNotification = notificationType; + currentNotification = notificationType; Trace.endSection(); } @@ -486,57 +486,57 @@ public class StatusBarNotifier // if new title is not null, it should be different from saved version OR // if new title is null, the saved version should not be null final boolean contentTitleChanged = - (contentTitle != null && !contentTitle.equals(mSavedContentTitle)) - || (contentTitle == null && mSavedContentTitle != null); + (contentTitle != null && !contentTitle.equals(savedContentTitle)) + || (contentTitle == null && savedContentTitle != null); boolean largeIconChanged; - if (mSavedLargeIcon == null) { + if (savedLargeIcon == null) { largeIconChanged = largeIcon != null; } else { - largeIconChanged = largeIcon == null || !mSavedLargeIcon.sameAs(largeIcon); + largeIconChanged = largeIcon == null || !savedLargeIcon.sameAs(largeIcon); } // any change means we are definitely updating boolean retval = - (mSavedIcon != icon) - || !Objects.equals(mSavedContent, content) - || (mCallState != state) - || (mVideoState != videoState) + (savedIcon != icon) + || !Objects.equals(savedContent, content) + || (callState != state) + || (this.videoState != videoState) || largeIconChanged || contentTitleChanged - || !Objects.equals(mRingtone, ringtone) + || !Objects.equals(this.ringtone, ringtone) || !Objects.equals(savedCallAudioState, callAudioState); LogUtil.d( "StatusBarNotifier.checkForChangeAndSaveData", "data changed: icon: %b, content: %b, state: %b, videoState: %b, largeIcon: %b, title: %b," + "ringtone: %b, audioState: %b, type: %b", - (mSavedIcon != icon), - !Objects.equals(mSavedContent, content), - (mCallState != state), - (mVideoState != videoState), + (savedIcon != icon), + !Objects.equals(savedContent, content), + (callState != state), + (this.videoState != videoState), largeIconChanged, contentTitleChanged, - !Objects.equals(mRingtone, ringtone), + !Objects.equals(this.ringtone, ringtone), !Objects.equals(savedCallAudioState, callAudioState), - mCurrentNotification != notificationType); + currentNotification != notificationType); // If we aren't showing a notification right now or the notification type is changing, // definitely do an update. - if (mCurrentNotification != notificationType) { - if (mCurrentNotification == NOTIFICATION_NONE) { + if (currentNotification != notificationType) { + if (currentNotification == NOTIFICATION_NONE) { LogUtil.d( "StatusBarNotifier.checkForChangeAndSaveData", "showing notification for first time."); } retval = true; } - mSavedIcon = icon; - mSavedContent = content; - mCallState = state; - mVideoState = videoState; - mSavedLargeIcon = largeIcon; - mSavedContentTitle = contentTitle; - mRingtone = ringtone; + savedIcon = icon; + savedContent = content; + callState = state; + this.videoState = videoState; + savedLargeIcon = largeIcon; + savedContentTitle = contentTitle; + this.ringtone = ringtone; savedCallAudioState = callAudioState; if (retval) { @@ -553,12 +553,12 @@ public class StatusBarNotifier String getContentTitle(ContactCacheEntry contactInfo, DialerCall call) { if (call.isConferenceCall()) { return CallerInfoUtils.getConferenceString( - mContext, call.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)); + context, call.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)); } String preferredName = ContactDisplayUtils.getPreferredDisplayName( - contactInfo.namePrimary, contactInfo.nameAlternative, mContactsPreferences); + contactInfo.namePrimary, contactInfo.nameAlternative, contactsPreferences); if (TextUtils.isEmpty(preferredName)) { return TextUtils.isEmpty(contactInfo.number) ? null @@ -623,9 +623,9 @@ public class StatusBarNotifier return null; } final int height = - (int) mContext.getResources().getDimension(android.R.dimen.notification_large_icon_height); + (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height); final int width = - (int) mContext.getResources().getDimension(android.R.dimen.notification_large_icon_width); + (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width); return BitmapUtil.getRoundedBitmap(bitmap, width, height); } @@ -649,7 +649,7 @@ public class StatusBarNotifier || call.isVideoCall()) { return R.drawable.quantum_ic_videocam_white_24; } else if (call.hasProperty(PROPERTY_HIGH_DEF_AUDIO) - && MotorolaUtils.shouldShowHdIconInNotification(mContext)) { + && MotorolaUtils.shouldShowHdIconInNotification(context)) { // Normally when a call is ongoing the status bar displays an icon of a phone. This is a // helpful hint for users so they know how to get back to the call. For Sprint HD calls, we // replace this icon with an icon of a phone with a HD badge. This is a carrier requirement. @@ -658,8 +658,7 @@ public class StatusBarNotifier return R.drawable.quantum_ic_phone_locked_vd_theme_24; } // If ReturnToCall is enabled, use the static icon. The animated one will show in the bubble. - if (ReturnToCallController.isEnabled(mContext) - || NewReturnToCallController.isEnabled(mContext)) { + if (ReturnToCallController.isEnabled(context) || NewReturnToCallController.isEnabled(context)) { return R.drawable.quantum_ic_call_vd_theme_24; } else { return R.drawable.on_going_call; @@ -676,14 +675,14 @@ public class StatusBarNotifier && call.getNumberPresentation() == TelecomManager.PRESENTATION_ALLOWED) { if (!TextUtils.isEmpty(call.getChildNumber())) { - return mContext.getString(R.string.child_number, call.getChildNumber()); + return context.getString(R.string.child_number, call.getChildNumber()); } else if (!TextUtils.isEmpty(call.getCallSubject()) && call.isCallSubjectSupported()) { return call.getCallSubject(); } } int resId = R.string.notification_ongoing_call; - String wifiBrand = mContext.getString(R.string.notification_call_wifi_brand); + String wifiBrand = context.getString(R.string.notification_call_wifi_brand); if (call.hasProperty(Details.PROPERTY_WIFI)) { resId = R.string.notification_ongoing_call_wifi_template; } @@ -720,16 +719,16 @@ public class StatusBarNotifier boolean isWorkCall = call.hasProperty(PROPERTY_ENTERPRISE_CALL); if (userType == ContactsUtils.USER_TYPE_WORK || isWorkCall) { resId = getWorkStringFromPersonalString(resId); - wifiBrand = mContext.getString(R.string.notification_call_wifi_work_brand); + wifiBrand = context.getString(R.string.notification_call_wifi_work_brand); } if (resId == R.string.notification_incoming_call_wifi_template || resId == R.string.notification_ongoing_call_wifi_template) { // TODO(a bug): Potentially apply this template logic everywhere. - return mContext.getString(resId, wifiBrand); + return context.getString(resId, wifiBrand); } - return mContext.getString(resId); + return context.getString(resId); } private boolean shouldShowEnrichedCallNotification(Session session) { @@ -769,7 +768,7 @@ public class StatusBarNotifier } else { resId = R.string.important_notification_incoming_call; } - if (mContext.getString(resId).length() > 50) { + if (context.getString(resId).length() > 50) { resId = R.string.important_notification_incoming_call_attachments; } } else { @@ -795,7 +794,7 @@ public class StatusBarNotifier resId = R.string.notification_incoming_call_with_message; } } - if (mContext.getString(resId).length() > 50) { + if (context.getString(resId).length() > 50) { resId = R.string.notification_incoming_call_attachments; } return resId; @@ -803,10 +802,10 @@ public class StatusBarNotifier private CharSequence getMultiSimIncomingText(DialerCall call) { PhoneAccount phoneAccount = - mContext.getSystemService(TelecomManager.class).getPhoneAccount(call.getAccountHandle()); + context.getSystemService(TelecomManager.class).getPhoneAccount(call.getAccountHandle()); SpannableString string = new SpannableString( - mContext.getString( + context.getString( R.string.notification_incoming_call_mutli_sim, phoneAccount.getLabel())); int accountStart = string.toString().lastIndexOf(phoneAccount.getLabel().toString()); int accountEnd = accountStart + phoneAccount.getLabel().length(); @@ -838,13 +837,13 @@ public class StatusBarNotifier } private Spannable getActionText(@StringRes int stringRes, @ColorRes int colorRes) { - Spannable spannable = new SpannableString(mContext.getText(stringRes)); + Spannable spannable = new SpannableString(context.getText(stringRes)); if (VERSION.SDK_INT >= VERSION_CODES.N_MR1) { // This will only work for cases where the Notification.Builder has a fullscreen intent set // Notification.Builder that does not have a full screen intent will take the color of the // app and the following leads to a no-op. spannable.setSpan( - new ForegroundColorSpan(mContext.getColor(colorRes)), 0, spannable.length(), 0); + new ForegroundColorSpan(context.getColor(colorRes)), 0, spannable.length(), 0); } return spannable; } @@ -854,10 +853,10 @@ public class StatusBarNotifier "StatusBarNotifier.addAnswerAction", "will show \"answer\" action in the incoming call Notification"); PendingIntent answerVoicePendingIntent = - createNotificationPendingIntent(mContext, ACTION_ANSWER_VOICE_INCOMING_CALL); + createNotificationPendingIntent(context, ACTION_ANSWER_VOICE_INCOMING_CALL); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_call_white_24), + Icon.createWithResource(context, R.drawable.quantum_ic_call_white_24), getActionText( R.string.notification_action_answer, R.color.notification_action_accept), answerVoicePendingIntent) @@ -869,10 +868,10 @@ public class StatusBarNotifier "StatusBarNotifier.addDismissAction", "will show \"decline\" action in the incoming call Notification"); PendingIntent declinePendingIntent = - createNotificationPendingIntent(mContext, ACTION_DECLINE_INCOMING_CALL); + createNotificationPendingIntent(context, ACTION_DECLINE_INCOMING_CALL); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_close_white_24), + Icon.createWithResource(context, R.drawable.quantum_ic_close_white_24), getActionText( R.string.notification_action_dismiss, R.color.notification_action_dismiss), declinePendingIntent) @@ -884,11 +883,11 @@ public class StatusBarNotifier "StatusBarNotifier.addHangupAction", "will show \"hang-up\" action in the ongoing active call Notification"); PendingIntent hangupPendingIntent = - createNotificationPendingIntent(mContext, ACTION_HANG_UP_ONGOING_CALL); + createNotificationPendingIntent(context, ACTION_HANG_UP_ONGOING_CALL); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_call_end_white_24), - mContext.getText(R.string.notification_action_end_call), + Icon.createWithResource(context, R.drawable.quantum_ic_call_end_white_24), + context.getText(R.string.notification_action_end_call), hangupPendingIntent) .build()); } @@ -911,11 +910,11 @@ public class StatusBarNotifier "StatusBarNotifier.addSpeakerOnAction", "will show \"Speaker on\" action in the ongoing active call Notification"); PendingIntent speakerOnPendingIntent = - createNotificationPendingIntent(mContext, ACTION_TURN_ON_SPEAKER); + createNotificationPendingIntent(context, ACTION_TURN_ON_SPEAKER); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_volume_up_white_24), - mContext.getText(R.string.notification_action_speaker_on), + Icon.createWithResource(context, R.drawable.quantum_ic_volume_up_white_24), + context.getText(R.string.notification_action_speaker_on), speakerOnPendingIntent) .build()); } @@ -925,11 +924,11 @@ public class StatusBarNotifier "StatusBarNotifier.addSpeakerOffAction", "will show \"Speaker off\" action in the ongoing active call Notification"); PendingIntent speakerOffPendingIntent = - createNotificationPendingIntent(mContext, ACTION_TURN_OFF_SPEAKER); + createNotificationPendingIntent(context, ACTION_TURN_OFF_SPEAKER); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_phone_in_talk_white_24), - mContext.getText(R.string.notification_action_speaker_off), + Icon.createWithResource(context, R.drawable.quantum_ic_phone_in_talk_white_24), + context.getText(R.string.notification_action_speaker_off), speakerOffPendingIntent) .build()); } @@ -939,10 +938,10 @@ public class StatusBarNotifier "StatusBarNotifier.addVideoCallAction", "will show \"video\" action in the incoming call Notification"); PendingIntent answerVideoPendingIntent = - createNotificationPendingIntent(mContext, ACTION_ANSWER_VIDEO_INCOMING_CALL); + createNotificationPendingIntent(context, ACTION_ANSWER_VIDEO_INCOMING_CALL); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_videocam_white_24), + Icon.createWithResource(context, R.drawable.quantum_ic_videocam_white_24), getActionText( R.string.notification_action_answer_video, R.color.notification_action_answer_video), @@ -955,10 +954,10 @@ public class StatusBarNotifier "StatusBarNotifier.addAcceptUpgradeRequestAction", "will show \"accept upgrade\" action in the incoming call Notification"); PendingIntent acceptVideoPendingIntent = - createNotificationPendingIntent(mContext, ACTION_ACCEPT_VIDEO_UPGRADE_REQUEST); + createNotificationPendingIntent(context, ACTION_ACCEPT_VIDEO_UPGRADE_REQUEST); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_videocam_white_24), + Icon.createWithResource(context, R.drawable.quantum_ic_videocam_white_24), getActionText( R.string.notification_action_accept, R.color.notification_action_accept), acceptVideoPendingIntent) @@ -970,10 +969,10 @@ public class StatusBarNotifier "StatusBarNotifier.addDismissUpgradeRequestAction", "will show \"dismiss upgrade\" action in the incoming call Notification"); PendingIntent declineVideoPendingIntent = - createNotificationPendingIntent(mContext, ACTION_DECLINE_VIDEO_UPGRADE_REQUEST); + createNotificationPendingIntent(context, ACTION_DECLINE_VIDEO_UPGRADE_REQUEST); builder.addAction( new Notification.Action.Builder( - Icon.createWithResource(mContext, R.drawable.quantum_ic_videocam_white_24), + Icon.createWithResource(context, R.drawable.quantum_ic_videocam_white_24), getActionText( R.string.notification_action_dismiss, R.color.notification_action_dismiss), declineVideoPendingIntent) @@ -992,7 +991,7 @@ public class StatusBarNotifier } private Notification.Builder getNotificationBuilder() { - final Notification.Builder builder = new Notification.Builder(mContext); + final Notification.Builder builder = new Notification.Builder(context); builder.setOngoing(true); builder.setOnlyAlertOnce(true); // This will be ignored on O+ and handled by the channel @@ -1005,7 +1004,7 @@ public class StatusBarNotifier private PendingIntent createLaunchPendingIntent(boolean isFullScreen) { Intent intent = InCallActivity.getIntent( - mContext, false /* showDialpad */, false /* newOutgoingCall */, isFullScreen); + context, false /* showDialpad */, false /* newOutgoingCall */, isFullScreen); int requestCode = InCallActivity.PendingIntentRequestCodes.NON_FULL_SCREEN; if (isFullScreen) { @@ -1019,14 +1018,14 @@ public class StatusBarNotifier // and clicks the notification's expanded view. It's also used to // launch the InCallActivity immediately when when there's an incoming // call (see the "fullScreenIntent" field below). - return PendingIntent.getActivity(mContext, requestCode, intent, 0); + return PendingIntent.getActivity(context, requestCode, intent, 0); } private void setStatusBarCallListener(StatusBarCallListener listener) { - if (mStatusBarCallListener != null) { - mStatusBarCallListener.cleanup(); + if (statusBarCallListener != null) { + statusBarCallListener.cleanup(); } - mStatusBarCallListener = listener; + statusBarCallListener = listener; } private boolean hasMultiplePhoneAccounts(DialerCall call) { @@ -1057,15 +1056,15 @@ public class StatusBarNotifier private class StatusBarCallListener implements DialerCallListener { - private DialerCall mDialerCall; + private DialerCall dialerCall; StatusBarCallListener(DialerCall dialerCall) { - mDialerCall = dialerCall; - mDialerCall.addListener(this); + this.dialerCall = dialerCall; + this.dialerCall.addListener(this); } void cleanup() { - mDialerCall.removeListener(this); + dialerCall.removeListener(this); } @Override @@ -1074,7 +1073,7 @@ public class StatusBarNotifier @Override public void onDialerCallUpdate() { if (CallList.getInstance().getIncomingCall() == null) { - mDialerRingtoneManager.stopCallWaitingTone(); + dialerRingtoneManager.stopCallWaitingTone(); } } @@ -1105,7 +1104,7 @@ public class StatusBarNotifier */ @Override public void onDialerCallSessionModificationStateChange() { - if (mDialerCall.getVideoTech().getSessionModificationState() + if (dialerCall.getVideoTech().getSessionModificationState() == SessionModificationState.NO_REQUEST) { cleanup(); updateNotification(); diff --git a/java/com/android/incallui/TransactionSafeFragmentActivity.java b/java/com/android/incallui/TransactionSafeFragmentActivity.java index a6b078cb4..696ecf1bd 100644 --- a/java/com/android/incallui/TransactionSafeFragmentActivity.java +++ b/java/com/android/incallui/TransactionSafeFragmentActivity.java @@ -25,30 +25,30 @@ import android.support.v4.app.FragmentActivity; */ public abstract class TransactionSafeFragmentActivity extends FragmentActivity { - 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 TransactionSafeFragmentActivity extends FragmentActivity { * 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/incallui/VideoCallPresenter.java b/java/com/android/incallui/VideoCallPresenter.java index e589bb317..a19d45f7a 100644 --- a/java/com/android/incallui/VideoCallPresenter.java +++ b/java/com/android/incallui/VideoCallPresenter.java @@ -82,61 +82,61 @@ public class VideoCallPresenter InCallPresenter.InCallEventListener, VideoCallScreenDelegate { - private static boolean mIsVideoMode = false; + private static boolean isVideoMode = false; - private final Handler mHandler = new Handler(); - private VideoCallScreen mVideoCallScreen; + private final Handler handler = new Handler(); + private VideoCallScreen videoCallScreen; /** The current context. */ - private Context mContext; + private Context context; /** The call the video surfaces are currently related to */ - private DialerCall mPrimaryCall; + private DialerCall primaryCall; /** * The {@link VideoCall} used to inform the video telephony layer of changes to the video * surfaces. */ - private VideoCall mVideoCall; + private VideoCall videoCall; /** Determines if the current UI state represents a video call. */ - private int mCurrentVideoState; + private int currentVideoState; /** DialerCall's current state */ - private int mCurrentCallState = DialerCall.State.INVALID; + private int currentCallState = DialerCall.State.INVALID; /** Determines the device orientation (portrait/lanscape). */ - private int mDeviceOrientation = InCallOrientationEventListener.SCREEN_ORIENTATION_UNKNOWN; + private int deviceOrientation = InCallOrientationEventListener.SCREEN_ORIENTATION_UNKNOWN; /** Tracks the state of the preview surface negotiation with the telephony layer. */ - private int mPreviewSurfaceState = PreviewSurfaceState.NONE; + private int previewSurfaceState = PreviewSurfaceState.NONE; /** * Determines whether video calls should automatically enter full screen mode after {@link - * #mAutoFullscreenTimeoutMillis} milliseconds. + * #autoFullscreenTimeoutMillis} milliseconds. */ - private boolean mIsAutoFullscreenEnabled = false; + private boolean isAutoFullscreenEnabled = false; /** * Determines the number of milliseconds after which a video call will automatically enter - * fullscreen mode. Requires {@link #mIsAutoFullscreenEnabled} to be {@code true}. + * fullscreen mode. Requires {@link #isAutoFullscreenEnabled} to be {@code true}. */ - private int mAutoFullscreenTimeoutMillis = 0; + private int autoFullscreenTimeoutMillis = 0; /** * Determines if the countdown is currently running to automatically enter full screen video mode. */ - private boolean mAutoFullScreenPending = false; + private boolean autoFullScreenPending = false; /** Whether if the call is remotely held. */ - private boolean mIsRemotelyHeld = false; + private boolean isRemotelyHeld = false; /** * Runnable which is posted to schedule automatically entering fullscreen mode. Will not auto * enter fullscreen mode if the dialpad is visible (doing so would make it impossible to exit the * dialpad). */ - private Runnable mAutoFullscreenRunnable = + private Runnable autoFullscreenRunnable = new Runnable() { @Override public void run() { - if (mAutoFullScreenPending + if (autoFullScreenPending && !InCallPresenter.getInstance().isDialpadVisible() - && mIsVideoMode) { + && isVideoMode) { LogUtil.v("VideoCallPresenter.mAutoFullScreenRunnable", "entering fullscreen mode"); InCallPresenter.getInstance().setFullScreen(true); - mAutoFullScreenPending = false; + autoFullScreenPending = false; } else { LogUtil.v( "VideoCallPresenter.mAutoFullScreenRunnable", @@ -293,12 +293,12 @@ public class VideoCallPresenter */ @Override public void initVideoCallScreenDelegate(Context context, VideoCallScreen videoCallScreen) { - mContext = context; - mVideoCallScreen = videoCallScreen; - mIsAutoFullscreenEnabled = - mContext.getResources().getBoolean(R.bool.video_call_auto_fullscreen); - mAutoFullscreenTimeoutMillis = - mContext.getResources().getInteger(R.integer.video_call_auto_fullscreen_timeout); + this.context = context; + this.videoCallScreen = videoCallScreen; + isAutoFullscreenEnabled = + this.context.getResources().getBoolean(R.bool.video_call_auto_fullscreen); + autoFullscreenTimeoutMillis = + this.context.getResources().getInteger(R.integer.video_call_auto_fullscreen_timeout); } /** Called when the user interface is ready to be used. */ @@ -313,7 +313,7 @@ public class VideoCallPresenter return; } - mDeviceOrientation = InCallOrientationEventListener.getCurrentOrientation(); + deviceOrientation = InCallOrientationEventListener.getCurrentOrientation(); // Register for call state changes last InCallPresenter.getInstance().addListener(this); @@ -327,8 +327,8 @@ public class VideoCallPresenter // Register for surface and video events from {@link InCallVideoCallListener}s. InCallVideoCallCallbackNotifier.getInstance().addSurfaceChangeListener(this); - mCurrentVideoState = VideoProfile.STATE_AUDIO_ONLY; - mCurrentCallState = DialerCall.State.INVALID; + currentVideoState = VideoProfile.STATE_AUDIO_ONLY; + currentCallState = DialerCall.State.INVALID; InCallPresenter.InCallState inCallState = InCallPresenter.getInstance().getInCallState(); onStateChange(inCallState, inCallState, CallList.getInstance()); @@ -359,8 +359,8 @@ public class VideoCallPresenter // Ensure that the call's camera direction is updated (most likely to UNKNOWN). Normally this // happens after any call state changes but we're unregistering from InCallPresenter above so // we won't get any more call state changes. See a bug. - if (mPrimaryCall != null) { - updateCameraSelection(mPrimaryCall); + if (primaryCall != null) { + updateCameraSelection(primaryCall); } isVideoCallScreenUiReady = false; @@ -376,7 +376,7 @@ public class VideoCallPresenter InCallPresenter.getInstance().setFullScreen(true); } else { InCallPresenter.getInstance().setFullScreen(false); - maybeAutoEnterFullscreen(mPrimaryCall); + maybeAutoEnterFullscreen(primaryCall); // If Activity is not multiwindow, fullscreen will be driven by SystemUI visibility changes // instead. See #onSystemUiVisibilityChange(boolean) @@ -391,7 +391,7 @@ public class VideoCallPresenter LogUtil.i("VideoCallPresenter.onSystemUiVisibilityChange", "visible: " + visible); if (visible) { InCallPresenter.getInstance().setFullScreen(false); - maybeAutoEnterFullscreen(mPrimaryCall); + maybeAutoEnterFullscreen(primaryCall); } } @@ -412,7 +412,7 @@ public class VideoCallPresenter @Override public int getDeviceOrientation() { - return mDeviceOrientation; + return deviceOrientation; } /** @@ -422,13 +422,13 @@ public class VideoCallPresenter @Override public void onCameraPermissionGranted() { LogUtil.i("VideoCallPresenter.onCameraPermissionGranted", ""); - PermissionsUtil.setCameraPrivacyToastShown(mContext); - enableCamera(mPrimaryCall, isCameraRequired()); + PermissionsUtil.setCameraPrivacyToastShown(context); + enableCamera(primaryCall, isCameraRequired()); showVideoUi( - mPrimaryCall.getVideoState(), - mPrimaryCall.getState(), - mPrimaryCall.getVideoTech().getSessionModificationState(), - mPrimaryCall.isRemotelyHeld()); + primaryCall.getVideoState(), + primaryCall.getState(), + primaryCall.getVideoTech().getSessionModificationState(), + primaryCall.isRemotelyHeld()); InCallPresenter.getInstance().getInCallCameraManager().onCameraPermissionGranted(); } @@ -438,10 +438,10 @@ public class VideoCallPresenter */ @Override public void resetAutoFullscreenTimer() { - if (mAutoFullScreenPending) { + if (autoFullScreenPending) { LogUtil.i("VideoCallPresenter.resetAutoFullscreenTimer", "resetting"); - mHandler.removeCallbacks(mAutoFullscreenRunnable); - mHandler.postDelayed(mAutoFullscreenRunnable, mAutoFullscreenTimeoutMillis); + handler.removeCallbacks(autoFullscreenRunnable); + handler.postDelayed(autoFullscreenRunnable, autoFullscreenTimeoutMillis); } } @@ -519,16 +519,16 @@ public class VideoCallPresenter currentCall = primary = callList.getActiveCall(); } - final boolean primaryChanged = !Objects.equals(mPrimaryCall, primary); + final boolean primaryChanged = !Objects.equals(primaryCall, primary); LogUtil.i( "VideoCallPresenter.onStateChange", "primaryChanged: %b, primary: %s, mPrimaryCall: %s", primaryChanged, primary, - mPrimaryCall); + primaryCall); if (primaryChanged) { onPrimaryCallChanged(primary); - } else if (mPrimaryCall != null) { + } else if (primaryCall != null) { updateVideoCall(primary); } updateCallCache(primary); @@ -549,9 +549,9 @@ public class VideoCallPresenter @Override public void onFullscreenModeChanged(boolean isFullscreenMode) { cancelAutoFullScreen(); - if (mPrimaryCall != null) { + if (primaryCall != null) { updateFullscreenAndGreenScreenMode( - mPrimaryCall.getState(), mPrimaryCall.getVideoTech().getSessionModificationState()); + primaryCall.getState(), primaryCall.getVideoTech().getSessionModificationState()); } else { updateFullscreenAndGreenScreenMode(State.INVALID, SessionModificationState.NO_REQUEST); } @@ -559,7 +559,7 @@ public class VideoCallPresenter private void checkForVideoStateChange(DialerCall call) { final boolean shouldShowVideoUi = shouldShowVideoUiForCall(call); - final boolean hasVideoStateChanged = mCurrentVideoState != call.getVideoState(); + final boolean hasVideoStateChanged = currentVideoState != call.getVideoState(); LogUtil.v( "VideoCallPresenter.checkForVideoStateChange", @@ -568,7 +568,7 @@ public class VideoCallPresenter shouldShowVideoUi, hasVideoStateChanged, isVideoMode(), - VideoProfile.videoStateToString(mCurrentVideoState), + VideoProfile.videoStateToString(currentVideoState), VideoProfile.videoStateToString(call.getVideoState())); if (!hasVideoStateChanged) { return; @@ -586,8 +586,8 @@ public class VideoCallPresenter private void checkForCallStateChange(DialerCall call) { final boolean shouldShowVideoUi = shouldShowVideoUiForCall(call); final boolean hasCallStateChanged = - mCurrentCallState != call.getState() || mIsRemotelyHeld != call.isRemotelyHeld(); - mIsRemotelyHeld = call.isRemotelyHeld(); + currentCallState != call.getState() || isRemotelyHeld != call.isRemotelyHeld(); + isRemotelyHeld = call.isRemotelyHeld(); LogUtil.v( "VideoCallPresenter.checkForCallStateChange", @@ -646,20 +646,20 @@ public class VideoCallPresenter } private boolean isVideoMode() { - return mIsVideoMode; + return isVideoMode; } private void updateCallCache(DialerCall call) { if (call == null) { - mCurrentVideoState = VideoProfile.STATE_AUDIO_ONLY; - mCurrentCallState = DialerCall.State.INVALID; - mVideoCall = null; - mPrimaryCall = null; + currentVideoState = VideoProfile.STATE_AUDIO_ONLY; + currentCallState = DialerCall.State.INVALID; + videoCall = null; + primaryCall = null; } else { - mCurrentVideoState = call.getVideoState(); - mVideoCall = call.getVideoCall(); - mCurrentCallState = call.getState(); - mPrimaryCall = call; + currentVideoState = call.getVideoState(); + videoCall = call.getVideoCall(); + currentCallState = call.getState(); + primaryCall = call; } } @@ -677,12 +677,12 @@ public class VideoCallPresenter "call: %s, details: %s, mPrimaryCall: %s", call, details, - mPrimaryCall); + primaryCall); if (call == null) { return; } // If the details change is not for the currently active call no update is required. - if (!call.equals(mPrimaryCall)) { + if (!call.equals(primaryCall)) { LogUtil.v("VideoCallPresenter.onDetailsChanged", "details not for current active call"); return; } @@ -708,14 +708,14 @@ public class VideoCallPresenter private void updateFullscreenAndGreenScreenMode( int callState, @SessionModificationState int sessionModificationState) { - if (mVideoCallScreen != null) { + if (videoCallScreen != null) { boolean shouldShowFullscreen = InCallPresenter.getInstance().isFullscreen(); boolean shouldShowGreenScreen = callState == State.DIALING || callState == State.CONNECTING || callState == State.INCOMING || isVideoUpgrade(sessionModificationState); - mVideoCallScreen.updateFullscreenAndGreenScreenMode( + videoCallScreen.updateFullscreenAndGreenScreenMode( shouldShowFullscreen, shouldShowGreenScreen); } } @@ -727,8 +727,8 @@ public class VideoCallPresenter "VideoCallPresenter.checkForVideoCallChange", "videoCall: %s, mVideoCall: %s", videoCall, - mVideoCall); - if (!Objects.equals(videoCall, mVideoCall)) { + this.videoCall); + if (!Objects.equals(videoCall, this.videoCall)) { changeVideoCall(call); } } @@ -745,11 +745,11 @@ public class VideoCallPresenter "VideoCallPresenter.changeVideoCall", "videoCall: %s, mVideoCall: %s", videoCall, - mVideoCall); - final boolean hasChanged = mVideoCall == null && videoCall != null; + this.videoCall); + final boolean hasChanged = this.videoCall == null && videoCall != null; - mVideoCall = videoCall; - if (mVideoCall == null) { + this.videoCall = videoCall; + if (this.videoCall == null) { LogUtil.v("VideoCallPresenter.changeVideoCall", "video call or primary call is null. Return"); return; } @@ -760,10 +760,9 @@ public class VideoCallPresenter } private boolean isCameraRequired() { - return mPrimaryCall != null + return primaryCall != null && isCameraRequired( - mPrimaryCall.getVideoState(), - mPrimaryCall.getVideoTech().getSessionModificationState()); + primaryCall.getVideoState(), primaryCall.getVideoTech().getSessionModificationState()); } /** @@ -781,7 +780,7 @@ public class VideoCallPresenter "videoCall: %s, videoState: %d", videoCall, newVideoState); - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.adjustVideoMode", "error VideoCallScreen is null so returning"); return; } @@ -803,14 +802,14 @@ public class VideoCallPresenter } Assert.checkState( - mDeviceOrientation != InCallOrientationEventListener.SCREEN_ORIENTATION_UNKNOWN); - videoCall.setDeviceOrientation(mDeviceOrientation); + deviceOrientation != InCallOrientationEventListener.SCREEN_ORIENTATION_UNKNOWN); + videoCall.setDeviceOrientation(deviceOrientation); enableCamera( call, isCameraRequired(newVideoState, call.getVideoTech().getSessionModificationState())); } - int previousVideoState = mCurrentVideoState; - mCurrentVideoState = newVideoState; - mIsVideoMode = true; + int previousVideoState = currentVideoState; + currentVideoState = newVideoState; + isVideoMode = true; // adjustVideoMode may be called if we are already in a 1-way video state. In this case // we do not want to trigger auto-fullscreen mode. @@ -842,17 +841,17 @@ public class VideoCallPresenter return; } - boolean hasCameraPermission = VideoUtils.hasCameraPermissionAndShownPrivacyToast(mContext); + boolean hasCameraPermission = VideoUtils.hasCameraPermissionAndShownPrivacyToast(context); if (!hasCameraPermission) { call.getVideoTech().setCamera(null); - mPreviewSurfaceState = PreviewSurfaceState.NONE; + previewSurfaceState = PreviewSurfaceState.NONE; // TODO(wangqi): Inform remote party that the video is off. This is similar to a bug. } else if (isCameraRequired) { InCallCameraManager cameraManager = InCallPresenter.getInstance().getInCallCameraManager(); call.getVideoTech().setCamera(cameraManager.getActiveCameraId()); - mPreviewSurfaceState = PreviewSurfaceState.CAMERA_SET; + previewSurfaceState = PreviewSurfaceState.CAMERA_SET; } else { - mPreviewSurfaceState = PreviewSurfaceState.NONE; + previewSurfaceState = PreviewSurfaceState.NONE; call.getVideoTech().setCamera(null); } } @@ -866,10 +865,10 @@ public class VideoCallPresenter DialerCall.State.ACTIVE, SessionModificationState.NO_REQUEST, false /* isRemotelyHeld */); - enableCamera(mPrimaryCall, false); + enableCamera(primaryCall, false); InCallPresenter.getInstance().setFullScreen(false); InCallPresenter.getInstance().enableScreenTimeout(false); - mIsVideoMode = false; + isVideoMode = false; } /** @@ -885,12 +884,12 @@ public class VideoCallPresenter int callState, @SessionModificationState int sessionModificationState, boolean isRemotelyHeld) { - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.showVideoUi", "videoCallScreen is null returning"); return; } boolean showIncomingVideo = showIncomingVideo(videoState, callState); - boolean showOutgoingVideo = showOutgoingVideo(mContext, videoState, sessionModificationState); + boolean showOutgoingVideo = showOutgoingVideo(context, videoState, sessionModificationState); LogUtil.i( "VideoCallPresenter.showVideoUi", "showIncoming: %b, showOutgoing: %b, isRemotelyHeld: %b", @@ -898,7 +897,7 @@ public class VideoCallPresenter showOutgoingVideo, isRemotelyHeld); updateRemoteVideoSurfaceDimensions(); - mVideoCallScreen.showVideoViews(showOutgoingVideo, showIncomingVideo, isRemotelyHeld); + videoCallScreen.showVideoViews(showOutgoingVideo, showIncomingVideo, isRemotelyHeld); InCallPresenter.getInstance().enableScreenTimeout(VideoProfile.isAudioOnly(videoState)); updateFullscreenAndGreenScreenMode(callState, sessionModificationState); @@ -914,20 +913,20 @@ public class VideoCallPresenter @Override public void onUpdatePeerDimensions(DialerCall call, int width, int height) { LogUtil.i("VideoCallPresenter.onUpdatePeerDimensions", "width: %d, height: %d", width, height); - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.onUpdatePeerDimensions", "videoCallScreen is null"); return; } - if (!call.equals(mPrimaryCall)) { + if (!call.equals(primaryCall)) { LogUtil.e( "VideoCallPresenter.onUpdatePeerDimensions", "current call is not equal to primary"); return; } // Change size of display surface to match the peer aspect ratio - if (width > 0 && height > 0 && mVideoCallScreen != null) { + if (width > 0 && height > 0 && videoCallScreen != null) { getRemoteVideoSurfaceTexture().setSourceVideoDimensions(new Point(width, height)); - mVideoCallScreen.onRemoteVideoDimensionsChanged(); + videoCallScreen.onRemoteVideoDimensionsChanged(); } } @@ -947,25 +946,25 @@ public class VideoCallPresenter call, width, height); - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.onCameraDimensionsChange", "ui is null"); return; } - if (!call.equals(mPrimaryCall)) { + if (!call.equals(primaryCall)) { LogUtil.e("VideoCallPresenter.onCameraDimensionsChange", "not the primary call"); return; } - mPreviewSurfaceState = PreviewSurfaceState.CAPABILITIES_RECEIVED; + previewSurfaceState = PreviewSurfaceState.CAPABILITIES_RECEIVED; changePreviewDimensions(width, height); // Check if the preview surface is ready yet; if it is, set it on the {@code VideoCall}. // If it not yet ready, it will be set when when creation completes. Surface surface = getLocalVideoSurfaceTexture().getSavedSurface(); if (surface != null) { - mPreviewSurfaceState = PreviewSurfaceState.SURFACE_SET; - mVideoCall.setPreviewSurface(surface); + previewSurfaceState = PreviewSurfaceState.SURFACE_SET; + videoCall.setPreviewSurface(surface); } } @@ -976,13 +975,13 @@ public class VideoCallPresenter * @param height The new height. */ private void changePreviewDimensions(int width, int height) { - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { return; } // Resize the surface used to display the preview video getLocalVideoSurfaceTexture().setSurfaceDimensions(new Point(width, height)); - mVideoCallScreen.onLocalVideoDimensionsChanged(); + videoCallScreen.onLocalVideoDimensionsChanged(); } /** @@ -999,11 +998,11 @@ public class VideoCallPresenter LogUtil.i( "VideoCallPresenter.onDeviceOrientationChanged", "orientation: %d -> %d", - mDeviceOrientation, + deviceOrientation, orientation); - mDeviceOrientation = orientation; + deviceOrientation = orientation; - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.onDeviceOrientationChanged", "videoCallScreen is null"); return; } @@ -1019,7 +1018,7 @@ public class VideoCallPresenter previewDimensions); changePreviewDimensions(previewDimensions.x, previewDimensions.y); - mVideoCallScreen.onLocalVideoOrientationChanged(); + videoCallScreen.onLocalVideoOrientationChanged(); } /** @@ -1046,7 +1045,7 @@ public class VideoCallPresenter * @param call The current call. */ protected void maybeAutoEnterFullscreen(DialerCall call) { - if (!mIsAutoFullscreenEnabled) { + if (!isAutoFullscreenEnabled) { return; } @@ -1054,63 +1053,62 @@ public class VideoCallPresenter || call.getState() != DialerCall.State.ACTIVE || !isBidirectionalVideoCall(call) || InCallPresenter.getInstance().isFullscreen() - || (mContext != null && AccessibilityUtil.isTouchExplorationEnabled(mContext))) { + || (context != null && AccessibilityUtil.isTouchExplorationEnabled(context))) { // Ensure any previously scheduled attempt to enter fullscreen is cancelled. cancelAutoFullScreen(); return; } - if (mAutoFullScreenPending) { + if (autoFullScreenPending) { LogUtil.v("VideoCallPresenter.maybeAutoEnterFullscreen", "already pending."); return; } LogUtil.v("VideoCallPresenter.maybeAutoEnterFullscreen", "scheduled"); - mAutoFullScreenPending = true; - mHandler.removeCallbacks(mAutoFullscreenRunnable); - mHandler.postDelayed(mAutoFullscreenRunnable, mAutoFullscreenTimeoutMillis); + autoFullScreenPending = true; + handler.removeCallbacks(autoFullscreenRunnable); + handler.postDelayed(autoFullscreenRunnable, autoFullscreenTimeoutMillis); } /** Cancels pending auto fullscreen mode. */ @Override public void cancelAutoFullScreen() { - if (!mAutoFullScreenPending) { + if (!autoFullScreenPending) { LogUtil.v("VideoCallPresenter.cancelAutoFullScreen", "none pending."); return; } LogUtil.v("VideoCallPresenter.cancelAutoFullScreen", "cancelling pending"); - mAutoFullScreenPending = false; - mHandler.removeCallbacks(mAutoFullscreenRunnable); + autoFullScreenPending = false; + handler.removeCallbacks(autoFullscreenRunnable); } @Override public boolean shouldShowCameraPermissionToast() { - if (mPrimaryCall == null) { + if (primaryCall == null) { LogUtil.i("VideoCallPresenter.shouldShowCameraPermissionToast", "null call"); return false; } - if (mPrimaryCall.didShowCameraPermission()) { + if (primaryCall.didShowCameraPermission()) { LogUtil.i( "VideoCallPresenter.shouldShowCameraPermissionToast", "already shown for this call"); return false; } - if (!ConfigProviderBindings.get(mContext) - .getBoolean("camera_permission_dialog_allowed", true)) { + if (!ConfigProviderBindings.get(context).getBoolean("camera_permission_dialog_allowed", true)) { LogUtil.i("VideoCallPresenter.shouldShowCameraPermissionToast", "disabled by config"); return false; } - return !VideoUtils.hasCameraPermission(mContext) - || !PermissionsUtil.hasCameraPrivacyToastShown(mContext); + return !VideoUtils.hasCameraPermission(context) + || !PermissionsUtil.hasCameraPrivacyToastShown(context); } @Override public void onCameraPermissionDialogShown() { - if (mPrimaryCall != null) { - mPrimaryCall.setDidShowCameraPermission(true); + if (primaryCall != null) { + primaryCall.setDidShowCameraPermission(true); } } private void updateRemoteVideoSurfaceDimensions() { - Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); + Activity activity = videoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); @@ -1131,46 +1129,46 @@ public class VideoCallPresenter private class LocalDelegate implements VideoSurfaceDelegate { @Override public void onSurfaceCreated(VideoSurfaceTexture videoCallSurface) { - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.LocalDelegate.onSurfaceCreated", "no UI"); return; } - if (mVideoCall == null) { + if (videoCall == null) { LogUtil.e("VideoCallPresenter.LocalDelegate.onSurfaceCreated", "no video call"); return; } // If the preview surface has just been created and we have already received camera // capabilities, but not yet set the surface, we will set the surface now. - if (mPreviewSurfaceState == PreviewSurfaceState.CAPABILITIES_RECEIVED) { - mPreviewSurfaceState = PreviewSurfaceState.SURFACE_SET; - mVideoCall.setPreviewSurface(videoCallSurface.getSavedSurface()); - } else if (mPreviewSurfaceState == PreviewSurfaceState.NONE && isCameraRequired()) { - enableCamera(mPrimaryCall, true); + if (previewSurfaceState == PreviewSurfaceState.CAPABILITIES_RECEIVED) { + previewSurfaceState = PreviewSurfaceState.SURFACE_SET; + videoCall.setPreviewSurface(videoCallSurface.getSavedSurface()); + } else if (previewSurfaceState == PreviewSurfaceState.NONE && isCameraRequired()) { + enableCamera(primaryCall, true); } } @Override public void onSurfaceReleased(VideoSurfaceTexture videoCallSurface) { - if (mVideoCall == null) { + if (videoCall == null) { LogUtil.e("VideoCallPresenter.LocalDelegate.onSurfaceReleased", "no video call"); return; } - mVideoCall.setPreviewSurface(null); - enableCamera(mPrimaryCall, false); + videoCall.setPreviewSurface(null); + enableCamera(primaryCall, false); } @Override public void onSurfaceDestroyed(VideoSurfaceTexture videoCallSurface) { - if (mVideoCall == null) { + if (videoCall == null) { LogUtil.e("VideoCallPresenter.LocalDelegate.onSurfaceDestroyed", "no video call"); return; } boolean isChangingConfigurations = InCallPresenter.getInstance().isChangingConfigurations(); if (!isChangingConfigurations) { - enableCamera(mPrimaryCall, false); + enableCamera(primaryCall, false); } else { LogUtil.i( "VideoCallPresenter.LocalDelegate.onSurfaceDestroyed", @@ -1187,24 +1185,24 @@ public class VideoCallPresenter private class RemoteDelegate implements VideoSurfaceDelegate { @Override public void onSurfaceCreated(VideoSurfaceTexture videoCallSurface) { - if (mVideoCallScreen == null) { + if (videoCallScreen == null) { LogUtil.e("VideoCallPresenter.RemoteDelegate.onSurfaceCreated", "no UI"); return; } - if (mVideoCall == null) { + if (videoCall == null) { LogUtil.e("VideoCallPresenter.RemoteDelegate.onSurfaceCreated", "no video call"); return; } - mVideoCall.setDisplaySurface(videoCallSurface.getSavedSurface()); + videoCall.setDisplaySurface(videoCallSurface.getSavedSurface()); } @Override public void onSurfaceReleased(VideoSurfaceTexture videoCallSurface) { - if (mVideoCall == null) { + if (videoCall == null) { LogUtil.e("VideoCallPresenter.RemoteDelegate.onSurfaceReleased", "no video call"); return; } - mVideoCall.setDisplaySurface(null); + videoCall.setDisplaySurface(null); } @Override diff --git a/java/com/android/incallui/VideoPauseController.java b/java/com/android/incallui/VideoPauseController.java index 36c9ef350..1a65010f0 100644 --- a/java/com/android/incallui/VideoPauseController.java +++ b/java/com/android/incallui/VideoPauseController.java @@ -32,26 +32,26 @@ import java.util.Objects; * to the background and subsequently brought back to the foreground. */ class VideoPauseController implements InCallStateListener, IncomingCallListener { - private static VideoPauseController sVideoPauseController; - private InCallPresenter mInCallPresenter; + private static VideoPauseController videoPauseController; + private InCallPresenter inCallPresenter; /** The current call, if applicable. */ - private DialerCall mPrimaryCall = null; + private DialerCall primaryCall = null; /** * The cached state of primary call, updated after onStateChange has processed. * *

These values are stored to detect specific changes in state between onStateChange calls. */ - private int mPrevCallState = State.INVALID; + private int prevCallState = State.INVALID; - private boolean mWasVideoCall = false; + private boolean wasVideoCall = false; /** * Tracks whether the application is in the background. {@code True} if the application is in the * background, {@code false} otherwise. */ - private boolean mIsInBackground = false; + private boolean isInBackground = false; /** * Singleton accessor for the {@link VideoPauseController}. @@ -60,10 +60,10 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener */ /*package*/ static synchronized VideoPauseController getInstance() { - if (sVideoPauseController == null) { - sVideoPauseController = new VideoPauseController(); + if (videoPauseController == null) { + videoPauseController = new VideoPauseController(); } - return sVideoPauseController; + return videoPauseController; } /** @@ -84,7 +84,7 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener * @return {@code true} if the call is dialing, {@code false} otherwise. */ private boolean wasDialing() { - return DialerCall.State.isDialing(mPrevCallState); + return DialerCall.State.isDialing(prevCallState); } /** @@ -95,9 +95,9 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener */ public void setUp(@NonNull InCallPresenter inCallPresenter) { LogUtil.enterBlock("VideoPauseController.setUp"); - mInCallPresenter = Assert.isNotNull(inCallPresenter); - mInCallPresenter.addListener(this); - mInCallPresenter.addIncomingCallListener(this); + this.inCallPresenter = Assert.isNotNull(inCallPresenter); + this.inCallPresenter.addListener(this); + this.inCallPresenter.addIncomingCallListener(this); } /** @@ -106,18 +106,18 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener */ public void tearDown() { LogUtil.enterBlock("VideoPauseController.tearDown"); - mInCallPresenter.removeListener(this); - mInCallPresenter.removeIncomingCallListener(this); + inCallPresenter.removeListener(this); + inCallPresenter.removeIncomingCallListener(this); clear(); } /** Clears the internal state for the {@link VideoPauseController}. */ private void clear() { - mInCallPresenter = null; - mPrimaryCall = null; - mPrevCallState = State.INVALID; - mWasVideoCall = false; - mIsInBackground = false; + inCallPresenter = null; + primaryCall = null; + prevCallState = State.INVALID; + wasVideoCall = false; + isInBackground = false; } /** @@ -143,7 +143,7 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener call = callList.getActiveCall(); } - boolean hasPrimaryCallChanged = !Objects.equals(call, mPrimaryCall); + boolean hasPrimaryCallChanged = !Objects.equals(call, primaryCall); boolean canVideoPause = videoCanPause(call); LogUtil.i( @@ -151,18 +151,18 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener "hasPrimaryCallChanged: %b, videoCanPause: %b, isInBackground: %b", hasPrimaryCallChanged, canVideoPause, - mIsInBackground); + isInBackground); if (hasPrimaryCallChanged) { onPrimaryCallChanged(call); return; } - if (wasDialing() && canVideoPause && mIsInBackground) { + if (wasDialing() && canVideoPause && isInBackground) { // Bring UI to foreground if outgoing request becomes active while UI is in // background. bringToForeground(); - } else if (!mWasVideoCall && canVideoPause && mIsInBackground) { + } else if (!wasVideoCall && canVideoPause && isInBackground) { // Bring UI to foreground if VoLTE call becomes active while UI is in // background. bringToForeground(); @@ -185,22 +185,22 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener "VideoPauseController.onPrimaryCallChanged", "new call: %s, old call: %s, mIsInBackground: %b", call, - mPrimaryCall, - mIsInBackground); + primaryCall, + isInBackground); - if (Objects.equals(call, mPrimaryCall)) { + if (Objects.equals(call, primaryCall)) { throw new IllegalStateException(); } final boolean canVideoPause = videoCanPause(call); - if (canVideoPause && !mIsInBackground) { + if (canVideoPause && !isInBackground) { // Send resume request for the active call, if user rejects incoming call, ends dialing // call, or the call was previously in a paused state and UI is in the foreground. sendRequest(call, true); - } else if (isIncomingCall(call) && videoCanPause(mPrimaryCall)) { + } else if (isIncomingCall(call) && videoCanPause(primaryCall)) { // Send pause request if there is an active video call, and we just received a new // incoming call. - sendRequest(mPrimaryCall, false); + sendRequest(primaryCall, false); } updatePrimaryCallContext(call); @@ -222,7 +222,7 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener newState, call); - if (Objects.equals(call, mPrimaryCall)) { + if (Objects.equals(call, primaryCall)) { return; } @@ -236,13 +236,13 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener */ private void updatePrimaryCallContext(DialerCall call) { if (call == null) { - mPrimaryCall = null; - mPrevCallState = State.INVALID; - mWasVideoCall = false; + primaryCall = null; + prevCallState = State.INVALID; + wasVideoCall = false; } else { - mPrimaryCall = call; - mPrevCallState = call.getState(); - mWasVideoCall = call.isVideoCall(); + primaryCall = call; + prevCallState = call.getState(); + wasVideoCall = call.isVideoCall(); } } @@ -252,11 +252,11 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener * @param showing true if UI is in the foreground, false otherwise. */ public void onUiShowing(boolean showing) { - if (mInCallPresenter == null) { + if (inCallPresenter == null) { return; } - final boolean isInCall = mInCallPresenter.getInCallState() == InCallState.INCALL; + final boolean isInCall = inCallPresenter.getInCallState() == InCallState.INCALL; if (showing) { onResume(isInCall); } else { @@ -272,9 +272,9 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener * video provider if we are in a call. */ private void onResume(boolean isInCall) { - mIsInBackground = false; + isInBackground = false; if (isInCall) { - sendRequest(mPrimaryCall, true); + sendRequest(primaryCall, true); } } @@ -286,16 +286,16 @@ class VideoPauseController implements InCallStateListener, IncomingCallListener * video provider if we are in a call. */ private void onPause(boolean isInCall) { - mIsInBackground = true; + isInBackground = true; if (isInCall) { - sendRequest(mPrimaryCall, false); + sendRequest(primaryCall, false); } } private void bringToForeground() { LogUtil.enterBlock("VideoPauseController.bringToForeground"); - if (mInCallPresenter != null) { - mInCallPresenter.bringToForeground(false); + if (inCallPresenter != null) { + inCallPresenter.bringToForeground(false); } else { LogUtil.e( "VideoPauseController.bringToForeground", diff --git a/java/com/android/incallui/answer/impl/FixedAspectSurfaceView.java b/java/com/android/incallui/answer/impl/FixedAspectSurfaceView.java index ad7d94d95..1f7e6fe91 100644 --- a/java/com/android/incallui/answer/impl/FixedAspectSurfaceView.java +++ b/java/com/android/incallui/answer/impl/FixedAspectSurfaceView.java @@ -34,7 +34,7 @@ import com.android.dialer.common.Assert; public class FixedAspectSurfaceView extends SurfaceView { /** Desired width/height ratio */ - private float mAspectRatio; + private float aspectRatio; private final boolean scaleWidth; private final boolean scaleHeight; @@ -60,7 +60,7 @@ public class FixedAspectSurfaceView extends SurfaceView { */ public void setAspectRatio(float aspect) { Assert.checkArgument(aspect >= 0, "Aspect ratio must be positive"); - mAspectRatio = aspect; + aspectRatio = aspect; requestLayout(); } @@ -71,9 +71,9 @@ public class FixedAspectSurfaceView extends SurfaceView { // Do the scaling if (scaleWidth) { - width = (int) (height * mAspectRatio); + width = (int) (height * aspectRatio); } else if (scaleHeight) { - height = (int) (width / mAspectRatio); + height = (int) (width / aspectRatio); } // Override width/height if needed for EXACTLY and AT_MOST specs diff --git a/java/com/android/incallui/answer/impl/affordance/SwipeButtonHelper.java b/java/com/android/incallui/answer/impl/affordance/SwipeButtonHelper.java index 1c66e63b8..6fb520c8c 100644 --- a/java/com/android/incallui/answer/impl/affordance/SwipeButtonHelper.java +++ b/java/com/android/incallui/answer/impl/affordance/SwipeButtonHelper.java @@ -273,16 +273,16 @@ public class SwipeButtonHelper { } animator.addListener( new AnimatorListenerAdapter() { - private boolean mCancelled; + private boolean cancelled; @Override public void onAnimationCancel(Animator animation) { - mCancelled = true; + cancelled = true; } @Override public void onAnimationEnd(Animator animation) { - if (mCancelled) { + if (cancelled) { swipeAnimator = null; targetedView = null; if (onFinishedListener != null) { diff --git a/java/com/android/incallui/answer/impl/affordance/SwipeButtonView.java b/java/com/android/incallui/answer/impl/affordance/SwipeButtonView.java index 46879ea3f..249c47a65 100644 --- a/java/com/android/incallui/answer/impl/affordance/SwipeButtonView.java +++ b/java/com/android/incallui/answer/impl/affordance/SwipeButtonView.java @@ -474,16 +474,16 @@ public class SwipeButtonView extends ImageView { private Animator.AnimatorListener getEndListener(final Runnable runnable) { return new AnimatorListenerAdapter() { - boolean mCancelled; + boolean cancelled; @Override public void onAnimationCancel(Animator animation) { - mCancelled = true; + cancelled = true; } @Override public void onAnimationEnd(Animator animation) { - if (!mCancelled) { + if (!cancelled) { runnable.run(); } } diff --git a/java/com/android/incallui/answer/impl/classifier/AccelerationClassifier.java b/java/com/android/incallui/answer/impl/classifier/AccelerationClassifier.java index ac504444e..ae0d1c800 100644 --- a/java/com/android/incallui/answer/impl/classifier/AccelerationClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/AccelerationClassifier.java @@ -29,10 +29,10 @@ import java.util.Map; * the speed of a part. */ class AccelerationClassifier extends StrokeClassifier { - private final Map mStrokeMap = new ArrayMap<>(); + private final Map strokeMap = new ArrayMap<>(); public AccelerationClassifier(ClassifierData classifierData) { - mClassifierData = classifierData; + this.classifierData = classifierData; } @Override @@ -45,23 +45,23 @@ class AccelerationClassifier extends StrokeClassifier { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mStrokeMap.clear(); + strokeMap.clear(); } for (int i = 0; i < event.getPointerCount(); i++) { - Stroke stroke = mClassifierData.getStroke(event.getPointerId(i)); + Stroke stroke = classifierData.getStroke(event.getPointerId(i)); Point point = stroke.getPoints().get(stroke.getPoints().size() - 1); - if (mStrokeMap.get(stroke) == null) { - mStrokeMap.put(stroke, new Data(point)); + if (strokeMap.get(stroke) == null) { + strokeMap.put(stroke, new Data(point)); } else { - mStrokeMap.get(stroke).addPoint(point); + strokeMap.get(stroke).addPoint(point); } } } @Override public float getFalseTouchEvaluation(Stroke stroke) { - Data data = mStrokeMap.get(stroke); + Data data = strokeMap.get(stroke); return 2 * SpeedRatioEvaluator.evaluate(data.maxSpeedRatio); } diff --git a/java/com/android/incallui/answer/impl/classifier/AnglesClassifier.java b/java/com/android/incallui/answer/impl/classifier/AnglesClassifier.java index dbfbcfc1c..24f04c438 100644 --- a/java/com/android/incallui/answer/impl/classifier/AnglesClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/AnglesClassifier.java @@ -47,10 +47,10 @@ import java.util.Map; * angels or right angles) */ class AnglesClassifier extends StrokeClassifier { - private Map mStrokeMap = new ArrayMap<>(); + private Map strokeMap = new ArrayMap<>(); public AnglesClassifier(ClassifierData classifierData) { - mClassifierData = classifierData; + this.classifierData = classifierData; } @Override @@ -63,22 +63,22 @@ class AnglesClassifier extends StrokeClassifier { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mStrokeMap.clear(); + strokeMap.clear(); } for (int i = 0; i < event.getPointerCount(); i++) { - Stroke stroke = mClassifierData.getStroke(event.getPointerId(i)); + Stroke stroke = classifierData.getStroke(event.getPointerId(i)); - if (mStrokeMap.get(stroke) == null) { - mStrokeMap.put(stroke, new Data()); + if (strokeMap.get(stroke) == null) { + strokeMap.put(stroke, new Data()); } - mStrokeMap.get(stroke).addPoint(stroke.getPoints().get(stroke.getPoints().size() - 1)); + strokeMap.get(stroke).addPoint(stroke.getPoints().get(stroke.getPoints().size() - 1)); } } @Override public float getFalseTouchEvaluation(Stroke stroke) { - Data data = mStrokeMap.get(stroke); + Data data = strokeMap.get(stroke); return AnglesVarianceEvaluator.evaluate(data.getAnglesVariance()) + AnglesPercentageEvaluator.evaluate(data.getAnglesPercentage()); } @@ -87,82 +87,82 @@ class AnglesClassifier extends StrokeClassifier { private static final float ANGLE_DEVIATION = (float) Math.PI / 20.0f; private static final float MIN_MOVE_DIST_DP = .01f; - private List mLastThreePoints = new ArrayList<>(); - private float mFirstAngleVariance; - private float mPreviousAngle; - private float mBiggestAngle; - private float mSumSquares; - private float mSecondSumSquares; - private float mSum; - private float mSecondSum; - private float mCount; - private float mSecondCount; - private float mFirstLength; - private float mLength; - private float mAnglesCount; - private float mLeftAngles; - private float mRightAngles; - private float mStraightAngles; + private List lastThreePoints = new ArrayList<>(); + private float firstAngleVariance; + private float previousAngle; + private float biggestAngle; + private float sumSquares; + private float secondSumSquares; + private float sum; + private float secondSum; + private float count; + private float secondCount; + private float firstLength; + private float length; + private float anglesCount; + private float leftAngles; + private float rightAngles; + private float straightAngles; public Data() { - mFirstAngleVariance = 0.0f; - mPreviousAngle = (float) Math.PI; - mBiggestAngle = 0.0f; - mSumSquares = mSecondSumSquares = 0.0f; - mSum = mSecondSum = 0.0f; - mCount = mSecondCount = 1.0f; - mLength = mFirstLength = 0.0f; - mAnglesCount = mLeftAngles = mRightAngles = mStraightAngles = 0.0f; + firstAngleVariance = 0.0f; + previousAngle = (float) Math.PI; + biggestAngle = 0.0f; + sumSquares = secondSumSquares = 0.0f; + sum = secondSum = 0.0f; + count = secondCount = 1.0f; + length = firstLength = 0.0f; + anglesCount = leftAngles = rightAngles = straightAngles = 0.0f; } public void addPoint(Point point) { // Checking if the added point is different than the previously added point // Repetitions and short distances are being ignored so that proper angles are calculated. - if (mLastThreePoints.isEmpty() - || (!mLastThreePoints.get(mLastThreePoints.size() - 1).equals(point) - && (mLastThreePoints.get(mLastThreePoints.size() - 1).dist(point) + if (lastThreePoints.isEmpty() + || (!lastThreePoints.get(lastThreePoints.size() - 1).equals(point) + && (lastThreePoints.get(lastThreePoints.size() - 1).dist(point) > MIN_MOVE_DIST_DP))) { - if (!mLastThreePoints.isEmpty()) { - mLength += mLastThreePoints.get(mLastThreePoints.size() - 1).dist(point); + if (!lastThreePoints.isEmpty()) { + length += lastThreePoints.get(lastThreePoints.size() - 1).dist(point); } - mLastThreePoints.add(point); - if (mLastThreePoints.size() == 4) { - mLastThreePoints.remove(0); + lastThreePoints.add(point); + if (lastThreePoints.size() == 4) { + lastThreePoints.remove(0); float angle = - mLastThreePoints.get(1).getAngle(mLastThreePoints.get(0), mLastThreePoints.get(2)); + lastThreePoints.get(1).getAngle(lastThreePoints.get(0), lastThreePoints.get(2)); - mAnglesCount++; + anglesCount++; if (angle < Math.PI - ANGLE_DEVIATION) { - mLeftAngles++; + leftAngles++; } else if (angle <= Math.PI + ANGLE_DEVIATION) { - mStraightAngles++; + straightAngles++; } else { - mRightAngles++; + rightAngles++; } - float difference = angle - mPreviousAngle; + float difference = angle - previousAngle; // If this is the biggest angle of the stroke so then we save the value of // the angle variance so far and start to count the values for the angle // variance of the second part. - if (mBiggestAngle < angle) { - mBiggestAngle = angle; - mFirstLength = mLength; - mFirstAngleVariance = getAnglesVariance(mSumSquares, mSum, mCount); - mSecondSumSquares = 0.0f; - mSecondSum = 0.0f; - mSecondCount = 1.0f; + if (biggestAngle < angle) { + biggestAngle = angle; + firstLength = length; + firstAngleVariance = getAnglesVariance(sumSquares, sum, count); + secondSumSquares = 0.0f; + secondSum = 0.0f; + secondCount = 1.0f; } else { - mSecondSum += difference; - mSecondSumSquares += difference * difference; - mSecondCount += 1.0f; + secondSum += difference; + secondSumSquares += difference * difference; + secondCount += 1.0f; } - mSum += difference; - mSumSquares += difference * difference; - mCount += 1.0f; - mPreviousAngle = angle; + sum += difference; + sumSquares += difference * difference; + count += 1.0f; + previousAngle = angle; } } } @@ -172,22 +172,21 @@ class AnglesClassifier extends StrokeClassifier { } public float getAnglesVariance() { - float anglesVariance = getAnglesVariance(mSumSquares, mSum, mCount); - if (mFirstLength < mLength / 2f) { + float anglesVariance = getAnglesVariance(sumSquares, sum, count); + if (firstLength < length / 2f) { anglesVariance = Math.min( anglesVariance, - mFirstAngleVariance - + getAnglesVariance(mSecondSumSquares, mSecondSum, mSecondCount)); + firstAngleVariance + getAnglesVariance(secondSumSquares, secondSum, secondCount)); } return anglesVariance; } public float getAnglesPercentage() { - if (mAnglesCount == 0.0f) { + if (anglesCount == 0.0f) { return 1.0f; } - return (Math.max(mLeftAngles, mRightAngles) + mStraightAngles) / mAnglesCount; + return (Math.max(leftAngles, rightAngles) + straightAngles) / anglesCount; } } } diff --git a/java/com/android/incallui/answer/impl/classifier/Classifier.java b/java/com/android/incallui/answer/impl/classifier/Classifier.java index c6fbff327..1baa6b4f4 100644 --- a/java/com/android/incallui/answer/impl/classifier/Classifier.java +++ b/java/com/android/incallui/answer/impl/classifier/Classifier.java @@ -23,7 +23,7 @@ import android.view.MotionEvent; abstract class Classifier { /** Contains all the information about touch events from which the classifier can query */ - protected ClassifierData mClassifierData; + protected ClassifierData classifierData; /** Informs the classifier that a new touch event has occurred */ public void onTouchEvent(MotionEvent event) {} diff --git a/java/com/android/incallui/answer/impl/classifier/ClassifierData.java b/java/com/android/incallui/answer/impl/classifier/ClassifierData.java index ae07d27a0..fe3fbe0cf 100644 --- a/java/com/android/incallui/answer/impl/classifier/ClassifierData.java +++ b/java/com/android/incallui/answer/impl/classifier/ClassifierData.java @@ -26,31 +26,31 @@ import java.util.concurrent.TimeUnit; * example, provide information on the current touch state. */ class ClassifierData { - private SparseArray mCurrentStrokes = new SparseArray<>(); - private ArrayList mEndingStrokes = new ArrayList<>(); - private final float mDpi; - private final float mScreenHeight; + private SparseArray currentStrokes = new SparseArray<>(); + private ArrayList endingStrokes = new ArrayList<>(); + private final float dpi; + private final float screenHeight; public ClassifierData(float dpi, float screenHeight) { - mDpi = dpi; - mScreenHeight = screenHeight / dpi; + this.dpi = dpi; + this.screenHeight = screenHeight / dpi; } public void update(MotionEvent event) { - mEndingStrokes.clear(); + endingStrokes.clear(); int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mCurrentStrokes.clear(); + currentStrokes.clear(); } for (int i = 0; i < event.getPointerCount(); i++) { int id = event.getPointerId(i); - if (mCurrentStrokes.get(id) == null) { + if (currentStrokes.get(id) == null) { // TODO (keyboardr): See if there's a way to use event.getEventTimeNanos() instead - mCurrentStrokes.put( - id, new Stroke(TimeUnit.MILLISECONDS.toNanos(event.getEventTime()), mDpi)); + currentStrokes.put( + id, new Stroke(TimeUnit.MILLISECONDS.toNanos(event.getEventTime()), dpi)); } - mCurrentStrokes + currentStrokes .get(id) .addPoint( event.getX(i), event.getY(i), TimeUnit.MILLISECONDS.toNanos(event.getEventTime())); @@ -58,27 +58,27 @@ class ClassifierData { if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || (action == MotionEvent.ACTION_POINTER_UP && i == event.getActionIndex())) { - mEndingStrokes.add(getStroke(id)); + endingStrokes.add(getStroke(id)); } } } void cleanUp(MotionEvent event) { - mEndingStrokes.clear(); + endingStrokes.clear(); int action = event.getActionMasked(); for (int i = 0; i < event.getPointerCount(); i++) { int id = event.getPointerId(i); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || (action == MotionEvent.ACTION_POINTER_UP && i == event.getActionIndex())) { - mCurrentStrokes.remove(id); + currentStrokes.remove(id); } } } /** @return the list of Strokes which are ending in the recently added MotionEvent */ public ArrayList getEndingStrokes() { - return mEndingStrokes; + return endingStrokes; } /** @@ -86,11 +86,11 @@ class ClassifierData { * @return the Stroke assigned to the id */ public Stroke getStroke(int id) { - return mCurrentStrokes.get(id); + return currentStrokes.get(id); } /** @return the height of the screen in inches */ public float getScreenHeight() { - return mScreenHeight; + return screenHeight; } } diff --git a/java/com/android/incallui/answer/impl/classifier/EndPointLengthClassifier.java b/java/com/android/incallui/answer/impl/classifier/EndPointLengthClassifier.java index 95b317638..a111ccc70 100644 --- a/java/com/android/incallui/answer/impl/classifier/EndPointLengthClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/EndPointLengthClassifier.java @@ -21,7 +21,7 @@ package com.android.incallui.answer.impl.classifier; */ class EndPointLengthClassifier extends StrokeClassifier { public EndPointLengthClassifier(ClassifierData classifierData) { - mClassifierData = classifierData; + this.classifierData = classifierData; } @Override diff --git a/java/com/android/incallui/answer/impl/classifier/EndPointRatioClassifier.java b/java/com/android/incallui/answer/impl/classifier/EndPointRatioClassifier.java index 01a35c126..4336e00da 100644 --- a/java/com/android/incallui/answer/impl/classifier/EndPointRatioClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/EndPointRatioClassifier.java @@ -22,7 +22,7 @@ package com.android.incallui.answer.impl.classifier; */ class EndPointRatioClassifier extends StrokeClassifier { public EndPointRatioClassifier(ClassifierData classifierData) { - mClassifierData = classifierData; + this.classifierData = classifierData; } @Override diff --git a/java/com/android/incallui/answer/impl/classifier/FalsingManager.java b/java/com/android/incallui/answer/impl/classifier/FalsingManager.java index 9cdd888d1..3deff8852 100644 --- a/java/com/android/incallui/answer/impl/classifier/FalsingManager.java +++ b/java/com/android/incallui/answer/impl/classifier/FalsingManager.java @@ -36,23 +36,23 @@ public class FalsingManager implements SensorEventListener { Sensor.TYPE_PROXIMITY, }; - private final SensorManager mSensorManager; - private final HumanInteractionClassifier mHumanInteractionClassifier; - private final AccessibilityManager mAccessibilityManager; + private final SensorManager sensorManager; + private final HumanInteractionClassifier humanInteractionClassifier; + private final AccessibilityManager accessibilityManager; - private boolean mSessionActive = false; - private boolean mScreenOn; + private boolean sessionActive = false; + private boolean screenOn; public FalsingManager(Context context) { - mSensorManager = context.getSystemService(SensorManager.class); - mAccessibilityManager = context.getSystemService(AccessibilityManager.class); - mHumanInteractionClassifier = new HumanInteractionClassifier(context); - mScreenOn = context.getSystemService(PowerManager.class).isInteractive(); + sensorManager = context.getSystemService(SensorManager.class); + accessibilityManager = context.getSystemService(AccessibilityManager.class); + humanInteractionClassifier = new HumanInteractionClassifier(context); + screenOn = context.getSystemService(PowerManager.class).isInteractive(); } /** Returns {@code true} iff the FalsingManager is enabled and able to classify touches */ public boolean isEnabled() { - return mHumanInteractionClassifier.isEnabled(); + return humanInteractionClassifier.isEnabled(); } /** @@ -62,8 +62,8 @@ public class FalsingManager implements SensorEventListener { public boolean isFalseTouch() { // Touch exploration triggers false positives in the classifier and // already sufficiently prevents false unlocks. - return !mAccessibilityManager.isTouchExplorationEnabled() - && mHumanInteractionClassifier.isFalseTouch(); + return !accessibilityManager.isTouchExplorationEnabled() + && humanInteractionClassifier.isFalseTouch(); } /** @@ -71,7 +71,7 @@ public class FalsingManager implements SensorEventListener { * tracking changes if the manager is enabled. */ public void onScreenOn() { - mScreenOn = true; + screenOn = true; sessionEntrypoint(); } @@ -80,7 +80,7 @@ public class FalsingManager implements SensorEventListener { * will cause the manager to stop tracking changes. */ public void onScreenOff() { - mScreenOn = false; + screenOn = false; sessionExitpoint(); } @@ -90,25 +90,25 @@ public class FalsingManager implements SensorEventListener { * @param event MotionEvent to be classified as human or false. */ public void onTouchEvent(MotionEvent event) { - if (mSessionActive) { - mHumanInteractionClassifier.onTouchEvent(event); + if (sessionActive) { + humanInteractionClassifier.onTouchEvent(event); } } @Override public synchronized void onSensorChanged(SensorEvent event) { - mHumanInteractionClassifier.onSensorChanged(event); + humanInteractionClassifier.onSensorChanged(event); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} private boolean shouldSessionBeActive() { - return isEnabled() && mScreenOn; + return isEnabled() && screenOn; } private boolean sessionEntrypoint() { - if (!mSessionActive && shouldSessionBeActive()) { + if (!sessionActive && shouldSessionBeActive()) { onSessionStart(); return true; } @@ -116,16 +116,16 @@ public class FalsingManager implements SensorEventListener { } private void sessionExitpoint() { - if (mSessionActive && !shouldSessionBeActive()) { - mSessionActive = false; - mSensorManager.unregisterListener(this); + if (sessionActive && !shouldSessionBeActive()) { + sessionActive = false; + sensorManager.unregisterListener(this); } } private void onSessionStart() { - mSessionActive = true; + sessionActive = true; - if (mHumanInteractionClassifier.isEnabled()) { + if (humanInteractionClassifier.isEnabled()) { registerSensors(CLASSIFIER_SENSORS); } } @@ -134,11 +134,11 @@ public class FalsingManager implements SensorEventListener { Trace.beginSection("FalsingManager.registerSensors"); for (int sensorType : sensors) { Trace.beginSection("get sensor " + sensorType); - Sensor s = mSensorManager.getDefaultSensor(sensorType); + Sensor s = sensorManager.getDefaultSensor(sensorType); Trace.endSection(); if (s != null) { Trace.beginSection("register"); - mSensorManager.registerListener(this, s, SensorManager.SENSOR_DELAY_GAME); + sensorManager.registerListener(this, s, SensorManager.SENSOR_DELAY_GAME); Trace.endSection(); } } diff --git a/java/com/android/incallui/answer/impl/classifier/HistoryEvaluator.java b/java/com/android/incallui/answer/impl/classifier/HistoryEvaluator.java index 3f302c65f..c0256a5d8 100644 --- a/java/com/android/incallui/answer/impl/classifier/HistoryEvaluator.java +++ b/java/com/android/incallui/answer/impl/classifier/HistoryEvaluator.java @@ -17,7 +17,6 @@ package com.android.incallui.answer.impl.classifier; import android.os.SystemClock; - import java.util.ArrayList; /** @@ -28,27 +27,27 @@ class HistoryEvaluator { private static final float HISTORY_FACTOR = 0.9f; private static final float EPSILON = 1e-5f; - private final ArrayList mStrokes = new ArrayList<>(); - private final ArrayList mGestureWeights = new ArrayList<>(); - private long mLastUpdate; + private final ArrayList strokes = new ArrayList<>(); + private final ArrayList gestureWeights = new ArrayList<>(); + private long lastUpdate; public HistoryEvaluator() { - mLastUpdate = SystemClock.elapsedRealtime(); + lastUpdate = SystemClock.elapsedRealtime(); } public void addStroke(float evaluation) { decayValue(); - mStrokes.add(new Data(evaluation)); + strokes.add(new Data(evaluation)); } public void addGesture(float evaluation) { decayValue(); - mGestureWeights.add(new Data(evaluation)); + gestureWeights.add(new Data(evaluation)); } /** Calculates the weighted average of strokes and adds to it the weighted average of gestures */ public float getEvaluation() { - return weightedAverage(mStrokes) + weightedAverage(mGestureWeights); + return weightedAverage(strokes) + weightedAverage(gestureWeights); } private float weightedAverage(ArrayList list) { @@ -71,16 +70,16 @@ class HistoryEvaluator { private void decayValue() { long time = SystemClock.elapsedRealtime(); - if (time <= mLastUpdate) { + if (time <= lastUpdate) { return; } // All weights are multiplied by HISTORY_FACTOR after each INTERVAL milliseconds. - float factor = (float) Math.pow(HISTORY_FACTOR, (time - mLastUpdate) / INTERVAL); + float factor = (float) Math.pow(HISTORY_FACTOR, (time - lastUpdate) / INTERVAL); - decayValue(mStrokes, factor); - decayValue(mGestureWeights, factor); - mLastUpdate = time; + decayValue(strokes, factor); + decayValue(gestureWeights, factor); + lastUpdate = time; } private void decayValue(ArrayList list, float factor) { diff --git a/java/com/android/incallui/answer/impl/classifier/HumanInteractionClassifier.java b/java/com/android/incallui/answer/impl/classifier/HumanInteractionClassifier.java index 5e83dfc78..b661579a3 100644 --- a/java/com/android/incallui/answer/impl/classifier/HumanInteractionClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/HumanInteractionClassifier.java @@ -28,10 +28,10 @@ class HumanInteractionClassifier extends Classifier { private static final String CONFIG_ANSWER_FALSE_TOUCH_DETECTION_ENABLED = "answer_false_touch_detection_enabled"; - private final StrokeClassifier[] mStrokeClassifiers; - private final GestureClassifier[] mGestureClassifiers; - private final HistoryEvaluator mHistoryEvaluator; - private final boolean mEnabled; + private final StrokeClassifier[] strokeClassifiers; + private final GestureClassifier[] gestureClassifiers; + private final HistoryEvaluator historyEvaluator; + private final boolean enabled; HumanInteractionClassifier(Context context) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); @@ -41,28 +41,28 @@ class HumanInteractionClassifier extends Classifier { // take the average. // Note that xdpi and ydpi are the physical pixels per inch and are not affected by scaling. float dpi = (displayMetrics.xdpi + displayMetrics.ydpi) / 2.0f; - mClassifierData = new ClassifierData(dpi, displayMetrics.heightPixels); - mHistoryEvaluator = new HistoryEvaluator(); - mEnabled = + classifierData = new ClassifierData(dpi, displayMetrics.heightPixels); + historyEvaluator = new HistoryEvaluator(); + enabled = ConfigProviderBindings.get(context) .getBoolean(CONFIG_ANSWER_FALSE_TOUCH_DETECTION_ENABLED, true); - mStrokeClassifiers = + strokeClassifiers = new StrokeClassifier[] { - new AnglesClassifier(mClassifierData), - new SpeedClassifier(mClassifierData), - new DurationCountClassifier(mClassifierData), - new EndPointRatioClassifier(mClassifierData), - new EndPointLengthClassifier(mClassifierData), - new AccelerationClassifier(mClassifierData), - new SpeedAnglesClassifier(mClassifierData), - new LengthCountClassifier(mClassifierData), - new DirectionClassifier(mClassifierData) + new AnglesClassifier(classifierData), + new SpeedClassifier(classifierData), + new DurationCountClassifier(classifierData), + new EndPointRatioClassifier(classifierData), + new EndPointLengthClassifier(classifierData), + new AccelerationClassifier(classifierData), + new SpeedAnglesClassifier(classifierData), + new LengthCountClassifier(classifierData), + new DirectionClassifier(classifierData) }; - mGestureClassifiers = + gestureClassifiers = new GestureClassifier[] { - new PointerCountClassifier(mClassifierData), new ProximityClassifier(mClassifierData) + new PointerCountClassifier(classifierData), new ProximityClassifier(classifierData) }; } @@ -80,59 +80,59 @@ class HumanInteractionClassifier extends Classifier { } private void addTouchEvent(MotionEvent event) { - mClassifierData.update(event); + classifierData.update(event); - for (StrokeClassifier c : mStrokeClassifiers) { + for (StrokeClassifier c : strokeClassifiers) { c.onTouchEvent(event); } - for (GestureClassifier c : mGestureClassifiers) { + for (GestureClassifier c : gestureClassifiers) { c.onTouchEvent(event); } - int size = mClassifierData.getEndingStrokes().size(); + int size = classifierData.getEndingStrokes().size(); for (int i = 0; i < size; i++) { - Stroke stroke = mClassifierData.getEndingStrokes().get(i); + Stroke stroke = classifierData.getEndingStrokes().get(i); float evaluation = 0.0f; - for (StrokeClassifier c : mStrokeClassifiers) { + for (StrokeClassifier c : strokeClassifiers) { float e = c.getFalseTouchEvaluation(stroke); evaluation += e; } - mHistoryEvaluator.addStroke(evaluation); + historyEvaluator.addStroke(evaluation); } int action = event.getActionMasked(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { float evaluation = 0.0f; - for (GestureClassifier c : mGestureClassifiers) { + for (GestureClassifier c : gestureClassifiers) { float e = c.getFalseTouchEvaluation(); evaluation += e; } - mHistoryEvaluator.addGesture(evaluation); + historyEvaluator.addGesture(evaluation); } - mClassifierData.cleanUp(event); + classifierData.cleanUp(event); } @Override public void onSensorChanged(SensorEvent event) { - for (Classifier c : mStrokeClassifiers) { + for (Classifier c : strokeClassifiers) { c.onSensorChanged(event); } - for (Classifier c : mGestureClassifiers) { + for (Classifier c : gestureClassifiers) { c.onSensorChanged(event); } } boolean isFalseTouch() { - float evaluation = mHistoryEvaluator.getEvaluation(); + float evaluation = historyEvaluator.getEvaluation(); return evaluation >= 5.0f; } public boolean isEnabled() { - return mEnabled; + return enabled; } @Override diff --git a/java/com/android/incallui/answer/impl/classifier/PointerCountClassifier.java b/java/com/android/incallui/answer/impl/classifier/PointerCountClassifier.java index 070de6c9b..b3ee84984 100644 --- a/java/com/android/incallui/answer/impl/classifier/PointerCountClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/PointerCountClassifier.java @@ -20,10 +20,10 @@ import android.view.MotionEvent; /** A classifier which looks at the total number of traces in the whole gesture. */ class PointerCountClassifier extends GestureClassifier { - private int mCount; + private int count; public PointerCountClassifier(ClassifierData classifierData) { - mCount = 0; + count = 0; } @Override @@ -36,16 +36,16 @@ class PointerCountClassifier extends GestureClassifier { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mCount = 1; + count = 1; } if (action == MotionEvent.ACTION_POINTER_DOWN) { - ++mCount; + ++count; } } @Override public float getFalseTouchEvaluation() { - return PointerCountEvaluator.evaluate(mCount); + return PointerCountEvaluator.evaluate(count); } } diff --git a/java/com/android/incallui/answer/impl/classifier/ProximityClassifier.java b/java/com/android/incallui/answer/impl/classifier/ProximityClassifier.java index 28701ea6d..b63f15d53 100644 --- a/java/com/android/incallui/answer/impl/classifier/ProximityClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/ProximityClassifier.java @@ -26,11 +26,11 @@ import java.util.concurrent.TimeUnit; * the proximity sensor showing the near state during the whole gesture */ class ProximityClassifier extends GestureClassifier { - private long mGestureStartTimeNano; - private long mNearStartTimeNano; - private long mNearDuration; - private boolean mNear; - private float mAverageNear; + private long gestureStartTimeNano; + private long nearStartTimeNano; + private long nearDuration; + private boolean near; + private float averageNear; public ProximityClassifier(ClassifierData classifierData) {} @@ -51,19 +51,19 @@ class ProximityClassifier extends GestureClassifier { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mGestureStartTimeNano = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()); - mNearStartTimeNano = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()); - mNearDuration = 0; + gestureStartTimeNano = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()); + nearStartTimeNano = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()); + nearDuration = 0; } if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { - update(mNear, TimeUnit.MILLISECONDS.toNanos(event.getEventTime())); - long duration = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()) - mGestureStartTimeNano; + update(near, TimeUnit.MILLISECONDS.toNanos(event.getEventTime())); + long duration = TimeUnit.MILLISECONDS.toNanos(event.getEventTime()) - gestureStartTimeNano; if (duration == 0) { - mAverageNear = mNear ? 1.0f : 0.0f; + averageNear = near ? 1.0f : 0.0f; } else { - mAverageNear = (float) mNearDuration / (float) duration; + averageNear = (float) nearDuration / (float) duration; } } } @@ -75,23 +75,23 @@ class ProximityClassifier extends GestureClassifier { private void update(boolean near, long timestampNano) { // This if is necessary because MotionEvents and SensorEvents do not come in // chronological order - if (timestampNano > mNearStartTimeNano) { + if (timestampNano > nearStartTimeNano) { // if the state before was near then add the difference of the current time and // mNearStartTimeNano to mNearDuration. - if (mNear) { - mNearDuration += timestampNano - mNearStartTimeNano; + if (this.near) { + nearDuration += timestampNano - nearStartTimeNano; } // if the new state is near, set mNearStartTimeNano equal to this moment. if (near) { - mNearStartTimeNano = timestampNano; + nearStartTimeNano = timestampNano; } } - mNear = near; + this.near = near; } @Override public float getFalseTouchEvaluation() { - return ProximityEvaluator.evaluate(mAverageNear); + return ProximityEvaluator.evaluate(averageNear); } } diff --git a/java/com/android/incallui/answer/impl/classifier/SpeedAnglesClassifier.java b/java/com/android/incallui/answer/impl/classifier/SpeedAnglesClassifier.java index 36ae3ad7c..034c4fea3 100644 --- a/java/com/android/incallui/answer/impl/classifier/SpeedAnglesClassifier.java +++ b/java/com/android/incallui/answer/impl/classifier/SpeedAnglesClassifier.java @@ -33,10 +33,10 @@ import java.util.Map; * a good stroke is most often increases, so most of these angels should be in this interval. */ class SpeedAnglesClassifier extends StrokeClassifier { - private Map mStrokeMap = new ArrayMap<>(); + private Map strokeMap = new ArrayMap<>(); public SpeedAnglesClassifier(ClassifierData classifierData) { - mClassifierData = classifierData; + this.classifierData = classifierData; } @Override @@ -49,27 +49,27 @@ class SpeedAnglesClassifier extends StrokeClassifier { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { - mStrokeMap.clear(); + strokeMap.clear(); } for (int i = 0; i < event.getPointerCount(); i++) { - Stroke stroke = mClassifierData.getStroke(event.getPointerId(i)); + Stroke stroke = classifierData.getStroke(event.getPointerId(i)); - if (mStrokeMap.get(stroke) == null) { - mStrokeMap.put(stroke, new Data()); + if (strokeMap.get(stroke) == null) { + strokeMap.put(stroke, new Data()); } if (action != MotionEvent.ACTION_UP && action != MotionEvent.ACTION_CANCEL && !(action == MotionEvent.ACTION_POINTER_UP && i == event.getActionIndex())) { - mStrokeMap.get(stroke).addPoint(stroke.getPoints().get(stroke.getPoints().size() - 1)); + strokeMap.get(stroke).addPoint(stroke.getPoints().get(stroke.getPoints().size() - 1)); } } } @Override public float getFalseTouchEvaluation(Stroke stroke) { - Data data = mStrokeMap.get(stroke); + Data data = strokeMap.get(stroke); return SpeedVarianceEvaluator.evaluate(data.getAnglesVariance()) + SpeedAnglesPercentageEvaluator.evaluate(data.getAnglesPercentage()); } @@ -79,69 +79,69 @@ class SpeedAnglesClassifier extends StrokeClassifier { private static final float LENGTH_SCALE = 1.0f; private static final float ANGLE_DEVIATION = (float) Math.PI / 10.0f; - private List mLastThreePoints = new ArrayList<>(); - private Point mPreviousPoint; - private float mPreviousAngle; - private float mSumSquares; - private float mSum; - private float mCount; - private float mDist; - private float mAnglesCount; - private float mAcceleratingAngles; + private List lastThreePoints = new ArrayList<>(); + private Point previousPoint; + private float previousAngle; + private float sumSquares; + private float sum; + private float count; + private float dist; + private float anglesCount; + private float acceleratingAngles; public Data() { - mPreviousPoint = null; - mPreviousAngle = (float) Math.PI; - mSumSquares = 0.0f; - mSum = 0.0f; - mCount = 1.0f; - mDist = 0.0f; - mAnglesCount = mAcceleratingAngles = 0.0f; + previousPoint = null; + previousAngle = (float) Math.PI; + sumSquares = 0.0f; + sum = 0.0f; + count = 1.0f; + dist = 0.0f; + anglesCount = acceleratingAngles = 0.0f; } public void addPoint(Point point) { - if (mPreviousPoint != null) { - mDist += mPreviousPoint.dist(point); + if (previousPoint != null) { + dist += previousPoint.dist(point); } - mPreviousPoint = point; + previousPoint = point; Point speedPoint = - new Point((float) point.timeOffsetNano / DURATION_SCALE, mDist / LENGTH_SCALE); + new Point((float) point.timeOffsetNano / DURATION_SCALE, dist / LENGTH_SCALE); // Checking if the added point is different than the previously added point // Repetitions are being ignored so that proper angles are calculated. - if (mLastThreePoints.isEmpty() - || !mLastThreePoints.get(mLastThreePoints.size() - 1).equals(speedPoint)) { - mLastThreePoints.add(speedPoint); - if (mLastThreePoints.size() == 4) { - mLastThreePoints.remove(0); + if (lastThreePoints.isEmpty() + || !lastThreePoints.get(lastThreePoints.size() - 1).equals(speedPoint)) { + lastThreePoints.add(speedPoint); + if (lastThreePoints.size() == 4) { + lastThreePoints.remove(0); float angle = - mLastThreePoints.get(1).getAngle(mLastThreePoints.get(0), mLastThreePoints.get(2)); + lastThreePoints.get(1).getAngle(lastThreePoints.get(0), lastThreePoints.get(2)); - mAnglesCount++; + anglesCount++; if (angle >= (float) Math.PI - ANGLE_DEVIATION) { - mAcceleratingAngles++; + acceleratingAngles++; } - float difference = angle - mPreviousAngle; - mSum += difference; - mSumSquares += difference * difference; - mCount += 1.0f; - mPreviousAngle = angle; + float difference = angle - previousAngle; + sum += difference; + sumSquares += difference * difference; + count += 1.0f; + previousAngle = angle; } } } public float getAnglesVariance() { - return mSumSquares / mCount - (mSum / mCount) * (mSum / mCount); + return sumSquares / count - (sum / count) * (sum / count); } public float getAnglesPercentage() { - if (mAnglesCount == 0.0f) { + if (anglesCount == 0.0f) { return 1.0f; } - return (mAcceleratingAngles) / mAnglesCount; + return (acceleratingAngles) / anglesCount; } } } diff --git a/java/com/android/incallui/answer/impl/classifier/Stroke.java b/java/com/android/incallui/answer/impl/classifier/Stroke.java index c542d0f7c..a33424946 100644 --- a/java/com/android/incallui/answer/impl/classifier/Stroke.java +++ b/java/com/android/incallui/answer/impl/classifier/Stroke.java @@ -26,40 +26,40 @@ class Stroke { private static final float NANOS_TO_SECONDS = 1e9f; - private ArrayList mPoints = new ArrayList<>(); - private long mStartTimeNano; - private long mEndTimeNano; - private float mLength; - private final float mDpi; + private ArrayList points = new ArrayList<>(); + private long startTimeNano; + private long endTimeNano; + private float length; + private final float dpi; public Stroke(long eventTimeNano, float dpi) { - mDpi = dpi; - mStartTimeNano = mEndTimeNano = eventTimeNano; + this.dpi = dpi; + startTimeNano = endTimeNano = eventTimeNano; } public void addPoint(float x, float y, long eventTimeNano) { - mEndTimeNano = eventTimeNano; - Point point = new Point(x / mDpi, y / mDpi, eventTimeNano - mStartTimeNano); - if (!mPoints.isEmpty()) { - mLength += mPoints.get(mPoints.size() - 1).dist(point); + endTimeNano = eventTimeNano; + Point point = new Point(x / dpi, y / dpi, eventTimeNano - startTimeNano); + if (!points.isEmpty()) { + length += points.get(points.size() - 1).dist(point); } - mPoints.add(point); + points.add(point); } public int getCount() { - return mPoints.size(); + return points.size(); } public float getTotalLength() { - return mLength; + return length; } public float getEndPointLength() { - return mPoints.get(0).dist(mPoints.get(mPoints.size() - 1)); + return points.get(0).dist(points.get(points.size() - 1)); } public long getDurationNanos() { - return mEndTimeNano - mStartTimeNano; + return endTimeNano - startTimeNano; } public float getDurationSeconds() { @@ -67,6 +67,6 @@ class Stroke { } public ArrayList getPoints() { - return mPoints; + return points; } } diff --git a/java/com/android/incallui/answer/impl/utils/FlingAnimationUtils.java b/java/com/android/incallui/answer/impl/utils/FlingAnimationUtils.java index 3acb2a205..baec30819 100644 --- a/java/com/android/incallui/answer/impl/utils/FlingAnimationUtils.java +++ b/java/com/android/incallui/answer/impl/utils/FlingAnimationUtils.java @@ -41,7 +41,7 @@ public class FlingAnimationUtils { private float maxLengthSeconds; private float highVelocityPxPerSecond; - private AnimatorProperties mAnimatorProperties = new AnimatorProperties(); + private AnimatorProperties animatorProperties = new AnimatorProperties(); public FlingAnimationUtils(Context ctx, float maxLengthSeconds) { this.maxLengthSeconds = maxLengthSeconds; @@ -127,23 +127,23 @@ public class FlingAnimationUtils { float velAbs = Math.abs(velocity); float durationSeconds = LINEAR_OUT_SLOW_IN_START_GRADIENT * diff / velAbs; if (durationSeconds <= maxLengthSeconds) { - mAnimatorProperties.interpolator = linearOutSlowIn; + animatorProperties.interpolator = linearOutSlowIn; } else if (velAbs >= minVelocityPxPerSecond) { // Cross fade between fast-out-slow-in and linear interpolator with current velocity. durationSeconds = maxLengthSeconds; VelocityInterpolator velocityInterpolator = new VelocityInterpolator(durationSeconds, velAbs, diff); - mAnimatorProperties.interpolator = + animatorProperties.interpolator = new InterpolatorInterpolator(velocityInterpolator, linearOutSlowIn, linearOutSlowIn); } else { // Just use a normal interpolator which doesn't take the velocity into account. durationSeconds = maxLengthSeconds; - mAnimatorProperties.interpolator = Interpolators.FAST_OUT_SLOW_IN; + animatorProperties.interpolator = Interpolators.FAST_OUT_SLOW_IN; } - mAnimatorProperties.duration = (long) (durationSeconds * 1000); - return mAnimatorProperties; + animatorProperties.duration = (long) (durationSeconds * 1000); + return animatorProperties; } /** @@ -203,7 +203,7 @@ public class FlingAnimationUtils { Interpolator mLinearOutFasterIn = new PathInterpolator(0, 0, LINEAR_OUT_FASTER_IN_X2, y2); float durationSeconds = startGradient * diff / velAbs; if (durationSeconds <= maxLengthSeconds) { - mAnimatorProperties.interpolator = mLinearOutFasterIn; + animatorProperties.interpolator = mLinearOutFasterIn; } else if (velAbs >= minVelocityPxPerSecond) { // Cross fade between linear-out-faster-in and linear interpolator with current @@ -213,15 +213,15 @@ public class FlingAnimationUtils { new VelocityInterpolator(durationSeconds, velAbs, diff); InterpolatorInterpolator superInterpolator = new InterpolatorInterpolator(velocityInterpolator, mLinearOutFasterIn, linearOutSlowIn); - mAnimatorProperties.interpolator = superInterpolator; + animatorProperties.interpolator = superInterpolator; } else { // Just use a normal interpolator which doesn't take the velocity into account. durationSeconds = maxLengthSeconds; - mAnimatorProperties.interpolator = Interpolators.FAST_OUT_LINEAR_IN; + animatorProperties.interpolator = Interpolators.FAST_OUT_LINEAR_IN; } - mAnimatorProperties.duration = (long) (durationSeconds * 1000); - return mAnimatorProperties; + animatorProperties.duration = (long) (durationSeconds * 1000); + return animatorProperties; } /** @@ -246,42 +246,42 @@ public class FlingAnimationUtils { /** An interpolator which interpolates two interpolators with an interpolator. */ private static final class InterpolatorInterpolator implements Interpolator { - private Interpolator mInterpolator1; - private Interpolator mInterpolator2; - private Interpolator mCrossfader; + private Interpolator interpolator1; + private Interpolator interpolator2; + private Interpolator crossfader; InterpolatorInterpolator( Interpolator interpolator1, Interpolator interpolator2, Interpolator crossfader) { - mInterpolator1 = interpolator1; - mInterpolator2 = interpolator2; - mCrossfader = crossfader; + this.interpolator1 = interpolator1; + this.interpolator2 = interpolator2; + this.crossfader = crossfader; } @Override public float getInterpolation(float input) { - float t = mCrossfader.getInterpolation(input); - return (1 - t) * mInterpolator1.getInterpolation(input) - + t * mInterpolator2.getInterpolation(input); + float t = crossfader.getInterpolation(input); + return (1 - t) * interpolator1.getInterpolation(input) + + t * interpolator2.getInterpolation(input); } } /** An interpolator which interpolates with a fixed velocity. */ private static final class VelocityInterpolator implements Interpolator { - private float mDurationSeconds; - private float mVelocity; - private float mDiff; + private float durationSeconds; + private float velocity; + private float diff; private VelocityInterpolator(float durationSeconds, float velocity, float diff) { - mDurationSeconds = durationSeconds; - mVelocity = velocity; - mDiff = diff; + this.durationSeconds = durationSeconds; + this.velocity = velocity; + this.diff = diff; } @Override public float getInterpolation(float input) { - float time = input * mDurationSeconds; - return time * mVelocity / mDiff; + float time = input * durationSeconds; + return time * velocity / diff; } } diff --git a/java/com/android/incallui/baseui/BaseFragment.java b/java/com/android/incallui/baseui/BaseFragment.java index 58b8c6f8d..c1b614899 100644 --- a/java/com/android/incallui/baseui/BaseFragment.java +++ b/java/com/android/incallui/baseui/BaseFragment.java @@ -24,10 +24,10 @@ public abstract class BaseFragment, U extends Ui> extends private static final String KEY_FRAGMENT_HIDDEN = "key_fragment_hidden"; - private T mPresenter; + private T presenter; protected BaseFragment() { - mPresenter = createPresenter(); + presenter = createPresenter(); } public abstract T createPresenter(); @@ -40,20 +40,20 @@ public abstract class BaseFragment, U extends Ui> extends * @return The presenter associated with this fragment. */ public T getPresenter() { - return mPresenter; + return presenter; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - mPresenter.onUiReady(getUi()); + presenter.onUiReady(getUi()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { - mPresenter.onRestoreInstanceState(savedInstanceState); + presenter.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.getBoolean(KEY_FRAGMENT_HIDDEN)) { getFragmentManager().beginTransaction().hide(this).commit(); } @@ -63,13 +63,13 @@ public abstract class BaseFragment, U extends Ui> extends @Override public void onDestroyView() { super.onDestroyView(); - mPresenter.onUiDestroy(getUi()); + presenter.onUiDestroy(getUi()); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - mPresenter.onSaveInstanceState(outState); + presenter.onSaveInstanceState(outState); outState.putBoolean(KEY_FRAGMENT_HIDDEN, isHidden()); } } diff --git a/java/com/android/incallui/baseui/Presenter.java b/java/com/android/incallui/baseui/Presenter.java index 581ad47c7..e4df9382f 100644 --- a/java/com/android/incallui/baseui/Presenter.java +++ b/java/com/android/incallui/baseui/Presenter.java @@ -21,7 +21,7 @@ import android.os.Bundle; /** Base class for Presenters. */ public abstract class Presenter { - private U mUi; + private U ui; /** * Called after the UI view has been created. That is when fragment.onViewCreated() is called. @@ -29,13 +29,13 @@ public abstract class Presenter { * @param ui The Ui implementation that is now ready to be used. */ public void onUiReady(U ui) { - mUi = ui; + this.ui = ui; } /** Called when the UI view is destroyed in Fragment.onDestroyView(). */ public final void onUiDestroy(U ui) { onUiUnready(ui); - mUi = null; + this.ui = null; } /** @@ -49,6 +49,6 @@ public abstract class Presenter { public void onRestoreInstanceState(Bundle savedInstanceState) {} public U getUi() { - return mUi; + return ui; } } diff --git a/java/com/android/incallui/call/CallList.java b/java/com/android/incallui/call/CallList.java index 150b20e28..e5948084d 100644 --- a/java/com/android/incallui/call/CallList.java +++ b/java/com/android/incallui/call/CallList.java @@ -65,24 +65,24 @@ public class CallList implements DialerCallDelegate { private static final int EVENT_DISCONNECTED_TIMEOUT = 1; - private static CallList sInstance = new CallList(); + private static CallList instance = new CallList(); - private final Map mCallById = new ArrayMap<>(); - private final Map mCallByTelecomCall = new ArrayMap<>(); + private final Map callById = new ArrayMap<>(); + private final Map callByTelecomCall = new ArrayMap<>(); /** * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before * resizing, 1 means we only expect a single thread to access the map so make only a single shard */ - private final Set mListeners = + private final Set listeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private final Set mPendingDisconnectCalls = + private final Set pendingDisconnectCalls = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); - private UiListener mUiListeners; + private UiListener uiListeners; /** Handles the timeout for destroying disconnected calls. */ - private final Handler mHandler = + private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { @@ -107,12 +107,12 @@ public class CallList implements DialerCallDelegate { @VisibleForTesting public static void setCallListInstance(CallList callList) { - sInstance = callList; + instance = callList; } /** Static singleton accessor method. */ public static CallList getInstance() { - return sInstance; + return instance; } public void onCallAdded( @@ -125,8 +125,8 @@ public class CallList implements DialerCallDelegate { Logger.get(context) .logStartLatencyTimer(LoggingBindings.ON_CALL_ADDED_TO_ON_INCALL_UI_SHOWN_INCOMING); } - if (mUiListeners != null) { - mUiListeners.onCallAdded(); + if (uiListeners != null) { + uiListeners.onCallAdded(); } final DialerCall call = new DialerCall(context, this, telecomCall, latencyReport, true /* registerCallback */); @@ -257,7 +257,7 @@ public class CallList implements DialerCallDelegate { @Override public DialerCall getDialerCallFromTelecomCall(Call telecomCall) { - return mCallByTelecomCall.get(telecomCall); + return callByTelecomCall.get(telecomCall); } private void updateUserMarkedSpamStatus( @@ -301,8 +301,8 @@ public class CallList implements DialerCallDelegate { } public void onCallRemoved(Context context, android.telecom.Call telecomCall) { - if (mCallByTelecomCall.containsKey(telecomCall)) { - DialerCall call = mCallByTelecomCall.get(telecomCall); + if (callByTelecomCall.containsKey(telecomCall)) { + DialerCall call = callByTelecomCall.get(telecomCall); Assert.checkArgument(!call.isExternalCall()); EnrichedCallManager manager = EnrichedCallComponent.get(context).getEnrichedCallManager(); @@ -352,8 +352,8 @@ public class CallList implements DialerCallDelegate { */ public void onInternalCallMadeExternal(Context context, android.telecom.Call telecomCall) { - if (mCallByTelecomCall.containsKey(telecomCall)) { - DialerCall call = mCallByTelecomCall.get(telecomCall); + if (callByTelecomCall.containsKey(telecomCall)) { + DialerCall call = callByTelecomCall.get(telecomCall); // Don't log an already logged call. logCall() might be called multiple times // for the same call due to a bug. @@ -367,8 +367,8 @@ public class CallList implements DialerCallDelegate { // However, the call won't be disconnected in this case. Also, logic in updateCallInMap // would just re-add the call anyways. call.unregisterCallback(); - mCallById.remove(call.getId()); - mCallByTelecomCall.remove(telecomCall); + callById.remove(call.getId()); + callByTelecomCall.remove(telecomCall); } } @@ -379,7 +379,7 @@ public class CallList implements DialerCallDelegate { LogUtil.i("CallList.onIncoming", String.valueOf(call)); } - for (Listener listener : mListeners) { + for (Listener listener : listeners) { listener.onIncomingCall(call); } Trace.endSection(); @@ -388,19 +388,19 @@ public class CallList implements DialerCallDelegate { public void addListener(@NonNull Listener listener) { Objects.requireNonNull(listener); - mListeners.add(listener); + listeners.add(listener); // Let the listener know about the active calls immediately. listener.onCallListChange(this); } public void setUiListener(UiListener uiListener) { - mUiListeners = uiListener; + uiListeners = uiListener; } public void removeListener(@Nullable Listener listener) { if (listener != null) { - mListeners.remove(listener); + listeners.remove(listener); } } @@ -517,7 +517,7 @@ public class CallList implements DialerCallDelegate { * @return The first call with the upgrade to video state. */ public DialerCall getVideoUpgradeRequestCall() { - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { if (call.getVideoTech().getSessionModificationState() == SessionModificationState.RECEIVED_UPGRADE_TO_VIDEO_REQUEST) { return call; @@ -527,11 +527,11 @@ public class CallList implements DialerCallDelegate { } public DialerCall getCallById(String callId) { - return mCallById.get(callId); + return callById.get(callId); } public Collection getAllCalls() { - return mCallById.values(); + return callById.values(); } /** Returns first call found in the call map with the specified state. */ @@ -546,7 +546,7 @@ public class CallList implements DialerCallDelegate { public DialerCall getCallWithState(int state, int positionToFind) { DialerCall retval = null; int position = 0; - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { if (call.getState() == state) { if (position >= positionToFind) { retval = call; @@ -565,7 +565,7 @@ public class CallList implements DialerCallDelegate { * call) */ public boolean hasNonParentActiveOrBackgroundCall() { - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { if ((call.getState() == State.ACTIVE || call.getState() == State.ONHOLD || call.getState() == State.CONFERENCED) @@ -583,7 +583,7 @@ public class CallList implements DialerCallDelegate { * active calls, so this is relatively safe thing to do. */ public void clearOnDisconnect() { - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { final int state = call.getState(); if (state != DialerCall.State.IDLE && state != DialerCall.State.INVALID @@ -602,7 +602,7 @@ public class CallList implements DialerCallDelegate { * disconnect cause, and that any pending disconnects should immediately occur. */ public void onErrorDialogDismissed() { - final Iterator iterator = mPendingDisconnectCalls.iterator(); + final Iterator iterator = pendingDisconnectCalls.iterator(); while (iterator.hasNext()) { DialerCall call = iterator.next(); iterator.remove(); @@ -619,7 +619,7 @@ public class CallList implements DialerCallDelegate { void onUpdateCall(DialerCall call) { Trace.beginSection("CallList.onUpdateCall"); LogUtil.d("CallList.onUpdateCall", String.valueOf(call)); - if (!mCallById.containsKey(call.getId()) && call.isExternalCall()) { + if (!callById.containsKey(call.getId()) && call.isExternalCall()) { // When a regular call becomes external, it is removed from the call list, and there may be // pending updates to Telecom which are queued up on the Telecom call's handler which we no // longer wish to cause updates to the call in the CallList. Bail here if the list of tracked @@ -639,14 +639,14 @@ public class CallList implements DialerCallDelegate { */ private void notifyGenericListeners() { Trace.beginSection("CallList.notifyGenericListeners"); - for (Listener listener : mListeners) { + for (Listener listener : listeners) { listener.onCallListChange(this); } Trace.endSection(); } private void notifyListenersOfDisconnect(DialerCall call) { - for (Listener listener : mListeners) { + for (Listener listener : listeners) { listener.onDisconnect(call); } } @@ -664,26 +664,26 @@ public class CallList implements DialerCallDelegate { if (call.getState() == DialerCall.State.DISCONNECTED) { // update existing (but do not add!!) disconnected calls - if (mCallById.containsKey(call.getId())) { + if (callById.containsKey(call.getId())) { // For disconnected calls, we want to keep them alive for a few seconds so that the // UI has a chance to display anything it needs when a call is disconnected. // Set up a timer to destroy the call after X seconds. - final Message msg = mHandler.obtainMessage(EVENT_DISCONNECTED_TIMEOUT, call); - mHandler.sendMessageDelayed(msg, getDelayForDisconnect(call)); - mPendingDisconnectCalls.add(call); + final Message msg = handler.obtainMessage(EVENT_DISCONNECTED_TIMEOUT, call); + handler.sendMessageDelayed(msg, getDelayForDisconnect(call)); + pendingDisconnectCalls.add(call); - mCallById.put(call.getId(), call); - mCallByTelecomCall.put(call.getTelecomCall(), call); + callById.put(call.getId(), call); + callByTelecomCall.put(call.getTelecomCall(), call); updated = true; } } else if (!isCallDead(call)) { - mCallById.put(call.getId(), call); - mCallByTelecomCall.put(call.getTelecomCall(), call); + callById.put(call.getId(), call); + callByTelecomCall.put(call.getTelecomCall(), call); updated = true; - } else if (mCallById.containsKey(call.getId())) { - mCallById.remove(call.getId()); - mCallByTelecomCall.remove(call.getTelecomCall()); + } else if (callById.containsKey(call.getId())) { + callById.remove(call.getId()); + callByTelecomCall.remove(call.getTelecomCall()); updated = true; } @@ -727,8 +727,8 @@ public class CallList implements DialerCallDelegate { /** Sets up a call for deletion and notifies listeners of change. */ private void finishDisconnectedCall(DialerCall call) { - if (mPendingDisconnectCalls.contains(call)) { - mPendingDisconnectCalls.remove(call); + if (pendingDisconnectCalls.contains(call)) { + pendingDisconnectCalls.remove(call); } call.setState(DialerCall.State.IDLE); updateCallInMap(call); @@ -741,17 +741,17 @@ public class CallList implements DialerCallDelegate { * @param rotation The new rotation angle (in degrees). */ public void notifyCallsOfDeviceRotation(int rotation) { - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { call.getVideoTech().setDeviceOrientation(rotation); } } public void onInCallUiShown(boolean forFullScreenIntent) { - for (DialerCall call : mCallById.values()) { + for (DialerCall call : callById.values()) { call.getLatencyReport().onInCallUiShown(forFullScreenIntent); } - if (mUiListeners != null) { - mUiListeners.onInCallUiShown(); + if (uiListeners != null) { + uiListeners.onInCallUiShown(); } } @@ -813,25 +813,25 @@ public class CallList implements DialerCallDelegate { private class DialerCallListenerImpl implements DialerCallListener { - @NonNull private final DialerCall mCall; + @NonNull private final DialerCall call; DialerCallListenerImpl(@NonNull DialerCall call) { - mCall = Assert.isNotNull(call); + this.call = Assert.isNotNull(call); } @Override public void onDialerCallDisconnect() { - if (updateCallInMap(mCall)) { - LogUtil.i("DialerCallListenerImpl.onDialerCallDisconnect", String.valueOf(mCall)); + if (updateCallInMap(call)) { + LogUtil.i("DialerCallListenerImpl.onDialerCallDisconnect", String.valueOf(call)); // notify those listening for all disconnects - notifyListenersOfDisconnect(mCall); + notifyListenersOfDisconnect(call); } } @Override public void onDialerCallUpdate() { Trace.beginSection("CallList.onDialerCallUpdate"); - onUpdateCall(mCall); + onUpdateCall(call); notifyGenericListeners(); Trace.endSection(); } @@ -844,30 +844,30 @@ public class CallList implements DialerCallDelegate { @Override public void onDialerCallUpgradeToVideo() { - for (Listener listener : mListeners) { - listener.onUpgradeToVideo(mCall); + for (Listener listener : listeners) { + listener.onUpgradeToVideo(call); } } @Override public void onWiFiToLteHandover() { - for (Listener listener : mListeners) { - listener.onWiFiToLteHandover(mCall); + for (Listener listener : listeners) { + listener.onWiFiToLteHandover(call); } } @Override public void onHandoverToWifiFailure() { - for (Listener listener : mListeners) { - listener.onHandoverToWifiFailed(mCall); + for (Listener listener : listeners) { + listener.onHandoverToWifiFailed(call); } } @Override public void onInternationalCallOnWifi() { LogUtil.enterBlock("DialerCallListenerImpl.onInternationalCallOnWifi"); - for (Listener listener : mListeners) { - listener.onInternationalCallOnWifi(mCall); + for (Listener listener : listeners) { + listener.onInternationalCallOnWifi(call); } } @@ -876,8 +876,8 @@ public class CallList implements DialerCallDelegate { @Override public void onDialerCallSessionModificationStateChange() { - for (Listener listener : mListeners) { - listener.onSessionModificationStateChange(mCall); + for (Listener listener : listeners) { + listener.onSessionModificationStateChange(call); } } } diff --git a/java/com/android/incallui/call/DialerCall.java b/java/com/android/incallui/call/DialerCall.java index 94c79e904..543cc3f07 100644 --- a/java/com/android/incallui/call/DialerCall.java +++ b/java/com/android/incallui/call/DialerCall.java @@ -102,14 +102,14 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa private static final String ID_PREFIX = "DialerCall_"; private static final String CONFIG_EMERGENCY_CALLBACK_WINDOW_MILLIS = "emergency_callback_window_millis"; - private static int sIdCounter = 0; + private static int idCounter = 0; /** * A counter used to append to restricted/private/hidden calls so that users can identify them in * a conversation. This value is reset in {@link CallList#onCallRemoved(Context, Call)} when there * are no live calls. */ - private static int sHiddenCounter; + private static int hiddenCounter; /** * The unique call ID for every call. This will help us to identify each call and allow us the @@ -117,34 +117,34 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa */ private final String uniqueCallId = UUID.randomUUID().toString(); - private final Call mTelecomCall; - private final LatencyReport mLatencyReport; - private final String mId; - private final int mHiddenId; - private final List mChildCallIds = new ArrayList<>(); - private final LogState mLogState = new LogState(); - private final Context mContext; - private final DialerCallDelegate mDialerCallDelegate; - private final List mListeners = new CopyOnWriteArrayList<>(); - private final List mCannedTextResponsesLoadedListeners = + private final Call telecomCall; + private final LatencyReport latencyReport; + private final String id; + private final int hiddenId; + private final List childCallIds = new ArrayList<>(); + private final LogState logState = new LogState(); + private final Context context; + private final DialerCallDelegate dialerCallDelegate; + private final List listeners = new CopyOnWriteArrayList<>(); + private final List cannedTextResponsesLoadedListeners = new CopyOnWriteArrayList<>(); - private final VideoTechManager mVideoTechManager; + private final VideoTechManager videoTechManager; - private boolean mIsEmergencyCall; - private Uri mHandle; - private int mState = State.INVALID; - private DisconnectCause mDisconnectCause; + private boolean isEmergencyCall; + private Uri handle; + private int state = State.INVALID; + private DisconnectCause disconnectCause; private boolean hasShownWiFiToLteHandoverToast; private boolean doNotShowDialogForHandoffToWifiFailure; - private String mChildNumber; - private String mLastForwardedNumber; - private String mCallSubject; - private PhoneAccountHandle mPhoneAccountHandle; - @CallHistoryStatus private int mCallHistoryStatus = CALL_HISTORY_STATUS_UNKNOWN; - private boolean mIsSpam; - private boolean mIsBlocked; + private String childNumber; + private String lastForwardedNumber; + private String callSubject; + private PhoneAccountHandle phoneAccountHandle; + @CallHistoryStatus private int callHistoryStatus = CALL_HISTORY_STATUS_UNKNOWN; + private boolean isSpam; + private boolean isBlocked; @Nullable private Boolean isInUserSpamList; @@ -154,9 +154,9 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa private boolean didShowCameraPermission; private String callProviderLabel; private String callbackNumber; - private int mCameraDirection = CameraDirection.CAMERA_DIRECTION_UNKNOWN; - private EnrichedCallCapabilities mEnrichedCallCapabilities; - private Session mEnrichedCallSession; + private int cameraDirection = CameraDirection.CAMERA_DIRECTION_UNKNOWN; + private EnrichedCallCapabilities enrichedCallCapabilities; + private Session enrichedCallSession; private int answerAndReleaseButtonDisplayedTimes = 0; private boolean releasedByAnsweringSecondCall = false; @@ -188,9 +188,9 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa * Indicates whether the phone account associated with this call supports specifying a call * subject. */ - private boolean mIsCallSubjectSupported; + private boolean isCallSubjectSupported; - private final Call.Callback mTelecomCallCallback = + private final Call.Callback telecomCallCallback = new Call.Callback() { @Override public void onStateChanged(Call call, int newState) { @@ -222,7 +222,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa LogUtil.v( "TelecomCallCallback.onCannedTextResponsesLoaded", "call=" + call + " cannedTextResponses=" + cannedTextResponses); - for (CannedTextResponsesLoadedListener listener : mCannedTextResponsesLoadedListeners) { + for (CannedTextResponsesLoadedListener listener : cannedTextResponsesLoadedListeners) { listener.onCannedTextResponsesLoaded(DialerCall.this); } } @@ -301,7 +301,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } }; - private long mTimeAddedMs; + private long timeAddedMs; public DialerCall( Context context, @@ -310,27 +310,27 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa LatencyReport latencyReport, boolean registerCallback) { Assert.isNotNull(context); - mContext = context; - mDialerCallDelegate = dialerCallDelegate; - mTelecomCall = telecomCall; - mLatencyReport = latencyReport; - mId = ID_PREFIX + Integer.toString(sIdCounter++); + this.context = context; + this.dialerCallDelegate = dialerCallDelegate; + this.telecomCall = telecomCall; + this.latencyReport = latencyReport; + id = ID_PREFIX + Integer.toString(idCounter++); // Must be after assigning mTelecomCall - mVideoTechManager = new VideoTechManager(this); + videoTechManager = new VideoTechManager(this); updateFromTelecomCall(); if (isHiddenNumber() && TextUtils.isEmpty(getNumber())) { - mHiddenId = ++sHiddenCounter; + hiddenId = ++hiddenCounter; } else { - mHiddenId = 0; + hiddenId = 0; } if (registerCallback) { - mTelecomCall.registerCallback(mTelecomCallCallback); + this.telecomCall.registerCallback(telecomCallCallback); } - mTimeAddedMs = System.currentTimeMillis(); + timeAddedMs = System.currentTimeMillis(); parseCallSpecificAppData(); updateEnrichedCallSession(); @@ -339,13 +339,13 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa /** Test only constructor to avoid initializing dependencies. */ @VisibleForTesting DialerCall(Context context) { - mContext = context; - mTelecomCall = null; - mLatencyReport = null; - mId = null; - mHiddenId = 0; - mDialerCallDelegate = null; - mVideoTechManager = null; + this.context = context; + telecomCall = null; + latencyReport = null; + id = null; + hiddenId = 0; + dialerCallDelegate = null; + videoTechManager = null; } private static int translateState(int state) { @@ -398,68 +398,68 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa public void addListener(DialerCallListener listener) { Assert.isMainThread(); - mListeners.add(listener); + listeners.add(listener); } public void removeListener(DialerCallListener listener) { Assert.isMainThread(); - mListeners.remove(listener); + listeners.remove(listener); } public void addCannedTextResponsesLoadedListener(CannedTextResponsesLoadedListener listener) { Assert.isMainThread(); - mCannedTextResponsesLoadedListeners.add(listener); + cannedTextResponsesLoadedListeners.add(listener); } public void removeCannedTextResponsesLoadedListener(CannedTextResponsesLoadedListener listener) { Assert.isMainThread(); - mCannedTextResponsesLoadedListeners.remove(listener); + cannedTextResponsesLoadedListeners.remove(listener); } public void notifyWiFiToLteHandover() { LogUtil.i("DialerCall.notifyWiFiToLteHandover", ""); - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onWiFiToLteHandover(); } } public void notifyHandoverToWifiFailed() { LogUtil.i("DialerCall.notifyHandoverToWifiFailed", ""); - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onHandoverToWifiFailure(); } } public void notifyInternationalCallOnWifi() { LogUtil.enterBlock("DialerCall.notifyInternationalCallOnWifi"); - for (DialerCallListener dialerCallListener : mListeners) { + for (DialerCallListener dialerCallListener : listeners) { dialerCallListener.onInternationalCallOnWifi(); } } /* package-private */ Call getTelecomCall() { - return mTelecomCall; + return telecomCall; } public StatusHints getStatusHints() { - return mTelecomCall.getDetails().getStatusHints(); + return telecomCall.getDetails().getStatusHints(); } public int getCameraDir() { - return mCameraDirection; + return cameraDirection; } public void setCameraDir(int cameraDir) { if (cameraDir == CameraDirection.CAMERA_DIRECTION_FRONT_FACING || cameraDir == CameraDirection.CAMERA_DIRECTION_BACK_FACING) { - mCameraDirection = cameraDir; + cameraDirection = cameraDir; } else { - mCameraDirection = CameraDirection.CAMERA_DIRECTION_UNKNOWN; + cameraDirection = CameraDirection.CAMERA_DIRECTION_UNKNOWN; } } public boolean wasParentCall() { - return mLogState.conferencedCalls != 0; + return logState.conferencedCalls != 0; } public boolean isVoiceMailNumber() { @@ -479,11 +479,11 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa isVoicemailNumber = true; } - if (!PermissionsUtil.hasPermission(mContext, permission.READ_PHONE_STATE)) { + if (!PermissionsUtil.hasPermission(context, permission.READ_PHONE_STATE)) { isVoicemailNumber = false; } - isVoicemailNumber = TelecomUtil.isVoicemailNumber(mContext, getAccountHandle(), getNumber()); + isVoicemailNumber = TelecomUtil.isVoicemailNumber(context, getAccountHandle(), getNumber()); } private void update() { @@ -494,17 +494,17 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa // We want to potentially register a video call callback here. updateFromTelecomCall(); if (oldState != getState() && getState() == DialerCall.State.DISCONNECTED) { - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onDialerCallDisconnect(); } - EnrichedCallComponent.get(mContext) + EnrichedCallComponent.get(context) .getEnrichedCallManager() .unregisterCapabilitiesListener(this); - EnrichedCallComponent.get(mContext) + EnrichedCallComponent.get(context) .getEnrichedCallManager() .unregisterStateChangedListener(this); } else { - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onDialerCallUpdate(); } } @@ -514,58 +514,58 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @SuppressWarnings("MissingPermission") private void updateFromTelecomCall() { Trace.beginSection("DialerCall.updateFromTelecomCall"); - LogUtil.v("DialerCall.updateFromTelecomCall", mTelecomCall.toString()); + LogUtil.v("DialerCall.updateFromTelecomCall", telecomCall.toString()); - mVideoTechManager.dispatchCallStateChanged(mTelecomCall.getState()); + videoTechManager.dispatchCallStateChanged(telecomCall.getState()); - final int translatedState = translateState(mTelecomCall.getState()); - if (mState != State.BLOCKED) { + final int translatedState = translateState(telecomCall.getState()); + if (state != State.BLOCKED) { setState(translatedState); - setDisconnectCause(mTelecomCall.getDetails().getDisconnectCause()); + setDisconnectCause(telecomCall.getDetails().getDisconnectCause()); } - mChildCallIds.clear(); - final int numChildCalls = mTelecomCall.getChildren().size(); + childCallIds.clear(); + final int numChildCalls = telecomCall.getChildren().size(); for (int i = 0; i < numChildCalls; i++) { - mChildCallIds.add( - mDialerCallDelegate - .getDialerCallFromTelecomCall(mTelecomCall.getChildren().get(i)) + childCallIds.add( + dialerCallDelegate + .getDialerCallFromTelecomCall(telecomCall.getChildren().get(i)) .getId()); } // The number of conferenced calls can change over the course of the call, so use the // maximum number of conferenced child calls as the metric for conference call usage. - mLogState.conferencedCalls = Math.max(numChildCalls, mLogState.conferencedCalls); + logState.conferencedCalls = Math.max(numChildCalls, logState.conferencedCalls); - updateFromCallExtras(mTelecomCall.getDetails().getExtras()); + updateFromCallExtras(telecomCall.getDetails().getExtras()); // If the handle of the call has changed, update state for the call determining if it is an // emergency call. - Uri newHandle = mTelecomCall.getDetails().getHandle(); - if (!Objects.equals(mHandle, newHandle)) { - mHandle = newHandle; + Uri newHandle = telecomCall.getDetails().getHandle(); + if (!Objects.equals(handle, newHandle)) { + handle = newHandle; updateEmergencyCallState(); } - TelecomManager telecomManager = mContext.getSystemService(TelecomManager.class); + TelecomManager telecomManager = context.getSystemService(TelecomManager.class); // If the phone account handle of the call is set, cache capability bit indicating whether // the phone account supports call subjects. - PhoneAccountHandle newPhoneAccountHandle = mTelecomCall.getDetails().getAccountHandle(); - if (!Objects.equals(mPhoneAccountHandle, newPhoneAccountHandle)) { - mPhoneAccountHandle = newPhoneAccountHandle; + PhoneAccountHandle newPhoneAccountHandle = telecomCall.getDetails().getAccountHandle(); + if (!Objects.equals(phoneAccountHandle, newPhoneAccountHandle)) { + phoneAccountHandle = newPhoneAccountHandle; - if (mPhoneAccountHandle != null) { - PhoneAccount phoneAccount = telecomManager.getPhoneAccount(mPhoneAccountHandle); + if (phoneAccountHandle != null) { + PhoneAccount phoneAccount = telecomManager.getPhoneAccount(phoneAccountHandle); if (phoneAccount != null) { - mIsCallSubjectSupported = + isCallSubjectSupported = phoneAccount.hasCapabilities(PhoneAccount.CAPABILITY_CALL_SUBJECT); } } } - if (PermissionsUtil.hasPermission(mContext, permission.READ_PHONE_STATE)) { + if (PermissionsUtil.hasPermission(context, permission.READ_PHONE_STATE)) { updateIsVoiceMailNumber(); callCapableAccounts = telecomManager.getCallCapablePhoneAccounts(); - countryIso = GeoUtil.getCurrentCountryIso(mContext); + countryIso = GeoUtil.getCurrentCountryIso(context); } Trace.endSection(); } @@ -605,9 +605,9 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa // Check for a change in the child address and notify any listeners. if (callExtras.containsKey(Connection.EXTRA_CHILD_ADDRESS)) { String childNumber = callExtras.getString(Connection.EXTRA_CHILD_ADDRESS); - if (!Objects.equals(childNumber, mChildNumber)) { - mChildNumber = childNumber; - for (DialerCallListener listener : mListeners) { + if (!Objects.equals(childNumber, this.childNumber)) { + this.childNumber = childNumber; + for (DialerCallListener listener : listeners) { listener.onDialerCallChildNumberChange(); } } @@ -626,9 +626,9 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa lastForwardedNumber = lastForwardedNumbers.get(lastForwardedNumbers.size() - 1); } - if (!Objects.equals(lastForwardedNumber, mLastForwardedNumber)) { - mLastForwardedNumber = lastForwardedNumber; - for (DialerCallListener listener : mListeners) { + if (!Objects.equals(lastForwardedNumber, this.lastForwardedNumber)) { + this.lastForwardedNumber = lastForwardedNumber; + for (DialerCallListener listener : listeners) { listener.onDialerCallLastForwardedNumberChange(); } } @@ -639,14 +639,14 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa // notify any other listeners of this. if (callExtras.containsKey(Connection.EXTRA_CALL_SUBJECT)) { String callSubject = callExtras.getString(Connection.EXTRA_CALL_SUBJECT); - if (!Objects.equals(mCallSubject, callSubject)) { - mCallSubject = callSubject; + if (!Objects.equals(this.callSubject, callSubject)) { + this.callSubject = callSubject; } } } public String getId() { - return mId; + return id; } /** @@ -655,14 +655,14 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa */ @Nullable public String updateNameIfRestricted(@Nullable String name) { - if (name != null && isHiddenNumber() && mHiddenId != 0 && sHiddenCounter > 1) { - return mContext.getString(R.string.unknown_counter, name, mHiddenId); + if (name != null && isHiddenNumber() && hiddenId != 0 && hiddenCounter > 1) { + return context.getString(R.string.unknown_counter, name, hiddenId); } return name; } public static void clearRestrictedCount() { - sHiddenCounter = 0; + hiddenCounter = 0; } private boolean isHiddenNumber() { @@ -687,26 +687,26 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } public long getTimeAddedMs() { - return mTimeAddedMs; + return timeAddedMs; } @Nullable public String getNumber() { - return TelecomCallUtil.getNumber(mTelecomCall); + return TelecomCallUtil.getNumber(telecomCall); } public void blockCall() { - mTelecomCall.reject(false, null); + telecomCall.reject(false, null); setState(State.BLOCKED); } @Nullable public Uri getHandle() { - return mTelecomCall == null ? null : mTelecomCall.getDetails().getHandle(); + return telecomCall == null ? null : telecomCall.getDetails().getHandle(); } public boolean isEmergencyCall() { - return mIsEmergencyCall; + return isEmergencyCall; } public boolean isPotentialEmergencyCallback() { @@ -731,78 +731,78 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa boolean isInEmergencyCallbackWindow(long timestampMillis) { long emergencyCallbackWindowMillis = - ConfigProviderBindings.get(mContext) + ConfigProviderBindings.get(context) .getLong(CONFIG_EMERGENCY_CALLBACK_WINDOW_MILLIS, TimeUnit.MINUTES.toMillis(5)); return System.currentTimeMillis() - timestampMillis < emergencyCallbackWindowMillis; } public int getState() { - if (mTelecomCall != null && mTelecomCall.getParent() != null) { + if (telecomCall != null && telecomCall.getParent() != null) { return State.CONFERENCED; } else { - return mState; + return state; } } public int getNonConferenceState() { - return mState; + return state; } public void setState(int state) { if (state == State.INCOMING) { - mLogState.isIncoming = true; + logState.isIncoming = true; } else if (state == State.DISCONNECTED) { long newDuration = getConnectTimeMillis() == 0 ? 0 : System.currentTimeMillis() - getConnectTimeMillis(); - if (mState != state) { - mLogState.duration = newDuration; + if (this.state != state) { + logState.duration = newDuration; } else { LogUtil.i( "DialerCall.setState", "ignoring state transition from DISCONNECTED to DISCONNECTED." + " Duration would have changed from %s to %s", - mLogState.duration, + logState.duration, newDuration); } } - mState = state; + this.state = state; } public int getNumberPresentation() { - return mTelecomCall == null ? -1 : mTelecomCall.getDetails().getHandlePresentation(); + return telecomCall == null ? -1 : telecomCall.getDetails().getHandlePresentation(); } public int getCnapNamePresentation() { - return mTelecomCall == null ? -1 : mTelecomCall.getDetails().getCallerDisplayNamePresentation(); + return telecomCall == null ? -1 : telecomCall.getDetails().getCallerDisplayNamePresentation(); } @Nullable public String getCnapName() { - return mTelecomCall == null ? null : getTelecomCall().getDetails().getCallerDisplayName(); + return telecomCall == null ? null : getTelecomCall().getDetails().getCallerDisplayName(); } public Bundle getIntentExtras() { - return mTelecomCall.getDetails().getIntentExtras(); + return telecomCall.getDetails().getIntentExtras(); } @Nullable public Bundle getExtras() { - return mTelecomCall == null ? null : mTelecomCall.getDetails().getExtras(); + return telecomCall == null ? null : telecomCall.getDetails().getExtras(); } /** @return The child number for the call, or {@code null} if none specified. */ public String getChildNumber() { - return mChildNumber; + return childNumber; } /** @return The last forwarded number for the call, or {@code null} if none specified. */ public String getLastForwardedNumber() { - return mLastForwardedNumber; + return lastForwardedNumber; } /** @return The call subject, or {@code null} if none specified. */ public String getCallSubject() { - return mCallSubject; + return callSubject; } /** @@ -810,36 +810,36 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa * otherwise. */ public boolean isCallSubjectSupported() { - return mIsCallSubjectSupported; + return isCallSubjectSupported; } /** Returns call disconnect cause, defined by {@link DisconnectCause}. */ public DisconnectCause getDisconnectCause() { - if (mState == State.DISCONNECTED || mState == State.IDLE) { - return mDisconnectCause; + if (state == State.DISCONNECTED || state == State.IDLE) { + return disconnectCause; } return new DisconnectCause(DisconnectCause.UNKNOWN); } public void setDisconnectCause(DisconnectCause disconnectCause) { - mDisconnectCause = disconnectCause; - mLogState.disconnectCause = mDisconnectCause; + this.disconnectCause = disconnectCause; + logState.disconnectCause = this.disconnectCause; } /** Returns the possible text message responses. */ public List getCannedSmsResponses() { - return mTelecomCall.getCannedTextResponses(); + return telecomCall.getCannedTextResponses(); } /** Checks if the call supports the given set of capabilities supplied as a bit mask. */ public boolean can(int capabilities) { - int supportedCapabilities = mTelecomCall.getDetails().getCallCapabilities(); + int supportedCapabilities = telecomCall.getDetails().getCallCapabilities(); if ((capabilities & Call.Details.CAPABILITY_MERGE_CONFERENCE) != 0) { // We allow you to merge if the capabilities allow it or if it is a call with // conferenceable calls. - if (mTelecomCall.getConferenceableCalls().isEmpty() + if (telecomCall.getConferenceableCalls().isEmpty() && ((Call.Details.CAPABILITY_MERGE_CONFERENCE & supportedCapabilities) == 0)) { // Cannot merge calls if there are no calls to merge with. return false; @@ -850,7 +850,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } public boolean hasProperty(int property) { - return mTelecomCall.getDetails().hasProperty(property); + return telecomCall.getDetails().hasProperty(property); } @NonNull @@ -860,7 +860,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa /** Gets the time when the call first became active. */ public long getConnectTimeMillis() { - return mTelecomCall.getDetails().getConnectTimeMillis(); + return telecomCall.getDetails().getConnectTimeMillis(); } public boolean isConferenceCall() { @@ -869,33 +869,33 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @Nullable public GatewayInfo getGatewayInfo() { - return mTelecomCall == null ? null : mTelecomCall.getDetails().getGatewayInfo(); + return telecomCall == null ? null : telecomCall.getDetails().getGatewayInfo(); } @Nullable public PhoneAccountHandle getAccountHandle() { - return mTelecomCall == null ? null : mTelecomCall.getDetails().getAccountHandle(); + return telecomCall == null ? null : telecomCall.getDetails().getAccountHandle(); } /** @return The {@link VideoCall} instance associated with the {@link Call}. */ public VideoCall getVideoCall() { - return mTelecomCall == null ? null : mTelecomCall.getVideoCall(); + return telecomCall == null ? null : telecomCall.getVideoCall(); } public List getChildCallIds() { - return mChildCallIds; + return childCallIds; } public String getParentId() { - Call parentCall = mTelecomCall.getParent(); + Call parentCall = telecomCall.getParent(); if (parentCall != null) { - return mDialerCallDelegate.getDialerCallFromTelecomCall(parentCall).getId(); + return dialerCallDelegate.getDialerCallFromTelecomCall(parentCall).getId(); } return null; } public int getVideoState() { - return mTelecomCall.getDetails().getVideoState(); + return telecomCall.getDetails().getVideoState(); } public boolean isVideoCall() { @@ -915,11 +915,11 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa * repeated calls to isEmergencyNumber. */ private void updateEmergencyCallState() { - mIsEmergencyCall = TelecomCallUtil.isEmergencyCall(mTelecomCall); + isEmergencyCall = TelecomCallUtil.isEmergencyCall(telecomCall); } public LogState getLogState() { - return mLogState; + return logState; } /** @@ -957,17 +957,17 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa return; } - mLogState.callSpecificAppData = CallIntentParser.getCallSpecificAppData(getIntentExtras()); - if (mLogState.callSpecificAppData == null) { + logState.callSpecificAppData = CallIntentParser.getCallSpecificAppData(getIntentExtras()); + if (logState.callSpecificAppData == null) { - mLogState.callSpecificAppData = + logState.callSpecificAppData = CallSpecificAppData.newBuilder() .setCallInitiationType(CallInitiationType.Type.EXTERNAL_INITIATION) .build(); } if (getState() == State.INCOMING) { - mLogState.callSpecificAppData = - mLogState + logState.callSpecificAppData = + logState .callSpecificAppData .toBuilder() .setCallInitiationType(CallInitiationType.Type.INCOMING_INITIATION) @@ -977,24 +977,24 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @Override public String toString() { - if (mTelecomCall == null) { + if (telecomCall == null) { // This should happen only in testing since otherwise we would never have a null // Telecom call. - return String.valueOf(mId); + return String.valueOf(id); } return String.format( Locale.US, "[%s, %s, %s, %s, children:%s, parent:%s, " + "conferenceable:%s, videoState:%s, mSessionModificationState:%d, CameraDir:%s]", - mId, + id, State.toString(getState()), - Details.capabilitiesToString(mTelecomCall.getDetails().getCallCapabilities()), - Details.propertiesToString(mTelecomCall.getDetails().getCallProperties()), - mChildCallIds, + Details.capabilitiesToString(telecomCall.getDetails().getCallCapabilities()), + Details.propertiesToString(telecomCall.getDetails().getCallProperties()), + childCallIds, getParentId(), - this.mTelecomCall.getConferenceableCalls(), - VideoProfile.videoStateToString(mTelecomCall.getDetails().getVideoState()), + this.telecomCall.getConferenceableCalls(), + VideoProfile.videoStateToString(telecomCall.getDetails().getVideoState()), getVideoTech().getSessionModificationState(), getCameraDir()); } @@ -1005,11 +1005,11 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @CallHistoryStatus public int getCallHistoryStatus() { - return mCallHistoryStatus; + return callHistoryStatus; } public void setCallHistoryStatus(@CallHistoryStatus int callHistoryStatus) { - mCallHistoryStatus = callHistoryStatus; + this.callHistoryStatus = callHistoryStatus; } public boolean didShowCameraPermission() { @@ -1048,19 +1048,19 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } public boolean isSpam() { - return mIsSpam; + return isSpam; } public void setSpam(boolean isSpam) { - mIsSpam = isSpam; + this.isSpam = isSpam; } public boolean isBlocked() { - return mIsBlocked; + return isBlocked; } public void setBlockedStatus(boolean isBlocked) { - mIsBlocked = isBlocked; + this.isBlocked = isBlocked; } public boolean isRemotelyHeld() { @@ -1072,7 +1072,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } public boolean isIncoming() { - return mLogState.isIncoming; + return logState.isIncoming; } /** @@ -1122,7 +1122,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } public LatencyReport getLatencyReport() { - return mLatencyReport; + return latencyReport; } public int getAnswerAndReleaseButtonDisplayedTimes() { @@ -1151,25 +1151,25 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @Nullable public EnrichedCallCapabilities getEnrichedCallCapabilities() { - return mEnrichedCallCapabilities; + return enrichedCallCapabilities; } public void setEnrichedCallCapabilities( @Nullable EnrichedCallCapabilities mEnrichedCallCapabilities) { - this.mEnrichedCallCapabilities = mEnrichedCallCapabilities; + this.enrichedCallCapabilities = mEnrichedCallCapabilities; } @Nullable public Session getEnrichedCallSession() { - return mEnrichedCallSession; + return enrichedCallSession; } public void setEnrichedCallSession(@Nullable Session mEnrichedCallSession) { - this.mEnrichedCallSession = mEnrichedCallSession; + this.enrichedCallSession = mEnrichedCallSession; } public void unregisterCallback() { - mTelecomCall.unregisterCallback(mTelecomCallCallback); + telecomCall.unregisterCallback(telecomCallCallback); } public void phoneAccountSelected(PhoneAccountHandle accountHandle, boolean setDefault) { @@ -1178,45 +1178,45 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa "accountHandle: %s, setDefault: %b", accountHandle, setDefault); - mTelecomCall.phoneAccountSelected(accountHandle, setDefault); + telecomCall.phoneAccountSelected(accountHandle, setDefault); } public void disconnect() { LogUtil.i("DialerCall.disconnect", ""); setState(DialerCall.State.DISCONNECTING); - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onDialerCallUpdate(); } - mTelecomCall.disconnect(); + telecomCall.disconnect(); } public void hold() { LogUtil.i("DialerCall.hold", ""); - mTelecomCall.hold(); + telecomCall.hold(); } public void unhold() { LogUtil.i("DialerCall.unhold", ""); - mTelecomCall.unhold(); + telecomCall.unhold(); } public void splitFromConference() { LogUtil.i("DialerCall.splitFromConference", ""); - mTelecomCall.splitFromConference(); + telecomCall.splitFromConference(); } public void answer(int videoState) { LogUtil.i("DialerCall.answer", "videoState: " + videoState); - mTelecomCall.answer(videoState); + telecomCall.answer(videoState); } public void answer() { - answer(mTelecomCall.getDetails().getVideoState()); + answer(telecomCall.getDetails().getVideoState()); } public void reject(boolean rejectWithMessage, String message) { LogUtil.i("DialerCall.reject", ""); - mTelecomCall.reject(rejectWithMessage, message); + telecomCall.reject(rejectWithMessage, message); } /** Return the string label to represent the call provider */ @@ -1240,12 +1240,12 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa if (accountHandle == null) { return null; } - return mContext.getSystemService(TelecomManager.class).getPhoneAccount(accountHandle); + return context.getSystemService(TelecomManager.class).getPhoneAccount(accountHandle); } public VideoTech getVideoTech() { if (videoTech == null) { - videoTech = mVideoTechManager.getVideoTech(); + videoTech = videoTechManager.getVideoTech(); // Only store the first video tech type found to be available during the life of the call. if (selectedAvailableVideoTechType == com.android.dialer.logging.VideoTech.Type.NONE) { @@ -1266,7 +1266,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa if (isEmergencyCall() || showCallbackNumber) { callbackNumber = - mContext.getSystemService(TelecomManager.class).getLine1Number(getAccountHandle()); + context.getSystemService(TelecomManager.class).getLine1Number(getAccountHandle()); } if (callbackNumber == null) { @@ -1278,8 +1278,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa public String getSimCountryIso() { String simCountryIso = - TelephonyManagerCompat.getTelephonyManagerForPhoneAccountHandle( - mContext, getAccountHandle()) + TelephonyManagerCompat.getTelephonyManagerForPhoneAccountHandle(context, getAccountHandle()) .getSimCountryIso(); if (!TextUtils.isEmpty(simCountryIso)) { simCountryIso = simCountryIso.toUpperCase(Locale.US); @@ -1295,7 +1294,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @Override public void onSessionModificationStateChanged() { Trace.beginSection("DialerCall.onSessionModificationStateChanged"); - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onDialerCallSessionModificationStateChange(); } Trace.endSection(); @@ -1315,13 +1314,13 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa public void onVideoUpgradeRequestReceived() { LogUtil.enterBlock("DialerCall.onVideoUpgradeRequestReceived"); - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onDialerCallUpgradeToVideo(); } update(); - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.VIDEO_CALL_REQUEST_RECEIVED, getUniqueCallId(), getTimeAddedMs()); } @@ -1356,7 +1355,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa return; } EnrichedCallCapabilities capabilities = - EnrichedCallComponent.get(mContext).getEnrichedCallManager().getCapabilities(getNumber()); + EnrichedCallComponent.get(context).getEnrichedCallManager().getCapabilities(getNumber()); if (capabilities != null) { setEnrichedCallCapabilities(capabilities); update(); @@ -1370,10 +1369,10 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa @Override public void onImpressionLoggingNeeded(DialerImpression.Type impressionType) { - Logger.get(mContext).logCallImpression(impressionType, getUniqueCallId(), getTimeAddedMs()); + Logger.get(context).logCallImpression(impressionType, getUniqueCallId(), getTimeAddedMs()); if (impressionType == DialerImpression.Type.LIGHTBRINGER_UPGRADE_REQUESTED) { if (getLogState().contactLookupResult == Type.NOT_FOUND) { - Logger.get(mContext) + Logger.get(context) .logCallImpression( DialerImpression.Type.LIGHTBRINGER_NON_CONTACT_UPGRADE_REQUESTED, getUniqueCallId(), @@ -1394,7 +1393,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa return; } - EnrichedCallManager manager = EnrichedCallComponent.get(mContext).getEnrichedCallManager(); + EnrichedCallManager manager = EnrichedCallComponent.get(context).getEnrichedCallManager(); Filter filter = isIncoming() @@ -1419,14 +1418,14 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa } private void dispatchOnEnrichedCallSessionUpdate() { - for (DialerCallListener listener : mListeners) { + for (DialerCallListener listener : listeners) { listener.onEnrichedCallSessionUpdate(); } } void onRemovedFromCallList() { // Ensure we clean up when this call is removed. - mVideoTechManager.dispatchRemovedFromCallList(); + videoTechManager.dispatchRemovedFromCallList(); } public com.android.dialer.logging.VideoTech.Type getSelectedAvailableVideoTechType() { @@ -1630,7 +1629,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa private VideoTech savedTech; VideoTechManager(DialerCall call) { - this.context = call.mContext; + this.context = call.context; String phoneNumber = call.getNumber(); phoneNumber = phoneNumber != null ? phoneNumber : ""; @@ -1639,13 +1638,13 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa // Insert order here determines the priority of that video tech option videoTechs = new ArrayList<>(); - videoTechs.add(new ImsVideoTech(Logger.get(call.mContext), call, call.mTelecomCall)); + videoTechs.add(new ImsVideoTech(Logger.get(call.context), call, call.telecomCall)); VideoTech rcsVideoTech = - EnrichedCallComponent.get(call.mContext) + EnrichedCallComponent.get(call.context) .getRcsVideoShareFactory() .newRcsVideoShare( - EnrichedCallComponent.get(call.mContext).getEnrichedCallManager(), + EnrichedCallComponent.get(call.context).getEnrichedCallManager(), call, phoneNumber); if (rcsVideoTech != null) { @@ -1654,7 +1653,7 @@ public class DialerCall implements VideoTechListener, StateChangedListener, Capa videoTechs.add( new DuoVideoTech( - DuoComponent.get(call.mContext).getDuo(), call, call.mTelecomCall, phoneNumber)); + DuoComponent.get(call.context).getDuo(), call, call.telecomCall, phoneNumber)); } VideoTech getVideoTech() { diff --git a/java/com/android/incallui/call/ExternalCallList.java b/java/com/android/incallui/call/ExternalCallList.java index f104dfe9f..603ebf7b8 100644 --- a/java/com/android/incallui/call/ExternalCallList.java +++ b/java/com/android/incallui/call/ExternalCallList.java @@ -35,11 +35,11 @@ import java.util.concurrent.ConcurrentHashMap; */ public class ExternalCallList { - private final Set mExternalCalls = new ArraySet<>(); - private final Set mExternalCallListeners = + private final Set externalCalls = new ArraySet<>(); + private final Set externalCallListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); /** Handles {@link android.telecom.Call.Callback} callbacks. */ - private final Call.Callback mTelecomCallCallback = + private final Call.Callback telecomCallCallback = new Call.Callback() { @Override public void onDetailsChanged(Call call, Call.Details details) { @@ -51,52 +51,52 @@ public class ExternalCallList { public void onCallAdded(Call telecomCall) { Assert.checkArgument( telecomCall.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)); - mExternalCalls.add(telecomCall); - telecomCall.registerCallback(mTelecomCallCallback, new Handler(Looper.getMainLooper())); + externalCalls.add(telecomCall); + telecomCall.registerCallback(telecomCallCallback, new Handler(Looper.getMainLooper())); notifyExternalCallAdded(telecomCall); } /** Stops tracking an external call and notifies listeners of the removal of the call. */ public void onCallRemoved(Call telecomCall) { - if (!mExternalCalls.contains(telecomCall)) { + if (!externalCalls.contains(telecomCall)) { // This can happen on M for external calls from blocked numbers LogUtil.i("ExternalCallList.onCallRemoved", "attempted to remove unregistered call"); return; } - mExternalCalls.remove(telecomCall); - telecomCall.unregisterCallback(mTelecomCallCallback); + externalCalls.remove(telecomCall); + telecomCall.unregisterCallback(telecomCallCallback); notifyExternalCallRemoved(telecomCall); } /** Adds a new listener to external call events. */ public void addExternalCallListener(@NonNull ExternalCallListener listener) { - mExternalCallListeners.add(listener); + externalCallListeners.add(listener); } /** Removes a listener to external call events. */ public void removeExternalCallListener(@NonNull ExternalCallListener listener) { - if (!mExternalCallListeners.contains(listener)) { + if (!externalCallListeners.contains(listener)) { LogUtil.i( "ExternalCallList.removeExternalCallListener", "attempt to remove unregistered listener."); } - mExternalCallListeners.remove(listener); + externalCallListeners.remove(listener); } public boolean isCallTracked(@NonNull android.telecom.Call telecomCall) { - return mExternalCalls.contains(telecomCall); + return externalCalls.contains(telecomCall); } /** Notifies listeners of the addition of a new external call. */ private void notifyExternalCallAdded(Call call) { - for (ExternalCallListener listener : mExternalCallListeners) { + for (ExternalCallListener listener : externalCallListeners) { listener.onExternalCallAdded(call); } } /** Notifies listeners of the removal of an external call. */ private void notifyExternalCallRemoved(Call call) { - for (ExternalCallListener listener : mExternalCallListeners) { + for (ExternalCallListener listener : externalCallListeners) { listener.onExternalCallRemoved(call); } } @@ -109,11 +109,11 @@ public class ExternalCallList { // change. onCallRemoved(call); - for (ExternalCallListener listener : mExternalCallListeners) { + for (ExternalCallListener listener : externalCallListeners) { listener.onExternalCallPulled(call); } } else { - for (ExternalCallListener listener : mExternalCallListeners) { + for (ExternalCallListener listener : externalCallListeners) { listener.onExternalCallUpdated(call); } } diff --git a/java/com/android/incallui/call/InCallVideoCallCallbackNotifier.java b/java/com/android/incallui/call/InCallVideoCallCallbackNotifier.java index ff94120bf..23a3dad05 100644 --- a/java/com/android/incallui/call/InCallVideoCallCallbackNotifier.java +++ b/java/com/android/incallui/call/InCallVideoCallCallbackNotifier.java @@ -27,13 +27,13 @@ import java.util.concurrent.ConcurrentHashMap; public class InCallVideoCallCallbackNotifier { /** Singleton instance of this class. */ - private static InCallVideoCallCallbackNotifier sInstance = new InCallVideoCallCallbackNotifier(); + private static InCallVideoCallCallbackNotifier instance = new InCallVideoCallCallbackNotifier(); /** * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before * resizing, 1 means we only expect a single thread to access the map so make only a single shard */ - private final Set mSurfaceChangeListeners = + private final Set surfaceChangeListeners = Collections.newSetFromMap(new ConcurrentHashMap(8, 0.9f, 1)); /** Private constructor. Instance should only be acquired through getRunningInstance(). */ @@ -41,7 +41,7 @@ public class InCallVideoCallCallbackNotifier { /** Static singleton accessor method. */ public static InCallVideoCallCallbackNotifier getInstance() { - return sInstance; + return instance; } /** @@ -51,7 +51,7 @@ public class InCallVideoCallCallbackNotifier { */ public void addSurfaceChangeListener(@NonNull SurfaceChangeListener listener) { Objects.requireNonNull(listener); - mSurfaceChangeListeners.add(listener); + surfaceChangeListeners.add(listener); } /** @@ -61,7 +61,7 @@ public class InCallVideoCallCallbackNotifier { */ public void removeSurfaceChangeListener(@Nullable SurfaceChangeListener listener) { if (listener != null) { - mSurfaceChangeListeners.remove(listener); + surfaceChangeListeners.remove(listener); } } @@ -73,7 +73,7 @@ public class InCallVideoCallCallbackNotifier { * @param height New peer height. */ public void peerDimensionsChanged(DialerCall call, int width, int height) { - for (SurfaceChangeListener listener : mSurfaceChangeListeners) { + for (SurfaceChangeListener listener : surfaceChangeListeners) { listener.onUpdatePeerDimensions(call, width, height); } } @@ -86,7 +86,7 @@ public class InCallVideoCallCallbackNotifier { * @param height The new camera video height. */ public void cameraDimensionsChanged(DialerCall call, int width, int height) { - for (SurfaceChangeListener listener : mSurfaceChangeListeners) { + for (SurfaceChangeListener listener : surfaceChangeListeners) { listener.onCameraDimensionsChange(call, width, height); } } diff --git a/java/com/android/incallui/call/TelecomAdapter.java b/java/com/android/incallui/call/TelecomAdapter.java index d48ab68c2..a7e10d37c 100644 --- a/java/com/android/incallui/call/TelecomAdapter.java +++ b/java/com/android/incallui/call/TelecomAdapter.java @@ -32,8 +32,8 @@ public class TelecomAdapter implements InCallServiceListener { private static final String ADD_CALL_MODE_KEY = "add_call_mode"; - private static TelecomAdapter sInstance; - private InCallService mInCallService; + private static TelecomAdapter instance; + private InCallService inCallService; private TelecomAdapter() {} @@ -42,25 +42,25 @@ public class TelecomAdapter implements InCallServiceListener { if (!Looper.getMainLooper().isCurrentThread()) { throw new IllegalStateException(); } - if (sInstance == null) { - sInstance = new TelecomAdapter(); + if (instance == null) { + instance = new TelecomAdapter(); } - return sInstance; + return instance; } @VisibleForTesting(otherwise = VisibleForTesting.NONE) public static void setInstanceForTesting(TelecomAdapter telecomAdapter) { - sInstance = telecomAdapter; + instance = telecomAdapter; } @Override public void setInCallService(InCallService inCallService) { - mInCallService = inCallService; + this.inCallService = inCallService; } @Override public void clearInCallService() { - mInCallService = null; + inCallService = null; } private android.telecom.Call getTelecomCallById(String callId) { @@ -69,16 +69,16 @@ public class TelecomAdapter implements InCallServiceListener { } public void mute(boolean shouldMute) { - if (mInCallService != null) { - mInCallService.setMuted(shouldMute); + if (inCallService != null) { + inCallService.setMuted(shouldMute); } else { LogUtil.e("TelecomAdapter.mute", "mInCallService is null"); } } public void setAudioRoute(int route) { - if (mInCallService != null) { - mInCallService.setAudioRoute(route); + if (inCallService != null) { + inCallService.setAudioRoute(route); } else { LogUtil.e("TelecomAdapter.setAudioRoute", "mInCallService is null"); } @@ -116,7 +116,7 @@ public class TelecomAdapter implements InCallServiceListener { } public void addCall() { - if (mInCallService != null) { + if (inCallService != null) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); @@ -126,7 +126,7 @@ public class TelecomAdapter implements InCallServiceListener { intent.putExtra(ADD_CALL_MODE_KEY, true); try { LogUtil.d("TelecomAdapter.addCall", "Sending the add DialerCall intent"); - mInCallService.startActivity(intent); + inCallService.startActivity(intent); } catch (ActivityNotFoundException e) { // This is rather rare but possible. // Note: this method is used even when the phone is encrypted. At that moment @@ -164,8 +164,8 @@ public class TelecomAdapter implements InCallServiceListener { } public boolean canAddCall() { - if (mInCallService != null) { - return mInCallService.canAddCall(); + if (inCallService != null) { + return inCallService.canAddCall(); } return false; } @@ -177,16 +177,16 @@ public class TelecomAdapter implements InCallServiceListener { */ public void startForegroundNotification(int id, Notification notification) { Assert.isNotNull( - mInCallService, "No inCallService available for starting foreground notification"); - mInCallService.startForeground(id, notification); + inCallService, "No inCallService available for starting foreground notification"); + inCallService.startForeground(id, notification); } /** * Stop a started foreground notification. This does not stop {@code mInCallService} from running. */ public void stopForegroundNotification() { - if (mInCallService != null) { - mInCallService.stopForeground(true /*removeNotification*/); + if (inCallService != null) { + inCallService.stopForeground(true /*removeNotification*/); } else { LogUtil.e( "TelecomAdapter.stopForegroundNotification", diff --git a/java/com/android/incallui/calllocation/impl/DownloadMapImageTask.java b/java/com/android/incallui/calllocation/impl/DownloadMapImageTask.java index 035f5cdac..c7249e0fa 100644 --- a/java/com/android/incallui/calllocation/impl/DownloadMapImageTask.java +++ b/java/com/android/incallui/calllocation/impl/DownloadMapImageTask.java @@ -31,15 +31,15 @@ class DownloadMapImageTask extends AsyncTask { private static final String STATIC_MAP_SRC_NAME = "src"; - private final WeakReference mUiReference; + private final WeakReference uiReference; public DownloadMapImageTask(WeakReference uiReference) { - mUiReference = uiReference; + this.uiReference = uiReference; } @Override protected Drawable doInBackground(Location... locations) { - LocationUi ui = mUiReference.get(); + LocationUi ui = uiReference.get(); if (ui == null) { return null; } @@ -64,7 +64,7 @@ class DownloadMapImageTask extends AsyncTask { @Override protected void onPostExecute(Drawable mapImage) { - LocationUi ui = mUiReference.get(); + LocationUi ui = uiReference.get(); if (ui == null) { return; } diff --git a/java/com/android/incallui/calllocation/impl/HttpFetcher.java b/java/com/android/incallui/calllocation/impl/HttpFetcher.java index 10cc34d25..c182fa156 100644 --- a/java/com/android/incallui/calllocation/impl/HttpFetcher.java +++ b/java/com/android/incallui/calllocation/impl/HttpFetcher.java @@ -221,8 +221,6 @@ public class HttpFetcher { /** * Lookup up url re-write rules from gServices and apply to the given url. - * - * * @return The new url. */ @@ -267,21 +265,21 @@ public class HttpFetcher { /** Disconnect {@link HttpURLConnection} when InputStream is closed */ private static class HttpInputStreamWrapper extends FilterInputStream { - final HttpURLConnection mHttpUrlConnection; - final long mStartMillis = SystemClock.uptimeMillis(); + final HttpURLConnection httpUrlConnection; + final long startMillis = SystemClock.uptimeMillis(); public HttpInputStreamWrapper(HttpURLConnection conn, InputStream in) { super(in); - mHttpUrlConnection = conn; + httpUrlConnection = conn; } @Override public void close() throws IOException { super.close(); - mHttpUrlConnection.disconnect(); + httpUrlConnection.disconnect(); if (LogUtil.isDebugEnabled()) { long endMillis = SystemClock.uptimeMillis(); - LogUtil.i("HttpFetcher.close", "fetch took " + (endMillis - mStartMillis) + " ms"); + LogUtil.i("HttpFetcher.close", "fetch took " + (endMillis - startMillis) + " ms"); } } } diff --git a/java/com/android/incallui/calllocation/impl/LocationPresenter.java b/java/com/android/incallui/calllocation/impl/LocationPresenter.java index 1199308a5..83195baf8 100644 --- a/java/com/android/incallui/calllocation/impl/LocationPresenter.java +++ b/java/com/android/incallui/calllocation/impl/LocationPresenter.java @@ -37,9 +37,9 @@ import java.util.Objects; public class LocationPresenter extends Presenter implements LocationListener { - private Location mLastLocation; - private AsyncTask mDownloadMapTask; - private AsyncTask mReverseGeocodeTask; + private Location lastLocation; + private AsyncTask downloadMapTask; + private AsyncTask reverseGeocodeTask; LocationPresenter() {} @@ -47,7 +47,7 @@ public class LocationPresenter extends Presenter public void onUiReady(LocationUi ui) { LogUtil.i("LocationPresenter.onUiReady", ""); super.onUiReady(ui); - updateLocation(mLastLocation, true); + updateLocation(lastLocation, true); } @Override @@ -55,11 +55,11 @@ public class LocationPresenter extends Presenter LogUtil.i("LocationPresenter.onUiUnready", ""); super.onUiUnready(ui); - if (mDownloadMapTask != null) { - mDownloadMapTask.cancel(true); + if (downloadMapTask != null) { + downloadMapTask.cancel(true); } - if (mReverseGeocodeTask != null) { - mReverseGeocodeTask.cancel(true); + if (reverseGeocodeTask != null) { + reverseGeocodeTask.cancel(true); } } @@ -71,13 +71,13 @@ public class LocationPresenter extends Presenter private void updateLocation(Location location, boolean forceUpdate) { LogUtil.i("LocationPresenter.updateLocation", "location: " + location); - if (forceUpdate || !Objects.equals(mLastLocation, location)) { - mLastLocation = location; + if (forceUpdate || !Objects.equals(lastLocation, location)) { + lastLocation = location; int status = LocationHelper.checkLocation(location); LocationUi ui = getUi(); if (status == LocationHelper.LOCATION_STATUS_OK) { - mDownloadMapTask = new DownloadMapImageTask(new WeakReference<>(ui)).execute(location); - mReverseGeocodeTask = new ReverseGeocodeTask(new WeakReference<>(ui)).execute(location); + downloadMapTask = new DownloadMapImageTask(new WeakReference<>(ui)).execute(location); + reverseGeocodeTask = new ReverseGeocodeTask(new WeakReference<>(ui)).execute(location); if (ui != null) { ui.setLocation(location); } else { diff --git a/java/com/android/incallui/calllocation/impl/ReverseGeocodeTask.java b/java/com/android/incallui/calllocation/impl/ReverseGeocodeTask.java index 060ec0b4f..f4592d4c8 100644 --- a/java/com/android/incallui/calllocation/impl/ReverseGeocodeTask.java +++ b/java/com/android/incallui/calllocation/impl/ReverseGeocodeTask.java @@ -39,15 +39,15 @@ class ReverseGeocodeTask extends AsyncTask { private static final String JSON_KEY_LONG_NAME = "long_name"; private static final String JSON_KEY_SHORT_NAME = "short_name"; - private WeakReference mUiReference; + private WeakReference uiReference; public ReverseGeocodeTask(WeakReference uiReference) { - mUiReference = uiReference; + this.uiReference = uiReference; } @Override protected String doInBackground(Location... locations) { - LocationUi ui = mUiReference.get(); + LocationUi ui = uiReference.get(); if (ui == null) { return null; } @@ -131,7 +131,7 @@ class ReverseGeocodeTask extends AsyncTask { @Override protected void onPostExecute(String address) { - LocationUi ui = mUiReference.get(); + LocationUi ui = uiReference.get(); if (ui == null) { return; } diff --git a/java/com/android/incallui/latencyreport/LatencyReport.java b/java/com/android/incallui/latencyreport/LatencyReport.java index 2e1fbd590..8ea66f9b3 100644 --- a/java/com/android/incallui/latencyreport/LatencyReport.java +++ b/java/com/android/incallui/latencyreport/LatencyReport.java @@ -30,111 +30,111 @@ public class LatencyReport { "android.telecom.extra.CALL_TELECOM_ROUTING_START_TIME_MILLIS"; private static final String EXTRA_CALL_TELECOM_ROUTING_END_TIME_MILLIS = "android.telecom.extra.CALL_TELECOM_ROUTING_END_TIME_MILLIS"; - private final boolean mWasIncoming; + private final boolean wasIncoming; // Time elapsed since boot when the call was created by the connection service. - private final long mCreatedTimeMillis; + private final long createdTimeMillis; // Time elapsed since boot when telecom began processing the call. - private final long mTelecomRoutingStartTimeMillis; + private final long telecomRoutingStartTimeMillis; // Time elapsed since boot when telecom finished processing the call. This includes things like // looking up contact info and call blocking but before showing any UI. - private final long mTelecomRoutingEndTimeMillis; + private final long telecomRoutingEndTimeMillis; // Time elapsed since boot when the call was added to the InCallUi. - private final long mCallAddedTimeMillis; + private final long callAddedTimeMillis; // Time elapsed since boot when the call was added and call blocking evaluation was completed. - private long mCallBlockingTimeMillis = INVALID_TIME; + private long callBlockingTimeMillis = INVALID_TIME; // Time elapsed since boot when the call notification was shown. - private long mCallNotificationTimeMillis = INVALID_TIME; + private long callNotificationTimeMillis = INVALID_TIME; // Time elapsed since boot when the InCallUI was shown. - private long mInCallUiShownTimeMillis = INVALID_TIME; + private long inCallUiShownTimeMillis = INVALID_TIME; // Whether the call was shown to the user as a heads up notification instead of a full screen // UI. - private boolean mDidDisplayHeadsUpNotification; + private boolean didDisplayHeadsUpNotification; public LatencyReport() { - mWasIncoming = false; - mCreatedTimeMillis = INVALID_TIME; - mTelecomRoutingStartTimeMillis = INVALID_TIME; - mTelecomRoutingEndTimeMillis = INVALID_TIME; - mCallAddedTimeMillis = SystemClock.elapsedRealtime(); + wasIncoming = false; + createdTimeMillis = INVALID_TIME; + telecomRoutingStartTimeMillis = INVALID_TIME; + telecomRoutingEndTimeMillis = INVALID_TIME; + callAddedTimeMillis = SystemClock.elapsedRealtime(); } public LatencyReport(android.telecom.Call telecomCall) { - mWasIncoming = telecomCall.getState() == android.telecom.Call.STATE_RINGING; + wasIncoming = telecomCall.getState() == android.telecom.Call.STATE_RINGING; Bundle extras = telecomCall.getDetails().getIntentExtras(); if (extras == null) { - mCreatedTimeMillis = INVALID_TIME; - mTelecomRoutingStartTimeMillis = INVALID_TIME; - mTelecomRoutingEndTimeMillis = INVALID_TIME; + createdTimeMillis = INVALID_TIME; + telecomRoutingStartTimeMillis = INVALID_TIME; + telecomRoutingEndTimeMillis = INVALID_TIME; } else { - mCreatedTimeMillis = extras.getLong(EXTRA_CALL_CREATED_TIME_MILLIS, INVALID_TIME); - mTelecomRoutingStartTimeMillis = + createdTimeMillis = extras.getLong(EXTRA_CALL_CREATED_TIME_MILLIS, INVALID_TIME); + telecomRoutingStartTimeMillis = extras.getLong(EXTRA_CALL_TELECOM_ROUTING_START_TIME_MILLIS, INVALID_TIME); - mTelecomRoutingEndTimeMillis = + telecomRoutingEndTimeMillis = extras.getLong(EXTRA_CALL_TELECOM_ROUTING_END_TIME_MILLIS, INVALID_TIME); } - mCallAddedTimeMillis = SystemClock.elapsedRealtime(); + callAddedTimeMillis = SystemClock.elapsedRealtime(); } public boolean getWasIncoming() { - return mWasIncoming; + return wasIncoming; } public long getCreatedTimeMillis() { - return mCreatedTimeMillis; + return createdTimeMillis; } public long getTelecomRoutingStartTimeMillis() { - return mTelecomRoutingStartTimeMillis; + return telecomRoutingStartTimeMillis; } public long getTelecomRoutingEndTimeMillis() { - return mTelecomRoutingEndTimeMillis; + return telecomRoutingEndTimeMillis; } public long getCallAddedTimeMillis() { - return mCallAddedTimeMillis; + return callAddedTimeMillis; } public long getCallBlockingTimeMillis() { - return mCallBlockingTimeMillis; + return callBlockingTimeMillis; } public void onCallBlockingDone() { - if (mCallBlockingTimeMillis == INVALID_TIME) { - mCallBlockingTimeMillis = SystemClock.elapsedRealtime(); + if (callBlockingTimeMillis == INVALID_TIME) { + callBlockingTimeMillis = SystemClock.elapsedRealtime(); } } public long getCallNotificationTimeMillis() { - return mCallNotificationTimeMillis; + return callNotificationTimeMillis; } public void onNotificationShown() { - if (mCallNotificationTimeMillis == INVALID_TIME) { - mCallNotificationTimeMillis = SystemClock.elapsedRealtime(); + if (callNotificationTimeMillis == INVALID_TIME) { + callNotificationTimeMillis = SystemClock.elapsedRealtime(); } } public long getInCallUiShownTimeMillis() { - return mInCallUiShownTimeMillis; + return inCallUiShownTimeMillis; } public void onInCallUiShown(boolean forFullScreenIntent) { - if (mInCallUiShownTimeMillis == INVALID_TIME) { - mInCallUiShownTimeMillis = SystemClock.elapsedRealtime(); - mDidDisplayHeadsUpNotification = mWasIncoming && !forFullScreenIntent; + if (inCallUiShownTimeMillis == INVALID_TIME) { + inCallUiShownTimeMillis = SystemClock.elapsedRealtime(); + didDisplayHeadsUpNotification = wasIncoming && !forFullScreenIntent; } } public boolean getDidDisplayHeadsUpNotification() { - return mDidDisplayHeadsUpNotification; + return didDisplayHeadsUpNotification; } } diff --git a/java/com/android/incallui/ringtone/DialerRingtoneManager.java b/java/com/android/incallui/ringtone/DialerRingtoneManager.java index 5ebd93378..49badf575 100644 --- a/java/com/android/incallui/ringtone/DialerRingtoneManager.java +++ b/java/com/android/incallui/ringtone/DialerRingtoneManager.java @@ -38,9 +38,9 @@ public class DialerRingtoneManager { * Once we're ready to enable Dialer Ringing, these flags should be removed. */ private static final boolean IS_DIALER_RINGING_ENABLED = false; - private final InCallTonePlayer mInCallTonePlayer; - private final CallList mCallList; - private Boolean mIsDialerRingingEnabledForTesting; + private final InCallTonePlayer inCallTonePlayer; + private final CallList callList; + private Boolean isDialerRingingEnabledForTesting; /** * Creates the DialerRingtoneManager with the given {@link InCallTonePlayer}. @@ -51,8 +51,8 @@ public class DialerRingtoneManager { */ public DialerRingtoneManager( @NonNull InCallTonePlayer inCallTonePlayer, @NonNull CallList callList) { - mInCallTonePlayer = Objects.requireNonNull(inCallTonePlayer); - mCallList = Objects.requireNonNull(callList); + this.inCallTonePlayer = Objects.requireNonNull(inCallTonePlayer); + this.callList = Objects.requireNonNull(callList); } /** @@ -88,13 +88,13 @@ public class DialerRingtoneManager { if (callState != State.INCOMING) { return callState; } - return mCallList.getActiveCall() == null ? State.INCOMING : State.CALL_WAITING; + return callList.getActiveCall() == null ? State.INCOMING : State.CALL_WAITING; } private boolean isDialerRingingEnabled() { boolean enabledFlag = - mIsDialerRingingEnabledForTesting != null - ? mIsDialerRingingEnabledForTesting + isDialerRingingEnabledForTesting != null + ? isDialerRingingEnabledForTesting : IS_DIALER_RINGING_ENABLED; return VERSION.SDK_INT >= VERSION_CODES.N && enabledFlag; } @@ -109,7 +109,7 @@ public class DialerRingtoneManager { public boolean shouldPlayCallWaitingTone(int callState) { return isDialerRingingEnabled() && translateCallStateForCallWaiting(callState) == State.CALL_WAITING - && !mInCallTonePlayer.isPlayingTone(); + && !inCallTonePlayer.isPlayingTone(); } /** Plays the call waiting tone. */ @@ -117,7 +117,7 @@ public class DialerRingtoneManager { if (!isDialerRingingEnabled()) { return; } - mInCallTonePlayer.play(InCallTonePlayer.TONE_CALL_WAITING); + inCallTonePlayer.play(InCallTonePlayer.TONE_CALL_WAITING); } /** Stops playing the call waiting tone. */ @@ -125,10 +125,10 @@ public class DialerRingtoneManager { if (!isDialerRingingEnabled()) { return; } - mInCallTonePlayer.stop(); + inCallTonePlayer.stop(); } void setDialerRingingEnabledForTesting(boolean status) { - mIsDialerRingingEnabledForTesting = status; + isDialerRingingEnabledForTesting = status; } } diff --git a/java/com/android/incallui/ringtone/InCallTonePlayer.java b/java/com/android/incallui/ringtone/InCallTonePlayer.java index c76b41d72..dac244d22 100644 --- a/java/com/android/incallui/ringtone/InCallTonePlayer.java +++ b/java/com/android/incallui/ringtone/InCallTonePlayer.java @@ -36,9 +36,9 @@ public class InCallTonePlayer { public static final int VOLUME_RELATIVE_HIGH_PRIORITY = 80; - @NonNull private final ToneGeneratorFactory mToneGeneratorFactory; - @NonNull private final PausableExecutor mExecutor; - private @Nullable CountDownLatch mNumPlayingTones; + @NonNull private final ToneGeneratorFactory toneGeneratorFactory; + @NonNull private final PausableExecutor executor; + private @Nullable CountDownLatch numPlayingTones; /** * Creates a new InCallTonePlayer. @@ -51,13 +51,13 @@ public class InCallTonePlayer { */ public InCallTonePlayer( @NonNull ToneGeneratorFactory toneGeneratorFactory, @NonNull PausableExecutor executor) { - mToneGeneratorFactory = Objects.requireNonNull(toneGeneratorFactory); - mExecutor = Objects.requireNonNull(executor); + this.toneGeneratorFactory = Objects.requireNonNull(toneGeneratorFactory); + this.executor = Objects.requireNonNull(executor); } /** @return {@code true} if a tone is currently playing, {@code false} otherwise. */ public boolean isPlayingTone() { - return mNumPlayingTones != null && mNumPlayingTones.getCount() > 0; + return numPlayingTones != null && numPlayingTones.getCount() > 0; } /** @@ -72,8 +72,8 @@ public class InCallTonePlayer { throw new IllegalStateException("Tone already playing"); } final ToneGeneratorInfo info = getToneGeneratorInfo(tone); - mNumPlayingTones = new CountDownLatch(1); - mExecutor.execute( + numPlayingTones = new CountDownLatch(1); + executor.execute( new Runnable() { @Override public void run() { @@ -106,17 +106,17 @@ public class InCallTonePlayer { ToneGenerator toneGenerator = null; try { Log.v(this, "Starting tone " + info); - toneGenerator = mToneGeneratorFactory.newInCallToneGenerator(info.stream, info.volume); + toneGenerator = toneGeneratorFactory.newInCallToneGenerator(info.stream, info.volume); toneGenerator.startTone(info.tone); /* * During tests, this will block until the tests call mExecutor.ackMilestone. This call * allows for synchronization to the point where the tone has started playing. */ - mExecutor.milestone(); - if (mNumPlayingTones != null) { - mNumPlayingTones.await(info.toneLengthMillis, TimeUnit.MILLISECONDS); + executor.milestone(); + if (numPlayingTones != null) { + numPlayingTones.await(info.toneLengthMillis, TimeUnit.MILLISECONDS); // Allows for synchronization to the point where the tone has completed playing. - mExecutor.milestone(); + executor.milestone(); } } catch (InterruptedException e) { Log.w(this, "Interrupted while playing in-call tone."); @@ -124,18 +124,18 @@ public class InCallTonePlayer { if (toneGenerator != null) { toneGenerator.release(); } - if (mNumPlayingTones != null) { - mNumPlayingTones.countDown(); + if (numPlayingTones != null) { + numPlayingTones.countDown(); } // Allows for synchronization to the point where this background thread has cleaned up. - mExecutor.milestone(); + executor.milestone(); } } /** Stops playback of the current tone. */ public void stop() { - if (mNumPlayingTones != null) { - mNumPlayingTones.countDown(); + if (numPlayingTones != null) { + numPlayingTones.countDown(); } } diff --git a/java/com/android/newbubble/NewCheckableButton.java b/java/com/android/newbubble/NewCheckableButton.java index 8e43335ca..15858d39e 100644 --- a/java/com/android/newbubble/NewCheckableButton.java +++ b/java/com/android/newbubble/NewCheckableButton.java @@ -33,7 +33,7 @@ import android.widget.Checkable; */ public class NewCheckableButton extends AppCompatButton implements Checkable { - private boolean mChecked; + private boolean checked; public NewCheckableButton(Context context) { this(context, null); @@ -67,8 +67,8 @@ public class NewCheckableButton extends AppCompatButton implements Checkable { @Override public void setChecked(boolean checked) { - if (mChecked != checked) { - mChecked = checked; + if (this.checked != checked) { + this.checked = checked; int newColor = checked ? getContext().getColor(R.color.bubble_button_color_blue) @@ -80,11 +80,11 @@ public class NewCheckableButton extends AppCompatButton implements Checkable { @Override public boolean isChecked() { - return mChecked; + return checked; } @Override public void toggle() { - setChecked(!mChecked); + setChecked(!checked); } } diff --git a/java/com/android/newbubble/RoundedRectRevealOutlineProvider.java b/java/com/android/newbubble/RoundedRectRevealOutlineProvider.java index d204e0f1c..2ade6cf05 100644 --- a/java/com/android/newbubble/RoundedRectRevealOutlineProvider.java +++ b/java/com/android/newbubble/RoundedRectRevealOutlineProvider.java @@ -32,38 +32,38 @@ import android.view.ViewOutlineProvider; * rounded rectangle. */ public class RoundedRectRevealOutlineProvider extends ViewOutlineProvider { - private final float mStartRadius; - private final float mEndRadius; + private final float startRadius; + private final float endRadius; - private final Rect mStartRect; - private final Rect mEndRect; + private final Rect startRect; + private final Rect endRect; - private final Rect mOutline; - private float mOutlineRadius; + private final Rect outline; + private float outlineRadius; public RoundedRectRevealOutlineProvider( float startRadius, float endRadius, Rect startRect, Rect endRect) { - mStartRadius = startRadius; - mEndRadius = endRadius; - mStartRect = startRect; - mEndRect = endRect; + this.startRadius = startRadius; + this.endRadius = endRadius; + this.startRect = startRect; + this.endRect = endRect; - mOutline = new Rect(); + outline = new Rect(); } @Override public void getOutline(View v, Outline outline) { - outline.setRoundRect(mOutline, mOutlineRadius); + outline.setRoundRect(this.outline, outlineRadius); } /** Sets the progress, from 0 to 1, of the reveal animation. */ public void setProgress(float progress) { - mOutlineRadius = (1 - progress) * mStartRadius + progress * mEndRadius; + outlineRadius = (1 - progress) * startRadius + progress * endRadius; - mOutline.left = (int) ((1 - progress) * mStartRect.left + progress * mEndRect.left); - mOutline.top = (int) ((1 - progress) * mStartRect.top + progress * mEndRect.top); - mOutline.right = (int) ((1 - progress) * mStartRect.right + progress * mEndRect.right); - mOutline.bottom = (int) ((1 - progress) * mStartRect.bottom + progress * mEndRect.bottom); + outline.left = (int) ((1 - progress) * startRect.left + progress * endRect.left); + outline.top = (int) ((1 - progress) * startRect.top + progress * endRect.top); + outline.right = (int) ((1 - progress) * startRect.right + progress * endRect.right); + outline.bottom = (int) ((1 - progress) * startRect.bottom + progress * endRect.bottom); } ValueAnimator createRevealAnimator(final View revealView, boolean isReversed) { @@ -72,7 +72,7 @@ public class RoundedRectRevealOutlineProvider extends ViewOutlineProvider { valueAnimator.addListener( new AnimatorListenerAdapter() { - private boolean mWasCanceled = false; + private boolean wasCanceled = false; @Override public void onAnimationStart(Animator animation) { @@ -82,12 +82,12 @@ public class RoundedRectRevealOutlineProvider extends ViewOutlineProvider { @Override public void onAnimationCancel(Animator animation) { - mWasCanceled = true; + wasCanceled = true; } @Override public void onAnimationEnd(Animator animation) { - if (!mWasCanceled) { + if (!wasCanceled) { revealView.setOutlineProvider(ViewOutlineProvider.BACKGROUND); revealView.setClipToOutline(false); } diff --git a/java/com/android/voicemail/impl/ActivationTask.java b/java/com/android/voicemail/impl/ActivationTask.java index 83f2fd836..3cdbee484 100644 --- a/java/com/android/voicemail/impl/ActivationTask.java +++ b/java/com/android/voicemail/impl/ActivationTask.java @@ -63,16 +63,16 @@ public class ActivationTask extends BaseTask { @VisibleForTesting static final String EXTRA_MESSAGE_DATA_BUNDLE = "extra_message_data_bundle"; - private final RetryPolicy mRetryPolicy; + private final RetryPolicy retryPolicy; @Nullable private OmtpVvmCarrierConfigHelper configForTest; - private Bundle mMessageData; + private Bundle messageData; public ActivationTask() { super(TASK_ACTIVATION); - mRetryPolicy = new RetryPolicy(RETRY_TIMES, RETRY_INTERVAL_MILLIS); - addPolicy(mRetryPolicy); + retryPolicy = new RetryPolicy(RETRY_TIMES, RETRY_INTERVAL_MILLIS); + addPolicy(retryPolicy); } /** Has the user gone through the setup wizard yet. */ @@ -108,7 +108,7 @@ public class ActivationTask extends BaseTask { @Override public void onCreate(Context context, Bundle extras) { super.onCreate(context, extras); - mMessageData = extras.getParcelable(EXTRA_MESSAGE_DATA_BUNDLE); + messageData = extras.getParcelable(EXTRA_MESSAGE_DATA_BUNDLE); } @Override @@ -168,7 +168,7 @@ public class ActivationTask extends BaseTask { } VvmLog.i(TAG, "VVM content provider configured - " + helper.getVvmType()); - if (mMessageData == null + if (messageData == null && VvmAccountManager.isAccountActivated(getContext(), phoneAccountHandle)) { VvmLog.i(TAG, "Account is already activated"); // The activated state might come from restored data, the filter still needs to be set up. @@ -191,15 +191,15 @@ public class ActivationTask extends BaseTask { } helper.activateSmsFilter(); - VoicemailStatus.Editor status = mRetryPolicy.getVoicemailStatusEditor(); + VoicemailStatus.Editor status = retryPolicy.getVoicemailStatusEditor(); VisualVoicemailProtocol protocol = helper.getProtocol(); Bundle data; - if (mMessageData != null) { + if (messageData != null) { // The content of STATUS SMS is provided to launch this task, no need to request it // again. - data = mMessageData; + data = messageData; } else { try (StatusSmsFetcher fetcher = new StatusSmsFetcher(getContext(), phoneAccountHandle)) { protocol.startActivation(helper, fetcher.getSentIntent()); diff --git a/java/com/android/voicemail/impl/Assert.java b/java/com/android/voicemail/impl/Assert.java index fe063727a..0e9e4dc7d 100644 --- a/java/com/android/voicemail/impl/Assert.java +++ b/java/com/android/voicemail/impl/Assert.java @@ -21,7 +21,7 @@ import android.os.Looper; /** Assertions which will result in program termination. */ public class Assert { - private static Boolean sIsMainThreadForTest; + private static Boolean isMainThreadForTest; public static void isTrue(boolean condition) { if (!condition) { @@ -30,16 +30,16 @@ public class Assert { } public static void isMainThread() { - if (sIsMainThreadForTest != null) { - isTrue(sIsMainThreadForTest); + if (isMainThreadForTest != null) { + isTrue(isMainThreadForTest); return; } isTrue(Looper.getMainLooper().equals(Looper.myLooper())); } public static void isNotMainThread() { - if (sIsMainThreadForTest != null) { - isTrue(!sIsMainThreadForTest); + if (isMainThreadForTest != null) { + isTrue(!isMainThreadForTest); return; } isTrue(!Looper.getMainLooper().equals(Looper.myLooper())); @@ -52,6 +52,6 @@ public class Assert { /** Override the main thread status for tests. Set to null to revert to normal behavior */ @NeededForTesting public static void setIsMainThreadForTesting(Boolean isMainThread) { - sIsMainThreadForTest = isMainThread; + isMainThreadForTest = isMainThread; } } diff --git a/java/com/android/voicemail/impl/OmtpEvents.java b/java/com/android/voicemail/impl/OmtpEvents.java index 6807edcf0..ddca80f1a 100644 --- a/java/com/android/voicemail/impl/OmtpEvents.java +++ b/java/com/android/voicemail/impl/OmtpEvents.java @@ -123,30 +123,30 @@ public enum OmtpEvents { public static final int OTHER = 4; } - private final int mType; - private final boolean mIsSuccess; + private final int type; + private final boolean isSuccess; OmtpEvents(int type, boolean isSuccess) { - mType = type; - mIsSuccess = isSuccess; + this.type = type; + this.isSuccess = isSuccess; } OmtpEvents(int type) { - mType = type; - mIsSuccess = false; + this.type = type; + isSuccess = false; } OmtpEvents() { - mType = Type.OTHER; - mIsSuccess = false; + type = Type.OTHER; + isSuccess = false; } @Type.Values public int getType() { - return mType; + return type; } public boolean isSuccess() { - return mIsSuccess; + return isSuccess; } } diff --git a/java/com/android/voicemail/impl/OmtpVvmCarrierConfigHelper.java b/java/com/android/voicemail/impl/OmtpVvmCarrierConfigHelper.java index 0b63e8658..d5cde72bd 100644 --- a/java/com/android/voicemail/impl/OmtpVvmCarrierConfigHelper.java +++ b/java/com/android/voicemail/impl/OmtpVvmCarrierConfigHelper.java @@ -88,86 +88,86 @@ public class OmtpVvmCarrierConfigHelper { public static final String KEY_VVM_CLIENT_PREFIX_STRING = "vvm_client_prefix_string"; - @Nullable private static PersistableBundle sOverrideConfigForTest; + @Nullable private static PersistableBundle overrideConfigForTest; - private final Context mContext; - private final PersistableBundle mCarrierConfig; - private final String mVvmType; - private final VisualVoicemailProtocol mProtocol; - private final PersistableBundle mTelephonyConfig; + private final Context context; + private final PersistableBundle carrierConfig; + private final String vvmType; + private final VisualVoicemailProtocol protocol; + private final PersistableBundle telephonyConfig; - @Nullable private final PersistableBundle mOverrideConfig; + @Nullable private final PersistableBundle overrideConfig; - private PhoneAccountHandle mPhoneAccountHandle; + private PhoneAccountHandle phoneAccountHandle; public OmtpVvmCarrierConfigHelper(Context context, @Nullable PhoneAccountHandle handle) { - mContext = context; - mPhoneAccountHandle = handle; + this.context = context; + phoneAccountHandle = handle; TelephonyManager telephonyManager = context .getSystemService(TelephonyManager.class) - .createForPhoneAccountHandle(mPhoneAccountHandle); + .createForPhoneAccountHandle(phoneAccountHandle); if (telephonyManager == null) { VvmLog.e(TAG, "PhoneAccountHandle is invalid"); - mCarrierConfig = null; - mTelephonyConfig = null; - mOverrideConfig = null; - mVvmType = null; - mProtocol = null; + carrierConfig = null; + telephonyConfig = null; + overrideConfig = null; + vvmType = null; + protocol = null; return; } - if (sOverrideConfigForTest != null) { - mOverrideConfig = sOverrideConfigForTest; - mCarrierConfig = new PersistableBundle(); - mTelephonyConfig = new PersistableBundle(); + if (overrideConfigForTest != null) { + overrideConfig = overrideConfigForTest; + carrierConfig = new PersistableBundle(); + telephonyConfig = new PersistableBundle(); } else { if (ConfigOverrideFragment.isOverridden(context)) { - mOverrideConfig = ConfigOverrideFragment.getConfig(context); - VvmLog.w(TAG, "Config override is activated: " + mOverrideConfig); + overrideConfig = ConfigOverrideFragment.getConfig(context); + VvmLog.w(TAG, "Config override is activated: " + overrideConfig); } else { - mOverrideConfig = null; + overrideConfig = null; } - mCarrierConfig = getCarrierConfig(telephonyManager); - mTelephonyConfig = + carrierConfig = getCarrierConfig(telephonyManager); + telephonyConfig = new TelephonyVvmConfigManager(context).getConfig(telephonyManager.getSimOperator()); } - mVvmType = getVvmType(); - mProtocol = VisualVoicemailProtocolFactory.create(mContext.getResources(), mVvmType); + vvmType = getVvmType(); + protocol = VisualVoicemailProtocolFactory.create(this.context.getResources(), vvmType); } @VisibleForTesting OmtpVvmCarrierConfigHelper( Context context, PersistableBundle carrierConfig, PersistableBundle telephonyConfig) { - mContext = context; - mCarrierConfig = carrierConfig; - mTelephonyConfig = telephonyConfig; - mOverrideConfig = null; - mVvmType = getVvmType(); - mProtocol = VisualVoicemailProtocolFactory.create(mContext.getResources(), mVvmType); + this.context = context; + this.carrierConfig = carrierConfig; + this.telephonyConfig = telephonyConfig; + overrideConfig = null; + vvmType = getVvmType(); + protocol = VisualVoicemailProtocolFactory.create(this.context.getResources(), vvmType); } public PersistableBundle getConfig() { PersistableBundle result = new PersistableBundle(); - if (mTelephonyConfig != null) { - result.putAll(mTelephonyConfig); + if (telephonyConfig != null) { + result.putAll(telephonyConfig); } - if (mCarrierConfig != null) { - result.putAll(mCarrierConfig); + if (carrierConfig != null) { + result.putAll(carrierConfig); } return result; } public Context getContext() { - return mContext; + return context; } @Nullable public PhoneAccountHandle getPhoneAccountHandle() { - return mPhoneAccountHandle; + return phoneAccountHandle; } /** @@ -175,7 +175,7 @@ public class OmtpVvmCarrierConfigHelper { * known protocol. */ public boolean isValid() { - if (mProtocol == null) { + if (protocol == null) { return false; } if (isCarrierAppPreloaded()) { @@ -191,7 +191,7 @@ public class OmtpVvmCarrierConfigHelper { @Nullable public VisualVoicemailProtocol getProtocol() { - return mProtocol; + return protocol; } /** @returns arbitrary String stored in the config file. Used for protocol specific values. */ @@ -209,15 +209,15 @@ public class OmtpVvmCarrierConfigHelper { @Nullable private Set getCarrierVvmPackageNamesWithoutValidation() { - Set names = getCarrierVvmPackageNames(mOverrideConfig); + Set names = getCarrierVvmPackageNames(overrideConfig); if (names != null) { return names; } - names = getCarrierVvmPackageNames(mCarrierConfig); + names = getCarrierVvmPackageNames(carrierConfig); if (names != null) { return names; } - return getCarrierVvmPackageNames(mTelephonyConfig); + return getCarrierVvmPackageNames(telephonyConfig); } private static Set getCarrierVvmPackageNames(@Nullable PersistableBundle bundle) { @@ -255,7 +255,7 @@ public class OmtpVvmCarrierConfigHelper { } for (String packageName : carrierPackages) { try { - mContext.getPackageManager().getPackageInfo(packageName, 0); + context.getPackageManager().getPackageInfo(packageName, 0); return false; } catch (NameNotFoundException e) { // Do nothing. @@ -305,15 +305,15 @@ public class OmtpVvmCarrierConfigHelper { public Set getDisabledCapabilities() { Assert.checkArgument(isValid()); Set disabledCapabilities; - disabledCapabilities = getDisabledCapabilities(mOverrideConfig); + disabledCapabilities = getDisabledCapabilities(overrideConfig); if (disabledCapabilities != null) { return disabledCapabilities; } - disabledCapabilities = getDisabledCapabilities(mCarrierConfig); + disabledCapabilities = getDisabledCapabilities(carrierConfig); if (disabledCapabilities != null) { return disabledCapabilities; } - return getDisabledCapabilities(mTelephonyConfig); + return getDisabledCapabilities(telephonyConfig); } @Nullable @@ -367,7 +367,7 @@ public class OmtpVvmCarrierConfigHelper { return; } - if (mVvmType == null || mVvmType.isEmpty()) { + if (vvmType == null || vvmType.isEmpty()) { // The VVM type is invalid; we should never have gotten here in the first place since // this is loaded initially in the constructor, and callers should check isValid() // before trying to start activation anyways. @@ -375,15 +375,15 @@ public class OmtpVvmCarrierConfigHelper { return; } - if (mProtocol != null) { - ActivationTask.start(mContext, mPhoneAccountHandle, null); + if (protocol != null) { + ActivationTask.start(context, this.phoneAccountHandle, null); } } public void activateSmsFilter() { Assert.checkArgument(isValid()); TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings( - mContext, + context, getPhoneAccountHandle(), new VisualVoicemailSmsFilterSettings.Builder().setClientPrefix(getClientPrefix()).build()); } @@ -394,18 +394,18 @@ public class OmtpVvmCarrierConfigHelper { if (!isLegacyModeEnabled()) { // SMS should still be filtered in legacy mode TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings( - mContext, getPhoneAccountHandle(), null); + context, getPhoneAccountHandle(), null); VvmLog.i(TAG, "filter disabled"); } - if (mProtocol != null) { - mProtocol.startDeactivation(this); + if (protocol != null) { + protocol.startDeactivation(this); } - VvmAccountManager.removeAccount(mContext, getPhoneAccountHandle()); + VvmAccountManager.removeAccount(context, getPhoneAccountHandle()); } public boolean supportsProvisioning() { Assert.checkArgument(isValid()); - return mProtocol.supportsProvisioning(); + return protocol.supportsProvisioning(); } public void startProvisioning( @@ -415,18 +415,18 @@ public class OmtpVvmCarrierConfigHelper { StatusMessage message, Bundle data) { Assert.checkArgument(isValid()); - mProtocol.startProvisioning(task, phone, this, status, message, data); + protocol.startProvisioning(task, phone, this, status, message, data); } public void requestStatus(@Nullable PendingIntent sentIntent) { Assert.checkArgument(isValid()); - mProtocol.requestStatus(this, sentIntent); + protocol.requestStatus(this, sentIntent); } public void handleEvent(VoicemailStatus.Editor status, OmtpEvents event) { Assert.checkArgument(isValid()); VvmLog.i(TAG, "OmtpEvent:" + event); - mProtocol.handleEvent(mContext, this, status, event); + protocol.handleEvent(context, this, status, event); } @Override @@ -434,11 +434,11 @@ public class OmtpVvmCarrierConfigHelper { StringBuilder builder = new StringBuilder("OmtpVvmCarrierConfigHelper ["); builder .append("phoneAccountHandle: ") - .append(mPhoneAccountHandle) + .append(phoneAccountHandle) .append(", carrierConfig: ") - .append(mCarrierConfig != null) + .append(carrierConfig != null) .append(", telephonyConfig: ") - .append(mTelephonyConfig != null) + .append(telephonyConfig != null) .append(", type: ") .append(getVvmType()) .append(", destinationNumber: ") @@ -462,7 +462,7 @@ public class OmtpVvmCarrierConfigHelper { @Nullable private PersistableBundle getCarrierConfig(@NonNull TelephonyManager telephonyManager) { CarrierConfigManager carrierConfigManager = - (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE); + (CarrierConfigManager) context.getSystemService(Context.CARRIER_CONFIG_SERVICE); if (carrierConfigManager == null) { VvmLog.w(TAG, "No carrier config service found."); return null; @@ -484,21 +484,21 @@ public class OmtpVvmCarrierConfigHelper { @Nullable private Object getValue(String key, Object defaultValue) { Object result; - if (mOverrideConfig != null) { - result = mOverrideConfig.get(key); + if (overrideConfig != null) { + result = overrideConfig.get(key); if (result != null) { return result; } } - if (mCarrierConfig != null) { - result = mCarrierConfig.get(key); + if (carrierConfig != null) { + result = carrierConfig.get(key); if (result != null) { return result; } } - if (mTelephonyConfig != null) { - result = mTelephonyConfig.get(key); + if (telephonyConfig != null) { + result = telephonyConfig.get(key); if (result != null) { return result; } @@ -508,7 +508,7 @@ public class OmtpVvmCarrierConfigHelper { @VisibleForTesting public static void setOverrideConfigForTest(PersistableBundle config) { - sOverrideConfigForTest = config; + overrideConfigForTest = config; } private boolean isCarrierAppPreloaded() { diff --git a/java/com/android/voicemail/impl/TelephonyVvmConfigManager.java b/java/com/android/voicemail/impl/TelephonyVvmConfigManager.java index 046113c26..ecf4e6ffc 100644 --- a/java/com/android/voicemail/impl/TelephonyVvmConfigManager.java +++ b/java/com/android/voicemail/impl/TelephonyVvmConfigManager.java @@ -43,28 +43,28 @@ public class TelephonyVvmConfigManager { private static final String KEY_FEATURE_FLAG_NAME = "feature_flag_name"; - private static Map sCachedConfigs; + private static Map cachedConfigs; - private final Map mConfigs; + private final Map configs; public TelephonyVvmConfigManager(Context context) { - if (sCachedConfigs == null) { - sCachedConfigs = loadConfigs(context, context.getResources().getXml(R.xml.vvm_config)); + if (cachedConfigs == null) { + cachedConfigs = loadConfigs(context, context.getResources().getXml(R.xml.vvm_config)); } - mConfigs = sCachedConfigs; + configs = cachedConfigs; } @VisibleForTesting TelephonyVvmConfigManager(Context context, XmlPullParser parser) { - mConfigs = loadConfigs(context, parser); + configs = loadConfigs(context, parser); } @Nullable public PersistableBundle getConfig(String mccMnc) { if (USE_DEBUG_CONFIG) { - return mConfigs.get("TEST"); + return configs.get("TEST"); } - return mConfigs.get(mccMnc); + return configs.get(mccMnc); } private static Map loadConfigs(Context context, XmlPullParser parser) { diff --git a/java/com/android/voicemail/impl/Voicemail.java b/java/com/android/voicemail/impl/Voicemail.java index f98d56f0a..a2282a92a 100644 --- a/java/com/android/voicemail/impl/Voicemail.java +++ b/java/com/android/voicemail/impl/Voicemail.java @@ -25,17 +25,17 @@ import android.text.TextUtils; /** Represents a single voicemail stored in the voicemail content provider. */ public class Voicemail implements Parcelable { - private final Long mTimestamp; - private final String mNumber; - private final PhoneAccountHandle mPhoneAccount; - private final Long mId; - private final Long mDuration; - private final String mSource; - private final String mProviderData; - private final Uri mUri; - private final Boolean mIsRead; - private final Boolean mHasContent; - private final String mTranscription; + private final Long timestamp; + private final String number; + private final PhoneAccountHandle phoneAccount; + private final Long id; + private final Long duration; + private final String source; + private final String providerData; + private final Uri uri; + private final Boolean isRead; + private final Boolean hasContent; + private final String transcription; private Voicemail( Long timestamp, @@ -49,17 +49,17 @@ public class Voicemail implements Parcelable { Boolean isRead, Boolean hasContent, String transcription) { - mTimestamp = timestamp; - mNumber = number; - mPhoneAccount = phoneAccountHandle; - mId = id; - mDuration = duration; - mSource = source; - mProviderData = providerData; - mUri = uri; - mIsRead = isRead; - mHasContent = hasContent; - mTranscription = transcription; + this.timestamp = timestamp; + this.number = number; + phoneAccount = phoneAccountHandle; + this.id = id; + this.duration = duration; + this.source = source; + this.providerData = providerData; + this.uri = uri; + this.isRead = isRead; + this.hasContent = hasContent; + this.transcription = transcription; } /** @@ -89,93 +89,93 @@ public class Voicemail implements Parcelable { */ public static class Builder { - private Long mBuilderTimestamp; - private String mBuilderNumber; - private PhoneAccountHandle mBuilderPhoneAccount; - private Long mBuilderId; - private Long mBuilderDuration; - private String mBuilderSourcePackage; - private String mBuilderSourceData; - private Uri mBuilderUri; - private Boolean mBuilderIsRead; - private boolean mBuilderHasContent; - private String mBuilderTranscription; + private Long builderTimestamp; + private String builderNumber; + private PhoneAccountHandle builderPhoneAccount; + private Long builderId; + private Long builderDuration; + private String builderSourcePackage; + private String builderSourceData; + private Uri builderUri; + private Boolean builderIsRead; + private boolean builderHasContent; + private String builderTranscription; /** You should use the correct factory method to construct a builder. */ private Builder() {} public Builder setNumber(String number) { - mBuilderNumber = number; + builderNumber = number; return this; } public Builder setTimestamp(long timestamp) { - mBuilderTimestamp = timestamp; + builderTimestamp = timestamp; return this; } public Builder setPhoneAccount(PhoneAccountHandle phoneAccount) { - mBuilderPhoneAccount = phoneAccount; + builderPhoneAccount = phoneAccount; return this; } public Builder setId(long id) { - mBuilderId = id; + builderId = id; return this; } public Builder setDuration(long duration) { - mBuilderDuration = duration; + builderDuration = duration; return this; } public Builder setSourcePackage(String sourcePackage) { - mBuilderSourcePackage = sourcePackage; + builderSourcePackage = sourcePackage; return this; } public Builder setSourceData(String sourceData) { - mBuilderSourceData = sourceData; + builderSourceData = sourceData; return this; } public Builder setUri(Uri uri) { - mBuilderUri = uri; + builderUri = uri; return this; } public Builder setIsRead(boolean isRead) { - mBuilderIsRead = isRead; + builderIsRead = isRead; return this; } public Builder setHasContent(boolean hasContent) { - mBuilderHasContent = hasContent; + builderHasContent = hasContent; return this; } public Builder setTranscription(String transcription) { - mBuilderTranscription = transcription; + builderTranscription = transcription; return this; } public Voicemail build() { - mBuilderId = mBuilderId == null ? -1 : mBuilderId; - mBuilderTimestamp = mBuilderTimestamp == null ? 0 : mBuilderTimestamp; - mBuilderDuration = mBuilderDuration == null ? 0 : mBuilderDuration; - mBuilderIsRead = mBuilderIsRead == null ? false : mBuilderIsRead; + builderId = builderId == null ? -1 : builderId; + builderTimestamp = builderTimestamp == null ? 0 : builderTimestamp; + builderDuration = builderDuration == null ? 0 : builderDuration; + builderIsRead = builderIsRead == null ? false : builderIsRead; return new Voicemail( - mBuilderTimestamp, - mBuilderNumber, - mBuilderPhoneAccount, - mBuilderId, - mBuilderDuration, - mBuilderSourcePackage, - mBuilderSourceData, - mBuilderUri, - mBuilderIsRead, - mBuilderHasContent, - mBuilderTranscription); + builderTimestamp, + builderNumber, + builderPhoneAccount, + builderId, + builderDuration, + builderSourcePackage, + builderSourceData, + builderUri, + builderIsRead, + builderHasContent, + builderTranscription); } } @@ -187,27 +187,27 @@ public class Voicemail implements Parcelable { * none is specified, we return -1. */ public long getId() { - return mId; + return id; } /** The number of the person leaving the voicemail, empty string if unknown, null if not set. */ public String getNumber() { - return mNumber; + return number; } /** The phone account associated with the voicemail, null if not set. */ public PhoneAccountHandle getPhoneAccount() { - return mPhoneAccount; + return phoneAccount; } /** The timestamp the voicemail was received, in millis since the epoch, zero if not set. */ public long getTimestampMillis() { - return mTimestamp; + return timestamp; } /** Gets the duration of the voicemail in millis, or zero if the field is not set. */ public long getDuration() { - return mDuration; + return duration; } /** @@ -215,7 +215,7 @@ public class Voicemail implements Parcelable { * set. */ public String getSourcePackage() { - return mSource; + return source; } /** @@ -227,7 +227,7 @@ public class Voicemail implements Parcelable { * server-generated identifying string. */ public String getSourceData() { - return mProviderData; + return providerData; } /** @@ -236,7 +236,7 @@ public class Voicemail implements Parcelable { *

Returns null if we don't know the Uri. */ public Uri getUri() { - return mUri; + return uri; } /** @@ -245,17 +245,17 @@ public class Voicemail implements Parcelable { *

Always returns false if this field has not been set, i.e. if hasRead() returns false. */ public boolean isRead() { - return mIsRead; + return isRead; } /** Tells us if there is content stored at the Uri. */ public boolean hasContent() { - return mHasContent; + return hasContent; } /** Returns the text transcription of this voicemail, or null if this field is not set. */ public String getTranscription() { - return mTranscription; + return transcription; } @Override @@ -265,35 +265,35 @@ public class Voicemail implements Parcelable { @Override public void writeToParcel(Parcel dest, int flags) { - dest.writeLong(mTimestamp); - writeCharSequence(dest, mNumber); - if (mPhoneAccount == null) { + dest.writeLong(timestamp); + writeCharSequence(dest, number); + if (phoneAccount == null) { dest.writeInt(0); } else { dest.writeInt(1); - mPhoneAccount.writeToParcel(dest, flags); + phoneAccount.writeToParcel(dest, flags); } - dest.writeLong(mId); - dest.writeLong(mDuration); - writeCharSequence(dest, mSource); - writeCharSequence(dest, mProviderData); - if (mUri == null) { + dest.writeLong(id); + dest.writeLong(duration); + writeCharSequence(dest, source); + writeCharSequence(dest, providerData); + if (uri == null) { dest.writeInt(0); } else { dest.writeInt(1); - mUri.writeToParcel(dest, flags); + uri.writeToParcel(dest, flags); } - if (mIsRead) { + if (isRead) { dest.writeInt(1); } else { dest.writeInt(0); } - if (mHasContent) { + if (hasContent) { dest.writeInt(1); } else { dest.writeInt(0); } - writeCharSequence(dest, mTranscription); + writeCharSequence(dest, transcription); } public static final Creator CREATOR = @@ -310,25 +310,25 @@ public class Voicemail implements Parcelable { }; private Voicemail(Parcel in) { - mTimestamp = in.readLong(); - mNumber = (String) readCharSequence(in); + timestamp = in.readLong(); + number = (String) readCharSequence(in); if (in.readInt() > 0) { - mPhoneAccount = PhoneAccountHandle.CREATOR.createFromParcel(in); + phoneAccount = PhoneAccountHandle.CREATOR.createFromParcel(in); } else { - mPhoneAccount = null; + phoneAccount = null; } - mId = in.readLong(); - mDuration = in.readLong(); - mSource = (String) readCharSequence(in); - mProviderData = (String) readCharSequence(in); + id = in.readLong(); + duration = in.readLong(); + source = (String) readCharSequence(in); + providerData = (String) readCharSequence(in); if (in.readInt() > 0) { - mUri = Uri.CREATOR.createFromParcel(in); + uri = Uri.CREATOR.createFromParcel(in); } else { - mUri = null; + uri = null; } - mIsRead = in.readInt() > 0 ? true : false; - mHasContent = in.readInt() > 0 ? true : false; - mTranscription = (String) readCharSequence(in); + isRead = in.readInt() > 0 ? true : false; + hasContent = in.readInt() > 0 ? true : false; + transcription = (String) readCharSequence(in); } private static CharSequence readCharSequence(Parcel in) { diff --git a/java/com/android/voicemail/impl/VoicemailStatus.java b/java/com/android/voicemail/impl/VoicemailStatus.java index a24bad4c4..2ebc49b05 100644 --- a/java/com/android/voicemail/impl/VoicemailStatus.java +++ b/java/com/android/voicemail/impl/VoicemailStatus.java @@ -32,15 +32,15 @@ public class VoicemailStatus { public static class Editor { - private final Context mContext; - @Nullable private final PhoneAccountHandle mPhoneAccountHandle; + private final Context context; + @Nullable private final PhoneAccountHandle phoneAccountHandle; - private ContentValues mValues = new ContentValues(); + private ContentValues values = new ContentValues(); private Editor(Context context, PhoneAccountHandle phoneAccountHandle) { - mContext = context; - mPhoneAccountHandle = phoneAccountHandle; - if (mPhoneAccountHandle == null) { + this.context = context; + this.phoneAccountHandle = phoneAccountHandle; + if (this.phoneAccountHandle == null) { VvmLog.w( TAG, "VoicemailStatus.Editor created with null phone account, status will" @@ -50,26 +50,26 @@ public class VoicemailStatus { @Nullable public PhoneAccountHandle getPhoneAccountHandle() { - return mPhoneAccountHandle; + return phoneAccountHandle; } public Editor setType(String type) { - mValues.put(Status.SOURCE_TYPE, type); + values.put(Status.SOURCE_TYPE, type); return this; } public Editor setConfigurationState(int configurationState) { - mValues.put(Status.CONFIGURATION_STATE, configurationState); + values.put(Status.CONFIGURATION_STATE, configurationState); return this; } public Editor setDataChannelState(int dataChannelState) { - mValues.put(Status.DATA_CHANNEL_STATE, dataChannelState); + values.put(Status.DATA_CHANNEL_STATE, dataChannelState); return this; } public Editor setNotificationChannelState(int notificationChannelState) { - mValues.put(Status.NOTIFICATION_CHANNEL_STATE, notificationChannelState); + values.put(Status.NOTIFICATION_CHANNEL_STATE, notificationChannelState); return this; } @@ -79,8 +79,8 @@ public class VoicemailStatus { return this; } - mValues.put(Status.QUOTA_OCCUPIED, occupied); - mValues.put(Status.QUOTA_TOTAL, total); + values.put(Status.QUOTA_OCCUPIED, occupied); + values.put(Status.QUOTA_TOTAL, total); return this; } @@ -90,28 +90,28 @@ public class VoicemailStatus { * @return {@code true} if the changes were successfully applied, {@code false} otherwise. */ public boolean apply() { - if (mPhoneAccountHandle == null) { + if (phoneAccountHandle == null) { return false; } - mValues.put( + values.put( Status.PHONE_ACCOUNT_COMPONENT_NAME, - mPhoneAccountHandle.getComponentName().flattenToString()); - mValues.put(Status.PHONE_ACCOUNT_ID, mPhoneAccountHandle.getId()); - ContentResolver contentResolver = mContext.getContentResolver(); - Uri statusUri = VoicemailContract.Status.buildSourceUri(mContext.getPackageName()); + phoneAccountHandle.getComponentName().flattenToString()); + values.put(Status.PHONE_ACCOUNT_ID, phoneAccountHandle.getId()); + ContentResolver contentResolver = context.getContentResolver(); + Uri statusUri = VoicemailContract.Status.buildSourceUri(context.getPackageName()); try { - StrictModeUtils.bypass(() -> contentResolver.insert(statusUri, mValues)); + StrictModeUtils.bypass(() -> contentResolver.insert(statusUri, values)); } catch (IllegalArgumentException iae) { VvmLog.e(TAG, "apply :: failed to insert content resolver ", iae); - mValues.clear(); + values.clear(); return false; } - mValues.clear(); + values.clear(); return true; } public ContentValues getValues() { - return mValues; + return values; } } diff --git a/java/com/android/voicemail/impl/VvmLog.java b/java/com/android/voicemail/impl/VvmLog.java index 6dc4fa6c0..7d47904cc 100644 --- a/java/com/android/voicemail/impl/VvmLog.java +++ b/java/com/android/voicemail/impl/VvmLog.java @@ -30,7 +30,7 @@ public class VvmLog { private static final int MAX_OMTP_VVM_LOGS = 100; - private static final LocalLog sLocalLog = new LocalLog(MAX_OMTP_VVM_LOGS); + private static final LocalLog localLog = new LocalLog(MAX_OMTP_VVM_LOGS); public static void log(String tag, String log) { PersistentLogger.logText(tag, log); @@ -39,7 +39,7 @@ public class VvmLog { public static void dump(FileDescriptor fd, PrintWriter printwriter, String[] args) { IndentingPrintWriter indentingPrintWriter = new IndentingPrintWriter(printwriter, " "); indentingPrintWriter.increaseIndent(); - sLocalLog.dump(fd, indentingPrintWriter, args); + localLog.dump(fd, indentingPrintWriter, args); indentingPrintWriter.decreaseIndent(); } @@ -116,16 +116,16 @@ public class VvmLog { public static class LocalLog { - private final Deque mLog; - private final int mMaxLines; + private final Deque log; + private final int maxLines; public LocalLog(int maxLines) { - mMaxLines = Math.max(0, maxLines); - mLog = new ArrayDeque<>(mMaxLines); + this.maxLines = Math.max(0, maxLines); + log = new ArrayDeque<>(this.maxLines); } public void log(String msg) { - if (mMaxLines <= 0) { + if (maxLines <= 0) { return; } Calendar c = Calendar.getInstance(); @@ -134,21 +134,21 @@ public class VvmLog { } private synchronized void append(String logLine) { - while (mLog.size() >= mMaxLines) { - mLog.remove(); + while (log.size() >= maxLines) { + log.remove(); } - mLog.add(logLine); + log.add(logLine); } public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - Iterator itr = mLog.iterator(); + Iterator itr = log.iterator(); while (itr.hasNext()) { pw.println(itr.next()); } } public synchronized void reverseDump(FileDescriptor fd, PrintWriter pw, String[] args) { - Iterator itr = mLog.descendingIterator(); + Iterator itr = log.descendingIterator(); while (itr.hasNext()) { pw.println(itr.next()); } @@ -156,18 +156,18 @@ public class VvmLog { public static class ReadOnlyLocalLog { - private final LocalLog mLog; + private final LocalLog log; ReadOnlyLocalLog(LocalLog log) { - mLog = log; + this.log = log; } public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { - mLog.dump(fd, pw, args); + log.dump(fd, pw, args); } public void reverseDump(FileDescriptor fd, PrintWriter pw, String[] args) { - mLog.reverseDump(fd, pw, args); + log.reverseDump(fd, pw, args); } } diff --git a/java/com/android/voicemail/impl/VvmPhoneStateListener.java b/java/com/android/voicemail/impl/VvmPhoneStateListener.java index 914120b69..a9082e895 100644 --- a/java/com/android/voicemail/impl/VvmPhoneStateListener.java +++ b/java/com/android/voicemail/impl/VvmPhoneStateListener.java @@ -31,73 +31,73 @@ public class VvmPhoneStateListener extends PhoneStateListener { private static final String TAG = "VvmPhoneStateListener"; - private PhoneAccountHandle mPhoneAccount; - private Context mContext; - private int mPreviousState = -1; + private PhoneAccountHandle phoneAccount; + private Context context; + private int previousState = -1; public VvmPhoneStateListener(Context context, PhoneAccountHandle accountHandle) { // TODO(twyen): a bug too much trouble to call super constructor through reflection, // just use non-phoneAccountHandle version for now. super(); - mContext = context; - mPhoneAccount = accountHandle; + this.context = context; + phoneAccount = accountHandle; } @Override public void onServiceStateChanged(ServiceState serviceState) { - if (mPhoneAccount == null) { + if (phoneAccount == null) { VvmLog.e( TAG, "onServiceStateChanged on phoneAccount " - + mPhoneAccount + + phoneAccount + " with invalid phoneAccountHandle, ignoring"); return; } int state = serviceState.getState(); - if (state == mPreviousState + if (state == previousState || (state != ServiceState.STATE_IN_SERVICE - && mPreviousState != ServiceState.STATE_IN_SERVICE)) { + && previousState != ServiceState.STATE_IN_SERVICE)) { // Only interested in state changes or transitioning into or out of "in service". // Otherwise just quit. - mPreviousState = state; + previousState = state; return; } - OmtpVvmCarrierConfigHelper helper = new OmtpVvmCarrierConfigHelper(mContext, mPhoneAccount); + OmtpVvmCarrierConfigHelper helper = new OmtpVvmCarrierConfigHelper(context, phoneAccount); if (state == ServiceState.STATE_IN_SERVICE) { VoicemailStatusQueryHelper voicemailStatusQueryHelper = - new VoicemailStatusQueryHelper(mContext); - if (voicemailStatusQueryHelper.isVoicemailSourceConfigured(mPhoneAccount)) { - if (!voicemailStatusQueryHelper.isNotificationsChannelActive(mPhoneAccount)) { - VvmLog.v(TAG, "Notifications channel is active for " + mPhoneAccount); + new VoicemailStatusQueryHelper(context); + if (voicemailStatusQueryHelper.isVoicemailSourceConfigured(phoneAccount)) { + if (!voicemailStatusQueryHelper.isNotificationsChannelActive(phoneAccount)) { + VvmLog.v(TAG, "Notifications channel is active for " + phoneAccount); helper.handleEvent( - VoicemailStatus.edit(mContext, mPhoneAccount), OmtpEvents.NOTIFICATION_IN_SERVICE); + VoicemailStatus.edit(context, phoneAccount), OmtpEvents.NOTIFICATION_IN_SERVICE); } } - if (VvmAccountManager.isAccountActivated(mContext, mPhoneAccount)) { - VvmLog.v(TAG, "Signal returned: requesting resync for " + mPhoneAccount); + if (VvmAccountManager.isAccountActivated(context, phoneAccount)) { + VvmLog.v(TAG, "Signal returned: requesting resync for " + phoneAccount); // If the source is already registered, run a full sync in case something was missed // while signal was down. - SyncTask.start(mContext, mPhoneAccount); + SyncTask.start(context, phoneAccount); } else { - VvmLog.v(TAG, "Signal returned: reattempting activation for " + mPhoneAccount); + VvmLog.v(TAG, "Signal returned: reattempting activation for " + phoneAccount); // Otherwise initiate an activation because this means that an OMTP source was // recognized but either the activation text was not successfully sent or a response // was not received. helper.startActivation(); } } else { - VvmLog.v(TAG, "Notifications channel is inactive for " + mPhoneAccount); + VvmLog.v(TAG, "Notifications channel is inactive for " + phoneAccount); - if (!VvmAccountManager.isAccountActivated(mContext, mPhoneAccount)) { + if (!VvmAccountManager.isAccountActivated(context, phoneAccount)) { return; } helper.handleEvent( - VoicemailStatus.edit(mContext, mPhoneAccount), OmtpEvents.NOTIFICATION_SERVICE_LOST); + VoicemailStatus.edit(context, phoneAccount), OmtpEvents.NOTIFICATION_SERVICE_LOST); } - mPreviousState = state; + previousState = state; } } diff --git a/java/com/android/voicemail/impl/fetch/FetchVoicemailReceiver.java b/java/com/android/voicemail/impl/fetch/FetchVoicemailReceiver.java index 0348a60c5..9fda37343 100644 --- a/java/com/android/voicemail/impl/fetch/FetchVoicemailReceiver.java +++ b/java/com/android/voicemail/impl/fetch/FetchVoicemailReceiver.java @@ -64,13 +64,13 @@ public class FetchVoicemailReceiver extends BroadcastReceiver { // Number of retries private static final int NETWORK_RETRY_COUNT = 3; - private ContentResolver mContentResolver; - private Uri mUri; - private VvmNetworkRequestCallback mNetworkCallback; - private Context mContext; - private String mUid; - private PhoneAccountHandle mPhoneAccount; - private int mRetryCount = NETWORK_RETRY_COUNT; + private ContentResolver contentResolver; + private Uri uri; + private VvmNetworkRequestCallback networkCallback; + private Context context; + private String uid; + private PhoneAccountHandle phoneAccount; + private int retryCount = NETWORK_RETRY_COUNT; @Override public void onReceive(final Context context, Intent intent) { @@ -79,31 +79,31 @@ public class FetchVoicemailReceiver extends BroadcastReceiver { } if (VoicemailContract.ACTION_FETCH_VOICEMAIL.equals(intent.getAction())) { VvmLog.i(TAG, "ACTION_FETCH_VOICEMAIL received"); - mContext = context; - mContentResolver = context.getContentResolver(); - mUri = intent.getData(); + this.context = context; + contentResolver = context.getContentResolver(); + uri = intent.getData(); - if (mUri == null) { + if (uri == null) { VvmLog.w(TAG, VoicemailContract.ACTION_FETCH_VOICEMAIL + " intent sent with no data"); return; } if (!context .getPackageName() - .equals(mUri.getQueryParameter(VoicemailContract.PARAM_KEY_SOURCE_PACKAGE))) { + .equals(uri.getQueryParameter(VoicemailContract.PARAM_KEY_SOURCE_PACKAGE))) { // Ignore if the fetch request is for a voicemail not from this package. VvmLog.e(TAG, "ACTION_FETCH_VOICEMAIL from foreign pacakge " + context.getPackageName()); return; } - Cursor cursor = mContentResolver.query(mUri, PROJECTION, null, null, null); + Cursor cursor = contentResolver.query(uri, PROJECTION, null, null, null); if (cursor == null) { VvmLog.i(TAG, "ACTION_FETCH_VOICEMAIL query returned null"); return; } try { if (cursor.moveToFirst()) { - mUid = cursor.getString(SOURCE_DATA); + uid = cursor.getString(SOURCE_DATA); String accountId = cursor.getString(PHONE_ACCOUNT_ID); if (TextUtils.isEmpty(accountId)) { TelephonyManager telephonyManager = @@ -116,31 +116,31 @@ public class FetchVoicemailReceiver extends BroadcastReceiver { } } - mPhoneAccount = + phoneAccount = new PhoneAccountHandle( ComponentName.unflattenFromString(cursor.getString(PHONE_ACCOUNT_COMPONENT_NAME)), cursor.getString(PHONE_ACCOUNT_ID)); TelephonyManager telephonyManager = context .getSystemService(TelephonyManager.class) - .createForPhoneAccountHandle(mPhoneAccount); + .createForPhoneAccountHandle(phoneAccount); if (telephonyManager == null) { // can happen when trying to fetch voicemails from a SIM that is no longer on the // device VvmLog.e(TAG, "account no longer valid, cannot retrieve message"); return; } - if (!VvmAccountManager.isAccountActivated(context, mPhoneAccount)) { - mPhoneAccount = getAccountFromMarshmallowAccount(context, mPhoneAccount); - if (mPhoneAccount == null) { + if (!VvmAccountManager.isAccountActivated(context, phoneAccount)) { + phoneAccount = getAccountFromMarshmallowAccount(context, phoneAccount); + if (phoneAccount == null) { VvmLog.w(TAG, "Account not registered - cannot retrieve message."); return; } VvmLog.i(TAG, "Fetching voicemail with Marshmallow PhoneAccountHandle"); } VvmLog.i(TAG, "Requesting network to fetch voicemail"); - mNetworkCallback = new fetchVoicemailNetworkRequestCallback(context, mPhoneAccount); - mNetworkCallback.requestNetwork(); + networkCallback = new fetchVoicemailNetworkRequestCallback(context, phoneAccount); + networkCallback.requestNetwork(); } } finally { cursor.close(); @@ -203,16 +203,16 @@ public class FetchVoicemailReceiver extends BroadcastReceiver { @Override public void run() { try { - while (mRetryCount > 0) { - VvmLog.i(TAG, "fetching voicemail, retry count=" + mRetryCount); + while (retryCount > 0) { + VvmLog.i(TAG, "fetching voicemail, retry count=" + retryCount); try (ImapHelper imapHelper = - new ImapHelper(mContext, mPhoneAccount, network, status)) { + new ImapHelper(context, phoneAccount, network, status)) { boolean success = imapHelper.fetchVoicemailPayload( - new VoicemailFetchedCallback(mContext, mUri, mPhoneAccount), mUid); - if (!success && mRetryCount > 0) { + new VoicemailFetchedCallback(context, uri, phoneAccount), uid); + if (!success && retryCount > 0) { VvmLog.i(TAG, "fetch voicemail failed, retrying"); - mRetryCount--; + retryCount--; } else { return; } @@ -222,8 +222,8 @@ public class FetchVoicemailReceiver extends BroadcastReceiver { } } } finally { - if (mNetworkCallback != null) { - mNetworkCallback.releaseNetwork(); + if (networkCallback != null) { + networkCallback.releaseNetwork(); } } } diff --git a/java/com/android/voicemail/impl/fetch/VoicemailFetchedCallback.java b/java/com/android/voicemail/impl/fetch/VoicemailFetchedCallback.java index e8e14bedb..78dbdc06f 100644 --- a/java/com/android/voicemail/impl/fetch/VoicemailFetchedCallback.java +++ b/java/com/android/voicemail/impl/fetch/VoicemailFetchedCallback.java @@ -40,16 +40,16 @@ import org.apache.commons.io.IOUtils; public class VoicemailFetchedCallback { private static final String TAG = "VoicemailFetchedCallback"; - private final Context mContext; - private final ContentResolver mContentResolver; - private final Uri mUri; - private final PhoneAccountHandle mPhoneAccountHandle; + private final Context context; + private final ContentResolver contentResolver; + private final Uri uri; + private final PhoneAccountHandle phoneAccountHandle; public VoicemailFetchedCallback(Context context, Uri uri, PhoneAccountHandle phoneAccountHandle) { - mContext = context; - mContentResolver = context.getContentResolver(); - mUri = uri; - mPhoneAccountHandle = phoneAccountHandle; + this.context = context; + contentResolver = context.getContentResolver(); + this.uri = uri; + this.phoneAccountHandle = phoneAccountHandle; } /** @@ -65,26 +65,26 @@ public class VoicemailFetchedCallback { ContentValues values = new ContentValues(); values.put( Voicemails.TRANSCRIPTION, - mContext.getString( + context.getString( R.string.vvm_unsupported_message_format, - mContext + context .getSystemService(TelecomManager.class) - .getVoiceMailNumber(mPhoneAccountHandle))); + .getVoiceMailNumber(phoneAccountHandle))); updateVoicemail(values); return; } - VvmLog.d(TAG, String.format("Writing new voicemail content: %s", mUri)); + VvmLog.d(TAG, String.format("Writing new voicemail content: %s", uri)); OutputStream outputStream = null; try { - outputStream = mContentResolver.openOutputStream(mUri); + outputStream = contentResolver.openOutputStream(uri); byte[] inputBytes = voicemailPayload.getBytes(); if (inputBytes != null) { outputStream.write(inputBytes); } } catch (IOException e) { - VvmLog.w(TAG, String.format("File not found for %s", mUri)); + VvmLog.w(TAG, String.format("File not found for %s", uri)); return; } finally { IOUtils.closeQuietly(outputStream); @@ -98,15 +98,15 @@ public class VoicemailFetchedCallback { ThreadUtil.postOnUiThread( () -> { if (!TranscriptionService.scheduleNewVoicemailTranscriptionJob( - mContext, mUri, mPhoneAccountHandle, true)) { - VvmLog.w(TAG, String.format("Failed to schedule transcription for %s", mUri)); + context, uri, phoneAccountHandle, true)) { + VvmLog.w(TAG, String.format("Failed to schedule transcription for %s", uri)); } }); } } private boolean updateVoicemail(ContentValues values) { - int updatedCount = mContentResolver.update(mUri, values, null, null); + int updatedCount = contentResolver.update(uri, values, null, null); if (updatedCount != 1) { VvmLog.e(TAG, "Updating voicemail should have updated 1 row, was: " + updatedCount); return false; diff --git a/java/com/android/voicemail/impl/imap/ImapHelper.java b/java/com/android/voicemail/impl/imap/ImapHelper.java index a0e86dcae..1f04edbef 100644 --- a/java/com/android/voicemail/impl/imap/ImapHelper.java +++ b/java/com/android/voicemail/impl/imap/ImapHelper.java @@ -66,17 +66,17 @@ public class ImapHelper implements Closeable { private static final String TAG = "ImapHelper"; - private ImapFolder mFolder; - private ImapStore mImapStore; + private ImapFolder folder; + private ImapStore imapStore; - private final Context mContext; - private final PhoneAccountHandle mPhoneAccount; - private final Network mNetwork; - private final Editor mStatus; + private final Context context; + private final PhoneAccountHandle phoneAccount; + private final Network network; + private final Editor status; - VisualVoicemailPreferences mPrefs; + VisualVoicemailPreferences prefs; - private final OmtpVvmCarrierConfigHelper mConfig; + private final OmtpVvmCarrierConfigHelper config; /** InitializingException */ public static class InitializingException extends Exception { @@ -104,30 +104,29 @@ public class ImapHelper implements Closeable { Network network, Editor status) throws InitializingException { - mContext = context; - mPhoneAccount = phoneAccount; - mNetwork = network; - mStatus = status; - mConfig = config; - mPrefs = new VisualVoicemailPreferences(context, phoneAccount); + this.context = context; + this.phoneAccount = phoneAccount; + this.network = network; + this.status = status; + this.config = config; + prefs = new VisualVoicemailPreferences(context, phoneAccount); try { TempDirectory.setTempDirectory(context); - String username = mPrefs.getString(OmtpConstants.IMAP_USER_NAME, null); - String password = mPrefs.getString(OmtpConstants.IMAP_PASSWORD, null); - String serverName = mPrefs.getString(OmtpConstants.SERVER_ADDRESS, null); - int port = Integer.parseInt(mPrefs.getString(OmtpConstants.IMAP_PORT, null)); + String username = prefs.getString(OmtpConstants.IMAP_USER_NAME, null); + String password = prefs.getString(OmtpConstants.IMAP_PASSWORD, null); + String serverName = prefs.getString(OmtpConstants.SERVER_ADDRESS, null); + int port = Integer.parseInt(prefs.getString(OmtpConstants.IMAP_PORT, null)); int auth = ImapStore.FLAG_NONE; - int sslPort = mConfig.getSslPort(); + int sslPort = this.config.getSslPort(); if (sslPort != 0) { port = sslPort; auth = ImapStore.FLAG_SSL; } - mImapStore = - new ImapStore(context, this, username, password, port, serverName, auth, network); + imapStore = new ImapStore(context, this, username, password, port, serverName, auth, network); } catch (NumberFormatException e) { handleEvent(OmtpEvents.DATA_INVALID_PORT); LogUtils.w(TAG, "Could not parse port number"); @@ -137,13 +136,13 @@ public class ImapHelper implements Closeable { @Override public void close() { - mImapStore.closeConnection(); + imapStore.closeConnection(); } public boolean isRoaming() { ConnectivityManager connectivityManager = - (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); - NetworkInfo info = connectivityManager.getNetworkInfo(mNetwork); + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo info = connectivityManager.getNetworkInfo(network); if (info == null) { return false; } @@ -151,11 +150,11 @@ public class ImapHelper implements Closeable { } public OmtpVvmCarrierConfigHelper getConfig() { - return mConfig; + return config; } public ImapConnection connect() { - return mImapStore.getConnection(); + return imapStore.getConnection(); } /** The caller thread will block until the method returns. */ @@ -169,7 +168,7 @@ public class ImapHelper implements Closeable { } public void handleEvent(OmtpEvents event) { - mConfig.handleEvent(mStatus, event); + config.handleEvent(status, event); } /** @@ -184,9 +183,9 @@ public class ImapHelper implements Closeable { return false; } try { - mFolder = openImapFolder(ImapFolder.MODE_READ_WRITE); - if (mFolder != null) { - mFolder.setFlags(convertToImapMessages(voicemails), flags, true); + folder = openImapFolder(ImapFolder.MODE_READ_WRITE); + if (folder != null) { + folder.setFlags(convertToImapMessages(voicemails), flags, true); return true; } return false; @@ -207,14 +206,14 @@ public class ImapHelper implements Closeable { List result = new ArrayList(); Message[] messages; try { - mFolder = openImapFolder(ImapFolder.MODE_READ_WRITE); - if (mFolder == null) { + folder = openImapFolder(ImapFolder.MODE_READ_WRITE); + if (folder == null) { // This means we were unable to successfully open the folder. return null; } // This method retrieves lightweight messages containing only the uid of the message. - messages = mFolder.getMessages(null); + messages = folder.getMessages(null); for (Message message : messages) { // Get the voicemail details (message structure). @@ -245,7 +244,7 @@ public class ImapHelper implements Closeable { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(messageStructureWrapper.transcriptionBodyPart); - mFolder.fetch(new Message[] {messageDetails}, fetchProfile, listener); + folder.fetch(new Message[] {messageDetails}, fetchProfile, listener); } // Found an audio attachment, this is a valid voicemail. @@ -255,8 +254,8 @@ public class ImapHelper implements Closeable { Long duration = messageDetails.getDuration(); Voicemail.Builder builder = Voicemail.createForInsertion(time, number) - .setPhoneAccount(mPhoneAccount) - .setSourcePackage(mContext.getPackageName()) + .setPhoneAccount(phoneAccount) + .setSourcePackage(context.getPackageName()) .setSourceData(messageDetails.getUid()) .setIsRead(isRead) .setTranscription(listener.getVoicemailTranscription()); @@ -307,18 +306,18 @@ public class ImapHelper implements Closeable { // The IMAP folder fetch method will call "messageRetrieved" on the listener when the // message is successfully retrieved. - mFolder.fetch(new Message[] {message}, fetchProfile, listener); + folder.fetch(new Message[] {message}, fetchProfile, listener); return listener.getMessageStructure(); } public boolean fetchVoicemailPayload(VoicemailFetchedCallback callback, final String uid) { try { - mFolder = openImapFolder(ImapFolder.MODE_READ_WRITE); - if (mFolder == null) { + folder = openImapFolder(ImapFolder.MODE_READ_WRITE); + if (folder == null) { // This means we were unable to successfully open the folder. return false; } - Message message = mFolder.getMessage(uid); + Message message = folder.getMessage(uid); if (message == null) { return false; } @@ -345,19 +344,19 @@ public class ImapHelper implements Closeable { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(FetchProfile.Item.BODY); - mFolder.fetch(new Message[] {message}, fetchProfile, listener); + folder.fetch(new Message[] {message}, fetchProfile, listener); return listener.getVoicemailPayload(); } public boolean fetchTranscription(TranscriptionFetchedCallback callback, String uid) { try { - mFolder = openImapFolder(ImapFolder.MODE_READ_WRITE); - if (mFolder == null) { + folder = openImapFolder(ImapFolder.MODE_READ_WRITE); + if (folder == null) { // This means we were unable to successfully open the folder. return false; } - Message message = mFolder.getMessage(uid); + Message message = folder.getMessage(uid); if (message == null) { return false; } @@ -371,7 +370,7 @@ public class ImapHelper implements Closeable { // This method is called synchronously so the transcription will be populated // in the listener once the next method is called. - mFolder.fetch(new Message[] {message}, fetchProfile, listener); + folder.fetch(new Message[] {message}, fetchProfile, listener); callback.setVoicemailTranscription(listener.getVoicemailTranscription()); } } @@ -386,7 +385,7 @@ public class ImapHelper implements Closeable { @ChangePinResult public int changePin(String oldPin, String newPin) throws MessagingException { - ImapConnection connection = mImapStore.getConnection(); + ImapConnection connection = imapStore.getConnection(); try { String command = getConfig().getProtocol().getCommand(OmtpConstants.IMAP_CHANGE_TUI_PWD_FORMAT); @@ -401,7 +400,7 @@ public class ImapHelper implements Closeable { } public void changeVoicemailTuiLanguage(String languageCode) throws MessagingException { - ImapConnection connection = mImapStore.getConnection(); + ImapConnection connection = imapStore.getConnection(); try { String command = getConfig().getProtocol().getCommand(OmtpConstants.IMAP_CHANGE_VM_LANG_FORMAT); @@ -414,7 +413,7 @@ public class ImapHelper implements Closeable { } public void closeNewUserTutorial() throws MessagingException { - ImapConnection connection = mImapStore.getConnection(); + ImapConnection connection = imapStore.getConnection(); try { String command = getConfig().getProtocol().getCommand(OmtpConstants.IMAP_CLOSE_NUT); connection.executeSimpleCommand(command, false); @@ -457,12 +456,12 @@ public class ImapHelper implements Closeable { public void updateQuota() { try { - mFolder = openImapFolder(ImapFolder.MODE_READ_WRITE); - if (mFolder == null) { + folder = openImapFolder(ImapFolder.MODE_READ_WRITE); + if (folder == null) { // This means we were unable to successfully open the folder. return; } - updateQuota(mFolder); + updateQuota(folder); } catch (MessagingException e) { LogUtils.e(TAG, e, "Messaging Exception"); } finally { @@ -473,13 +472,13 @@ public class ImapHelper implements Closeable { @Nullable public Quota getQuota() { try { - mFolder = openImapFolder(ImapFolder.MODE_READ_ONLY); - if (mFolder == null) { + folder = openImapFolder(ImapFolder.MODE_READ_ONLY); + if (folder == null) { // This means we were unable to successfully open the folder. LogUtils.e(TAG, "Unable to open folder"); return null; } - return mFolder.getQuota(); + return folder.getQuota(); } catch (MessagingException e) { LogUtils.e(TAG, e, "Messaging Exception"); return null; @@ -505,7 +504,7 @@ public class ImapHelper implements Closeable { + quota.occupied + " new quota total:" + quota.total); - VoicemailStatus.edit(mContext, mPhoneAccount).setQuota(quota.occupied, quota.total).apply(); + VoicemailStatus.edit(context, phoneAccount).setQuota(quota.occupied, quota.total).apply(); LogUtils.i(TAG, "Updated quota occupied and total"); } @@ -525,12 +524,12 @@ public class ImapHelper implements Closeable { private final class MessageStructureFetchedListener implements ImapFolder.MessageRetrievalListener { - private MessageStructureWrapper mMessageStructure; + private MessageStructureWrapper messageStructure; public MessageStructureFetchedListener() {} public MessageStructureWrapper getMessageStructure() { - return mMessageStructure; + return messageStructure; } @Override @@ -538,8 +537,8 @@ public class ImapHelper implements Closeable { LogUtils.d(TAG, "Fetched message structure for " + message.getUid()); LogUtils.d(TAG, "Message retrieved: " + message); try { - mMessageStructure = getMessageOrNull(message); - if (mMessageStructure == null) { + messageStructure = getMessageOrNull(message); + if (messageStructure == null) { LogUtils.d(TAG, "This voicemail does not have an attachment..."); return; } @@ -591,11 +590,11 @@ public class ImapHelper implements Closeable { /** Listener for the message body being fetched. */ private final class MessageBodyFetchedListener implements ImapFolder.MessageRetrievalListener { - private VoicemailPayload mVoicemailPayload; + private VoicemailPayload voicemailPayload; /** Returns the fetch voicemail payload. */ public VoicemailPayload getVoicemailPayload() { - return mVoicemailPayload; + return voicemailPayload; } @Override @@ -603,7 +602,7 @@ public class ImapHelper implements Closeable { LogUtils.d(TAG, "Fetched message body for " + message.getUid()); LogUtils.d(TAG, "Message retrieved: " + message); try { - mVoicemailPayload = getVoicemailPayloadFromMessage(message); + voicemailPayload = getVoicemailPayloadFromMessage(message); } catch (MessagingException e) { LogUtils.e(TAG, "Messaging Exception:", e); } catch (IOException e) { @@ -633,18 +632,18 @@ public class ImapHelper implements Closeable { /** Listener for the transcription being fetched. */ private final class TranscriptionFetchedListener implements ImapFolder.MessageRetrievalListener { - private String mVoicemailTranscription; + private String voicemailTranscription; /** Returns the fetched voicemail transcription. */ public String getVoicemailTranscription() { - return mVoicemailTranscription; + return voicemailTranscription; } @Override public void messageRetrieved(Message message) { LogUtils.d(TAG, "Fetched transcription for " + message.getUid()); try { - mVoicemailTranscription = new String(getDataFromBody(message.getBody())); + voicemailTranscription = new String(getDataFromBody(message.getBody())); } catch (MessagingException e) { LogUtils.e(TAG, "Messaging Exception:", e); } catch (IOException e) { @@ -655,10 +654,10 @@ public class ImapHelper implements Closeable { private ImapFolder openImapFolder(String modeReadWrite) { try { - if (mImapStore == null) { + if (imapStore == null) { return null; } - ImapFolder folder = new ImapFolder(mImapStore, ImapConstants.INBOX); + ImapFolder folder = new ImapFolder(imapStore, ImapConstants.INBOX); folder.open(modeReadWrite); return folder; } catch (MessagingException e) { @@ -677,8 +676,8 @@ public class ImapHelper implements Closeable { } private void closeImapFolder() { - if (mFolder != null) { - mFolder.close(true); + if (folder != null) { + folder.close(true); } } diff --git a/java/com/android/voicemail/impl/imap/VoicemailPayload.java b/java/com/android/voicemail/impl/imap/VoicemailPayload.java index 69befb42f..e91726456 100644 --- a/java/com/android/voicemail/impl/imap/VoicemailPayload.java +++ b/java/com/android/voicemail/impl/imap/VoicemailPayload.java @@ -18,19 +18,19 @@ package com.android.voicemail.impl.imap; /** The payload for a voicemail, usually audio data. */ public class VoicemailPayload { - private final String mMimeType; - private final byte[] mBytes; + private final String mimeType; + private final byte[] bytes; public VoicemailPayload(String mimeType, byte[] bytes) { - mMimeType = mimeType; - mBytes = bytes; + this.mimeType = mimeType; + this.bytes = bytes; } public byte[] getBytes() { - return mBytes; + return bytes; } public String getMimeType() { - return mMimeType; + return mimeType; } } diff --git a/java/com/android/voicemail/impl/mail/Address.java b/java/com/android/voicemail/impl/mail/Address.java index ac8e8a294..7556e4d39 100644 --- a/java/com/android/voicemail/impl/mail/Address.java +++ b/java/com/android/voicemail/impl/mail/Address.java @@ -39,19 +39,19 @@ import org.apache.james.mime4j.codec.EncoderUtil; public class Address implements Parcelable { public static final String ADDRESS_DELIMETER = ","; /** Address part, in the form local_part@domain_part. No surrounding angle brackets. */ - private String mAddress; + private String address; /** * Name part. No surrounding double quote, and no MIME/base64 encoding. This must be null if * Address has no name part. */ - private String mPersonal; + private String personal; /** * When personal is set, it will return the first token of the personal string. Otherwise, it will * return the e-mail address up to the '@' sign. */ - private String mSimplifiedName; + private String simplifiedName; // Regex that matches address surrounded by '<>' optionally. '^]+)>?$' private static final Pattern REMOVE_OPTIONAL_BRACKET = Pattern.compile("^]+)>?$"); @@ -96,26 +96,26 @@ public class Address implements Parcelable { * first token of that name. Otherwise, it will return the e-mail address up to the '@' sign. */ public String getSimplifiedName() { - if (mSimplifiedName == null) { - if (TextUtils.isEmpty(mPersonal) && !TextUtils.isEmpty(mAddress)) { - int atSign = mAddress.indexOf('@'); - mSimplifiedName = (atSign != -1) ? mAddress.substring(0, atSign) : ""; - } else if (!TextUtils.isEmpty(mPersonal)) { + if (simplifiedName == null) { + if (TextUtils.isEmpty(personal) && !TextUtils.isEmpty(address)) { + int atSign = address.indexOf('@'); + simplifiedName = (atSign != -1) ? address.substring(0, atSign) : ""; + } else if (!TextUtils.isEmpty(personal)) { // TODO: use Contacts' NameSplitter for more reliable first-name extraction - int end = mPersonal.indexOf(' '); - while (end > 0 && mPersonal.charAt(end - 1) == ',') { + int end = personal.indexOf(' '); + while (end > 0 && personal.charAt(end - 1) == ',') { end--; } - mSimplifiedName = (end < 1) ? mPersonal : mPersonal.substring(0, end); + simplifiedName = (end < 1) ? personal : personal.substring(0, end); } else { LogUtils.w(LOG_TAG, "Unable to get a simplified name"); - mSimplifiedName = ""; + simplifiedName = ""; } } - return mSimplifiedName; + return simplifiedName; } public static synchronized Address getEmailAddress(String rawAddress) { @@ -137,11 +137,11 @@ public class Address implements Parcelable { } public String getAddress() { - return mAddress; + return address; } public void setAddress(String address) { - mAddress = REMOVE_OPTIONAL_BRACKET.matcher(address).replaceAll("$1"); + this.address = REMOVE_OPTIONAL_BRACKET.matcher(address).replaceAll("$1"); } /** @@ -150,7 +150,7 @@ public class Address implements Parcelable { * @return Name part of email address. Returns null if it is omitted. */ public String getPersonal() { - return mPersonal; + return personal; } /** @@ -160,7 +160,7 @@ public class Address implements Parcelable { * @param personal name part of email address as UTF-16 string. Null is acceptable. */ public void setPersonal(String personal) { - mPersonal = decodeAddressPersonal(personal); + this.personal = decodeAddressPersonal(personal); } /** @@ -265,14 +265,14 @@ public class Address implements Parcelable { */ @Override public String toString() { - if (mPersonal != null && !mPersonal.equals(mAddress)) { - if (mPersonal.matches(".*[\\(\\)<>@,;:\\\\\".\\[\\]].*")) { - return ensureQuotedString(mPersonal) + " <" + mAddress + ">"; + if (personal != null && !personal.equals(address)) { + if (personal.matches(".*[\\(\\)<>@,;:\\\\\".\\[\\]].*")) { + return ensureQuotedString(personal) + " <" + address + ">"; } else { - return mPersonal + " <" + mAddress + ">"; + return personal + " <" + address + ">"; } } else { - return mAddress; + return address; } } @@ -336,10 +336,10 @@ public class Address implements Parcelable { * and MIME/base64 encoded if necessary. */ public String toHeader() { - if (mPersonal != null) { - return EncoderUtil.encodeAddressDisplayName(mPersonal) + " <" + mAddress + ">"; + if (personal != null) { + return EncoderUtil.encodeAddressDisplayName(personal) + " <" + address + ">"; } else { - return mAddress; + return address; } } @@ -374,10 +374,10 @@ public class Address implements Parcelable { */ @VisibleForTesting public String toFriendly() { - if (mPersonal != null && mPersonal.length() > 0) { - return mPersonal; + if (personal != null && personal.length() > 0) { + return personal; } else { - return mAddress; + return address; } } @@ -516,7 +516,7 @@ public class Address implements Parcelable { @Override public void writeToParcel(Parcel out, int flags) { - out.writeString(mPersonal); - out.writeString(mAddress); + out.writeString(personal); + out.writeString(address); } } diff --git a/java/com/android/voicemail/impl/mail/Base64Body.java b/java/com/android/voicemail/impl/mail/Base64Body.java index def94dbb5..5c14296af 100644 --- a/java/com/android/voicemail/impl/mail/Base64Body.java +++ b/java/com/android/voicemail/impl/mail/Base64Body.java @@ -23,17 +23,17 @@ import java.io.OutputStream; import org.apache.commons.io.IOUtils; public class Base64Body implements Body { - private final InputStream mSource; + private final InputStream source; // Because we consume the input stream, we can only write out once - private boolean mAlreadyWritten; + private boolean alreadyWritten; public Base64Body(InputStream source) { - mSource = source; + this.source = source; } @Override public InputStream getInputStream() throws MessagingException { - return mSource; + return source; } /** @@ -47,15 +47,15 @@ public class Base64Body implements Body { @Override public void writeTo(OutputStream out) throws IllegalStateException, IOException, MessagingException { - if (mAlreadyWritten) { + if (alreadyWritten) { throw new IllegalStateException("Base64Body can only be written once"); } - mAlreadyWritten = true; + alreadyWritten = true; try { final Base64OutputStream b64out = new Base64OutputStream(out, Base64.DEFAULT); - IOUtils.copyLarge(mSource, b64out); + IOUtils.copyLarge(source, b64out); } finally { - mSource.close(); + source.close(); } } } diff --git a/java/com/android/voicemail/impl/mail/BodyPart.java b/java/com/android/voicemail/impl/mail/BodyPart.java index 3d15d4bad..669b08804 100644 --- a/java/com/android/voicemail/impl/mail/BodyPart.java +++ b/java/com/android/voicemail/impl/mail/BodyPart.java @@ -16,9 +16,9 @@ package com.android.voicemail.impl.mail; public abstract class BodyPart implements Part { - protected Multipart mParent; + protected Multipart parent; public Multipart getParent() { - return mParent; + return parent; } } diff --git a/java/com/android/voicemail/impl/mail/FixedLengthInputStream.java b/java/com/android/voicemail/impl/mail/FixedLengthInputStream.java index bd3c16401..473281e09 100644 --- a/java/com/android/voicemail/impl/mail/FixedLengthInputStream.java +++ b/java/com/android/voicemail/impl/mail/FixedLengthInputStream.java @@ -24,25 +24,25 @@ import java.io.InputStream; * where the protocol handler intended the client to read. */ public class FixedLengthInputStream extends InputStream { - private final InputStream mIn; - private final int mLength; - private int mCount; + private final InputStream in; + private final int length; + private int count; public FixedLengthInputStream(InputStream in, int length) { - this.mIn = in; - this.mLength = length; + this.in = in; + this.length = length; } @Override public int available() throws IOException { - return mLength - mCount; + return length - count; } @Override public int read() throws IOException { - if (mCount < mLength) { - mCount++; - return mIn.read(); + if (count < length) { + count++; + return in.read(); } else { return -1; } @@ -50,12 +50,12 @@ public class FixedLengthInputStream extends InputStream { @Override public int read(byte[] b, int offset, int length) throws IOException { - if (mCount < mLength) { - int d = mIn.read(b, offset, Math.min(mLength - mCount, length)); + if (count < this.length) { + int d = in.read(b, offset, Math.min(this.length - count, length)); if (d == -1) { return -1; } else { - mCount += d; + count += d; return d; } } else { @@ -69,11 +69,11 @@ public class FixedLengthInputStream extends InputStream { } public int getLength() { - return mLength; + return length; } @Override public String toString() { - return String.format("FixedLengthInputStream(in=%s, length=%d)", mIn.toString(), mLength); + return String.format("FixedLengthInputStream(in=%s, length=%d)", in.toString(), length); } } diff --git a/java/com/android/voicemail/impl/mail/MailTransport.java b/java/com/android/voicemail/impl/mail/MailTransport.java index c35e41450..a2a6a691a 100644 --- a/java/com/android/voicemail/impl/mail/MailTransport.java +++ b/java/com/android/voicemail/impl/mail/MailTransport.java @@ -52,17 +52,17 @@ public class MailTransport { private static final HostnameVerifier HOSTNAME_VERIFIER = HttpsURLConnection.getDefaultHostnameVerifier(); - private final Context mContext; - private final ImapHelper mImapHelper; - private final Network mNetwork; - private final String mHost; - private final int mPort; - private Socket mSocket; - private BufferedInputStream mIn; - private BufferedOutputStream mOut; - private final int mFlags; - private SocketCreator mSocketCreator; - private InetSocketAddress mAddress; + private final Context context; + private final ImapHelper imapHelper; + private final Network network; + private final String host; + private final int port; + private Socket socket; + private BufferedInputStream in; + private BufferedOutputStream out; + private final int flags; + private SocketCreator socketCreator; + private InetSocketAddress address; public MailTransport( Context context, @@ -71,12 +71,12 @@ public class MailTransport { String address, int port, int flags) { - mContext = context; - mImapHelper = imapHelper; - mNetwork = network; - mHost = address; - mPort = port; - mFlags = flags; + this.context = context; + this.imapHelper = imapHelper; + this.network = network; + host = address; + this.port = port; + this.flags = flags; } /** @@ -85,15 +85,15 @@ public class MailTransport { */ @Override public MailTransport clone() { - return new MailTransport(mContext, mImapHelper, mNetwork, mHost, mPort, mFlags); + return new MailTransport(context, imapHelper, network, host, port, flags); } public boolean canTrySslSecurity() { - return (mFlags & ImapStore.FLAG_SSL) != 0; + return (flags & ImapStore.FLAG_SSL) != 0; } public boolean canTrustAllCertificates() { - return (mFlags & ImapStore.FLAG_TRUST_ALL) != 0; + return (flags & ImapStore.FLAG_TRUST_ALL) != 0; } /** @@ -101,36 +101,36 @@ public class MailTransport { * SSL connection if indicated. */ public void open() throws MessagingException { - LogUtils.d(TAG, "*** IMAP open " + mHost + ":" + String.valueOf(mPort)); + LogUtils.d(TAG, "*** IMAP open " + host + ":" + String.valueOf(port)); List socketAddresses = new ArrayList(); - if (mNetwork == null) { - socketAddresses.add(new InetSocketAddress(mHost, mPort)); + if (network == null) { + socketAddresses.add(new InetSocketAddress(host, port)); } else { try { - InetAddress[] inetAddresses = mNetwork.getAllByName(mHost); + InetAddress[] inetAddresses = network.getAllByName(host); if (inetAddresses.length == 0) { throw new MessagingException( MessagingException.IOERROR, - "Host name " + mHost + "cannot be resolved on designated network"); + "Host name " + host + "cannot be resolved on designated network"); } for (int i = 0; i < inetAddresses.length; i++) { - socketAddresses.add(new InetSocketAddress(inetAddresses[i], mPort)); + socketAddresses.add(new InetSocketAddress(inetAddresses[i], port)); } } catch (IOException ioe) { LogUtils.d(TAG, ioe.toString()); - mImapHelper.handleEvent(OmtpEvents.DATA_CANNOT_RESOLVE_HOST_ON_NETWORK); + imapHelper.handleEvent(OmtpEvents.DATA_CANNOT_RESOLVE_HOST_ON_NETWORK); throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } } boolean success = false; while (socketAddresses.size() > 0) { - mSocket = createSocket(); + socket = createSocket(); try { - mAddress = socketAddresses.remove(0); - mSocket.connect(mAddress, SOCKET_CONNECT_TIMEOUT); + address = socketAddresses.remove(0); + socket.connect(address, SOCKET_CONNECT_TIMEOUT); if (canTrySslSecurity()) { /* @@ -140,9 +140,9 @@ public class MailTransport { */ reopenTls(); } else { - mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); - mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); - mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); + in = new BufferedInputStream(socket.getInputStream(), 1024); + out = new BufferedOutputStream(socket.getOutputStream(), 512); + socket.setSoTimeout(SOCKET_READ_TIMEOUT); } success = true; return; @@ -150,14 +150,14 @@ public class MailTransport { LogUtils.d(TAG, ioe.toString()); if (socketAddresses.size() == 0) { // Only throw an error when there are no more sockets to try. - mImapHelper.handleEvent(OmtpEvents.DATA_ALL_SOCKET_CONNECTION_FAILED); + imapHelper.handleEvent(OmtpEvents.DATA_ALL_SOCKET_CONNECTION_FAILED); throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } } finally { if (!success) { try { - mSocket.close(); - mSocket = null; + socket.close(); + socket = null; } catch (IOException ioe) { throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } @@ -175,15 +175,15 @@ public class MailTransport { @VisibleForTesting void setSocketCreator(SocketCreator creator) { - mSocketCreator = creator; + socketCreator = creator; } protected Socket createSocket() throws MessagingException { - if (mSocketCreator != null) { - return mSocketCreator.createSocket(); + if (socketCreator != null) { + return socketCreator.createSocket(); } - if (mNetwork == null) { + if (network == null) { LogUtils.v(TAG, "createSocket: network not specified"); return new Socket(); } @@ -191,7 +191,7 @@ public class MailTransport { try { LogUtils.v(TAG, "createSocket: network specified"); TrafficStats.setThreadStatsTag(TrafficStatsTags.VISUAL_VOICEMAIL_TAG); - return mNetwork.getSocketFactory().createSocket(); + return network.getSocketFactory().createSocket(); } catch (IOException ioe) { LogUtils.d(TAG, ioe.toString()); throw new MessagingException(MessagingException.IOERROR, ioe.toString()); @@ -204,17 +204,17 @@ public class MailTransport { public void reopenTls() throws MessagingException { try { LogUtils.d(TAG, "open: converting to TLS socket"); - mSocket = + socket = HttpsURLConnection.getDefaultSSLSocketFactory() - .createSocket(mSocket, mAddress.getHostName(), mAddress.getPort(), true); + .createSocket(socket, address.getHostName(), address.getPort(), true); // After the socket connects to an SSL server, confirm that the hostname is as // expected if (!canTrustAllCertificates()) { - verifyHostname(mSocket, mHost); + verifyHostname(socket, host); } - mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); - mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); - mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); + socket.setSoTimeout(SOCKET_READ_TIMEOUT); + in = new BufferedInputStream(socket.getInputStream(), 1024); + out = new BufferedOutputStream(socket.getOutputStream(), 512); } catch (SSLException e) { LogUtils.d(TAG, e.toString()); @@ -248,7 +248,7 @@ public class MailTransport { SSLSession session = ssl.getSession(); if (session == null) { - mImapHelper.handleEvent(OmtpEvents.DATA_CANNOT_ESTABLISH_SSL_SESSION); + imapHelper.handleEvent(OmtpEvents.DATA_CANNOT_ESTABLISH_SSL_SESSION); throw new SSLException("Cannot verify SSL socket without session"); } // TODO: Instead of reporting the name of the server we think we're connecting to, @@ -256,52 +256,52 @@ public class MailTransport { // in the verifier code and is not available in the verifier API, and extracting the // CN & alts is beyond the scope of this patch. if (!HOSTNAME_VERIFIER.verify(hostname, session)) { - mImapHelper.handleEvent(OmtpEvents.DATA_SSL_INVALID_HOST_NAME); + imapHelper.handleEvent(OmtpEvents.DATA_SSL_INVALID_HOST_NAME); throw new SSLPeerUnverifiedException( "Certificate hostname not useable for server: " + session.getPeerPrincipal()); } } public boolean isOpen() { - return (mIn != null - && mOut != null - && mSocket != null - && mSocket.isConnected() - && !mSocket.isClosed()); + return (in != null + && out != null + && socket != null + && socket.isConnected() + && !socket.isClosed()); } /** Close the connection. MUST NOT return any exceptions - must be "best effort" and safe. */ public void close() { try { - mIn.close(); + in.close(); } catch (Exception e) { // May fail if the connection is already closed. } try { - mOut.close(); + out.close(); } catch (Exception e) { // May fail if the connection is already closed. } try { - mSocket.close(); + socket.close(); } catch (Exception e) { // May fail if the connection is already closed. } - mIn = null; - mOut = null; - mSocket = null; + in = null; + out = null; + socket = null; } public String getHost() { - return mHost; + return host; } public InputStream getInputStream() { - return mIn; + return in; } public OutputStream getOutputStream() { - return mOut; + return out; } /** Writes a single line to the server using \r\n termination. */ diff --git a/java/com/android/voicemail/impl/mail/Message.java b/java/com/android/voicemail/impl/mail/Message.java index ca65d3d73..4e2c64239 100644 --- a/java/com/android/voicemail/impl/mail/Message.java +++ b/java/com/android/voicemail/impl/mail/Message.java @@ -33,18 +33,18 @@ public abstract class Message implements Part, Body { BCC, } - protected String mUid; + protected String uid; - private HashSet mFlags = null; + private HashSet flags = null; - protected Date mInternalDate; + protected Date internalDate; public String getUid() { - return mUid; + return uid; } public void setUid(String uid) { - this.mUid = uid; + this.uid = uid; } public abstract String getSubject() throws MessagingException; @@ -52,11 +52,11 @@ public abstract class Message implements Part, Body { public abstract void setSubject(String subject) throws MessagingException; public Date getInternalDate() { - return mInternalDate; + return internalDate; } public void setInternalDate(Date internalDate) { - this.mInternalDate = internalDate; + this.internalDate = internalDate; } public abstract Date getReceivedDate() throws MessagingException; @@ -95,10 +95,10 @@ public abstract class Message implements Part, Body { } private HashSet getFlagSet() { - if (mFlags == null) { - mFlags = new HashSet(); + if (flags == null) { + flags = new HashSet(); } - return mFlags; + return flags; } /* @@ -145,6 +145,6 @@ public abstract class Message implements Part, Body { @Override public String toString() { - return getClass().getSimpleName() + ':' + mUid; + return getClass().getSimpleName() + ':' + uid; } } diff --git a/java/com/android/voicemail/impl/mail/MessagingException.java b/java/com/android/voicemail/impl/mail/MessagingException.java index c1e3051df..fda5fbc9d 100644 --- a/java/com/android/voicemail/impl/mail/MessagingException.java +++ b/java/com/android/voicemail/impl/mail/MessagingException.java @@ -70,9 +70,9 @@ public class MessagingException extends Exception { /** The server indicates it experienced an internal error */ public static final int SERVER_ERROR = 19; - protected int mExceptionType; + protected int exceptionType; // Exception type-specific data - protected Object mExceptionData; + protected Object exceptionData; public MessagingException(String message, Throwable throwable) { this(UNSPECIFIED_EXCEPTION, message, throwable); @@ -80,8 +80,8 @@ public class MessagingException extends Exception { public MessagingException(int exceptionType, String message, Throwable throwable) { super(message, throwable); - mExceptionType = exceptionType; - mExceptionData = null; + this.exceptionType = exceptionType; + exceptionData = null; } /** @@ -120,8 +120,8 @@ public class MessagingException extends Exception { */ public MessagingException(int exceptionType, String message, Object data) { super(message); - mExceptionType = exceptionType; - mExceptionData = data; + this.exceptionType = exceptionType; + exceptionData = data; } /** @@ -130,7 +130,7 @@ public class MessagingException extends Exception { * @return Returns the exception type. */ public int getExceptionType() { - return mExceptionType; + return exceptionType; } /** * Return the exception data. Will be null if not explicitly set. @@ -138,6 +138,6 @@ public class MessagingException extends Exception { * @return Returns the exception data. */ public Object getExceptionData() { - return mExceptionData; + return exceptionData; } } diff --git a/java/com/android/voicemail/impl/mail/Multipart.java b/java/com/android/voicemail/impl/mail/Multipart.java index e8d5046d5..c226ca5ce 100644 --- a/java/com/android/voicemail/impl/mail/Multipart.java +++ b/java/com/android/voicemail/impl/mail/Multipart.java @@ -18,45 +18,45 @@ package com.android.voicemail.impl.mail; import java.util.ArrayList; public abstract class Multipart implements Body { - protected Part mParent; + protected Part parent; - protected ArrayList mParts = new ArrayList(); + protected ArrayList parts = new ArrayList(); - protected String mContentType; + protected String contentType; public void addBodyPart(BodyPart part) throws MessagingException { - mParts.add(part); + parts.add(part); } public void addBodyPart(BodyPart part, int index) throws MessagingException { - mParts.add(index, part); + parts.add(index, part); } public BodyPart getBodyPart(int index) throws MessagingException { - return mParts.get(index); + return parts.get(index); } public String getContentType() throws MessagingException { - return mContentType; + return contentType; } public int getCount() throws MessagingException { - return mParts.size(); + return parts.size(); } public boolean removeBodyPart(BodyPart part) throws MessagingException { - return mParts.remove(part); + return parts.remove(part); } public void removeBodyPart(int index) throws MessagingException { - mParts.remove(index); + parts.remove(index); } public Part getParent() throws MessagingException { - return mParent; + return parent; } public void setParent(Part parent) throws MessagingException { - this.mParent = parent; + this.parent = parent; } } diff --git a/java/com/android/voicemail/impl/mail/PackedString.java b/java/com/android/voicemail/impl/mail/PackedString.java index 701dab62b..de04b6bbc 100644 --- a/java/com/android/voicemail/impl/mail/PackedString.java +++ b/java/com/android/voicemail/impl/mail/PackedString.java @@ -36,8 +36,8 @@ public class PackedString { private static final char DELIMITER_TAG = '\2'; - private String mString; - private ArrayMap mExploded; + private String string; + private ArrayMap exploded; private static final ArrayMap EMPTY_MAP = new ArrayMap(); /** @@ -46,8 +46,8 @@ public class PackedString { * @param string packed string */ public PackedString(String string) { - mString = string; - mExploded = null; + this.string = string; + exploded = null; } /** @@ -57,10 +57,10 @@ public class PackedString { * @return returns value, or null if no string is found */ public String get(String tag) { - if (mExploded == null) { - mExploded = explode(mString); + if (exploded == null) { + exploded = explode(string); } - return mExploded.get(tag); + return exploded.get(tag); } /** @@ -70,10 +70,10 @@ public class PackedString { * @return a map of the values in the packed string */ public Map unpack() { - if (mExploded == null) { - mExploded = explode(mString); + if (exploded == null) { + exploded = explode(string); } - return new ArrayMap(mExploded); + return new ArrayMap(exploded); } /** Read out all values into a map. */ @@ -118,16 +118,16 @@ public class PackedString { * PackedString representations. */ public static class Builder { - ArrayMap mMap; + ArrayMap map; /** Create a builder that's empty (for filling) */ public Builder() { - mMap = new ArrayMap(); + map = new ArrayMap(); } /** Create a builder using the values of an existing PackedString (for editing). */ public Builder(String packed) { - mMap = explode(packed); + map = explode(packed); } /** @@ -138,9 +138,9 @@ public class PackedString { */ public void put(String tag, String value) { if (value == null) { - mMap.remove(tag); + map.remove(tag); } else { - mMap.put(tag, value); + map.put(tag, value); } } @@ -151,14 +151,14 @@ public class PackedString { * @return returns value, or null if no string is found */ public String get(String tag) { - return mMap.get(tag); + return map.get(tag); } /** Pack the values and return a single, encoded string */ @Override public String toString() { StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : mMap.entrySet()) { + for (Map.Entry entry : map.entrySet()) { if (sb.length() > 0) { sb.append(DELIMITER_ELEMENT); } diff --git a/java/com/android/voicemail/impl/mail/PeekableInputStream.java b/java/com/android/voicemail/impl/mail/PeekableInputStream.java index 08f867f82..cc362e801 100644 --- a/java/com/android/voicemail/impl/mail/PeekableInputStream.java +++ b/java/com/android/voicemail/impl/mail/PeekableInputStream.java @@ -25,40 +25,40 @@ import java.io.InputStream; * will still return the peeked byte. */ public class PeekableInputStream extends InputStream { - private final InputStream mIn; - private boolean mPeeked; - private int mPeekedByte; + private final InputStream in; + private boolean peeked; + private int peekedByte; public PeekableInputStream(InputStream in) { - this.mIn = in; + this.in = in; } @Override public int read() throws IOException { - if (!mPeeked) { - return mIn.read(); + if (!peeked) { + return in.read(); } else { - mPeeked = false; - return mPeekedByte; + peeked = false; + return peekedByte; } } public int peek() throws IOException { - if (!mPeeked) { - mPeekedByte = read(); - mPeeked = true; + if (!peeked) { + peekedByte = read(); + peeked = true; } - return mPeekedByte; + return peekedByte; } @Override public int read(byte[] b, int offset, int length) throws IOException { - if (!mPeeked) { - return mIn.read(b, offset, length); + if (!peeked) { + return in.read(b, offset, length); } else { - b[0] = (byte) mPeekedByte; - mPeeked = false; - int r = mIn.read(b, offset + 1, length - 1); + b[0] = (byte) peekedByte; + peeked = false; + int r = in.read(b, offset + 1, length - 1); if (r == -1) { return 1; } else { @@ -75,7 +75,6 @@ public class PeekableInputStream extends InputStream { @Override public String toString() { return String.format( - "PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)", - mIn.toString(), mPeeked, mPeekedByte); + "PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)", in.toString(), peeked, peekedByte); } } diff --git a/java/com/android/voicemail/impl/mail/TempDirectory.java b/java/com/android/voicemail/impl/mail/TempDirectory.java index 42adbeb1f..f12e45b82 100644 --- a/java/com/android/voicemail/impl/mail/TempDirectory.java +++ b/java/com/android/voicemail/impl/mail/TempDirectory.java @@ -23,18 +23,18 @@ import java.io.File; * initialization. */ public class TempDirectory { - private static File sTempDirectory = null; + private static File tempDirectory = null; public static void setTempDirectory(Context context) { - sTempDirectory = context.getCacheDir(); + tempDirectory = context.getCacheDir(); } public static File getTempDirectory() { - if (sTempDirectory == null) { + if (tempDirectory == null) { throw new RuntimeException( "TempDirectory not set. " + "If in a unit test, call Email.setTempDirectory(context) in setUp()."); } - return sTempDirectory; + return tempDirectory; } } diff --git a/java/com/android/voicemail/impl/mail/internet/BinaryTempFileBody.java b/java/com/android/voicemail/impl/mail/internet/BinaryTempFileBody.java index 753b70f23..d1521bdcb 100644 --- a/java/com/android/voicemail/impl/mail/internet/BinaryTempFileBody.java +++ b/java/com/android/voicemail/impl/mail/internet/BinaryTempFileBody.java @@ -36,7 +36,7 @@ import org.apache.commons.io.IOUtils; * closed the file is deleted and the Body should be considered disposed of. */ public class BinaryTempFileBody implements Body { - private File mFile; + private File file; /** * An alternate way to put data into a BinaryTempFileBody is to simply supply an already- created @@ -45,19 +45,19 @@ public class BinaryTempFileBody implements Body { * @param filePath The file containing the data to be stored on disk temporarily */ public void setFile(String filePath) { - mFile = new File(filePath); + file = new File(filePath); } public OutputStream getOutputStream() throws IOException { - mFile = File.createTempFile("body", null, TempDirectory.getTempDirectory()); - mFile.deleteOnExit(); - return new FileOutputStream(mFile); + file = File.createTempFile("body", null, TempDirectory.getTempDirectory()); + file.deleteOnExit(); + return new FileOutputStream(file); } @Override public InputStream getInputStream() throws MessagingException { try { - return new BinaryTempFileBodyInputStream(new FileInputStream(mFile)); + return new BinaryTempFileBodyInputStream(new FileInputStream(file)); } catch (IOException ioe) { throw new MessagingException("Unable to open body", ioe); } @@ -69,7 +69,7 @@ public class BinaryTempFileBody implements Body { Base64OutputStream base64Out = new Base64OutputStream(out, Base64.CRLF | Base64.NO_CLOSE); IOUtils.copy(in, base64Out); base64Out.close(); - mFile.delete(); + file.delete(); in.close(); } @@ -81,7 +81,7 @@ public class BinaryTempFileBody implements Body { @Override public void close() throws IOException { super.close(); - mFile.delete(); + file.delete(); } } } diff --git a/java/com/android/voicemail/impl/mail/internet/MimeBodyPart.java b/java/com/android/voicemail/impl/mail/internet/MimeBodyPart.java index 2add76c72..12a2b0b7d 100644 --- a/java/com/android/voicemail/impl/mail/internet/MimeBodyPart.java +++ b/java/com/android/voicemail/impl/mail/internet/MimeBodyPart.java @@ -27,10 +27,10 @@ import java.util.regex.Pattern; /** TODO this is a close approximation of Message, need to update along with Message. */ public class MimeBodyPart extends BodyPart { - protected MimeHeader mHeader = new MimeHeader(); - protected MimeHeader mExtendedHeader; - protected Body mBody; - protected int mSize; + protected MimeHeader header = new MimeHeader(); + protected MimeHeader extendedHeader; + protected Body body; + protected int size; // regex that matches content id surrounded by "<>" optionally. private static final Pattern REMOVE_OPTIONAL_BRACKETS = Pattern.compile("^]+)>?$"); @@ -53,37 +53,37 @@ public class MimeBodyPart extends BodyPart { } protected String getFirstHeader(String name) throws MessagingException { - return mHeader.getFirstHeader(name); + return header.getFirstHeader(name); } @Override public void addHeader(String name, String value) throws MessagingException { - mHeader.addHeader(name, value); + header.addHeader(name, value); } @Override public void setHeader(String name, String value) throws MessagingException { - mHeader.setHeader(name, value); + header.setHeader(name, value); } @Override public String[] getHeader(String name) throws MessagingException { - return mHeader.getHeader(name); + return header.getHeader(name); } @Override public void removeHeader(String name) throws MessagingException { - mHeader.removeHeader(name); + header.removeHeader(name); } @Override public Body getBody() throws MessagingException { - return mBody; + return body; } @Override public void setBody(Body body) throws MessagingException { - this.mBody = body; + this.body = body; if (body instanceof Multipart) { Multipart multipart = ((Multipart) body); @@ -142,12 +142,12 @@ public class MimeBodyPart extends BodyPart { } public void setSize(int size) { - this.mSize = size; + this.size = size; } @Override public int getSize() throws MessagingException { - return mSize; + return size; } /** @@ -160,15 +160,15 @@ public class MimeBodyPart extends BodyPart { @Override public void setExtendedHeader(String name, String value) throws MessagingException { if (value == null) { - if (mExtendedHeader != null) { - mExtendedHeader.removeHeader(name); + if (extendedHeader != null) { + extendedHeader.removeHeader(name); } return; } - if (mExtendedHeader == null) { - mExtendedHeader = new MimeHeader(); + if (extendedHeader == null) { + extendedHeader = new MimeHeader(); } - mExtendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll("")); + extendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll("")); } /** @@ -180,21 +180,21 @@ public class MimeBodyPart extends BodyPart { */ @Override public String getExtendedHeader(String name) throws MessagingException { - if (mExtendedHeader == null) { + if (extendedHeader == null) { return null; } - return mExtendedHeader.getFirstHeader(name); + return extendedHeader.getFirstHeader(name); } /** Write the MimeMessage out in MIME format. */ @Override public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); - mHeader.writeTo(out); + header.writeTo(out); writer.write("\r\n"); writer.flush(); - if (mBody != null) { - mBody.writeTo(out); + if (body != null) { + body.writeTo(out); } } } diff --git a/java/com/android/voicemail/impl/mail/internet/MimeHeader.java b/java/com/android/voicemail/impl/mail/internet/MimeHeader.java index 8f0817650..00a9eccf2 100644 --- a/java/com/android/voicemail/impl/mail/internet/MimeHeader.java +++ b/java/com/android/voicemail/impl/mail/internet/MimeHeader.java @@ -45,10 +45,10 @@ public class MimeHeader { HEADER_ANDROID_ATTACHMENT_STORE_DATA }; - protected final ArrayList mFields = new ArrayList(); + protected final ArrayList fields = new ArrayList(); public void clear() { - mFields.clear(); + fields.clear(); } public String getFirstHeader(String name) throws MessagingException { @@ -60,7 +60,7 @@ public class MimeHeader { } public void addHeader(String name, String value) throws MessagingException { - mFields.add(new Field(name, value)); + fields.add(new Field(name, value)); } public void setHeader(String name, String value) throws MessagingException { @@ -73,7 +73,7 @@ public class MimeHeader { public String[] getHeader(String name) throws MessagingException { ArrayList values = new ArrayList(); - for (Field field : mFields) { + for (Field field : fields) { if (field.name.equalsIgnoreCase(name)) { values.add(field.value); } @@ -86,12 +86,12 @@ public class MimeHeader { public void removeHeader(String name) throws MessagingException { ArrayList removeFields = new ArrayList(); - for (Field field : mFields) { + for (Field field : fields) { if (field.name.equalsIgnoreCase(name)) { removeFields.add(field); } } - mFields.removeAll(removeFields); + fields.removeAll(removeFields); } /** @@ -101,11 +101,11 @@ public class MimeHeader { * empty */ public String writeToString() { - if (mFields.size() == 0) { + if (fields.size() == 0) { return null; } StringBuilder builder = new StringBuilder(); - for (Field field : mFields) { + for (Field field : fields) { if (!arrayContains(WRITE_OMIT_FIELDS, field.name)) { builder.append(field.name + ": " + field.value + "\r\n"); } @@ -115,7 +115,7 @@ public class MimeHeader { public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); - for (Field field : mFields) { + for (Field field : fields) { if (!arrayContains(WRITE_OMIT_FIELDS, field.name)) { writer.write(field.name + ": " + field.value + "\r\n"); } @@ -140,7 +140,7 @@ public class MimeHeader { @Override public String toString() { - return (mFields == null) ? null : mFields.toString(); + return (fields == null) ? null : fields.toString(); } public static final boolean arrayContains(Object[] a, Object o) { diff --git a/java/com/android/voicemail/impl/mail/internet/MimeMessage.java b/java/com/android/voicemail/impl/mail/internet/MimeMessage.java index 39378a092..2997ad8c5 100644 --- a/java/com/android/voicemail/impl/mail/internet/MimeMessage.java +++ b/java/com/android/voicemail/impl/mail/internet/MimeMessage.java @@ -53,24 +53,24 @@ import org.apache.james.mime4j.stream.Field; * It would be better to simply do it explicitly on local creation of new outgoing messages. */ public class MimeMessage extends Message { - private MimeHeader mHeader; - private MimeHeader mExtendedHeader; + private MimeHeader header; + private MimeHeader extendedHeader; // NOTE: The fields here are transcribed out of headers, and values stored here will supersede // the values found in the headers. Use caution to prevent any out-of-phase errors. In // particular, any adds/changes/deletes here must be echoed by changes in the parse() function. - private Address[] mFrom; - private Address[] mTo; - private Address[] mCc; - private Address[] mBcc; - private Address[] mReplyTo; - private Date mSentDate; - private Body mBody; - protected int mSize; - private boolean mInhibitLocalMessageId = false; + private Address[] from; + private Address[] to; + private Address[] cc; + private Address[] bcc; + private Address[] replyTo; + private Date sentDate; + private Body body; + protected int size; + private boolean inhibitLocalMessageId = false; // Shared random source for generating local message-id values - private static final java.util.Random sRandom = new java.util.Random(); + private static final java.util.Random random = new java.util.Random(); // In MIME, en_US-like date format should be used. In other words "MMM" should be encoded to // "Jan", not the other localized format like "Ene" (meaning January in locale es). @@ -86,7 +86,7 @@ public class MimeMessage extends Message { private static final Pattern END_OF_LINE = Pattern.compile("\r?\n"); public MimeMessage() { - mHeader = null; + header = null; } /** @@ -100,7 +100,7 @@ public class MimeMessage extends Message { sb.append("<"); for (int i = 0; i < 24; i++) { // We'll use a 5-bit range (0..31) - final int value = sRandom.nextInt() & 31; + final int value = random.nextInt() & 31; final char c = "0123456789abcdefghijklmnopqrstuv".charAt(value); sb.append(c); } @@ -125,14 +125,14 @@ public class MimeMessage extends Message { // Before parsing the input stream, clear all local fields that may be superceded by // the new incoming message. getMimeHeaders().clear(); - mInhibitLocalMessageId = true; - mFrom = null; - mTo = null; - mCc = null; - mBcc = null; - mReplyTo = null; - mSentDate = null; - mBody = null; + inhibitLocalMessageId = true; + from = null; + to = null; + cc = null; + bcc = null; + replyTo = null; + sentDate = null; + body = null; final MimeStreamParser parser = new MimeStreamParser(); parser.setContentHandler(new MimeMessageBuilder()); @@ -149,10 +149,10 @@ public class MimeMessage extends Message { * not creating the headers until needed. */ private MimeHeader getMimeHeaders() { - if (mHeader == null) { - mHeader = new MimeHeader(); + if (header == null) { + header = new MimeHeader(); } - return mHeader; + return header; } @Override @@ -162,40 +162,40 @@ public class MimeMessage extends Message { @Override public Date getSentDate() throws MessagingException { - if (mSentDate == null) { + if (sentDate == null) { try { DateTimeField field = (DateTimeField) DefaultFieldParser.parse( "Date: " + MimeUtility.unfoldAndDecode(getFirstHeader("Date"))); - mSentDate = field.getDate(); + sentDate = field.getDate(); // TODO: We should make it more clear what exceptions can be thrown here, // and whether they reflect a normal or error condition. } catch (Exception e) { LogUtils.v(LogUtils.TAG, "Message missing Date header"); } } - if (mSentDate == null) { + if (sentDate == null) { // If we still don't have a date, fall back to "Delivery-date" try { DateTimeField field = (DateTimeField) DefaultFieldParser.parse( "Date: " + MimeUtility.unfoldAndDecode(getFirstHeader("Delivery-date"))); - mSentDate = field.getDate(); + sentDate = field.getDate(); // TODO: We should make it more clear what exceptions can be thrown here, // and whether they reflect a normal or error condition. } catch (Exception e) { LogUtils.v(LogUtils.TAG, "Message also missing Delivery-Date header"); } } - return mSentDate; + return sentDate; } @Override public void setSentDate(Date sentDate) throws MessagingException { setHeader("Date", DATE_FORMAT.format(sentDate)); - this.mSentDate = sentDate; + this.sentDate = sentDate; } @Override @@ -253,7 +253,7 @@ public class MimeMessage extends Message { @Override public int getSize() throws MessagingException { - return mSize; + return size; } /** @@ -263,20 +263,20 @@ public class MimeMessage extends Message { @Override public Address[] getRecipients(String type) throws MessagingException { if (type == RECIPIENT_TYPE_TO) { - if (mTo == null) { - mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To"))); + if (to == null) { + to = Address.parse(MimeUtility.unfold(getFirstHeader("To"))); } - return mTo; + return to; } else if (type == RECIPIENT_TYPE_CC) { - if (mCc == null) { - mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC"))); + if (cc == null) { + cc = Address.parse(MimeUtility.unfold(getFirstHeader("CC"))); } - return mCc; + return cc; } else if (type == RECIPIENT_TYPE_BCC) { - if (mBcc == null) { - mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC"))); + if (bcc == null) { + bcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC"))); } - return mBcc; + return bcc; } else { throw new MessagingException("Unrecognized recipient type."); } @@ -290,26 +290,26 @@ public class MimeMessage extends Message { if (type == RECIPIENT_TYPE_TO) { if (addresses == null || addresses.length == 0) { removeHeader("To"); - this.mTo = null; + this.to = null; } else { setHeader("To", MimeUtility.fold(Address.toHeader(addresses), toLength)); - this.mTo = addresses; + this.to = addresses; } } else if (type == RECIPIENT_TYPE_CC) { if (addresses == null || addresses.length == 0) { removeHeader("CC"); - this.mCc = null; + this.cc = null; } else { setHeader("CC", MimeUtility.fold(Address.toHeader(addresses), ccLength)); - this.mCc = addresses; + this.cc = addresses; } } else if (type == RECIPIENT_TYPE_BCC) { if (addresses == null || addresses.length == 0) { removeHeader("BCC"); - this.mBcc = null; + this.bcc = null; } else { setHeader("BCC", MimeUtility.fold(Address.toHeader(addresses), bccLength)); - this.mBcc = addresses; + this.bcc = addresses; } } else { throw new MessagingException("Unrecognized recipient type."); @@ -330,14 +330,14 @@ public class MimeMessage extends Message { @Override public Address[] getFrom() throws MessagingException { - if (mFrom == null) { + if (from == null) { String list = MimeUtility.unfold(getFirstHeader("From")); if (list == null || list.length() == 0) { list = MimeUtility.unfold(getFirstHeader("Sender")); } - mFrom = Address.parse(list); + from = Address.parse(list); } - return mFrom; + return from; } @Override @@ -345,18 +345,18 @@ public class MimeMessage extends Message { final int fromLength = 6; // "From: " if (from != null) { setHeader("From", MimeUtility.fold(from.toHeader(), fromLength)); - this.mFrom = new Address[] {from}; + this.from = new Address[] {from}; } else { - this.mFrom = null; + this.from = null; } } @Override public Address[] getReplyTo() throws MessagingException { - if (mReplyTo == null) { - mReplyTo = Address.parse(MimeUtility.unfold(getFirstHeader("Reply-to"))); + if (replyTo == null) { + replyTo = Address.parse(MimeUtility.unfold(getFirstHeader("Reply-to"))); } - return mReplyTo; + return replyTo; } @Override @@ -364,10 +364,10 @@ public class MimeMessage extends Message { final int replyToLength = 10; // "Reply-to: " if (replyTo == null || replyTo.length == 0) { removeHeader("Reply-to"); - mReplyTo = null; + this.replyTo = null; } else { setHeader("Reply-to", MimeUtility.fold(Address.toHeader(replyTo), replyToLength)); - mReplyTo = replyTo; + this.replyTo = replyTo; } } @@ -392,7 +392,7 @@ public class MimeMessage extends Message { @Override public String getMessageId() throws MessagingException { String messageId = getFirstHeader("Message-ID"); - if (messageId == null && !mInhibitLocalMessageId) { + if (messageId == null && !inhibitLocalMessageId) { messageId = generateMessageId(); setMessageId(messageId); } @@ -406,12 +406,12 @@ public class MimeMessage extends Message { @Override public Body getBody() throws MessagingException { - return mBody; + return body; } @Override public void setBody(Body body) throws MessagingException { - this.mBody = body; + this.body = body; if (body instanceof Multipart) { final Multipart multipart = ((Multipart) body); multipart.setParent(this); @@ -447,7 +447,7 @@ public class MimeMessage extends Message { public void removeHeader(String name) throws MessagingException { getMimeHeaders().removeHeader(name); if ("Message-ID".equalsIgnoreCase(name)) { - mInhibitLocalMessageId = true; + inhibitLocalMessageId = true; } } @@ -461,15 +461,15 @@ public class MimeMessage extends Message { @Override public void setExtendedHeader(String name, String value) throws MessagingException { if (value == null) { - if (mExtendedHeader != null) { - mExtendedHeader.removeHeader(name); + if (extendedHeader != null) { + extendedHeader.removeHeader(name); } return; } - if (mExtendedHeader == null) { - mExtendedHeader = new MimeHeader(); + if (extendedHeader == null) { + extendedHeader = new MimeHeader(); } - mExtendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll("")); + extendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll("")); } /** @@ -481,10 +481,10 @@ public class MimeMessage extends Message { */ @Override public String getExtendedHeader(String name) throws MessagingException { - if (mExtendedHeader == null) { + if (extendedHeader == null) { return null; } - return mExtendedHeader.getFirstHeader(name); + return extendedHeader.getFirstHeader(name); } /** @@ -496,15 +496,15 @@ public class MimeMessage extends Message { */ public void setExtendedHeaders(String headers) throws MessagingException { if (TextUtils.isEmpty(headers)) { - mExtendedHeader = null; + extendedHeader = null; } else { - mExtendedHeader = new MimeHeader(); + extendedHeader = new MimeHeader(); for (final String header : END_OF_LINE.split(headers)) { final String[] tokens = header.split(":", 2); if (tokens.length != 2) { throw new MessagingException("Illegal extended headers: " + headers); } - mExtendedHeader.setHeader(tokens[0].trim(), tokens[1].trim()); + extendedHeader.setHeader(tokens[0].trim(), tokens[1].trim()); } } } @@ -515,8 +515,8 @@ public class MimeMessage extends Message { * @return "CR-NL-separated extended headers - null if extended header does not exist */ public String getExtendedHeaders() { - if (mExtendedHeader != null) { - return mExtendedHeader.writeToString(); + if (extendedHeader != null) { + return extendedHeader.writeToString(); } return null; } @@ -536,8 +536,8 @@ public class MimeMessage extends Message { // because it is intended to internal use. writer.write("\r\n"); writer.flush(); - if (mBody != null) { - mBody.writeTo(out); + if (body != null) { + body.writeTo(out); } } diff --git a/java/com/android/voicemail/impl/mail/internet/MimeMultipart.java b/java/com/android/voicemail/impl/mail/internet/MimeMultipart.java index 87b88b52a..6cb2c2701 100644 --- a/java/com/android/voicemail/impl/mail/internet/MimeMultipart.java +++ b/java/com/android/voicemail/impl/mail/internet/MimeMultipart.java @@ -25,25 +25,25 @@ import java.io.OutputStream; import java.io.OutputStreamWriter; public class MimeMultipart extends Multipart { - protected String mPreamble; + protected String preamble; - protected String mContentType; + protected String contentType; - protected String mBoundary; + protected String boundary; - protected String mSubType; + protected String subType; public MimeMultipart() throws MessagingException { - mBoundary = generateBoundary(); + boundary = generateBoundary(); setSubType("mixed"); } public MimeMultipart(String contentType) throws MessagingException { - this.mContentType = contentType; + this.contentType = contentType; try { - mSubType = MimeUtility.getHeaderParameter(contentType, null).split("/")[1]; - mBoundary = MimeUtility.getHeaderParameter(contentType, "boundary"); - if (mBoundary == null) { + subType = MimeUtility.getHeaderParameter(contentType, null).split("/")[1]; + boundary = MimeUtility.getHeaderParameter(contentType, "boundary"); + if (boundary == null) { throw new MessagingException("MultiPart does not contain boundary: " + contentType); } } catch (Exception e) { @@ -65,40 +65,40 @@ public class MimeMultipart extends Multipart { } public String getPreamble() throws MessagingException { - return mPreamble; + return preamble; } public void setPreamble(String preamble) throws MessagingException { - this.mPreamble = preamble; + this.preamble = preamble; } @Override public String getContentType() throws MessagingException { - return mContentType; + return contentType; } public void setSubType(String subType) throws MessagingException { - this.mSubType = subType; - mContentType = String.format("multipart/%s; boundary=\"%s\"", subType, mBoundary); + this.subType = subType; + contentType = String.format("multipart/%s; boundary=\"%s\"", subType, boundary); } @Override public void writeTo(OutputStream out) throws IOException, MessagingException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024); - if (mPreamble != null) { - writer.write(mPreamble + "\r\n"); + if (preamble != null) { + writer.write(preamble + "\r\n"); } - for (int i = 0, count = mParts.size(); i < count; i++) { - BodyPart bodyPart = mParts.get(i); - writer.write("--" + mBoundary + "\r\n"); + for (int i = 0, count = parts.size(); i < count; i++) { + BodyPart bodyPart = parts.get(i); + writer.write("--" + boundary + "\r\n"); writer.flush(); bodyPart.writeTo(out); writer.write("\r\n"); } - writer.write("--" + mBoundary + "--\r\n"); + writer.write("--" + boundary + "--\r\n"); writer.flush(); } @@ -108,6 +108,6 @@ public class MimeMultipart extends Multipart { } public String getSubTypeForTest() { - return mSubType; + return subType; } } diff --git a/java/com/android/voicemail/impl/mail/internet/TextBody.java b/java/com/android/voicemail/impl/mail/internet/TextBody.java index dae562508..506e1f52e 100644 --- a/java/com/android/voicemail/impl/mail/internet/TextBody.java +++ b/java/com/android/voicemail/impl/mail/internet/TextBody.java @@ -25,15 +25,15 @@ import java.io.OutputStream; import java.io.UnsupportedEncodingException; public class TextBody implements Body { - String mBody; + String body; public TextBody(String body) { - this.mBody = body; + this.body = body; } @Override public void writeTo(OutputStream out) throws IOException, MessagingException { - byte[] bytes = mBody.getBytes("UTF-8"); + byte[] bytes = body.getBytes("UTF-8"); out.write(Base64.encode(bytes, Base64.CRLF)); } @@ -43,14 +43,14 @@ public class TextBody implements Body { * @return */ public String getText() { - return mBody; + return body; } /** Returns an InputStream that reads this body's text in UTF-8 format. */ @Override public InputStream getInputStream() throws MessagingException { try { - byte[] b = mBody.getBytes("UTF-8"); + byte[] b = body.getBytes("UTF-8"); return new ByteArrayInputStream(b); } catch (UnsupportedEncodingException usee) { return null; diff --git a/java/com/android/voicemail/impl/mail/store/ImapConnection.java b/java/com/android/voicemail/impl/mail/store/ImapConnection.java index 0a48dfc69..ac43f8d72 100644 --- a/java/com/android/voicemail/impl/mail/store/ImapConnection.java +++ b/java/com/android/voicemail/impl/mail/store/ImapConnection.java @@ -42,11 +42,11 @@ import javax.net.ssl.SSLException; public class ImapConnection { private final String TAG = "ImapConnection"; - private String mLoginPhrase; - private ImapStore mImapStore; - private MailTransport mTransport; - private ImapResponseParser mParser; - private Set mCapabilities = new ArraySet<>(); + private String loginPhrase; + private ImapStore imapStore; + private MailTransport transport; + private ImapResponseParser parser; + private Set capabilities = new ArraySet<>(); static final String IMAP_REDACTED_LOG = "[IMAP command redacted]"; @@ -55,7 +55,7 @@ public class ImapConnection { * counter to make tests simpler. (Some of the tests involve multiple connections but only have a * single counter to track the tag.) */ - private final AtomicInteger mNextCommandTag = new AtomicInteger(0); + private final AtomicInteger nextCommandTag = new AtomicInteger(0); ImapConnection(ImapStore store) { setStore(store); @@ -65,8 +65,8 @@ public class ImapConnection { // TODO: maybe we should throw an exception if the connection is not closed here, // if it's not currently closed, then we won't reopen it, so if the credentials have // changed, the connection will not be reestablished. - mImapStore = store; - mLoginPhrase = null; + imapStore = store; + loginPhrase = null; } /** @@ -76,42 +76,42 @@ public class ImapConnection { * @return the login command string to sent to the IMAP server */ String getLoginPhrase() { - if (mLoginPhrase == null) { - if (mImapStore.getUsername() != null && mImapStore.getPassword() != null) { + if (loginPhrase == null) { + if (imapStore.getUsername() != null && imapStore.getPassword() != null) { // build the LOGIN string once (instead of over-and-over again.) // apply the quoting here around the built-up password - mLoginPhrase = + loginPhrase = ImapConstants.LOGIN + " " - + mImapStore.getUsername() + + imapStore.getUsername() + " " - + ImapUtility.imapQuoted(mImapStore.getPassword()); + + ImapUtility.imapQuoted(imapStore.getPassword()); } } - return mLoginPhrase; + return loginPhrase; } public void open() throws IOException, MessagingException { - if (mTransport != null && mTransport.isOpen()) { + if (transport != null && transport.isOpen()) { return; } try { // copy configuration into a clean transport, if necessary - if (mTransport == null) { - mTransport = mImapStore.cloneTransport(); + if (transport == null) { + transport = imapStore.cloneTransport(); } - mTransport.open(); + transport.open(); createParser(); // The server should greet us with something like // * OK IMAP4rev1 Server // consume the response before doing anything else. - ImapResponse response = mParser.readResponse(false); + ImapResponse response = parser.readResponse(false); if (!response.isOk()) { - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_INVALID_INITIAL_SERVER_RESPONSE); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_INVALID_INITIAL_SERVER_RESPONSE); throw new MessagingException( MessagingException.AUTHENTICATION_FAILED_OR_SERVER_ERROR, "Invalid server initial response"); @@ -125,11 +125,11 @@ public class ImapConnection { doLogin(); } catch (SSLException e) { LogUtils.d(TAG, "SSLException ", e); - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_SSL_EXCEPTION); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_SSL_EXCEPTION); throw new CertificateValidationException(e.getMessage(), e); } catch (IOException ioe) { LogUtils.d(TAG, "IOException", ioe); - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_IOE_ON_OPEN); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_IOE_ON_OPEN); throw ioe; } finally { destroyResponses(); @@ -139,10 +139,10 @@ public class ImapConnection { void logout() { try { sendCommand(ImapConstants.LOGOUT, false); - if (!mParser.readResponse(true).is(0, ImapConstants.BYE)) { + if (!parser.readResponse(true).is(0, ImapConstants.BYE)) { VvmLog.e(TAG, "Server did not respond LOGOUT with BYE"); } - if (!mParser.readResponse(false).isOk()) { + if (!parser.readResponse(false).isOk()) { VvmLog.e(TAG, "Server did not respond OK after LOGOUT"); } } catch (IOException | MessagingException e) { @@ -155,14 +155,14 @@ public class ImapConnection { * {@link #setStore(ImapStore)} is called. */ void close() { - if (mTransport != null) { + if (transport != null) { logout(); - mTransport.close(); - mTransport = null; + transport.close(); + transport = null; } destroyResponses(); - mParser = null; - mImapStore = null; + parser = null; + imapStore = null; } /** Attempts to convert the connection into secure connection. */ @@ -171,7 +171,7 @@ public class ImapConnection { // Make sure the server does have this capability if (hasCapability(ImapConstants.CAPABILITY_STARTTLS)) { executeSimpleCommand(ImapConstants.STARTTLS); - mTransport.reopenTls(); + transport.reopenTls(); createParser(); // The cached capabilities should be refreshed after TLS is established. queryCapability(); @@ -181,7 +181,7 @@ public class ImapConnection { /** Logs into the IMAP server */ private void doLogin() throws IOException, MessagingException, AuthenticationFailedException { try { - if (mCapabilities.contains(ImapConstants.CAPABILITY_AUTH_DIGEST_MD5)) { + if (capabilities.contains(ImapConstants.CAPABILITY_AUTH_DIGEST_MD5)) { doDigestMd5Auth(); } else { executeSimpleCommand(getLoginPhrase(), true); @@ -195,36 +195,36 @@ public class ImapConnection { if (ImapConstants.NO.equals(status)) { switch (statusMessage) { case ImapConstants.NO_UNKNOWN_USER: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_UNKNOWN_USER); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_UNKNOWN_USER); break; case ImapConstants.NO_UNKNOWN_CLIENT: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_UNKNOWN_DEVICE); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_UNKNOWN_DEVICE); break; case ImapConstants.NO_INVALID_PASSWORD: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_INVALID_PASSWORD); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_INVALID_PASSWORD); break; case ImapConstants.NO_MAILBOX_NOT_INITIALIZED: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_MAILBOX_NOT_INITIALIZED); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_MAILBOX_NOT_INITIALIZED); break; case ImapConstants.NO_SERVICE_IS_NOT_PROVISIONED: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_SERVICE_NOT_PROVISIONED); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_SERVICE_NOT_PROVISIONED); break; case ImapConstants.NO_SERVICE_IS_NOT_ACTIVATED: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_SERVICE_NOT_ACTIVATED); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_SERVICE_NOT_ACTIVATED); break; case ImapConstants.NO_USER_IS_BLOCKED: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_USER_IS_BLOCKED); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_AUTH_USER_IS_BLOCKED); break; case ImapConstants.NO_APPLICATION_ERROR: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_REJECTED_SERVER_RESPONSE); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_REJECTED_SERVER_RESPONSE); break; default: - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_BAD_IMAP_CREDENTIAL); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_BAD_IMAP_CREDENTIAL); } throw new AuthenticationFailedException(alertText, ie); } - mImapStore.getImapHelper().handleEvent(OmtpEvents.DATA_REJECTED_SERVER_RESPONSE); + imapStore.getImapHelper().handleEvent(OmtpEvents.DATA_REJECTED_SERVER_RESPONSE); throw new MessagingException(alertText, ie); } } @@ -243,7 +243,7 @@ public class ImapConnection { String decodedChallenge = decodeBase64(responses.get(0).getStringOrEmpty(0).getString()); Map challenge = DigestMd5Utils.parseDigestMessage(decodedChallenge); - DigestMd5Utils.Data data = new DigestMd5Utils.Data(mImapStore, mTransport, challenge); + DigestMd5Utils.Data data = new DigestMd5Utils.Data(imapStore, transport, challenge); String response = data.createResponse(); // Respond to the challenge. If the server accepts it, it will reply a response-auth which @@ -281,9 +281,9 @@ public class ImapConnection { private void queryCapability() throws IOException, MessagingException { List responses = executeSimpleCommand(ImapConstants.CAPABILITY); - mCapabilities.clear(); + capabilities.clear(); Set disabledCapabilities = - mImapStore.getImapHelper().getConfig().getDisabledCapabilities(); + imapStore.getImapHelper().getConfig().getDisabledCapabilities(); for (ImapResponse response : responses) { if (response.isTagged()) { continue; @@ -292,40 +292,40 @@ public class ImapConnection { String capability = response.getStringOrEmpty(i).getString(); if (disabledCapabilities != null) { if (!disabledCapabilities.contains(capability)) { - mCapabilities.add(capability); + capabilities.add(capability); } } else { - mCapabilities.add(capability); + capabilities.add(capability); } } } - LogUtils.d(TAG, "Capabilities: " + mCapabilities.toString()); + LogUtils.d(TAG, "Capabilities: " + capabilities.toString()); } private boolean hasCapability(String capability) { - return mCapabilities.contains(capability); + return capabilities.contains(capability); } /** * Create an {@link ImapResponseParser} from {@code mTransport.getInputStream()} and set it to - * {@link #mParser}. + * {@link #parser}. * *

If we already have an {@link ImapResponseParser}, we {@link #destroyResponses()} and throw * it away. */ private void createParser() { destroyResponses(); - mParser = new ImapResponseParser(mTransport.getInputStream()); + parser = new ImapResponseParser(transport.getInputStream()); } public void destroyResponses() { - if (mParser != null) { - mParser.destroyResponses(); + if (parser != null) { + parser.destroyResponses(); } } public ImapResponse readResponse() throws IOException, MessagingException { - return mParser.readResponse(false); + return parser.readResponse(false); } public List executeSimpleCommand(String command) @@ -356,18 +356,18 @@ public class ImapConnection { throws IOException, MessagingException { open(); - if (mTransport == null) { + if (transport == null) { throw new IOException("Null transport"); } - String tag = Integer.toString(mNextCommandTag.incrementAndGet()); + String tag = Integer.toString(nextCommandTag.incrementAndGet()); String commandToSend = tag + " " + command; - mTransport.writeLine(commandToSend, (sensitive ? IMAP_REDACTED_LOG : command)); + transport.writeLine(commandToSend, (sensitive ? IMAP_REDACTED_LOG : command)); return tag; } List executeContinuationResponse(String response, boolean sensitive) throws IOException, MessagingException { - mTransport.writeLine(response, (sensitive ? IMAP_REDACTED_LOG : response)); + transport.writeLine(response, (sensitive ? IMAP_REDACTED_LOG : response)); return getCommandResponses(); } @@ -382,7 +382,7 @@ public class ImapConnection { final List responses = new ArrayList(); ImapResponse response; do { - response = mParser.readResponse(false); + response = parser.readResponse(false); responses.add(response); } while (!(response.isTagged() || response.isContinuationRequest())); diff --git a/java/com/android/voicemail/impl/mail/store/ImapFolder.java b/java/com/android/voicemail/impl/mail/store/ImapFolder.java index 5760ee216..3c76ec33d 100644 --- a/java/com/android/voicemail/impl/mail/store/ImapFolder.java +++ b/java/com/android/voicemail/impl/mail/store/ImapFolder.java @@ -59,21 +59,21 @@ public class ImapFolder { }; private static final int COPY_BUFFER_SIZE = 16 * 1024; - private final ImapStore mStore; - private final String mName; - private int mMessageCount = -1; - private ImapConnection mConnection; - private String mMode; - private boolean mExists; + private final ImapStore store; + private final String name; + private int messageCount = -1; + private ImapConnection connection; + private String mode; + private boolean exists; /** A set of hashes that can be used to track dirtiness */ - Object[] mHash; + Object[] hash; public static final String MODE_READ_ONLY = "mode_read_only"; public static final String MODE_READ_WRITE = "mode_read_write"; public ImapFolder(ImapStore store, String name) { - mStore = store; - mName = name; + this.store = store; + this.name = name; } /** Callback for each message retrieval. */ @@ -82,8 +82,8 @@ public class ImapFolder { } private void destroyResponses() { - if (mConnection != null) { - mConnection.destroyResponses(); + if (connection != null) { + connection.destroyResponses(); } } @@ -93,7 +93,7 @@ public class ImapFolder { throw new AssertionError("Duplicated open on ImapFolder"); } synchronized (this) { - mConnection = mStore.getConnection(); + connection = store.getConnection(); } // * FLAGS (\Answered \Flagged \Deleted \Seen \Draft NonJunk // $MDNSent) @@ -107,28 +107,28 @@ public class ImapFolder { try { doSelect(); } catch (IOException ioe) { - throw ioExceptionHandler(mConnection, ioe); + throw ioExceptionHandler(connection, ioe); } finally { destroyResponses(); } } catch (AuthenticationFailedException e) { // Don't cache this connection, so we're forced to try connecting/login again - mConnection = null; + connection = null; close(false); throw e; } catch (MessagingException e) { - mExists = false; + exists = false; close(false); throw e; } } public boolean isOpen() { - return mExists && mConnection != null; + return exists && connection != null; } public String getMode() { - return mMode; + return mode; } public void close(boolean expunge) { @@ -139,14 +139,14 @@ public class ImapFolder { VvmLog.e(TAG, "Messaging Exception", e); } } - mMessageCount = -1; + messageCount = -1; synchronized (this) { - mConnection = null; + connection = null; } } public int getMessageCount() { - return mMessageCount; + return messageCount; } String[] getSearchUids(List responses) { @@ -173,7 +173,7 @@ public class ImapFolder { try { try { final String command = ImapConstants.UID_SEARCH + " " + searchCriteria; - final String[] result = getSearchUids(mConnection.executeSimpleCommand(command)); + final String[] result = getSearchUids(connection.executeSimpleCommand(command)); VvmLog.d(TAG, "searchForUids '" + searchCriteria + "' results: " + result.length); return result; } catch (ImapException me) { @@ -181,8 +181,8 @@ public class ImapFolder { return Utility.EMPTY_STRINGS; // Not found } catch (IOException ioe) { VvmLog.d(TAG, "IOException in search: " + searchCriteria, ioe); - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); - throw ioExceptionHandler(mConnection, ioe); + store.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); + throw ioExceptionHandler(connection, ioe); } } finally { destroyResponses(); @@ -296,7 +296,7 @@ public class ImapFolder { } try { - mConnection.sendCommand( + connection.sendCommand( String.format( Locale.US, ImapConstants.UID_FETCH + " %s (%s)", @@ -307,7 +307,7 @@ public class ImapFolder { do { response = null; try { - response = mConnection.readResponse(); + response = connection.readResponse(); if (!response.isDataResponse(1, ImapConstants.FETCH)) { continue; // Ignore @@ -395,7 +395,7 @@ public class ImapFolder { // (We'll need to share a temp file. Protect it with a ref-count.) message.setBody( decodeBody( - mStore.getContext(), + store.getContext(), bodyStream, contentTransferEncoding, fetchPart.getSize(), @@ -417,8 +417,8 @@ public class ImapFolder { } } while (!response.isTagged()); } catch (IOException ioe) { - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); - throw ioExceptionHandler(mConnection, ioe); + store.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); + throw ioExceptionHandler(connection, ioe); } } @@ -476,7 +476,7 @@ public class ImapFolder { */ private void handleUntaggedResponse(ImapResponse response) { if (response.isDataResponse(1, ImapConstants.EXISTS)) { - mMessageCount = response.getStringOrEmpty(0).getNumberOrZero(); + messageCount = response.getStringOrEmpty(0).getNumberOrZero(); } } @@ -660,10 +660,10 @@ public class ImapFolder { public Message[] expunge() throws MessagingException { checkOpen(); try { - handleUntaggedResponses(mConnection.executeSimpleCommand(ImapConstants.EXPUNGE)); + handleUntaggedResponses(connection.executeSimpleCommand(ImapConstants.EXPUNGE)); } catch (IOException ioe) { - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); - throw ioExceptionHandler(mConnection, ioe); + store.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); + throw ioExceptionHandler(connection, ioe); } finally { destroyResponses(); } @@ -692,7 +692,7 @@ public class ImapFolder { allFlags = flagList.substring(1); } try { - mConnection.executeSimpleCommand( + connection.executeSimpleCommand( String.format( Locale.US, ImapConstants.UID_STORE + " %s %s" + ImapConstants.FLAGS_SILENT + " (%s)", @@ -701,8 +701,8 @@ public class ImapFolder { allFlags)); } catch (IOException ioe) { - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); - throw ioExceptionHandler(mConnection, ioe); + store.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); + throw ioExceptionHandler(connection, ioe); } finally { destroyResponses(); } @@ -714,11 +714,11 @@ public class ImapFolder { */ private void doSelect() throws IOException, MessagingException { final List responses = - mConnection.executeSimpleCommand( - String.format(Locale.US, ImapConstants.SELECT + " \"%s\"", mName)); + connection.executeSimpleCommand( + String.format(Locale.US, ImapConstants.SELECT + " \"%s\"", name)); // Assume the folder is opened read-write; unless we are notified otherwise - mMode = MODE_READ_WRITE; + mode = MODE_READ_WRITE; int messageCount = -1; for (ImapResponse response : responses) { if (response.isDataResponse(1, ImapConstants.EXISTS)) { @@ -726,12 +726,12 @@ public class ImapFolder { } else if (response.isOk()) { final ImapString responseCode = response.getResponseCodeOrEmpty(); if (responseCode.is(ImapConstants.READ_ONLY)) { - mMode = MODE_READ_ONLY; + mode = MODE_READ_ONLY; } else if (responseCode.is(ImapConstants.READ_WRITE)) { - mMode = MODE_READ_WRITE; + mode = MODE_READ_WRITE; } } else if (response.isTagged()) { // Not OK - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_MAILBOX_OPEN_FAILED); + store.getImapHelper().handleEvent(OmtpEvents.DATA_MAILBOX_OPEN_FAILED); throw new MessagingException( "Can't open mailbox: " + response.getStatusResponseTextOrEmpty()); } @@ -739,8 +739,8 @@ public class ImapFolder { if (messageCount == -1) { throw new MessagingException("Did not find message count during select"); } - mMessageCount = messageCount; - mExists = true; + this.messageCount = messageCount; + exists = true; } public class Quota { @@ -757,8 +757,8 @@ public class ImapFolder { public Quota getQuota() throws MessagingException { try { final List responses = - mConnection.executeSimpleCommand( - String.format(Locale.US, ImapConstants.GETQUOTAROOT + " \"%s\"", mName)); + connection.executeSimpleCommand( + String.format(Locale.US, ImapConstants.GETQUOTAROOT + " \"%s\"", name)); for (ImapResponse response : responses) { if (!response.isDataResponse(0, ImapConstants.QUOTA)) { @@ -775,8 +775,8 @@ public class ImapFolder { } } } catch (IOException ioe) { - mStore.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); - throw ioExceptionHandler(mConnection, ioe); + store.getImapHelper().handleEvent(OmtpEvents.DATA_GENERIC_IMAP_IOE); + throw ioExceptionHandler(connection, ioe); } finally { destroyResponses(); } @@ -785,15 +785,15 @@ public class ImapFolder { private void checkOpen() throws MessagingException { if (!isOpen()) { - throw new MessagingException("Folder " + mName + " is not open."); + throw new MessagingException("Folder " + name + " is not open."); } } private MessagingException ioExceptionHandler(ImapConnection connection, IOException ioe) { VvmLog.d(TAG, "IO Exception detected: ", ioe); connection.close(); - if (connection == mConnection) { - mConnection = null; // To prevent close() from returning the connection to the pool. + if (connection == this.connection) { + this.connection = null; // To prevent close() from returning the connection to the pool. close(false); } return new MessagingException(MessagingException.IOERROR, "IO Error", ioe); diff --git a/java/com/android/voicemail/impl/mail/store/ImapStore.java b/java/com/android/voicemail/impl/mail/store/ImapStore.java index 838bae257..6b88080fe 100644 --- a/java/com/android/voicemail/impl/mail/store/ImapStore.java +++ b/java/com/android/voicemail/impl/mail/store/ImapStore.java @@ -34,12 +34,12 @@ public class ImapStore { */ public static final int FETCH_BODY_SANE_SUGGESTED_SIZE = (125 * 1024); - private final Context mContext; - private final ImapHelper mHelper; - private final String mUsername; - private final String mPassword; - private final MailTransport mTransport; - private ImapConnection mConnection; + private final Context context; + private final ImapHelper helper; + private final String username; + private final String password; + private final MailTransport transport; + private ImapConnection connection; public static final int FLAG_NONE = 0x00; // No flags public static final int FLAG_SSL = 0x01; // Use SSL @@ -58,32 +58,32 @@ public class ImapStore { String serverName, int flags, Network network) { - mContext = context; - mHelper = helper; - mUsername = username; - mPassword = password; - mTransport = new MailTransport(context, this.getImapHelper(), network, serverName, port, flags); + this.context = context; + this.helper = helper; + this.username = username; + this.password = password; + transport = new MailTransport(context, this.getImapHelper(), network, serverName, port, flags); } public Context getContext() { - return mContext; + return context; } public ImapHelper getImapHelper() { - return mHelper; + return helper; } public String getUsername() { - return mUsername; + return username; } public String getPassword() { - return mPassword; + return password; } /** Returns a clone of the transport associated with this store. */ MailTransport cloneTransport() { - return mTransport.clone(); + return transport.clone(); } /** Returns UIDs of Messages joined with "," as the separator. */ @@ -101,15 +101,15 @@ public class ImapStore { } static class ImapMessage extends MimeMessage { - private ImapFolder mFolder; + private ImapFolder folder; ImapMessage(String uid, ImapFolder folder) { - mUid = uid; - mFolder = folder; + this.uid = uid; + this.folder = folder; } public void setSize(int size) { - mSize = size; + this.size = size; } @Override @@ -124,17 +124,17 @@ public class ImapStore { @Override public void setFlag(String flag, boolean set) throws MessagingException { super.setFlag(flag, set); - mFolder.setFlags(new Message[] {this}, new String[] {flag}, set); + folder.setFlags(new Message[] {this}, new String[] {flag}, set); } } static class ImapException extends MessagingException { private static final long serialVersionUID = 1L; - private final String mStatus; - private final String mStatusMessage; - private final String mAlertText; - private final String mResponseCode; + private final String status; + private final String statusMessage; + private final String alertText; + private final String responseCode; public ImapException( String message, @@ -143,40 +143,40 @@ public class ImapStore { String alertText, String responseCode) { super(message); - mStatus = status; - mStatusMessage = statusMessage; - mAlertText = alertText; - mResponseCode = responseCode; + this.status = status; + this.statusMessage = statusMessage; + this.alertText = alertText; + this.responseCode = responseCode; } public String getStatus() { - return mStatus; + return status; } public String getStatusMessage() { - return mStatusMessage; + return statusMessage; } public String getAlertText() { - return mAlertText; + return alertText; } public String getResponseCode() { - return mResponseCode; + return responseCode; } } public void closeConnection() { - if (mConnection != null) { - mConnection.close(); - mConnection = null; + if (connection != null) { + connection.close(); + connection = null; } } public ImapConnection getConnection() { - if (mConnection == null) { - mConnection = new ImapConnection(this); + if (connection == null) { + connection = new ImapConnection(this); } - return mConnection; + return connection; } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/DigestMd5Utils.java b/java/com/android/voicemail/impl/mail/store/imap/DigestMd5Utils.java index f156f67c1..aa2886812 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/DigestMd5Utils.java +++ b/java/com/android/voicemail/impl/mail/store/imap/DigestMd5Utils.java @@ -121,27 +121,27 @@ public class DigestMd5Utils { private static class ResponseBuilder { - private StringBuilder mBuilder = new StringBuilder(); + private StringBuilder builder = new StringBuilder(); public ResponseBuilder appendQuoted(String key, String value) { - if (mBuilder.length() != 0) { - mBuilder.append(","); + if (builder.length() != 0) { + builder.append(","); } - mBuilder.append(key).append("=\"").append(value).append("\""); + builder.append(key).append("=\"").append(value).append("\""); return this; } public ResponseBuilder append(String key, String value) { - if (mBuilder.length() != 0) { - mBuilder.append(","); + if (builder.length() != 0) { + builder.append(","); } - mBuilder.append(key).append("=").append(value); + builder.append(key).append("=").append(value); return this; } @Override public String toString() { - return mBuilder.toString(); + return builder.toString(); } } } @@ -229,20 +229,20 @@ public class DigestMd5Utils { /** Parse the key-value pair returned by the server. */ private static class DigestMessageParser { - private final String mMessage; - private int mPosition = 0; - private Map mResult = new ArrayMap<>(); + private final String message; + private int position = 0; + private Map result = new ArrayMap<>(); public DigestMessageParser(String message) { - mMessage = message; + this.message = message; } @Nullable public Map parse() { try { - while (mPosition < mMessage.length()) { + while (position < message.length()) { parsePair(); - if (mPosition != mMessage.length()) { + if (position != message.length()) { expect(','); } } @@ -250,42 +250,42 @@ public class DigestMd5Utils { VvmLog.e(TAG, e.toString()); return null; } - return mResult; + return result; } private void parsePair() { String key = parseKey(); expect('='); String value = parseValue(); - mResult.put(key, value); + result.put(key, value); } private void expect(char c) { if (pop() != c) { - throw new IllegalStateException("unexpected character " + mMessage.charAt(mPosition)); + throw new IllegalStateException("unexpected character " + message.charAt(position)); } } private char pop() { char result = peek(); - mPosition++; + position++; return result; } private char peek() { - return mMessage.charAt(mPosition); + return message.charAt(position); } private void goToNext(char c) { while (peek() != c) { - mPosition++; + position++; } } private String parseKey() { - int start = mPosition; + int start = position; goToNext('='); - return mMessage.substring(start, mPosition); + return message.substring(start, position); } private String parseValue() { @@ -319,13 +319,13 @@ public class DigestMd5Utils { if (c == '\\') { result.append(pop()); } else if (c == ',') { - mPosition--; + position--; break; } else { result.append(c); } - if (mPosition == mMessage.length()) { + if (position == message.length()) { break; } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapElement.java b/java/com/android/voicemail/impl/mail/store/imap/ImapElement.java index ee255d1eb..c2571f3d9 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapElement.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapElement.java @@ -77,14 +77,14 @@ public abstract class ImapElement { } }; - private boolean mDestroyed = false; + private boolean destroyed = false; public abstract boolean isList(); public abstract boolean isString(); protected boolean isDestroyed() { - return mDestroyed; + return destroyed; } /** @@ -92,12 +92,12 @@ public abstract class ImapElement { * ImapTempFileLiteral}. */ public void destroy() { - mDestroyed = true; + destroyed = true; } /** Throws {@link RuntimeException} if it's already destroyed. */ protected final void checkNotDestroyed() { - if (mDestroyed) { + if (destroyed) { throw new RuntimeException("Already destroyed"); } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapList.java b/java/com/android/voicemail/impl/mail/store/imap/ImapList.java index e4a6ec0ac..a72883fa6 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapList.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapList.java @@ -35,13 +35,13 @@ public class ImapList extends ImapElement { } }; - private ArrayList mList = new ArrayList(); + private ArrayList list = new ArrayList(); /* package */ void add(ImapElement e) { if (e == null) { throw new RuntimeException("Can't add null"); } - mList.add(e); + list.add(e); } @Override @@ -55,7 +55,7 @@ public class ImapList extends ImapElement { } public final int size() { - return mList.size(); + return list.size(); } public final boolean isEmpty() { @@ -84,7 +84,7 @@ public class ImapList extends ImapElement { * ImapElement#NONE}. */ public final ImapElement getElementOrNone(int index) { - return (index >= mList.size()) ? ImapElement.NONE : mList.get(index); + return (index >= list.size()) ? ImapElement.NONE : list.get(index); } /** @@ -112,7 +112,7 @@ public class ImapList extends ImapElement { /* package */ final ImapElement getKeyedElementOrNull(String key, boolean prefixMatch) { for (int i = 1; i < size(); i += 2) { if (is(i - 1, key, prefixMatch)) { - return mList.get(i); + return list.get(i); } } return null; @@ -162,18 +162,18 @@ public class ImapList extends ImapElement { @Override public void destroy() { - if (mList != null) { - for (ImapElement e : mList) { + if (list != null) { + for (ImapElement e : list) { e.destroy(); } - mList = null; + list = null; } super.destroy(); } @Override public String toString() { - return mList.toString(); + return list.toString(); } /** Return the text representations of the contents concatenated with ",". */ @@ -192,7 +192,7 @@ public class ImapList extends ImapElement { */ private final StringBuilder flatten(StringBuilder sb) { sb.append('['); - for (int i = 0; i < mList.size(); i++) { + for (int i = 0; i < list.size(); i++) { if (i > 0) { sb.append(','); } @@ -217,7 +217,7 @@ public class ImapList extends ImapElement { return false; } for (int i = 0; i < size(); i++) { - if (!mList.get(i).equalsForTest(thatList.getElementOrNone(i))) { + if (!list.get(i).equalsForTest(thatList.getElementOrNone(i))) { return false; } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapMemoryLiteral.java b/java/com/android/voicemail/impl/mail/store/imap/ImapMemoryLiteral.java index 96a8c4ae5..46f3fc5ed 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapMemoryLiteral.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapMemoryLiteral.java @@ -26,35 +26,35 @@ import java.io.UnsupportedEncodingException; /** Subclass of {@link ImapString} used for literals backed by an in-memory byte array. */ public class ImapMemoryLiteral extends ImapString { private final String TAG = "ImapMemoryLiteral"; - private byte[] mData; + private byte[] data; /* package */ ImapMemoryLiteral(FixedLengthInputStream in) throws IOException { // We could use ByteArrayOutputStream and IOUtils.copy, but it'd perform an unnecessary // copy.... - mData = new byte[in.getLength()]; + data = new byte[in.getLength()]; int pos = 0; - while (pos < mData.length) { - int read = in.read(mData, pos, mData.length - pos); + while (pos < data.length) { + int read = in.read(data, pos, data.length - pos); if (read < 0) { break; } pos += read; } - if (pos != mData.length) { + if (pos != data.length) { VvmLog.w(TAG, "length mismatch"); } } @Override public void destroy() { - mData = null; + data = null; super.destroy(); } @Override public String getString() { try { - return new String(mData, "US-ASCII"); + return new String(data, "US-ASCII"); } catch (UnsupportedEncodingException e) { VvmLog.e(TAG, "Unsupported encoding: ", e); } @@ -63,11 +63,11 @@ public class ImapMemoryLiteral extends ImapString { @Override public InputStream getAsStream() { - return new ByteArrayInputStream(mData); + return new ByteArrayInputStream(data); } @Override public String toString() { - return String.format("{%d byte literal(memory)}", mData.length); + return String.format("{%d byte literal(memory)}", data.length); } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapResponse.java b/java/com/android/voicemail/impl/mail/store/imap/ImapResponse.java index d53d458da..48eb39d2d 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapResponse.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapResponse.java @@ -18,12 +18,12 @@ package com.android.voicemail.impl.mail.store.imap; /** Class represents an IMAP response. */ public class ImapResponse extends ImapList { - private final String mTag; - private final boolean mIsContinuationRequest; + private final String tag; + private final boolean isContinuationRequest; /* package */ ImapResponse(String tag, boolean isContinuationRequest) { - mTag = tag; - mIsContinuationRequest = isContinuationRequest; + this.tag = tag; + this.isContinuationRequest = isContinuationRequest; } /* package */ static boolean isStatusResponse(String symbol) { @@ -36,12 +36,12 @@ public class ImapResponse extends ImapList { /** @return whether it's a tagged response. */ public boolean isTagged() { - return mTag != null; + return tag != null; } /** @return whether it's a continuation request. */ public boolean isContinuationRequest() { - return mIsContinuationRequest; + return isContinuationRequest; } public boolean isStatusResponse() { @@ -112,7 +112,7 @@ public class ImapResponse extends ImapList { @Override public String toString() { - String tag = mTag; + String tag = this.tag; if (isContinuationRequest()) { tag = "+"; } @@ -125,16 +125,16 @@ public class ImapResponse extends ImapList { return false; } final ImapResponse thatResponse = (ImapResponse) that; - if (mTag == null) { - if (thatResponse.mTag != null) { + if (tag == null) { + if (thatResponse.tag != null) { return false; } } else { - if (!mTag.equals(thatResponse.mTag)) { + if (!tag.equals(thatResponse.tag)) { return false; } } - if (mIsContinuationRequest != thatResponse.mIsContinuationRequest) { + if (isContinuationRequest != thatResponse.isContinuationRequest) { return false; } return true; diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapResponseParser.java b/java/com/android/voicemail/impl/mail/store/imap/ImapResponseParser.java index e37106a69..68d6babbd 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapResponseParser.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapResponseParser.java @@ -33,21 +33,21 @@ public class ImapResponseParser { public static final int LITERAL_KEEP_IN_MEMORY_THRESHOLD = 2 * 1024 * 1024; /** Input stream */ - private final PeekableInputStream mIn; + private final PeekableInputStream in; - private final int mLiteralKeepInMemoryThreshold; + private final int literalKeepInMemoryThreshold; /** StringBuilder used by readUntil() */ - private final StringBuilder mBufferReadUntil = new StringBuilder(); + private final StringBuilder bufferReadUntil = new StringBuilder(); /** StringBuilder used by parseBareString() */ - private final StringBuilder mParseBareString = new StringBuilder(); + private final StringBuilder parseBareString = new StringBuilder(); /** * We store all {@link ImapResponse} in it. {@link #destroyResponses()} must be called from time * to time to destroy them and clear it. */ - private final ArrayList mResponsesToDestroy = new ArrayList(); + private final ArrayList responsesToDestroy = new ArrayList(); /** * Exception thrown when we receive BYE. It derives from IOException, so it'll be treated in the @@ -68,8 +68,8 @@ public class ImapResponseParser { /** Constructor for testing to override the literal size threshold. */ /* package for test */ ImapResponseParser(InputStream in, int literalKeepInMemoryThreshold) { - mIn = new PeekableInputStream(in); - mLiteralKeepInMemoryThreshold = literalKeepInMemoryThreshold; + this.in = new PeekableInputStream(in); + this.literalKeepInMemoryThreshold = literalKeepInMemoryThreshold; } private static IOException newEOSException() { @@ -85,7 +85,7 @@ public class ImapResponseParser { * shouldn't see EOF during parsing. */ private int peek() throws IOException { - final int next = mIn.peek(); + final int next = in.peek(); if (next == -1) { throw newEOSException(); } @@ -93,13 +93,13 @@ public class ImapResponseParser { } /** - * Read and return one byte from {@link #mIn}, and put it in {@link #mDiscourseLogger}. + * Read and return one byte from {@link #in}, and put it in {@link #mDiscourseLogger}. * *

Throws IOException() if reaches EOF. As long as logical response lines end with \r\n, we * shouldn't see EOF during parsing. */ private int readByte() throws IOException { - int next = mIn.read(); + int next = in.read(); if (next == -1) { throw newEOSException(); } @@ -112,10 +112,10 @@ public class ImapResponseParser { * @see #readResponse() */ public void destroyResponses() { - for (ImapResponse r : mResponsesToDestroy) { + for (ImapResponse r : responsesToDestroy) { r.destroy(); } - mResponsesToDestroy.clear(); + responsesToDestroy.clear(); } /** @@ -151,7 +151,7 @@ public class ImapResponseParser { response.destroy(); throw new ByeException(); } - mResponsesToDestroy.add(response); + responsesToDestroy.add(response); return response; } @@ -192,13 +192,13 @@ public class ImapResponseParser { * (rather than peeked) and won't be included in the result. */ /* package for test */ String readUntil(char end) throws IOException { - mBufferReadUntil.setLength(0); + bufferReadUntil.setLength(0); for (; ; ) { final int ch = readByte(); if (ch != end) { - mBufferReadUntil.append((char) ch); + bufferReadUntil.append((char) ch); } else { - return mBufferReadUntil.toString(); + return bufferReadUntil.toString(); } } } @@ -326,7 +326,7 @@ public class ImapResponseParser { *

If the value is "NIL", returns an empty string. */ private ImapString parseBareString() throws IOException, MessagingException { - mParseBareString.setLength(0); + parseBareString.setLength(0); for (; ; ) { final int ch = peek(); @@ -351,10 +351,10 @@ public class ImapResponseParser { ch == '"' || (0x00 <= ch && ch <= 0x1f) || ch == 0x7f) { - if (mParseBareString.length() == 0) { + if (parseBareString.length() == 0) { throw new MessagingException("Expected string, none found."); } - String s = mParseBareString.toString(); + String s = parseBareString.toString(); // NIL will be always converted into the empty string. if (ImapConstants.NIL.equalsIgnoreCase(s)) { @@ -363,11 +363,11 @@ public class ImapResponseParser { return new ImapSimpleString(s); } else if (ch == '[') { // Eat all until next ']' - mParseBareString.append((char) readByte()); - mParseBareString.append(readUntil(']')); - mParseBareString.append(']'); // readUntil won't include the end char. + parseBareString.append((char) readByte()); + parseBareString.append(readUntil(']')); + parseBareString.append(']'); // readUntil won't include the end char. } else { - mParseBareString.append((char) readByte()); + parseBareString.append((char) readByte()); } } } @@ -414,8 +414,8 @@ public class ImapResponseParser { } expect('\r'); expect('\n'); - FixedLengthInputStream in = new FixedLengthInputStream(mIn, size); - if (size > mLiteralKeepInMemoryThreshold) { + FixedLengthInputStream in = new FixedLengthInputStream(this.in, size); + if (size > literalKeepInMemoryThreshold) { return new ImapTempFileLiteral(in); } else { return new ImapMemoryLiteral(in); diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapSimpleString.java b/java/com/android/voicemail/impl/mail/store/imap/ImapSimpleString.java index 7cc866b74..76d3c6e91 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapSimpleString.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapSimpleString.java @@ -24,27 +24,27 @@ import java.io.UnsupportedEncodingException; /** Subclass of {@link ImapString} used for non literals. */ public class ImapSimpleString extends ImapString { private final String TAG = "ImapSimpleString"; - private String mString; + private String string; /* package */ ImapSimpleString(String string) { - mString = (string != null) ? string : ""; + this.string = (string != null) ? string : ""; } @Override public void destroy() { - mString = null; + string = null; super.destroy(); } @Override public String getString() { - return mString; + return string; } @Override public InputStream getAsStream() { try { - return new ByteArrayInputStream(mString.getBytes("US-ASCII")); + return new ByteArrayInputStream(string.getBytes("US-ASCII")); } catch (UnsupportedEncodingException e) { VvmLog.e(TAG, "Unsupported encoding: ", e); } @@ -54,6 +54,6 @@ public class ImapSimpleString extends ImapString { @Override public String toString() { // Purposefully not return just mString, in order to prevent using it instead of getString. - return "\"" + mString + "\""; + return "\"" + string + "\""; } } diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapString.java b/java/com/android/voicemail/impl/mail/store/imap/ImapString.java index d5c555126..099e569a8 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapString.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapString.java @@ -64,9 +64,9 @@ public abstract class ImapString extends ImapElement { private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z", Locale.US); - private boolean mIsInteger; - private int mParsedInteger; - private Date mParsedDate; + private boolean isInteger; + private int parsedInteger; + private Date parsedDate; @Override public final boolean isList() { @@ -94,12 +94,12 @@ public abstract class ImapString extends ImapElement { /** @return whether it can be parsed as a number. */ public final boolean isNumber() { - if (mIsInteger) { + if (isInteger) { return true; } try { - mParsedInteger = Integer.parseInt(getString()); - mIsInteger = true; + parsedInteger = Integer.parseInt(getString()); + isInteger = true; return true; } catch (NumberFormatException e) { return false; @@ -116,19 +116,19 @@ public abstract class ImapString extends ImapElement { if (!isNumber()) { return defaultValue; } - return mParsedInteger; + return parsedInteger; } /** @return whether it can be parsed as a date using {@link #DATE_TIME_FORMAT}. */ public final boolean isDate() { - if (mParsedDate != null) { + if (parsedDate != null) { return true; } if (isEmpty()) { return false; } try { - mParsedDate = DATE_TIME_FORMAT.parse(getString()); + parsedDate = DATE_TIME_FORMAT.parse(getString()); return true; } catch (ParseException e) { VvmLog.w("ImapString", getString() + " can't be parsed as a date."); @@ -141,7 +141,7 @@ public abstract class ImapString extends ImapElement { if (!isDate()) { return null; } - return mParsedDate; + return parsedDate; } /** @return whether the value case-insensitively equals to {@code s}. */ diff --git a/java/com/android/voicemail/impl/mail/store/imap/ImapTempFileLiteral.java b/java/com/android/voicemail/impl/mail/store/imap/ImapTempFileLiteral.java index ab64d8537..417adcc02 100644 --- a/java/com/android/voicemail/impl/mail/store/imap/ImapTempFileLiteral.java +++ b/java/com/android/voicemail/impl/mail/store/imap/ImapTempFileLiteral.java @@ -33,20 +33,20 @@ import org.apache.commons.io.IOUtils; public class ImapTempFileLiteral extends ImapString { private final String TAG = "ImapTempFileLiteral"; - /* package for test */ final File mFile; + /* package for test */ final File file; /** Size is purely for toString() */ - private final int mSize; + private final int size; /* package */ ImapTempFileLiteral(FixedLengthInputStream stream) throws IOException { - mSize = stream.getLength(); - mFile = File.createTempFile("imap", ".tmp", TempDirectory.getTempDirectory()); + size = stream.getLength(); + file = File.createTempFile("imap", ".tmp", TempDirectory.getTempDirectory()); // Unfortunately, we can't really use deleteOnExit(), because temp filenames are random // so it'd simply cause a memory leak. // deleteOnExit() simply adds filenames to a static list and the list will never shrink. // mFile.deleteOnExit(); - OutputStream out = new FileOutputStream(mFile); + OutputStream out = new FileOutputStream(file); IOUtils.copy(stream, out); out.close(); } @@ -69,7 +69,7 @@ public class ImapTempFileLiteral extends ImapString { public InputStream getAsStream() { checkNotDestroyed(); try { - return new FileInputStream(mFile); + return new FileInputStream(file); } catch (FileNotFoundException e) { // It's probably possible if we're low on storage and the system clears the cache dir. LogUtils.w(TAG, "ImapTempFileLiteral: Temp file not found"); @@ -98,8 +98,8 @@ public class ImapTempFileLiteral extends ImapString { @Override public void destroy() { try { - if (!isDestroyed() && mFile.exists()) { - mFile.delete(); + if (!isDestroyed() && file.exists()) { + file.delete(); } } catch (RuntimeException re) { // Just log and ignore. @@ -110,10 +110,10 @@ public class ImapTempFileLiteral extends ImapString { @Override public String toString() { - return String.format("{%d byte literal(file)}", mSize); + return String.format("{%d byte literal(file)}", size); } public boolean tempFileExistsForTest() { - return mFile.exists(); + return file.exists(); } } diff --git a/java/com/android/voicemail/impl/mail/utility/CountingOutputStream.java b/java/com/android/voicemail/impl/mail/utility/CountingOutputStream.java index c3586105f..0136b0272 100644 --- a/java/com/android/voicemail/impl/mail/utility/CountingOutputStream.java +++ b/java/com/android/voicemail/impl/mail/utility/CountingOutputStream.java @@ -23,26 +23,26 @@ import java.io.OutputStream; * count available to callers. */ public class CountingOutputStream extends OutputStream { - private long mCount; - private final OutputStream mOutputStream; + private long count; + private final OutputStream outputStream; public CountingOutputStream(OutputStream outputStream) { - mOutputStream = outputStream; + this.outputStream = outputStream; } public long getCount() { - return mCount; + return count; } @Override public void write(byte[] buffer, int offset, int count) throws IOException { - mOutputStream.write(buffer, offset, count); - mCount += count; + outputStream.write(buffer, offset, count); + this.count += count; } @Override public void write(int oneByte) throws IOException { - mOutputStream.write(oneByte); - mCount++; + outputStream.write(oneByte); + count++; } } diff --git a/java/com/android/voicemail/impl/mail/utils/LogUtils.java b/java/com/android/voicemail/impl/mail/utils/LogUtils.java index f6c3c6ba3..772048d49 100644 --- a/java/com/android/voicemail/impl/mail/utils/LogUtils.java +++ b/java/com/android/voicemail/impl/mail/utils/LogUtils.java @@ -1,5 +1,5 @@ -/** - * Copyright (c) 2015 The Android Open Source Project +/* + * Copyright (C) 2015 The Android Open Source Project * *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at @@ -46,7 +46,7 @@ public class LogUtils { */ private static final int MAX_ENABLED_LOG_LEVEL = DEBUG; - private static Boolean sDebugLoggingEnabledForTests = null; + private static Boolean debugLoggingEnabledForTests = null; /** Enable debug logging for unit tests. */ @VisibleForTesting @@ -55,7 +55,7 @@ public class LogUtils { } protected static void setDebugLoggingEnabledForTestsInternal(boolean enabled) { - sDebugLoggingEnabledForTests = Boolean.valueOf(enabled); + debugLoggingEnabledForTests = Boolean.valueOf(enabled); } /** Returns true if the build configuration prevents debug logging. */ @@ -69,8 +69,8 @@ public class LogUtils { if (buildPreventsDebugLogging()) { return false; } - if (sDebugLoggingEnabledForTests != null) { - return sDebugLoggingEnabledForTests.booleanValue(); + if (debugLoggingEnabledForTests != null) { + return debugLoggingEnabledForTests.booleanValue(); } return Log.isLoggable(tag, Log.DEBUG) || Log.isLoggable(TAG, Log.DEBUG); } diff --git a/java/com/android/voicemail/impl/protocol/Vvm3Subscriber.java b/java/com/android/voicemail/impl/protocol/Vvm3Subscriber.java index d9a06494e..ce5094f1a 100644 --- a/java/com/android/voicemail/impl/protocol/Vvm3Subscriber.java +++ b/java/com/android/voicemail/impl/protocol/Vvm3Subscriber.java @@ -131,15 +131,15 @@ public class Vvm3Subscriber { private static final int REQUEST_TIMEOUT_SECONDS = 30; - private final ActivationTask mTask; - private final PhoneAccountHandle mHandle; - private final OmtpVvmCarrierConfigHelper mHelper; - private final VoicemailStatus.Editor mStatus; - private final Bundle mData; + private final ActivationTask task; + private final PhoneAccountHandle handle; + private final OmtpVvmCarrierConfigHelper helper; + private final VoicemailStatus.Editor status; + private final Bundle data; - private final String mNumber; + private final String number; - private RequestQueue mRequestQueue; + private RequestQueue requestQueue; @VisibleForTesting static class ProvisioningException extends Exception { @@ -166,19 +166,19 @@ public class Vvm3Subscriber { VoicemailStatus.Editor status, Bundle data) { Assert.isNotMainThread(); - mTask = task; - mHandle = handle; - mHelper = helper; - mStatus = status; - mData = data; + this.task = task; + this.handle = handle; + this.helper = helper; + this.status = status; + this.data = data; // Assuming getLine1Number() will work with VVM3. For unprovisioned users the IMAP username // is not included in the status SMS, thus no other way to get the current phone number. - mNumber = - mHelper + number = + this.helper .getContext() .getSystemService(TelephonyManager.class) - .createForPhoneAccountHandle(mHandle) + .createForPhoneAccountHandle(this.handle) .getLine1Number(); } @@ -189,15 +189,15 @@ public class Vvm3Subscriber { // processSubscription() is called after network is available. VvmLog.i(TAG, "Subscribing"); - try (NetworkWrapper wrapper = VvmNetworkRequest.getNetwork(mHelper, mHandle, mStatus)) { + try (NetworkWrapper wrapper = VvmNetworkRequest.getNetwork(helper, handle, status)) { Network network = wrapper.get(); VvmLog.d(TAG, "provisioning: network available"); - mRequestQueue = - Volley.newRequestQueue(mHelper.getContext(), new NetworkSpecifiedHurlStack(network)); + requestQueue = + Volley.newRequestQueue(helper.getContext(), new NetworkSpecifiedHurlStack(network)); processSubscription(); } catch (RequestFailedException e) { - mHelper.handleEvent(mStatus, OmtpEvents.VVM3_VMG_CONNECTION_FAILED); - mTask.fail(); + helper.handleEvent(status, OmtpEvents.VVM3_VMG_CONNECTION_FAILED); + task.fail(); } } @@ -206,11 +206,11 @@ public class Vvm3Subscriber { String gatewayUrl = getSelfProvisioningGateway(); String selfProvisionResponse = getSelfProvisionResponse(gatewayUrl); String subscribeLink = - findSubscribeLink(getSubscribeLinkPatterns(mHelper.getContext()), selfProvisionResponse); + findSubscribeLink(getSubscribeLinkPatterns(helper.getContext()), selfProvisionResponse); clickSubscribeLink(subscribeLink); } catch (ProvisioningException e) { VvmLog.e(TAG, e.toString()); - mTask.fail(); + task.fail(); } } @@ -236,7 +236,7 @@ public class Vvm3Subscriber { @Override protected Map getParams() { Map params = new ArrayMap<>(); - params.put(SPG_VZW_MDN_PARAM, mNumber); + params.put(SPG_VZW_MDN_PARAM, number); params.put(SPG_VZW_SERVICE_PARAM, SPG_VZW_SERVICE_BASIC); params.put(SPG_DEVICE_MODEL_PARAM, SPG_DEVICE_MODEL_ANDROID); params.put(SPG_APP_TOKEN_PARAM, SPG_APP_TOKEN); @@ -247,11 +247,11 @@ public class Vvm3Subscriber { } }; - mRequestQueue.add(stringRequest); + requestQueue.add(stringRequest); try { return future.get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { - mHelper.handleEvent(mStatus, OmtpEvents.VVM3_SPG_CONNECTION_FAILED); + helper.handleEvent(status, OmtpEvents.VVM3_SPG_CONNECTION_FAILED); throw new ProvisioningException(e.toString()); } } @@ -262,12 +262,12 @@ public class Vvm3Subscriber { StringRequest stringRequest = new StringRequest(Request.Method.POST, subscribeLink, future, future); - mRequestQueue.add(stringRequest); + requestQueue.add(stringRequest); try { // A new STATUS SMS will be sent after this request. future.get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (TimeoutException | ExecutionException | InterruptedException e) { - mHelper.handleEvent(mStatus, OmtpEvents.VVM3_SPG_CONNECTION_FAILED); + helper.handleEvent(status, OmtpEvents.VVM3_SPG_CONNECTION_FAILED); throw new ProvisioningException(e.toString()); } // It could take very long for the STATUS SMS to return. Waiting for it is unreliable. @@ -277,7 +277,7 @@ public class Vvm3Subscriber { private String vvm3XmlRequest(String operation) throws ProvisioningException { VvmLog.d(TAG, "Sending vvm3XmlRequest for " + operation); - String voicemailManagementGateway = mData.getString(VMG_URL_KEY); + String voicemailManagementGateway = data.getString(VMG_URL_KEY); if (voicemailManagementGateway == null) { VvmLog.e(TAG, "voicemailManagementGateway url unknown"); return null; @@ -285,7 +285,7 @@ public class Vvm3Subscriber { String transactionId = createTransactionId(); String body = String.format( - Locale.US, VMG_XML_REQUEST_FORMAT, transactionId, mNumber, operation, Build.MODEL); + Locale.US, VMG_XML_REQUEST_FORMAT, transactionId, number, operation, Build.MODEL); RequestFuture future = RequestFuture.newFuture(); StringRequest stringRequest = @@ -295,7 +295,7 @@ public class Vvm3Subscriber { return body.getBytes(); } }; - mRequestQueue.add(stringRequest); + requestQueue.add(stringRequest); try { String response = future.get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -304,7 +304,7 @@ public class Vvm3Subscriber { } return response; } catch (InterruptedException | ExecutionException | TimeoutException e) { - mHelper.handleEvent(mStatus, OmtpEvents.VVM3_VMG_CONNECTION_FAILED); + helper.handleEvent(status, OmtpEvents.VVM3_VMG_CONNECTION_FAILED); throw new ProvisioningException(e.toString()); } } @@ -364,15 +364,15 @@ public class Vvm3Subscriber { private static class NetworkSpecifiedHurlStack extends HurlStack { - private final Network mNetwork; + private final Network network; public NetworkSpecifiedHurlStack(Network network) { - mNetwork = network; + this.network = network; } @Override protected HttpURLConnection createConnection(URL url) throws IOException { - return (HttpURLConnection) mNetwork.openConnection(url); + return (HttpURLConnection) network.openConnection(url); } } } diff --git a/java/com/android/voicemail/impl/scheduling/BaseTask.java b/java/com/android/voicemail/impl/scheduling/BaseTask.java index 773d026bf..0b707583c 100644 --- a/java/com/android/voicemail/impl/scheduling/BaseTask.java +++ b/java/com/android/voicemail/impl/scheduling/BaseTask.java @@ -44,25 +44,25 @@ public abstract class BaseTask implements Task { private static final String EXTRA_EXECUTION_TIME = "extra_execution_time"; - private Bundle mExtras; + private Bundle extras; - private Context mContext; + private Context context; - private int mId; - private PhoneAccountHandle mPhoneAccountHandle; + private int id; + private PhoneAccountHandle phoneAccountHandle; - private boolean mHasStarted; - private volatile boolean mHasFailed; + private boolean hasStarted; + private volatile boolean hasFailed; - @NonNull private final List mPolicies = new ArrayList<>(); + @NonNull private final List policies = new ArrayList<>(); - private long mExecutionTime; + private long executionTime; - private static Clock sClock = new Clock(); + private static Clock clock = new Clock(); protected BaseTask(int id) { - mId = id; - mExecutionTime = getTimeMillis(); + this.id = id; + executionTime = getTimeMillis(); } /** @@ -72,27 +72,27 @@ public abstract class BaseTask implements Task { @MainThread public void setId(int id) { Assert.isMainThread(); - mId = id; + this.id = id; } @MainThread public boolean hasStarted() { Assert.isMainThread(); - return mHasStarted; + return hasStarted; } @MainThread public boolean hasFailed() { Assert.isMainThread(); - return mHasFailed; + return hasFailed; } public Context getContext() { - return mContext; + return context; } public PhoneAccountHandle getPhoneAccountHandle() { - return mPhoneAccountHandle; + return phoneAccountHandle; } /** * Should be call in the constructor or {@link Policy#onCreate(BaseTask, Bundle)} will be missed. @@ -100,7 +100,7 @@ public abstract class BaseTask implements Task { @MainThread public BaseTask addPolicy(Policy policy) { Assert.isMainThread(); - mPolicies.add(policy); + policies.add(policy); return this; } @@ -112,18 +112,18 @@ public abstract class BaseTask implements Task { @WorkerThread public void fail() { Assert.isNotMainThread(); - mHasFailed = true; + hasFailed = true; } /** @param timeMillis the time since epoch, in milliseconds. */ @MainThread public void setExecutionTime(long timeMillis) { Assert.isMainThread(); - mExecutionTime = timeMillis; + executionTime = timeMillis; } public long getTimeMillis() { - return sClock.getTimeMillis(); + return clock.getTimeMillis(); } /** @@ -131,7 +131,7 @@ public abstract class BaseTask implements Task { * their intent upon this. */ public Intent createRestartIntent() { - return createIntent(getContext(), this.getClass(), mPhoneAccountHandle); + return createIntent(getContext(), this.getClass(), phoneAccountHandle); } /** @@ -147,22 +147,22 @@ public abstract class BaseTask implements Task { @Override public TaskId getId() { - return new TaskId(mId, mPhoneAccountHandle); + return new TaskId(id, phoneAccountHandle); } @Override public Bundle toBundle() { - mExtras.putLong(EXTRA_EXECUTION_TIME, mExecutionTime); - return mExtras; + extras.putLong(EXTRA_EXECUTION_TIME, executionTime); + return extras; } @Override @CallSuper public void onCreate(Context context, Bundle extras) { - mContext = context; - mExtras = extras; - mPhoneAccountHandle = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); - for (Policy policy : mPolicies) { + this.context = context; + this.extras = extras; + phoneAccountHandle = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); + for (Policy policy : policies) { policy.onCreate(this, extras); } } @@ -170,42 +170,42 @@ public abstract class BaseTask implements Task { @Override @CallSuper public void onRestore(Bundle extras) { - if (mExtras.containsKey(EXTRA_EXECUTION_TIME)) { - mExecutionTime = extras.getLong(EXTRA_EXECUTION_TIME); + if (this.extras.containsKey(EXTRA_EXECUTION_TIME)) { + executionTime = extras.getLong(EXTRA_EXECUTION_TIME); } } @Override public long getReadyInMilliSeconds() { - return mExecutionTime - getTimeMillis(); + return executionTime - getTimeMillis(); } @Override @CallSuper public void onBeforeExecute() { - for (Policy policy : mPolicies) { + for (Policy policy : policies) { policy.onBeforeExecute(); } - mHasStarted = true; + hasStarted = true; } @Override @CallSuper public void onCompleted() { - if (mHasFailed) { - for (Policy policy : mPolicies) { + if (hasFailed) { + for (Policy policy : policies) { policy.onFail(); } } - for (Policy policy : mPolicies) { + for (Policy policy : policies) { policy.onCompleted(); } } @Override public void onDuplicatedTaskAdded(Task task) { - for (Policy policy : mPolicies) { + for (Policy policy : policies) { policy.onDuplicatedTaskAdded(); } } @@ -221,6 +221,6 @@ public abstract class BaseTask implements Task { /** Used to replace the clock with an deterministic clock */ @NeededForTesting static void setClockForTesting(Clock clock) { - sClock = clock; + BaseTask.clock = clock; } } diff --git a/java/com/android/voicemail/impl/scheduling/MinimalIntervalPolicy.java b/java/com/android/voicemail/impl/scheduling/MinimalIntervalPolicy.java index 342b56e8a..6d6a0a1af 100644 --- a/java/com/android/voicemail/impl/scheduling/MinimalIntervalPolicy.java +++ b/java/com/android/voicemail/impl/scheduling/MinimalIntervalPolicy.java @@ -27,18 +27,18 @@ import com.android.voicemail.impl.scheduling.Task.TaskId; */ public class MinimalIntervalPolicy implements Policy { - BaseTask mTask; - TaskId mId; - int mBlockForMillis; + BaseTask task; + TaskId id; + int blockForMillis; public MinimalIntervalPolicy(int blockForMillis) { - mBlockForMillis = blockForMillis; + this.blockForMillis = blockForMillis; } @Override public void onCreate(BaseTask task, Bundle extras) { - mTask = task; - mId = mTask.getId(); + this.task = task; + id = this.task.getId(); } @Override @@ -46,12 +46,12 @@ public class MinimalIntervalPolicy implements Policy { @Override public void onCompleted() { - if (!mTask.hasFailed()) { + if (!task.hasFailed()) { Intent intent = - BaseTask.createIntent(mTask.getContext(), BlockerTask.class, mId.phoneAccountHandle); - intent.putExtra(BlockerTask.EXTRA_TASK_ID, mId.id); - intent.putExtra(BlockerTask.EXTRA_BLOCK_FOR_MILLIS, mBlockForMillis); - mTask.getContext().sendBroadcast(intent); + BaseTask.createIntent(task.getContext(), BlockerTask.class, id.phoneAccountHandle); + intent.putExtra(BlockerTask.EXTRA_TASK_ID, id.id); + intent.putExtra(BlockerTask.EXTRA_BLOCK_FOR_MILLIS, blockForMillis); + task.getContext().sendBroadcast(intent); } } diff --git a/java/com/android/voicemail/impl/scheduling/PostponePolicy.java b/java/com/android/voicemail/impl/scheduling/PostponePolicy.java index 46773b53a..8ff1478e3 100644 --- a/java/com/android/voicemail/impl/scheduling/PostponePolicy.java +++ b/java/com/android/voicemail/impl/scheduling/PostponePolicy.java @@ -29,17 +29,17 @@ public class PostponePolicy implements Policy { private static final String TAG = "PostponePolicy"; - private final int mPostponeMillis; - private BaseTask mTask; + private final int postponeMillis; + private BaseTask task; public PostponePolicy(int postponeMillis) { - mPostponeMillis = postponeMillis; + this.postponeMillis = postponeMillis; } @Override public void onCreate(BaseTask task, Bundle extras) { - mTask = task; - mTask.setExecutionTime(mTask.getTimeMillis() + mPostponeMillis); + this.task = task; + this.task.setExecutionTime(this.task.getTimeMillis() + postponeMillis); } @Override @@ -59,10 +59,10 @@ public class PostponePolicy implements Policy { @Override public void onDuplicatedTaskAdded() { - if (mTask.hasStarted()) { + if (task.hasStarted()) { return; } - VvmLog.i(TAG, "postponing " + mTask); - mTask.setExecutionTime(mTask.getTimeMillis() + mPostponeMillis); + VvmLog.i(TAG, "postponing " + task); + task.setExecutionTime(task.getTimeMillis() + postponeMillis); } } diff --git a/java/com/android/voicemail/impl/scheduling/RetryPolicy.java b/java/com/android/voicemail/impl/scheduling/RetryPolicy.java index c408bdc4a..ec4d72de9 100644 --- a/java/com/android/voicemail/impl/scheduling/RetryPolicy.java +++ b/java/com/android/voicemail/impl/scheduling/RetryPolicy.java @@ -32,23 +32,23 @@ public class RetryPolicy implements Policy { private static final String TAG = "RetryPolicy"; private static final String EXTRA_RETRY_COUNT = "extra_retry_count"; - private final int mRetryLimit; - private final int mRetryDelayMillis; + private final int retryLimit; + private final int retryDelayMillis; - private BaseTask mTask; + private BaseTask task; - private int mRetryCount; - private boolean mFailed; + private int retryCount; + private boolean failed; - private VoicemailStatus.DeferredEditor mVoicemailStatusEditor; + private VoicemailStatus.DeferredEditor voicemailStatusEditor; public RetryPolicy(int retryLimit, int retryDelayMillis) { - mRetryLimit = retryLimit; - mRetryDelayMillis = retryDelayMillis; + this.retryLimit = retryLimit; + this.retryDelayMillis = retryDelayMillis; } private boolean hasMoreRetries() { - return mRetryCount < mRetryLimit; + return retryCount < retryLimit; } /** @@ -57,18 +57,23 @@ public class RetryPolicy implements Policy { * the task is successful or there are no retries left. */ public VoicemailStatus.Editor getVoicemailStatusEditor() { - return mVoicemailStatusEditor; + return voicemailStatusEditor; } @Override public void onCreate(BaseTask task, Bundle extras) { - mTask = task; - mRetryCount = extras.getInt(EXTRA_RETRY_COUNT, 0); - if (mRetryCount > 0) { + this.task = task; + retryCount = extras.getInt(EXTRA_RETRY_COUNT, 0); + if (retryCount > 0) { VvmLog.i( TAG, - "retry #" + mRetryCount + " for " + mTask + " queued, executing in " + mRetryDelayMillis); - mTask.setExecutionTime(mTask.getTimeMillis() + mRetryDelayMillis); + "retry #" + + retryCount + + " for " + + this.task + + " queued, executing in " + + retryDelayMillis); + this.task.setExecutionTime(this.task.getTimeMillis() + retryDelayMillis); } PhoneAccountHandle phoneAccountHandle = task.getPhoneAccountHandle(); if (phoneAccountHandle == null) { @@ -76,7 +81,7 @@ public class RetryPolicy implements Policy { // This should never happen, but continue on if it does. The status write will be // discarded. } - mVoicemailStatusEditor = VoicemailStatus.deferredEdit(task.getContext(), phoneAccountHandle); + voicemailStatusEditor = VoicemailStatus.deferredEdit(task.getContext(), phoneAccountHandle); } @Override @@ -84,27 +89,27 @@ public class RetryPolicy implements Policy { @Override public void onCompleted() { - if (!mFailed || !hasMoreRetries()) { - if (!mFailed) { - VvmLog.i(TAG, mTask + " completed successfully"); + if (!failed || !hasMoreRetries()) { + if (!failed) { + VvmLog.i(TAG, task + " completed successfully"); } if (!hasMoreRetries()) { - VvmLog.i(TAG, "Retry limit for " + mTask + " reached"); + VvmLog.i(TAG, "Retry limit for " + task + " reached"); } - VvmLog.i(TAG, "committing deferred status: " + mVoicemailStatusEditor.getValues()); - mVoicemailStatusEditor.deferredApply(); + VvmLog.i(TAG, "committing deferred status: " + voicemailStatusEditor.getValues()); + voicemailStatusEditor.deferredApply(); return; } - VvmLog.i(TAG, "discarding deferred status: " + mVoicemailStatusEditor.getValues()); - Intent intent = mTask.createRestartIntent(); - intent.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1); + VvmLog.i(TAG, "discarding deferred status: " + voicemailStatusEditor.getValues()); + Intent intent = task.createRestartIntent(); + intent.putExtra(EXTRA_RETRY_COUNT, retryCount + 1); - mTask.getContext().sendBroadcast(intent); + task.getContext().sendBroadcast(intent); } @Override public void onFail() { - mFailed = true; + failed = true; } @Override diff --git a/java/com/android/voicemail/impl/sms/OmtpMessageReceiver.java b/java/com/android/voicemail/impl/sms/OmtpMessageReceiver.java index 43835276b..eae990ab0 100644 --- a/java/com/android/voicemail/impl/sms/OmtpMessageReceiver.java +++ b/java/com/android/voicemail/impl/sms/OmtpMessageReceiver.java @@ -46,11 +46,11 @@ public class OmtpMessageReceiver extends BroadcastReceiver { private static final String TAG = "OmtpMessageReceiver"; - private Context mContext; + private Context context; @Override public void onReceive(Context context, Intent intent) { - mContext = context; + this.context = context; VisualVoicemailSms sms = intent.getExtras().getParcelable(OmtpService.EXTRA_VOICEMAIL_SMS); PhoneAccountHandle phone = sms.getPhoneAccountHandle(); @@ -69,12 +69,12 @@ public class OmtpMessageReceiver extends BroadcastReceiver { return; } - OmtpVvmCarrierConfigHelper helper = new OmtpVvmCarrierConfigHelper(mContext, phone); + OmtpVvmCarrierConfigHelper helper = new OmtpVvmCarrierConfigHelper(this.context, phone); if (!helper.isValid()) { VvmLog.e(TAG, "vvm config no longer valid"); return; } - if (!VisualVoicemailSettingsUtil.isEnabled(mContext, phone)) { + if (!VisualVoicemailSettingsUtil.isEnabled(this.context, phone)) { if (helper.isLegacyModeEnabled()) { LegacyModeSmsHandler.handle(context, sms); } else { @@ -140,18 +140,18 @@ public class OmtpMessageReceiver extends BroadcastReceiver { .setPhoneAccount(phone) .setSourceData(message.getId()) .setDuration(message.getLength()) - .setSourcePackage(mContext.getPackageName()); + .setSourcePackage(context.getPackageName()); Voicemail voicemail = builder.build(); - VoicemailsQueryHelper queryHelper = new VoicemailsQueryHelper(mContext); + VoicemailsQueryHelper queryHelper = new VoicemailsQueryHelper(context); if (queryHelper.isVoicemailUnique(voicemail)) { - Uri uri = VoicemailDatabaseUtil.insert(mContext, voicemail); + Uri uri = VoicemailDatabaseUtil.insert(context, voicemail); voicemail = builder.setId(ContentUris.parseId(uri)).setUri(uri).build(); - SyncOneTask.start(mContext, phone, voicemail); + SyncOneTask.start(context, phone, voicemail); } break; case OmtpConstants.MAILBOX_UPDATE: - SyncTask.start(mContext, phone); + SyncTask.start(context, phone); break; case OmtpConstants.GREETINGS_UPDATE: // Not implemented in V1 diff --git a/java/com/android/voicemail/impl/sms/OmtpMessageSender.java b/java/com/android/voicemail/impl/sms/OmtpMessageSender.java index 19661e99d..76a258366 100644 --- a/java/com/android/voicemail/impl/sms/OmtpMessageSender.java +++ b/java/com/android/voicemail/impl/sms/OmtpMessageSender.java @@ -35,20 +35,20 @@ import com.android.voicemail.impl.VvmLog; */ public abstract class OmtpMessageSender { protected static final String TAG = "OmtpMessageSender"; - protected final Context mContext; - protected final PhoneAccountHandle mPhoneAccountHandle; - protected final short mApplicationPort; - protected final String mDestinationNumber; + protected final Context context; + protected final PhoneAccountHandle phoneAccountHandle; + protected final short applicationPort; + protected final String destinationNumber; public OmtpMessageSender( Context context, PhoneAccountHandle phoneAccountHandle, short applicationPort, String destinationNumber) { - mContext = context; - mPhoneAccountHandle = phoneAccountHandle; - mApplicationPort = applicationPort; - mDestinationNumber = destinationNumber; + this.context = context; + this.phoneAccountHandle = phoneAccountHandle; + this.applicationPort = applicationPort; + this.destinationNumber = destinationNumber; } /** @@ -78,11 +78,10 @@ public abstract class OmtpMessageSender { protected void sendSms(String text, PendingIntent sentIntent) { VvmLog.v( - TAG, - String.format("Sending sms '%s' to %s:%d", text, mDestinationNumber, mApplicationPort)); + TAG, String.format("Sending sms '%s' to %s:%d", text, destinationNumber, applicationPort)); TelephonyMangerCompat.sendVisualVoicemailSms( - mContext, mPhoneAccountHandle, mDestinationNumber, mApplicationPort, text, sentIntent); + context, phoneAccountHandle, destinationNumber, applicationPort, text, sentIntent); } protected void appendField(StringBuilder sb, String field, Object value) { diff --git a/java/com/android/voicemail/impl/sms/OmtpStandardMessageSender.java b/java/com/android/voicemail/impl/sms/OmtpStandardMessageSender.java index 7974699a0..a8d27ff99 100644 --- a/java/com/android/voicemail/impl/sms/OmtpStandardMessageSender.java +++ b/java/com/android/voicemail/impl/sms/OmtpStandardMessageSender.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2015 Google Inc. All Rights Reserved. + * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,9 @@ import com.android.voicemail.impl.OmtpConstants; /** A implementation of the OmtpMessageSender using the standard OMTP sms protocol. */ public class OmtpStandardMessageSender extends OmtpMessageSender { - private final String mClientType; - private final String mProtocolVersion; - private final String mClientPrefix; + private final String clientType; + private final String protocolVersion; + private final String clientPrefix; /** * Creates a new instance of OmtpStandardMessageSender. @@ -49,9 +49,9 @@ public class OmtpStandardMessageSender extends OmtpMessageSender { String protocolVersion, String clientPrefix) { super(context, phoneAccountHandle, applicationPort, destinationNumber); - mClientType = clientType; - mProtocolVersion = protocolVersion; - mClientPrefix = clientPrefix; + this.clientType = clientType; + this.protocolVersion = protocolVersion; + this.clientPrefix = clientPrefix; } // Activate message: @@ -63,8 +63,8 @@ public class OmtpStandardMessageSender extends OmtpMessageSender { StringBuilder sb = new StringBuilder().append(OmtpConstants.ACTIVATE_REQUEST); appendProtocolVersionAndClientType(sb); - if (TextUtils.equals(mProtocolVersion, OmtpConstants.PROTOCOL_VERSION1_2) - || TextUtils.equals(mProtocolVersion, OmtpConstants.PROTOCOL_VERSION1_3)) { + if (TextUtils.equals(protocolVersion, OmtpConstants.PROTOCOL_VERSION1_2) + || TextUtils.equals(protocolVersion, OmtpConstants.PROTOCOL_VERSION1_3)) { appendApplicationPort(sb); appendClientPrefix(sb); } @@ -92,7 +92,7 @@ public class OmtpStandardMessageSender extends OmtpMessageSender { public void requestVvmStatus(@Nullable PendingIntent sentIntent) { StringBuilder sb = new StringBuilder().append(OmtpConstants.STATUS_REQUEST); - if (TextUtils.equals(mProtocolVersion, OmtpConstants.PROTOCOL_VERSION1_3)) { + if (TextUtils.equals(protocolVersion, OmtpConstants.PROTOCOL_VERSION1_3)) { appendProtocolVersionAndClientType(sb); appendApplicationPort(sb); appendClientPrefix(sb); @@ -103,18 +103,18 @@ public class OmtpStandardMessageSender extends OmtpMessageSender { private void appendProtocolVersionAndClientType(StringBuilder sb) { sb.append(OmtpConstants.SMS_PREFIX_SEPARATOR); - appendField(sb, OmtpConstants.PROTOCOL_VERSION, mProtocolVersion); + appendField(sb, OmtpConstants.PROTOCOL_VERSION, protocolVersion); sb.append(OmtpConstants.SMS_FIELD_SEPARATOR); - appendField(sb, OmtpConstants.CLIENT_TYPE, mClientType); + appendField(sb, OmtpConstants.CLIENT_TYPE, clientType); } private void appendApplicationPort(StringBuilder sb) { sb.append(OmtpConstants.SMS_FIELD_SEPARATOR); - appendField(sb, OmtpConstants.APPLICATION_PORT, mApplicationPort); + appendField(sb, OmtpConstants.APPLICATION_PORT, applicationPort); } private void appendClientPrefix(StringBuilder sb) { sb.append(OmtpConstants.SMS_FIELD_SEPARATOR); - sb.append(mClientPrefix); + sb.append(clientPrefix); } } diff --git a/java/com/android/voicemail/impl/sms/StatusMessage.java b/java/com/android/voicemail/impl/sms/StatusMessage.java index a5766a61a..7fd2966a4 100644 --- a/java/com/android/voicemail/impl/sms/StatusMessage.java +++ b/java/com/android/voicemail/impl/sms/StatusMessage.java @@ -32,66 +32,66 @@ public class StatusMessage { // to be useful for initial omtp source implementation. // lang, g_len, vs_len, pw_len, pm, gm, vtc, vt - private final String mProvisioningStatus; - private final String mStatusReturnCode; - private final String mSubscriptionUrl; - private final String mServerAddress; - private final String mTuiAccessNumber; - private final String mClientSmsDestinationNumber; - private final String mImapPort; - private final String mImapUserName; - private final String mImapPassword; - private final String mSmtpPort; - private final String mSmtpUserName; - private final String mSmtpPassword; - private final String mTuiPasswordLength; + private final String provisioningStatus; + private final String statusReturnCode; + private final String subscriptionUrl; + private final String serverAddress; + private final String tuiAccessNumber; + private final String clientSmsDestinationNumber; + private final String imapPort; + private final String imapUserName; + private final String imapPassword; + private final String smtpPort; + private final String smtpUserName; + private final String smtpPassword; + private final String tuiPasswordLength; @Override public String toString() { return "StatusMessage [mProvisioningStatus=" - + mProvisioningStatus + + provisioningStatus + ", mStatusReturnCode=" - + mStatusReturnCode + + statusReturnCode + ", mSubscriptionUrl=" - + mSubscriptionUrl + + subscriptionUrl + ", mServerAddress=" - + mServerAddress + + serverAddress + ", mTuiAccessNumber=" - + mTuiAccessNumber + + tuiAccessNumber + ", mClientSmsDestinationNumber=" - + mClientSmsDestinationNumber + + clientSmsDestinationNumber + ", mImapPort=" - + mImapPort + + imapPort + ", mImapUserName=" - + mImapUserName + + imapUserName + ", mImapPassword=" - + VvmLog.pii(mImapPassword) + + VvmLog.pii(imapPassword) + ", mSmtpPort=" - + mSmtpPort + + smtpPort + ", mSmtpUserName=" - + mSmtpUserName + + smtpUserName + ", mSmtpPassword=" - + VvmLog.pii(mSmtpPassword) + + VvmLog.pii(smtpPassword) + ", mTuiPasswordLength=" - + mTuiPasswordLength + + tuiPasswordLength + "]"; } public StatusMessage(Bundle wrappedData) { - mProvisioningStatus = unquote(getString(wrappedData, OmtpConstants.PROVISIONING_STATUS)); - mStatusReturnCode = getString(wrappedData, OmtpConstants.RETURN_CODE); - mSubscriptionUrl = getString(wrappedData, OmtpConstants.SUBSCRIPTION_URL); - mServerAddress = getString(wrappedData, OmtpConstants.SERVER_ADDRESS); - mTuiAccessNumber = getString(wrappedData, OmtpConstants.TUI_ACCESS_NUMBER); - mClientSmsDestinationNumber = + provisioningStatus = unquote(getString(wrappedData, OmtpConstants.PROVISIONING_STATUS)); + statusReturnCode = getString(wrappedData, OmtpConstants.RETURN_CODE); + subscriptionUrl = getString(wrappedData, OmtpConstants.SUBSCRIPTION_URL); + serverAddress = getString(wrappedData, OmtpConstants.SERVER_ADDRESS); + tuiAccessNumber = getString(wrappedData, OmtpConstants.TUI_ACCESS_NUMBER); + clientSmsDestinationNumber = getString(wrappedData, OmtpConstants.CLIENT_SMS_DESTINATION_NUMBER); - mImapPort = getString(wrappedData, OmtpConstants.IMAP_PORT); - mImapUserName = getString(wrappedData, OmtpConstants.IMAP_USER_NAME); - mImapPassword = getString(wrappedData, OmtpConstants.IMAP_PASSWORD); - mSmtpPort = getString(wrappedData, OmtpConstants.SMTP_PORT); - mSmtpUserName = getString(wrappedData, OmtpConstants.SMTP_USER_NAME); - mSmtpPassword = getString(wrappedData, OmtpConstants.SMTP_PASSWORD); - mTuiPasswordLength = getString(wrappedData, OmtpConstants.TUI_PASSWORD_LENGTH); + imapPort = getString(wrappedData, OmtpConstants.IMAP_PORT); + imapUserName = getString(wrappedData, OmtpConstants.IMAP_USER_NAME); + imapPassword = getString(wrappedData, OmtpConstants.IMAP_PASSWORD); + smtpPort = getString(wrappedData, OmtpConstants.SMTP_PORT); + smtpUserName = getString(wrappedData, OmtpConstants.SMTP_USER_NAME); + smtpPassword = getString(wrappedData, OmtpConstants.SMTP_PASSWORD); + tuiPasswordLength = getString(wrappedData, OmtpConstants.TUI_PASSWORD_LENGTH); } private static String unquote(String string) { @@ -106,12 +106,12 @@ public class StatusMessage { /** @return the subscriber's VVM provisioning status. */ public String getProvisioningStatus() { - return mProvisioningStatus; + return provisioningStatus; } /** @return the return-code of the status SMS. */ public String getReturnCode() { - return mStatusReturnCode; + return statusReturnCode; } /** @@ -120,14 +120,14 @@ public class StatusMessage { */ @NeededForTesting public String getSubscriptionUrl() { - return mSubscriptionUrl; + return subscriptionUrl; } /** * @return the voicemail server address. Either server IP address or fully qualified domain name. */ public String getServerAddress() { - return mServerAddress; + return serverAddress; } /** @@ -135,50 +135,50 @@ public class StatusMessage { */ @NeededForTesting public String getTuiAccessNumber() { - return mTuiAccessNumber; + return tuiAccessNumber; } /** @return the number to which client originated SMSes should be sent to. */ @NeededForTesting public String getClientSmsDestinationNumber() { - return mClientSmsDestinationNumber; + return clientSmsDestinationNumber; } /** @return the IMAP server port to talk to. */ public String getImapPort() { - return mImapPort; + return imapPort; } /** @return the IMAP user name to be used for authentication. */ public String getImapUserName() { - return mImapUserName; + return imapUserName; } /** @return the IMAP password to be used for authentication. */ public String getImapPassword() { - return mImapPassword; + return imapPassword; } /** @return the SMTP server port to talk to. */ @NeededForTesting public String getSmtpPort() { - return mSmtpPort; + return smtpPort; } /** @return the SMTP user name to be used for SMTP authentication. */ @NeededForTesting public String getSmtpUserName() { - return mSmtpUserName; + return smtpUserName; } /** @return the SMTP password to be used for SMTP authentication. */ @NeededForTesting public String getSmtpPassword() { - return mSmtpPassword; + return smtpPassword; } public String getTuiPasswordLength() { - return mTuiPasswordLength; + return tuiPasswordLength; } private static String getString(Bundle bundle, String key) { diff --git a/java/com/android/voicemail/impl/sms/StatusSmsFetcher.java b/java/com/android/voicemail/impl/sms/StatusSmsFetcher.java index d178628c6..73e0c7f3c 100644 --- a/java/com/android/voicemail/impl/sms/StatusSmsFetcher.java +++ b/java/com/android/voicemail/impl/sms/StatusSmsFetcher.java @@ -58,14 +58,14 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { "com.android.voicemailomtp.sms.REQUEST_SENT"; private static final int ACTION_REQUEST_SENT_REQUEST_CODE = 0; - private CompletableFuture mFuture = new CompletableFuture<>(); + private CompletableFuture future = new CompletableFuture<>(); - private final Context mContext; - private final PhoneAccountHandle mPhoneAccountHandle; + private final Context context; + private final PhoneAccountHandle phoneAccountHandle; public StatusSmsFetcher(Context context, PhoneAccountHandle phoneAccountHandle) { - mContext = context; - mPhoneAccountHandle = phoneAccountHandle; + this.context = context; + this.phoneAccountHandle = phoneAccountHandle; IntentFilter filter = new IntentFilter(ACTION_REQUEST_SENT_INTENT); filter.addAction(OmtpService.ACTION_SMS_RECEIVED); context.registerReceiver(this, filter); @@ -73,7 +73,7 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { @Override public void close() throws IOException { - mContext.unregisterReceiver(this); + context.unregisterReceiver(this); } @WorkerThread @@ -81,16 +81,16 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { public Bundle get() throws InterruptedException, ExecutionException, TimeoutException, CancellationException { Assert.isNotMainThread(); - return mFuture.get(STATUS_SMS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + return future.get(STATUS_SMS_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } public PendingIntent getSentIntent() { Intent intent = new Intent(ACTION_REQUEST_SENT_INTENT); - intent.setPackage(mContext.getPackageName()); + intent.setPackage(context.getPackageName()); // Because the receiver is registered dynamically, implicit intent must be used. // There should only be a single status SMS request at a time. return PendingIntent.getBroadcast( - mContext, ACTION_REQUEST_SENT_REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); + context, ACTION_REQUEST_SENT_REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT); } @Override @@ -106,19 +106,19 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { } VvmLog.e(TAG, "Request SMS send failed: " + sentSmsResultToString(resultCode)); - mFuture.cancel(true); + future.cancel(true); return; } VisualVoicemailSms sms = intent.getExtras().getParcelable(OmtpService.EXTRA_VOICEMAIL_SMS); - if (!mPhoneAccountHandle.equals(sms.getPhoneAccountHandle())) { + if (!phoneAccountHandle.equals(sms.getPhoneAccountHandle())) { return; } String eventType = sms.getPrefix(); if (eventType.equals(OmtpConstants.STATUS_SMS_PREFIX)) { - mFuture.complete(sms.getFields()); + future.complete(sms.getFields()); return; } @@ -129,8 +129,7 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { VvmLog.i( TAG, "VVM SMS with event " + eventType + " received, attempting to translate to STATUS SMS"); - OmtpVvmCarrierConfigHelper helper = - new OmtpVvmCarrierConfigHelper(context, mPhoneAccountHandle); + OmtpVvmCarrierConfigHelper helper = new OmtpVvmCarrierConfigHelper(context, phoneAccountHandle); VisualVoicemailProtocol protocol = helper.getProtocol(); if (protocol == null) { return; @@ -139,7 +138,7 @@ public class StatusSmsFetcher extends BroadcastReceiver implements Closeable { if (translatedBundle != null) { VvmLog.i(TAG, "Translated to STATUS SMS"); - mFuture.complete(translatedBundle); + future.complete(translatedBundle); } } diff --git a/java/com/android/voicemail/impl/sms/SyncMessage.java b/java/com/android/voicemail/impl/sms/SyncMessage.java index 3cfa1a7b3..de5b3ce35 100644 --- a/java/com/android/voicemail/impl/sms/SyncMessage.java +++ b/java/com/android/voicemail/impl/sms/SyncMessage.java @@ -31,47 +31,47 @@ import java.util.Locale; */ public class SyncMessage { // Sync event that triggered this message. - private final String mSyncTriggerEvent; + private final String syncTriggerEvent; // Total number of new messages on the server. - private final int mNewMessageCount; + private final int newMessageCount; // UID of the new message. - private final String mMessageId; + private final String messageId; // Length of the message. - private final int mMessageLength; + private final int messageLength; // Content type (voice, video, fax...) of the new message. - private final String mContentType; + private final String contentType; // Sender of the new message. - private final String mSender; + private final String sender; // Timestamp (in millis) of the new message. - private final long mMsgTimeMillis; + private final long msgTimeMillis; @Override public String toString() { return "SyncMessage [mSyncTriggerEvent=" - + mSyncTriggerEvent + + syncTriggerEvent + ", mNewMessageCount=" - + mNewMessageCount + + newMessageCount + ", mMessageId=" - + mMessageId + + messageId + ", mMessageLength=" - + mMessageLength + + messageLength + ", mContentType=" - + mContentType + + contentType + ", mSender=" - + mSender + + sender + ", mMsgTimeMillis=" - + mMsgTimeMillis + + msgTimeMillis + "]"; } public SyncMessage(Bundle wrappedData) { - mSyncTriggerEvent = getString(wrappedData, OmtpConstants.SYNC_TRIGGER_EVENT); - mMessageId = getString(wrappedData, OmtpConstants.MESSAGE_UID); - mMessageLength = getInt(wrappedData, OmtpConstants.MESSAGE_LENGTH); - mContentType = getString(wrappedData, OmtpConstants.CONTENT_TYPE); - mSender = getString(wrappedData, OmtpConstants.SENDER); - mNewMessageCount = getInt(wrappedData, OmtpConstants.NUM_MESSAGE_COUNT); - mMsgTimeMillis = parseTime(wrappedData.getString(OmtpConstants.TIME)); + syncTriggerEvent = getString(wrappedData, OmtpConstants.SYNC_TRIGGER_EVENT); + messageId = getString(wrappedData, OmtpConstants.MESSAGE_UID); + messageLength = getInt(wrappedData, OmtpConstants.MESSAGE_LENGTH); + contentType = getString(wrappedData, OmtpConstants.CONTENT_TYPE); + sender = getString(wrappedData, OmtpConstants.SENDER); + newMessageCount = getInt(wrappedData, OmtpConstants.NUM_MESSAGE_COUNT); + msgTimeMillis = parseTime(wrappedData.getString(OmtpConstants.TIME)); } private static long parseTime(@Nullable String value) { @@ -89,13 +89,13 @@ public class SyncMessage { * set. */ public String getSyncTriggerEvent() { - return mSyncTriggerEvent; + return syncTriggerEvent; } /** @return the number of new messages stored on the voicemail server. */ @NeededForTesting public int getNewMessageCount() { - return mNewMessageCount; + return newMessageCount; } /** @@ -103,7 +103,7 @@ public class SyncMessage { *

Expected to be set only for {@link OmtpConstants#NEW_MESSAGE} */ public String getId() { - return mMessageId; + return messageId; } /** @@ -112,7 +112,7 @@ public class SyncMessage { */ @NeededForTesting public String getContentType() { - return mContentType; + return contentType; } /** @@ -120,7 +120,7 @@ public class SyncMessage { *

Expected to be set only for {@link OmtpConstants#NEW_MESSAGE} */ public int getLength() { - return mMessageLength; + return messageLength; } /** @@ -128,7 +128,7 @@ public class SyncMessage { *

Expected to be set only for {@link OmtpConstants#NEW_MESSAGE} */ public String getSender() { - return mSender; + return sender; } /** @@ -136,7 +136,7 @@ public class SyncMessage { *

Expected to be set only for {@link OmtpConstants#NEW_MESSAGE} */ public long getTimestampMillis() { - return mMsgTimeMillis; + return msgTimeMillis; } private static int getInt(Bundle wrappedData, String key) { diff --git a/java/com/android/voicemail/impl/sync/OmtpVvmSyncService.java b/java/com/android/voicemail/impl/sync/OmtpVvmSyncService.java index f7c8f29c7..cf2763be7 100644 --- a/java/com/android/voicemail/impl/sync/OmtpVvmSyncService.java +++ b/java/com/android/voicemail/impl/sync/OmtpVvmSyncService.java @@ -56,12 +56,12 @@ public class OmtpVvmSyncService { /** Threshold for whether we should archive and delete voicemails from the remote VM server. */ private static final float AUTO_DELETE_ARCHIVE_VM_THRESHOLD = 0.75f; - private final Context mContext; - private final VoicemailsQueryHelper mQueryHelper; + private final Context context; + private final VoicemailsQueryHelper queryHelper; public OmtpVvmSyncService(Context context) { - mContext = context; - mQueryHelper = new VoicemailsQueryHelper(mContext); + this.context = context; + queryHelper = new VoicemailsQueryHelper(this.context); } public void sync( @@ -79,22 +79,22 @@ public class OmtpVvmSyncService { PhoneAccountHandle phoneAccount, Voicemail voicemail, VoicemailStatus.Editor status) { - if (!VisualVoicemailSettingsUtil.isEnabled(mContext, phoneAccount)) { + if (!VisualVoicemailSettingsUtil.isEnabled(context, phoneAccount)) { VvmLog.e(TAG, "Sync requested for disabled account"); return; } - if (!VvmAccountManager.isAccountActivated(mContext, phoneAccount)) { - ActivationTask.start(mContext, phoneAccount, null); + if (!VvmAccountManager.isAccountActivated(context, phoneAccount)) { + ActivationTask.start(context, phoneAccount, null); return; } - OmtpVvmCarrierConfigHelper config = new OmtpVvmCarrierConfigHelper(mContext, phoneAccount); - LoggerUtils.logImpressionOnMainThread(mContext, DialerImpression.Type.VVM_SYNC_STARTED); + OmtpVvmCarrierConfigHelper config = new OmtpVvmCarrierConfigHelper(context, phoneAccount); + LoggerUtils.logImpressionOnMainThread(context, DialerImpression.Type.VVM_SYNC_STARTED); // DATA_IMAP_OPERATION_STARTED posting should not be deferred. This event clears all data // channel errors, which should happen when the task starts, not when it ends. It is the // "Sync in progress..." status, which is currently displayed to the user as no error. config.handleEvent( - VoicemailStatus.edit(mContext, phoneAccount), OmtpEvents.DATA_IMAP_OPERATION_STARTED); + VoicemailStatus.edit(context, phoneAccount), OmtpEvents.DATA_IMAP_OPERATION_STARTED); try (NetworkWrapper network = VvmNetworkRequest.getNetwork(config, phoneAccount, status)) { if (network == null) { VvmLog.e(TAG, "unable to acquire network"); @@ -114,7 +114,7 @@ public class OmtpVvmSyncService { PhoneAccountHandle phoneAccount, Voicemail voicemail, VoicemailStatus.Editor status) { - try (ImapHelper imapHelper = new ImapHelper(mContext, phoneAccount, network, status)) { + try (ImapHelper imapHelper = new ImapHelper(context, phoneAccount, network, status)) { boolean success; if (voicemail == null) { success = syncAll(imapHelper, phoneAccount); @@ -126,7 +126,7 @@ public class OmtpVvmSyncService { imapHelper.updateQuota(); autoDeleteAndArchiveVM(imapHelper, phoneAccount); imapHelper.handleEvent(OmtpEvents.DATA_IMAP_OPERATION_COMPLETED); - LoggerUtils.logImpressionOnMainThread(mContext, DialerImpression.Type.VVM_SYNC_COMPLETED); + LoggerUtils.logImpressionOnMainThread(context, DialerImpression.Type.VVM_SYNC_COMPLETED); } else { task.fail(); } @@ -142,16 +142,16 @@ public class OmtpVvmSyncService { */ private void autoDeleteAndArchiveVM( ImapHelper imapHelper, PhoneAccountHandle phoneAccountHandle) { - if (!isArchiveAllowedAndEnabled(mContext, phoneAccountHandle)) { + if (!isArchiveAllowedAndEnabled(context, phoneAccountHandle)) { VvmLog.i(TAG, "autoDeleteAndArchiveVM is turned off"); LoggerUtils.logImpressionOnMainThread( - mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_TURNED_OFF); + context, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_TURNED_OFF); return; } Quota quotaOnServer = imapHelper.getQuota(); if (quotaOnServer == null) { LoggerUtils.logImpressionOnMainThread( - mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_FAILED_DUE_TO_FAILED_QUOTA_CHECK); + context, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETE_FAILED_DUE_TO_FAILED_QUOTA_CHECK); VvmLog.e(TAG, "autoDeleteAndArchiveVM failed - Can't retrieve Imap quota."); return; } @@ -161,7 +161,7 @@ public class OmtpVvmSyncService { deleteAndArchiveVM(imapHelper, quotaOnServer); imapHelper.updateQuota(); LoggerUtils.logImpressionOnMainThread( - mContext, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETED_VM_FROM_SERVER); + context, DialerImpression.Type.VVM_ARCHIVE_AUTO_DELETED_VM_FROM_SERVER); } else { VvmLog.i(TAG, "no need to archive and auto delete VM, quota below threshold"); } @@ -194,10 +194,10 @@ public class OmtpVvmSyncService { // The number of voicemails that exceed our threshold and should be deleted from the server int numVoicemails = quotaOnServer.occupied - (int) (AUTO_DELETE_ARCHIVE_VM_THRESHOLD * quotaOnServer.total); - List oldestVoicemails = mQueryHelper.oldestVoicemailsOnServer(numVoicemails); + List oldestVoicemails = queryHelper.oldestVoicemailsOnServer(numVoicemails); VvmLog.w(TAG, "number of voicemails to delete " + numVoicemails); if (!oldestVoicemails.isEmpty()) { - mQueryHelper.markArchivedInDatabase(oldestVoicemails); + queryHelper.markArchivedInDatabase(oldestVoicemails); imapHelper.markMessagesAsDeleted(oldestVoicemails); VvmLog.i( TAG, @@ -211,8 +211,8 @@ public class OmtpVvmSyncService { private boolean syncAll(ImapHelper imapHelper, PhoneAccountHandle account) { List serverVoicemails = imapHelper.fetchAllVoicemails(); - List localVoicemails = mQueryHelper.getAllVoicemails(account); - List deletedVoicemails = mQueryHelper.getDeletedVoicemails(account); + List localVoicemails = queryHelper.getAllVoicemails(account); + List deletedVoicemails = queryHelper.getDeletedVoicemails(account); boolean succeeded = true; if (localVoicemails == null || serverVoicemails == null) { @@ -225,7 +225,7 @@ public class OmtpVvmSyncService { if (imapHelper.markMessagesAsDeleted(deletedVoicemails)) { // Delete only the voicemails that was deleted on the server, in case more are deleted // since the IMAP query was completed. - mQueryHelper.deleteFromDatabase(deletedVoicemails); + queryHelper.deleteFromDatabase(deletedVoicemails); } else { succeeded = false; } @@ -249,10 +249,10 @@ public class OmtpVvmSyncService { // Do not delete voicemails that are archived marked as archived. if (remoteVoicemail == null) { - mQueryHelper.deleteNonArchivedFromDatabase(localVoicemail); + queryHelper.deleteNonArchivedFromDatabase(localVoicemail); } else { if (remoteVoicemail.isRead() && !localVoicemail.isRead()) { - mQueryHelper.markReadInDatabase(localVoicemail); + queryHelper.markReadInDatabase(localVoicemail); } else if (localVoicemail.isRead() && !remoteVoicemail.isRead()) { localReadVoicemails.add(localVoicemail); } @@ -260,8 +260,8 @@ public class OmtpVvmSyncService { if (!TextUtils.isEmpty(remoteVoicemail.getTranscription()) && TextUtils.isEmpty(localVoicemail.getTranscription())) { LoggerUtils.logImpressionOnMainThread( - mContext, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED); - mQueryHelper.updateWithTranscription(localVoicemail, remoteVoicemail.getTranscription()); + context, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED); + queryHelper.updateWithTranscription(localVoicemail, remoteVoicemail.getTranscription()); } } } @@ -270,7 +270,7 @@ public class OmtpVvmSyncService { VvmLog.i(TAG, "Marking voicemails as read"); if (imapHelper.markMessagesAsRead(localReadVoicemails)) { VvmLog.i(TAG, "Marking voicemails as clean"); - mQueryHelper.markCleanInDatabase(localReadVoicemails); + queryHelper.markCleanInDatabase(localReadVoicemails); } else { return false; } @@ -281,12 +281,12 @@ public class OmtpVvmSyncService { for (Voicemail remoteVoicemail : remoteMap.values()) { if (!TextUtils.isEmpty(remoteVoicemail.getTranscription())) { LoggerUtils.logImpressionOnMainThread( - mContext, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED); + context, DialerImpression.Type.VVM_TRANSCRIPTION_DOWNLOADED); } - Uri uri = VoicemailDatabaseUtil.insert(mContext, remoteVoicemail); + Uri uri = VoicemailDatabaseUtil.insert(context, remoteVoicemail); if (prefetchEnabled) { VoicemailFetchedCallback fetchedCallback = - new VoicemailFetchedCallback(mContext, uri, account); + new VoicemailFetchedCallback(context, uri, account); imapHelper.fetchVoicemailPayload(fetchedCallback, remoteVoicemail.getSourceData()); } } @@ -298,17 +298,17 @@ public class OmtpVvmSyncService { ImapHelper imapHelper, Voicemail voicemail, PhoneAccountHandle account) { if (shouldPerformPrefetch(account, imapHelper)) { VoicemailFetchedCallback callback = - new VoicemailFetchedCallback(mContext, voicemail.getUri(), account); + new VoicemailFetchedCallback(context, voicemail.getUri(), account); imapHelper.fetchVoicemailPayload(callback, voicemail.getSourceData()); } return imapHelper.fetchTranscription( - new TranscriptionFetchedCallback(mContext, voicemail), voicemail.getSourceData()); + new TranscriptionFetchedCallback(context, voicemail), voicemail.getSourceData()); } private boolean shouldPerformPrefetch(PhoneAccountHandle account, ImapHelper imapHelper) { OmtpVvmCarrierConfigHelper carrierConfigHelper = - new OmtpVvmCarrierConfigHelper(mContext, account); + new OmtpVvmCarrierConfigHelper(context, account); return carrierConfigHelper.isPrefetchEnabled() && !imapHelper.isRoaming(); } @@ -324,17 +324,17 @@ public class OmtpVvmSyncService { /** Callback for {@link ImapHelper#fetchTranscription(TranscriptionFetchedCallback, String)} */ public static class TranscriptionFetchedCallback { - private Context mContext; - private Voicemail mVoicemail; + private Context context; + private Voicemail voicemail; public TranscriptionFetchedCallback(Context context, Voicemail voicemail) { - mContext = context; - mVoicemail = voicemail; + this.context = context; + this.voicemail = voicemail; } public void setVoicemailTranscription(String transcription) { - VoicemailsQueryHelper queryHelper = new VoicemailsQueryHelper(mContext); - queryHelper.updateWithTranscription(mVoicemail, transcription); + VoicemailsQueryHelper queryHelper = new VoicemailsQueryHelper(context); + queryHelper.updateWithTranscription(voicemail, transcription); } } } diff --git a/java/com/android/voicemail/impl/sync/SyncOneTask.java b/java/com/android/voicemail/impl/sync/SyncOneTask.java index 70c6bd890..2f0b23f46 100644 --- a/java/com/android/voicemail/impl/sync/SyncOneTask.java +++ b/java/com/android/voicemail/impl/sync/SyncOneTask.java @@ -41,8 +41,8 @@ public class SyncOneTask extends BaseTask { private static final String EXTRA_PHONE_ACCOUNT_HANDLE = "extra_phone_account_handle"; private static final String EXTRA_VOICEMAIL = "extra_voicemail"; - private PhoneAccountHandle mPhone; - private Voicemail mVoicemail; + private PhoneAccountHandle phone; + private Voicemail voicemail; public static void start(Context context, PhoneAccountHandle phone, Voicemail voicemail) { Intent intent = BaseTask.createIntent(context, SyncOneTask.class, phone); @@ -59,22 +59,22 @@ public class SyncOneTask extends BaseTask { @Override public void onCreate(Context context, Bundle extras) { super.onCreate(context, extras); - mPhone = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); - mVoicemail = extras.getParcelable(EXTRA_VOICEMAIL); + phone = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); + voicemail = extras.getParcelable(EXTRA_VOICEMAIL); } @Override public void onExecuteInBackgroundThread() { OmtpVvmSyncService service = new OmtpVvmSyncService(getContext()); - service.sync(this, mPhone, mVoicemail, VoicemailStatus.edit(getContext(), mPhone)); + service.sync(this, phone, voicemail, VoicemailStatus.edit(getContext(), phone)); } @Override public Intent createRestartIntent() { LoggerUtils.logImpressionOnMainThread(getContext(), DialerImpression.Type.VVM_AUTO_RETRY_SYNC); Intent intent = super.createRestartIntent(); - intent.putExtra(EXTRA_PHONE_ACCOUNT_HANDLE, mPhone); - intent.putExtra(EXTRA_VOICEMAIL, mVoicemail); + intent.putExtra(EXTRA_PHONE_ACCOUNT_HANDLE, phone); + intent.putExtra(EXTRA_VOICEMAIL, voicemail); return intent; } } diff --git a/java/com/android/voicemail/impl/sync/SyncTask.java b/java/com/android/voicemail/impl/sync/SyncTask.java index 68ce0122e..06a5e9e81 100644 --- a/java/com/android/voicemail/impl/sync/SyncTask.java +++ b/java/com/android/voicemail/impl/sync/SyncTask.java @@ -38,9 +38,9 @@ public class SyncTask extends BaseTask { private static final String EXTRA_PHONE_ACCOUNT_HANDLE = "extra_phone_account_handle"; - private final RetryPolicy mRetryPolicy; + private final RetryPolicy retryPolicy; - private PhoneAccountHandle mPhone; + private PhoneAccountHandle phone; public static void start(Context context, PhoneAccountHandle phone) { Intent intent = BaseTask.createIntent(context, SyncTask.class, phone); @@ -50,28 +50,28 @@ public class SyncTask extends BaseTask { public SyncTask() { super(TASK_SYNC); - mRetryPolicy = new RetryPolicy(RETRY_TIMES, RETRY_INTERVAL_MILLIS); - addPolicy(mRetryPolicy); + retryPolicy = new RetryPolicy(RETRY_TIMES, RETRY_INTERVAL_MILLIS); + addPolicy(retryPolicy); addPolicy(new MinimalIntervalPolicy(MINIMAL_INTERVAL_MILLIS)); } @Override public void onCreate(Context context, Bundle extras) { super.onCreate(context, extras); - mPhone = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); + phone = extras.getParcelable(EXTRA_PHONE_ACCOUNT_HANDLE); } @Override public void onExecuteInBackgroundThread() { OmtpVvmSyncService service = new OmtpVvmSyncService(getContext()); - service.sync(this, mPhone, null, mRetryPolicy.getVoicemailStatusEditor()); + service.sync(this, phone, null, retryPolicy.getVoicemailStatusEditor()); } @Override public Intent createRestartIntent() { LoggerUtils.logImpressionOnMainThread(getContext(), DialerImpression.Type.VVM_AUTO_RETRY_SYNC); Intent intent = super.createRestartIntent(); - intent.putExtra(EXTRA_PHONE_ACCOUNT_HANDLE, mPhone); + intent.putExtra(EXTRA_PHONE_ACCOUNT_HANDLE, phone); return intent; } } diff --git a/java/com/android/voicemail/impl/sync/VoicemailStatusQueryHelper.java b/java/com/android/voicemail/impl/sync/VoicemailStatusQueryHelper.java index 4ef19daf6..259d79bcc 100644 --- a/java/com/android/voicemail/impl/sync/VoicemailStatusQueryHelper.java +++ b/java/com/android/voicemail/impl/sync/VoicemailStatusQueryHelper.java @@ -39,14 +39,14 @@ public class VoicemailStatusQueryHelper { public static final int NOTIFICATION_CHANNEL_STATE = 2; public static final int SOURCE_PACKAGE = 3; - private Context mContext; - private ContentResolver mContentResolver; - private Uri mSourceUri; + private Context context; + private ContentResolver contentResolver; + private Uri sourceUri; public VoicemailStatusQueryHelper(Context context) { - mContext = context; - mContentResolver = context.getContentResolver(); - mSourceUri = VoicemailContract.Status.buildSourceUri(mContext.getPackageName()); + this.context = context; + contentResolver = context.getContentResolver(); + sourceUri = VoicemailContract.Status.buildSourceUri(this.context.getPackageName()); } /** @@ -97,8 +97,8 @@ public class VoicemailStatusQueryHelper { + "=? AND " + Status.SOURCE_PACKAGE + "=?"; - String[] whereArgs = {phoneAccountComponentName, phoneAccountId, mContext.getPackageName()}; - cursor = mContentResolver.query(mSourceUri, PROJECTION, whereClause, whereArgs, null); + String[] whereArgs = {phoneAccountComponentName, phoneAccountId, context.getPackageName()}; + cursor = contentResolver.query(sourceUri, PROJECTION, whereClause, whereArgs, null); if (cursor != null && cursor.moveToFirst()) { return cursor.getInt(columnIndex) == value; } diff --git a/java/com/android/voicemail/impl/sync/VoicemailsQueryHelper.java b/java/com/android/voicemail/impl/sync/VoicemailsQueryHelper.java index 1af5e688e..c47b40dab 100644 --- a/java/com/android/voicemail/impl/sync/VoicemailsQueryHelper.java +++ b/java/com/android/voicemail/impl/sync/VoicemailsQueryHelper.java @@ -52,14 +52,14 @@ public class VoicemailsQueryHelper { static final String DELETED_SELECTION = Voicemails.DELETED + "=1"; static final String ARCHIVED_SELECTION = Voicemails.ARCHIVED + "=0"; - private Context mContext; - private ContentResolver mContentResolver; - private Uri mSourceUri; + private Context context; + private ContentResolver contentResolver; + private Uri sourceUri; public VoicemailsQueryHelper(Context context) { - mContext = context; - mContentResolver = context.getContentResolver(); - mSourceUri = VoicemailContract.Voicemails.buildSourceUri(mContext.getPackageName()); + this.context = context; + contentResolver = context.getContentResolver(); + sourceUri = VoicemailContract.Voicemails.buildSourceUri(this.context.getPackageName()); } /** @@ -90,7 +90,7 @@ public class VoicemailsQueryHelper { */ private List getLocalVoicemails( @NonNull PhoneAccountHandle unusedPhoneAccountHandle, String selection) { - Cursor cursor = mContentResolver.query(mSourceUri, PROJECTION, selection, null, null); + Cursor cursor = contentResolver.query(sourceUri, PROJECTION, selection, null, null); if (cursor == null) { return null; } @@ -135,12 +135,12 @@ public class VoicemailsQueryHelper { } String selectionStatement = String.format(Voicemails._ID + " IN (%s)", sb.toString()); - return mContentResolver.delete(Voicemails.CONTENT_URI, selectionStatement, null); + return contentResolver.delete(Voicemails.CONTENT_URI, selectionStatement, null); } /** Utility method to delete a single voicemail that is not archived. */ public void deleteNonArchivedFromDatabase(Voicemail voicemail) { - mContentResolver.delete( + contentResolver.delete( Voicemails.CONTENT_URI, Voicemails._ID + "=? AND " + Voicemails.ARCHIVED + "= 0", new String[] {Long.toString(voicemail.getId())}); @@ -156,10 +156,10 @@ public class VoicemailsQueryHelper { /** Utility method to mark single message as read. */ public void markReadInDatabase(Voicemail voicemail) { - Uri uri = ContentUris.withAppendedId(mSourceUri, voicemail.getId()); + Uri uri = ContentUris.withAppendedId(sourceUri, voicemail.getId()); ContentValues contentValues = new ContentValues(); contentValues.put(Voicemails.IS_READ, "1"); - mContentResolver.update(uri, contentValues, null, null); + contentResolver.update(uri, contentValues, null, null); } /** @@ -181,17 +181,17 @@ public class VoicemailsQueryHelper { /** Utility method to mark single message as clean. */ public void markCleanInDatabase(Voicemail voicemail) { - Uri uri = ContentUris.withAppendedId(mSourceUri, voicemail.getId()); + Uri uri = ContentUris.withAppendedId(sourceUri, voicemail.getId()); ContentValues contentValues = new ContentValues(); - mContentResolver.update(uri, contentValues, null, null); + contentResolver.update(uri, contentValues, null, null); } /** Utility method to add a transcription to the voicemail. */ public void updateWithTranscription(Voicemail voicemail, String transcription) { - Uri uri = ContentUris.withAppendedId(mSourceUri, voicemail.getId()); + Uri uri = ContentUris.withAppendedId(sourceUri, voicemail.getId()); ContentValues contentValues = new ContentValues(); contentValues.put(Voicemails.TRANSCRIPTION, transcription); - mContentResolver.update(uri, contentValues, null, null); + contentResolver.update(uri, contentValues, null, null); } /** @@ -221,7 +221,7 @@ public class VoicemailsQueryHelper { + Voicemails.SOURCE_DATA + "=?"; String[] whereArgs = {phoneAccountComponentName, phoneAccountId, sourceData}; - cursor = mContentResolver.query(mSourceUri, PROJECTION, whereClause, whereArgs, null); + cursor = contentResolver.query(sourceUri, PROJECTION, whereClause, whereArgs, null); if (cursor.getCount() == 0) { return true; } else { @@ -249,10 +249,10 @@ public class VoicemailsQueryHelper { /** Utility method to mark single voicemail as archived. */ public void markArchiveInDatabase(Voicemail voicemail) { - Uri uri = ContentUris.withAppendedId(mSourceUri, voicemail.getId()); + Uri uri = ContentUris.withAppendedId(sourceUri, voicemail.getId()); ContentValues contentValues = new ContentValues(); contentValues.put(Voicemails.ARCHIVED, "1"); - mContentResolver.update(uri, contentValues, null, null); + contentResolver.update(uri, contentValues, null, null); } /** Find the oldest voicemails that are on the device, and also on the server. */ @@ -265,7 +265,7 @@ public class VoicemailsQueryHelper { String sortAndLimit = "date ASC limit " + numVoicemails; try (Cursor cursor = - mContentResolver.query(mSourceUri, PROJECTION, ARCHIVED_SELECTION, null, sortAndLimit)) { + contentResolver.query(sourceUri, PROJECTION, ARCHIVED_SELECTION, null, sortAndLimit)) { Assert.isNotNull(cursor); diff --git a/java/com/android/voicemail/impl/sync/VvmNetworkRequest.java b/java/com/android/voicemail/impl/sync/VvmNetworkRequest.java index 189dc8f2b..e7517363c 100644 --- a/java/com/android/voicemail/impl/sync/VvmNetworkRequest.java +++ b/java/com/android/voicemail/impl/sync/VvmNetworkRequest.java @@ -45,21 +45,21 @@ public class VvmNetworkRequest { */ public static class NetworkWrapper implements Closeable { - private final Network mNetwork; - private final VvmNetworkRequestCallback mCallback; + private final Network network; + private final VvmNetworkRequestCallback callback; private NetworkWrapper(Network network, VvmNetworkRequestCallback callback) { - mNetwork = network; - mCallback = callback; + this.network = network; + this.callback = callback; } public Network get() { - return mNetwork; + return network; } @Override public void close() { - mCallback.releaseNetwork(); + callback.releaseNetwork(); } } @@ -92,7 +92,7 @@ public class VvmNetworkRequest { * {@link CompletableFuture#get()} will block until {@link CompletableFuture# complete(Object) } * has been called on the other thread. */ - private final CompletableFuture mFuture = new CompletableFuture<>(); + private final CompletableFuture future = new CompletableFuture<>(); public FutureNetworkRequestCallback( OmtpVvmCarrierConfigHelper config, @@ -102,19 +102,19 @@ public class VvmNetworkRequest { } public Future getFuture() { - return mFuture; + return future; } @Override public void onAvailable(Network network) { super.onAvailable(network); - mFuture.complete(new NetworkWrapper(network, this)); + future.complete(new NetworkWrapper(network, this)); } @Override public void onFailed(String reason) { super.onFailed(reason); - mFuture.complete(null); + future.complete(null); } } } diff --git a/java/com/android/voicemail/impl/sync/VvmNetworkRequestCallback.java b/java/com/android/voicemail/impl/sync/VvmNetworkRequestCallback.java index 17f5c1608..60ba166ba 100644 --- a/java/com/android/voicemail/impl/sync/VvmNetworkRequestCallback.java +++ b/java/com/android/voicemail/impl/sync/VvmNetworkRequestCallback.java @@ -48,37 +48,37 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw public static final String NETWORK_REQUEST_FAILED_TIMEOUT = "timeout"; public static final String NETWORK_REQUEST_FAILED_LOST = "lost"; - protected Context mContext; - protected PhoneAccountHandle mPhoneAccount; - protected NetworkRequest mNetworkRequest; - private ConnectivityManager mConnectivityManager; - private final OmtpVvmCarrierConfigHelper mCarrierConfigHelper; - private final VoicemailStatus.Editor mStatus; - private boolean mRequestSent = false; - private boolean mResultReceived = false; + protected Context context; + protected PhoneAccountHandle phoneAccount; + protected NetworkRequest networkRequest; + private ConnectivityManager connectivityManager; + private final OmtpVvmCarrierConfigHelper carrierConfigHelper; + private final VoicemailStatus.Editor status; + private boolean requestSent = false; + private boolean resultReceived = false; public VvmNetworkRequestCallback( Context context, PhoneAccountHandle phoneAccount, VoicemailStatus.Editor status) { - mContext = context; - mPhoneAccount = phoneAccount; - mStatus = status; - mCarrierConfigHelper = new OmtpVvmCarrierConfigHelper(context, mPhoneAccount); - mNetworkRequest = createNetworkRequest(); + this.context = context; + this.phoneAccount = phoneAccount; + this.status = status; + carrierConfigHelper = new OmtpVvmCarrierConfigHelper(context, this.phoneAccount); + networkRequest = createNetworkRequest(); } public VvmNetworkRequestCallback( OmtpVvmCarrierConfigHelper config, PhoneAccountHandle phoneAccount, VoicemailStatus.Editor status) { - mContext = config.getContext(); - mPhoneAccount = phoneAccount; - mStatus = status; - mCarrierConfigHelper = config; - mNetworkRequest = createNetworkRequest(); + context = config.getContext(); + this.phoneAccount = phoneAccount; + this.status = status; + carrierConfigHelper = config; + networkRequest = createNetworkRequest(); } public VoicemailStatus.Editor getVoicemailStatusEditor() { - return mStatus; + return status; } /** @@ -91,12 +91,10 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw new NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); TelephonyManager telephonyManager = - mContext - .getSystemService(TelephonyManager.class) - .createForPhoneAccountHandle(mPhoneAccount); + context.getSystemService(TelephonyManager.class).createForPhoneAccountHandle(phoneAccount); // At this point mPhoneAccount should always be valid and telephonyManager will never be null Assert.isNotNull(telephonyManager); - if (mCarrierConfigHelper.isCellularDataRequired()) { + if (carrierConfigHelper.isCellularDataRequired()) { VvmLog.d(TAG, "Transport type: CELLULAR"); builder .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) @@ -108,14 +106,14 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw } public NetworkRequest getNetworkRequest() { - return mNetworkRequest; + return networkRequest; } @Override @CallSuper public void onLost(Network network) { VvmLog.d(TAG, "onLost"); - mResultReceived = true; + resultReceived = true; onFailed(NETWORK_REQUEST_FAILED_LOST); } @@ -123,22 +121,22 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw @CallSuper public void onAvailable(Network network) { super.onAvailable(network); - mResultReceived = true; + resultReceived = true; } @CallSuper public void onUnavailable() { // TODO(twyen): a bug this is hidden, do we really need this? - mResultReceived = true; + resultReceived = true; onFailed(NETWORK_REQUEST_FAILED_TIMEOUT); } public void requestNetwork() { - if (mRequestSent == true) { + if (requestSent == true) { VvmLog.e(TAG, "requestNetwork() called twice"); return; } - mRequestSent = true; + requestSent = true; getConnectivityManager().requestNetwork(getNetworkRequest(), this); /** * Somehow requestNetwork() with timeout doesn't work, and it's a hidden method. Implement our @@ -149,7 +147,7 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw new Runnable() { @Override public void run() { - if (mResultReceived == false) { + if (resultReceived == false) { onFailed(NETWORK_REQUEST_FAILED_TIMEOUT); } } @@ -163,20 +161,20 @@ public abstract class VvmNetworkRequestCallback extends ConnectivityManager.Netw } public ConnectivityManager getConnectivityManager() { - if (mConnectivityManager == null) { - mConnectivityManager = - (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); + if (connectivityManager == null) { + connectivityManager = + (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } - return mConnectivityManager; + return connectivityManager; } @CallSuper public void onFailed(String reason) { VvmLog.d(TAG, "onFailed: " + reason); - if (mCarrierConfigHelper.isCellularDataRequired()) { - mCarrierConfigHelper.handleEvent(mStatus, OmtpEvents.DATA_NO_CONNECTION_CELLULAR_REQUIRED); + if (carrierConfigHelper.isCellularDataRequired()) { + carrierConfigHelper.handleEvent(status, OmtpEvents.DATA_NO_CONNECTION_CELLULAR_REQUIRED); } else { - mCarrierConfigHelper.handleEvent(mStatus, OmtpEvents.DATA_NO_CONNECTION); + carrierConfigHelper.handleEvent(status, OmtpEvents.DATA_NO_CONNECTION); } releaseNetwork(); } diff --git a/java/com/android/voicemail/impl/utils/IndentingPrintWriter.java b/java/com/android/voicemail/impl/utils/IndentingPrintWriter.java index bbc1d6601..b72aecebf 100644 --- a/java/com/android/voicemail/impl/utils/IndentingPrintWriter.java +++ b/java/com/android/voicemail/impl/utils/IndentingPrintWriter.java @@ -29,23 +29,23 @@ import java.util.Arrays; */ public class IndentingPrintWriter extends PrintWriter { - private final String mSingleIndent; - private final int mWrapLength; + private final String singleIndent; + private final int wrapLength; /** Mutable version of current indent */ - private StringBuilder mIndentBuilder = new StringBuilder(); - /** Cache of current {@link #mIndentBuilder} value */ - private char[] mCurrentIndent; + private StringBuilder indentBuilder = new StringBuilder(); + /** Cache of current {@link #indentBuilder} value */ + private char[] currentIndent; /** Length of current line being built, excluding any indent */ - private int mCurrentLength; + private int currentLength; /** * Flag indicating if we're currently sitting on an empty line, and that next write should be * prefixed with the current indent. */ - private boolean mEmptyLine = true; + private boolean emptyLine = true; - private char[] mSingleChar = new char[1]; + private char[] singleChar = new char[1]; public IndentingPrintWriter(Writer writer, String singleIndent) { this(writer, singleIndent, -1); @@ -53,18 +53,18 @@ public class IndentingPrintWriter extends PrintWriter { public IndentingPrintWriter(Writer writer, String singleIndent, int wrapLength) { super(writer); - mSingleIndent = singleIndent; - mWrapLength = wrapLength; + this.singleIndent = singleIndent; + this.wrapLength = wrapLength; } public void increaseIndent() { - mIndentBuilder.append(mSingleIndent); - mCurrentIndent = null; + indentBuilder.append(singleIndent); + currentIndent = null; } public void decreaseIndent() { - mIndentBuilder.delete(0, mSingleIndent.length()); - mCurrentIndent = null; + indentBuilder.delete(0, singleIndent.length()); + currentIndent = null; } public void printPair(String key, Object value) { @@ -86,8 +86,8 @@ public class IndentingPrintWriter extends PrintWriter { @Override public void write(int c) { - mSingleChar[0] = (char) c; - write(mSingleChar, 0, 1); + singleChar[0] = (char) c; + write(singleChar, 0, 1); } @Override @@ -99,7 +99,7 @@ public class IndentingPrintWriter extends PrintWriter { @Override public void write(char[] buf, int offset, int count) { - final int indentLength = mIndentBuilder.length(); + final int indentLength = indentBuilder.length(); final int bufferEnd = offset + count; int lineStart = offset; int lineEnd = offset; @@ -107,30 +107,30 @@ public class IndentingPrintWriter extends PrintWriter { // March through incoming buffer looking for newlines while (lineEnd < bufferEnd) { char ch = buf[lineEnd++]; - mCurrentLength++; + currentLength++; if (ch == '\n') { maybeWriteIndent(); super.write(buf, lineStart, lineEnd - lineStart); lineStart = lineEnd; - mEmptyLine = true; - mCurrentLength = 0; + emptyLine = true; + currentLength = 0; } // Wrap if we've pushed beyond line length - if (mWrapLength > 0 && mCurrentLength >= mWrapLength - indentLength) { - if (!mEmptyLine) { + if (wrapLength > 0 && currentLength >= wrapLength - indentLength) { + if (!emptyLine) { // Give ourselves a fresh line to work with super.write('\n'); - mEmptyLine = true; - mCurrentLength = lineEnd - lineStart; + emptyLine = true; + currentLength = lineEnd - lineStart; } else { // We need more than a dedicated line, slice it hard maybeWriteIndent(); super.write(buf, lineStart, lineEnd - lineStart); super.write('\n'); - mEmptyLine = true; + emptyLine = true; lineStart = lineEnd; - mCurrentLength = 0; + currentLength = 0; } } } @@ -142,13 +142,13 @@ public class IndentingPrintWriter extends PrintWriter { } private void maybeWriteIndent() { - if (mEmptyLine) { - mEmptyLine = false; - if (mIndentBuilder.length() != 0) { - if (mCurrentIndent == null) { - mCurrentIndent = mIndentBuilder.toString().toCharArray(); + if (emptyLine) { + emptyLine = false; + if (indentBuilder.length() != 0) { + if (currentIndent == null) { + currentIndent = indentBuilder.toString().toCharArray(); } - super.write(mCurrentIndent, 0, mCurrentIndent.length); + super.write(currentIndent, 0, currentIndent.length); } } } -- cgit v1.2.3