下面列出了android.view.MenuItem.OnMenuItemClickListener#org.chromium.base.metrics.RecordUserAction 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Initializes the class. Note that this will start listening to signin related events and
* update itself if needed.
*/
BookmarkPromoHeader(Context context,
PromoHeaderShowingChangeListener showingChangeListener) {
mContext = context;
mShowingChangeListener = showingChangeListener;
AndroidSyncSettings.registerObserver(mContext, this);
mSignInManager = SigninManager.get(mContext);
mSignInManager.addSignInStateObserver(this);
updateShouldShow(false);
if (shouldShow()) {
int promoShowCount = ContextUtils.getAppSharedPreferences()
.getInt(PREF_SIGNIN_PROMO_SHOW_COUNT, 0) + 1;
ContextUtils.getAppSharedPreferences().edit()
.putInt(PREF_SIGNIN_PROMO_SHOW_COUNT, promoShowCount).apply();
RecordUserAction.record("Signin_Impression_FromBookmarkManager");
}
}
@Override
public void finishNativeInitialization() {
RecordUserAction.record("MobileAddBookmarkViaIntent");
final String title = getIntent().getStringExtra(EXTRA_TITLE);
final String url = getIntent().getStringExtra(EXTRA_URL);
// Partner bookmarks need to be loaded explicitly.
PartnerBookmarksShim.kickOffReading(this);
// Store mModel as a member variable so it can't be garbage collected. Otherwise the
// Runnable might never be run.
mModel = new BookmarkModel();
mModel.runAfterBookmarkModelLoaded(new Runnable() {
@Override
public void run() {
BookmarkId bookmarkId = BookmarkUtils.addBookmarkSilently(
BookmarkAddActivity.this, mModel, title, url);
if (bookmarkId != null) {
BookmarkUtils.startEditActivity(BookmarkAddActivity.this, bookmarkId);
}
finish();
}
});
}
/**
* Shows the app menu if it is not already shown.
* @param view View that initiated showing this menu. Normally it is a menu button.
* @param startDragging Whether dragging is started.
* @return Whether or not if the app menu is successfully shown.
*/
private boolean showAppMenu(View view, boolean startDragging) {
if (!mMenuHandler.isAppMenuShowing()
&& mMenuHandler.showAppMenu(view, startDragging)) {
// Initial start dragging can be canceled in case if it was just single tap.
// So we only record non-dragging here, and will deal with those dragging cases in
// AppMenuDragHelper class.
if (!startDragging) RecordUserAction.record("MobileUsingMenuBySwButtonTap");
if (mOnAppMenuShownListener != null) {
mOnAppMenuShownListener.run();
}
return true;
}
return false;
}
@Override
public void onStartWithNative() {
super.onStartWithNative();
setActiveContentHandler(mCustomTabContentHandler);
if (getSavedInstanceState() != null || !mIsInitialStart) {
RecordUserAction.record("CustomTabs.StartedReopened");
} else {
ExternalAppId externalId =
IntentHandler.determineExternalIntentSource(getPackageName(), getIntent());
RecordHistogram.recordEnumeratedHistogram("CustomTabs.ClientAppId",
externalId.ordinal(), ExternalAppId.INDEX_BOUNDARY.ordinal());
RecordUserAction.record("CustomTabs.StartedInitially");
}
mIsInitialStart = false;
}
@Override
protected boolean handleBackPressed() {
RecordUserAction.record("CustomTabs.SystemBack");
if (getActivityTab() == null) return false;
if (exitFullscreenIfShowing()) return true;
if (!getToolbarManager().back()) {
if (getCurrentTabModel().getCount() > 1) {
getCurrentTabModel().closeTab(getActivityTab(), false, false, false);
} else {
if (mIntentDataProvider.isOpenedByChrome() && isHerbResultNeeded()) {
createHerbResultIntent(RESULT_BACK_PRESSED);
}
finishAndClose();
}
}
return true;
}
/**
* Configures the custom button on toolbar. Does nothing if invalid data is provided by clients.
*/
private void showCustomButtonOnToolbar() {
final CustomButtonParams params = mIntentDataProvider.getCustomButtonOnToolbar();
if (params == null) return;
getToolbarManager().setCustomActionButton(
params.getIcon(getResources()),
params.getDescription(),
new OnClickListener() {
@Override
public void onClick(View v) {
mIntentDataProvider.sendButtonPendingIntentWithUrl(
getApplicationContext(), getActivityTab().getUrl());
RecordUserAction.record("CustomTabsCustomActionButtonClick");
}
});
}
@Override
public void onClick(View v) {
if (v == mDeleteButton) {
if (!TextUtils.isEmpty(mUrlBar.getQueryText())) {
setUrlBarText("", null);
hideSuggestions();
updateButtonVisibility();
}
startZeroSuggest();
return;
} else if (!mUrlHasFocus && shouldShowPageInfoForView(v)) {
Tab currentTab = getCurrentTab();
if (currentTab != null && currentTab.getWebContents() != null) {
Activity activity = currentTab.getWindowAndroid().getActivity().get();
if (activity != null) {
WebsiteSettingsPopup.show(
activity, currentTab, null, WebsiteSettingsPopup.OPENED_FROM_TOOLBAR);
}
}
} else if (v == mMicButton) {
RecordUserAction.record("MobileOmniboxVoiceSearch");
startVoiceRecognition();
}
}
@Override
public final void onBackPressed() {
RecordUserAction.record("SystemBack");
if (mCompositorViewHolder != null) {
LayoutManager layoutManager = mCompositorViewHolder.getLayoutManager();
if (layoutManager != null && layoutManager.onBackPressed()) return;
}
ContentViewCore contentViewCore = getContentViewCore();
if (contentViewCore != null && contentViewCore.isSelectActionBarShowing()) {
contentViewCore.clearSelection();
return;
}
if (mContextualSearchManager != null && mContextualSearchManager.onBackPressed()) return;
if (handleBackPressed()) return;
super.onBackPressed();
}
@Override
View getChildView(int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
if (convertView == null) {
SigninAndSyncView.Listener listener = new SigninAndSyncView.Listener() {
@Override
public void onViewDismissed() {
mRecentTabsManager.setSigninPromoDeclined();
notifyDataSetChanged();
}
};
convertView =
SigninAndSyncView.create(parent, listener, SigninAccessPoint.RECENT_TABS);
}
if (!mRecentTabsManager.isSignedIn()) {
RecordUserAction.record("Signin_Impression_FromRecentTabs");
}
return convertView;
}
/**
* This clears all the storage for websites that are displayed to the user. This happens
* asynchronously, and then we call {@link #getInfoForOrigins()} when we're done.
*/
public void clearStorage() {
if (mWebsites == null) {
return;
}
RecordUserAction.record("MobileSettingsStorageClearAll");
// The goal is to refresh the info for origins again after we've cleared all of them, so we
// wait until the last website is cleared to refresh the origin list.
final int[] numLeft = new int[1];
numLeft[0] = mWebsites.size();
for (int i = 0; i < mWebsites.size(); i++) {
WebsitePreference preference = mWebsites.get(i);
preference.site().clearAllStoredData(new StoredDataClearedCallback() {
@Override
public void onStoredDataCleared() {
if (--numLeft[0] <= 0) {
getInfoForOrigins();
}
}
});
}
}
@Override
public void onClick(View v) {
if (v == mCancelButton) {
getActivity().finish();
} else if (v == mSaveButton) {
TemplateUrlService.getInstance().setSearchEngine(mSelectedIndex);
// If the user has manually set the default search engine, disable auto switching.
boolean manualSwitch = mSelectedIndex != mSearchEngineAdapter
.getInitialSearchEnginePosition();
if (manualSwitch) {
RecordUserAction.record("SearchEngine_ManualChange");
LocaleManager.getInstance().setSearchEngineAutoSwitch(false);
}
getActivity().finish();
}
}
@Override
public void onClick(View v) {
if (mToggleTabStackButton == v) {
// The button is clickable before the native library is loaded
// and the listener is setup.
if (mToggleTabStackButton != null && mToggleTabStackButton.isClickable()
&& mTabSwitcherListener != null) {
dismissTabSwitcherCallout();
cancelAppMenuUpdateBadgeAnimation();
mTabSwitcherListener.onClick(mToggleTabStackButton);
RecordUserAction.record("MobileToolbarShowStackView");
}
} else if (mNewTabButton == v) {
v.setEnabled(false);
if (mNewTabListener != null) {
mNewTabListener.onClick(v);
RecordUserAction.record("MobileToolbarStackViewNewTab");
RecordUserAction.record("MobileNewTabOpened");
// TODO(kkimlabs): Record UMA action for homepage button.
}
} else if (mHomeButton == v) {
openHomepage();
}
}
/**
* When a minidump is detected, upload it to Google crash server
*/
@Override
public void onEvent(int event, String path) {
// This is executed on a thread dedicated to FileObserver.
if (CrashFileManager.isMinidumpMIMEFirstTry(path)) {
Context appContext = ContextUtils.getApplicationContext();
try {
Intent intent =
MinidumpUploadService.createFindAndUploadLastCrashIntent(appContext);
appContext.startService(intent);
Log.i(TAG, "Detects a new minidump %s send intent to MinidumpUploadService", path);
RecordUserAction.record("MobileBreakpadUploadAttempt");
} catch (SecurityException e) {
// For KitKat and below, there was a framework bug which cause us to not be able to
// find our own crash uploading service. Ignore a SecurityException here on older
// OS versions since the crash will eventually get uploaded on next start.
// crbug/542533
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
throw e;
}
}
}
}
private void setUpMoreButtonVisible(boolean enabled) {
if (enabled) {
mPositiveButton.setVisibility(View.GONE);
mMoreButton.setVisibility(View.VISIBLE);
mMoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mSigninConfirmationView.smoothScrollBy(0, mSigninConfirmationView.getHeight());
RecordUserAction.record("Signin_MoreButton_Shown");
}
});
} else {
mPositiveButton.setVisibility(View.VISIBLE);
mMoreButton.setVisibility(View.GONE);
}
}
/**
* Initializes the class. Note that this will start listening to signin related events and
* update itself if needed.
*/
BookmarkPromoHeader(Context context,
PromoHeaderShowingChangeListener showingChangeListener) {
mContext = context;
mShowingChangeListener = showingChangeListener;
AndroidSyncSettings.registerObserver(mContext, this);
mSignInManager = SigninManager.get(mContext);
mSignInManager.addSignInStateObserver(this);
updateShouldShow(false);
if (shouldShow()) {
int promoShowCount = ContextUtils.getAppSharedPreferences()
.getInt(PREF_SIGNIN_PROMO_SHOW_COUNT, 0) + 1;
ContextUtils.getAppSharedPreferences().edit()
.putInt(PREF_SIGNIN_PROMO_SHOW_COUNT, promoShowCount).apply();
RecordUserAction.record("Signin_Impression_FromBookmarkManager");
}
}
@Override
public void finishNativeInitialization() {
RecordUserAction.record("MobileAddBookmarkViaIntent");
final String title = getIntent().getStringExtra(EXTRA_TITLE);
final String url = getIntent().getStringExtra(EXTRA_URL);
// Partner bookmarks need to be loaded explicitly.
PartnerBookmarksShim.kickOffReading(this);
// Store mModel as a member variable so it can't be garbage collected. Otherwise the
// Runnable might never be run.
mModel = new BookmarkModel();
mModel.runAfterBookmarkModelLoaded(new Runnable() {
@Override
public void run() {
BookmarkId bookmarkId = BookmarkUtils.addBookmarkSilently(
BookmarkAddActivity.this, mModel, title, url);
if (bookmarkId != null) {
BookmarkUtils.startEditActivity(BookmarkAddActivity.this, bookmarkId);
}
finish();
}
});
}
/**
* Shows the app menu if it is not already shown.
* @param view View that initiated showing this menu. Normally it is a menu button.
* @param startDragging Whether dragging is started.
* @return Whether or not if the app menu is successfully shown.
*/
private boolean showAppMenu(View view, boolean startDragging) {
if (!mMenuHandler.isAppMenuShowing()
&& mMenuHandler.showAppMenu(view, startDragging)) {
// Initial start dragging can be canceled in case if it was just single tap.
// So we only record non-dragging here, and will deal with those dragging cases in
// AppMenuDragHelper class.
if (!startDragging) RecordUserAction.record("MobileUsingMenuBySwButtonTap");
if (mOnAppMenuShownListener != null) {
mOnAppMenuShownListener.run();
}
return true;
}
return false;
}
@Override
public void onSelectionStateChange(List<DownloadHistoryItemWrapper> selectedItems) {
boolean wasSelectionEnabled = mIsSelectionEnabled;
super.onSelectionStateChange(selectedItems);
if (!mIsSelectionEnabled) {
updateTitle();
} else {
int numSelected = mSelectionDelegate.getSelectedItems().size();
findViewById(R.id.selection_mode_share_menu_id).setContentDescription(
getResources().getQuantityString(R.plurals.accessibility_share_selected_items,
numSelected, numSelected));
findViewById(R.id.selection_mode_delete_menu_id).setContentDescription(
getResources().getQuantityString(R.plurals.accessibility_remove_selected_items,
numSelected, numSelected));
if (!wasSelectionEnabled) {
RecordUserAction.record("Android.DownloadManager.SelectionEstablished");
}
}
}
/**
* Checks if a wrapper corresponds to an item that was already deleted.
* @return True if it does, false otherwise.
*/
private boolean updateDeletedFileMap(DownloadHistoryItemWrapper wrapper) {
// TODO(twellington): The native downloads service should remove externally deleted
// downloads rather than passing them to Java.
if (sDeletedFileTracker.contains(wrapper)) return true;
if (wrapper.hasBeenExternallyRemoved()) {
sDeletedFileTracker.add(wrapper);
wrapper.remove();
mFilePathsToItemsMap.removeItem(wrapper);
RecordUserAction.record("Android.DownloadManager.Item.ExternallyDeleted");
return true;
}
return false;
}
private void showConfirmSigninPage() {
mSignedIn = true;
updateSignedInAccountInfo();
mSigninChooseView.setVisibility(View.GONE);
mSigninConfirmationView.setVisibility(View.VISIBLE);
setButtonsEnabled(true);
setUpConfirmButton();
setUpUndoButton();
NoUnderlineClickableSpan settingsSpan = new NoUnderlineClickableSpan() {
@Override
public void onClick(View widget) {
mListener.onAccountSelected(getSelectedAccountName(), true);
RecordUserAction.record("Signin_Signin_WithAdvancedSyncSettings");
}
};
mSigninSettingsControl.setText(
SpanApplier.applySpans(getSettingsControlDescription(mIsChildAccount),
new SpanInfo(SETTINGS_LINK_OPEN, SETTINGS_LINK_CLOSE, settingsSpan)));
}
private void search() {
RecordUserAction.record("MobileActionMode.WebSearch");
if (mTab.getTabModelSelector() == null) return;
String query = mHelper.sanitizeQuery(mHelper.getSelectedText(),
ActionModeCallbackHelper.MAX_SEARCH_QUERY_LENGTH);
if (TextUtils.isEmpty(query)) return;
String url = TemplateUrlService.getInstance().getUrlForSearchQuery(query);
String headers = GeolocationHeader.getGeoHeader(mContext.getApplicationContext(),
url, mTab.isIncognito());
LoadUrlParams loadUrlParams = new LoadUrlParams(url);
loadUrlParams.setVerbatimHeaders(headers);
loadUrlParams.setTransitionType(PageTransition.GENERATED);
mTab.getTabModelSelector().openNewTab(loadUrlParams,
TabLaunchType.FROM_LONGPRESS_FOREGROUND, mTab, mTab.isIncognito());
}
@Override
protected boolean handleBackPressed() {
RecordUserAction.record("CustomTabs.SystemBack");
if (getActivityTab() == null) return false;
if (exitFullscreenIfShowing()) return true;
if (!getToolbarManager().back()) {
if (getCurrentTabModel().getCount() > 1) {
getCurrentTabModel().closeTab(getActivityTab(), false, false, false);
} else {
finishAndClose(false);
}
}
return true;
}
private void recordExternalNavigationDispatched(Intent intent) {
ArrayList<String> specializedHandlers = intent.getStringArrayListExtra(
IntentHandler.EXTRA_EXTERNAL_NAV_PACKAGES);
if (specializedHandlers != null && specializedHandlers.size() > 0) {
RecordUserAction.record("MobileExternalNavigationDispatched");
}
}
@Override
public void swipeFinished(long time) {
if (mFromTab == null || mTabModelSelector == null) return;
// Figures out the tab to snap to and how to animate to it.
float commitDistance = Math.min(mCommitDistanceFromEdge, getWidth() / 3);
float offsetTo = 0;
mToTab = mFromTab;
if (mOffsetTarget > commitDistance && mLeftTab != null) {
mToTab = mLeftTab;
offsetTo += getWidth();
} else if (mOffsetTarget < -commitDistance && mRightTab != null) {
mToTab = mRightTab;
offsetTo -= getWidth();
}
if (mToTab != mFromTab) {
RecordUserAction.record("MobileSideSwipeFinished");
}
startHiding(mToTab.getId(), false);
// Animate gracefully the end of the swiping effect.
forceAnimationToFinish();
float start = mOffsetTarget;
float end = offsetTo;
long duration = (long) (ANIMATION_SPEED_SCREEN * Math.abs(start - end) / getWidth());
if (duration > 0) {
addToAnimation(this, Property.OFFSET, start, end, duration, 0);
}
requestRender();
}
/**
* Called on touch click event.
*
* @param time The current time of the app in ms.
* @param x The x coordinate in pixel inside the stack view.
* @param y The y coordinate in pixel inside the stack view.
*/
public void click(long time, float x, float y) {
if (mOverviewAnimationType != OverviewAnimationType.NONE
&& mOverviewAnimationType != OverviewAnimationType.DISCARD
&& mOverviewAnimationType != OverviewAnimationType.UNDISCARD
&& mOverviewAnimationType != OverviewAnimationType.DISCARD_ALL) {
return;
}
int clicked = getTabIndexAtPositon(x, y, LayoutTab.getTouchSlop());
if (clicked >= 0) {
// Check if the click was within the boundaries of the close button defined by its
// visible coordinates.
boolean isRtl =
!((mCurrentMode == Orientation.PORTRAIT) ^ LocalizationUtils.isLayoutRtl());
if (mStackTabs[clicked].getLayoutTab().checkCloseHitTest(x, y, isRtl)) {
// Tell the model to close the tab because the close button was pressed. The model
// will then trigger a notification which will start the actual close process here
// if necessary.
StackTab tab = mStackTabs[clicked];
final float halfCloseBtnWidth = LayoutTab.CLOSE_BUTTON_WIDTH_DP / 2.f;
final float halfCloseBtnHeight = mBorderTopPadding / 2.f;
final float contentWidth = tab.getLayoutTab().getOriginalContentWidth();
tab.setDiscardOriginY(halfCloseBtnHeight);
tab.setDiscardOriginX(isRtl ? halfCloseBtnWidth : contentWidth - halfCloseBtnWidth);
tab.setDiscardFromClick(true);
mLayout.uiRequestingCloseTab(time, tab.getId());
RecordUserAction.record("MobileStackViewCloseTab");
RecordUserAction.record("MobileTabClosed");
} else {
// Let the model know that a new {@link LayoutTab} was selected. The model will
// notify us if we need to do anything visual. setIndex() will possibly switch the
// models and broadcast the event.
mLayout.uiSelectingTab(time, mStackTabs[clicked].getId());
}
}
}
/**
* Records user actions associated with entering and exiting Android N multi-window mode
* @param isInMultiWindowMode True if the activity is in multi-window mode.
*/
protected void recordMultiWindowModeChangedUserAction(boolean isInMultiWindowMode) {
if (isInMultiWindowMode) {
RecordUserAction.record("Android.MultiWindowMode.Enter");
} else {
RecordUserAction.record("Android.MultiWindowMode.Exit");
}
}
/**
* A static method for native code to call to open the distiller UI settings.
* @param webContents The WebContents containing the distilled content.
*/
@CalledByNative
public static void openSettings(WebContents webContents) {
Activity activity = getActivityFromWebContents(webContents);
if (webContents != null && activity != null) {
RecordUserAction.record("DomDistiller_DistilledPagePrefsOpened");
AlertDialog.Builder builder =
new AlertDialog.Builder(activity, R.style.AlertDialogTheme);
builder.setView(DistilledPagePrefsView.create(activity));
builder.show();
}
}
@UiThread
@SuppressFBWarnings("DM_EXIT")
@Override
public void onCreate() {
// Required to be applied here redundantly to prevent crashes in the cases where the
// package data is deleted or the Chrome application forced to stop.
try {
ChromeBrowserInitializer.getInstance(mContext).handleSynchronousStartup();
} catch (ProcessInitException e) {
Log.e(TAG, "Failed to start browser process.", e);
// Since the library failed to initialize nothing in the application
// can work, so kill the whole application not just the activity
System.exit(-1);
}
if (isWidgetNewlyCreated()) {
RecordUserAction.record("BookmarkNavigatorWidgetAdded");
}
// Partner bookmarks need to be loaded explicitly.
PartnerBookmarksShim.kickOffReading(mContext);
mBookmarkModel = new BookmarkModel();
mBookmarkModel.addObserver(new BookmarkModelObserver() {
@Override
public void bookmarkModelLoaded() {
// Do nothing. No need to refresh.
}
@Override
public void bookmarkModelChanged() {
refreshWidget();
}
});
}
/**
* Trigger an error about NFC if we don't want to send anything. Also
* records a UMA stat. On ICS we only show the error if they attempt to
* beam, since the recipient will receive the market link. On JB we'll
* always show the error, since the beam animation won't trigger, which
* could be confusing to the user.
*
* @param errorStringId The resid of the string to display as error.
*/
private void onInvalidBeam(final int errorStringId) {
RecordUserAction.record("MobileBeamInvalidAppState");
Runnable errorRunnable = new Runnable() {
@Override
public void run() {
Toast.makeText(mActivity, errorStringId, Toast.LENGTH_SHORT).show();
}
};
if (NFC_BUGS_ACTIVE) {
mErrorRunnableIfBeamSent = errorRunnable;
} else {
ThreadUtils.runOnUiThread(errorRunnable);
}
}
private void uploadActions(String key) {
int count = mPrefs.getInt(key, 0);
removePref(key);
for (int i = 0; i < count; i++) {
RecordUserAction.record(key);
}
}