Java Code Examples for org.chromium.chrome.browser.profiles.Profile#getLastUsedProfile()

The following examples show how to use org.chromium.chrome.browser.profiles.Profile#getLastUsedProfile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 6 votes vote down vote up
private boolean preconnectUrls(List<Bundle> likelyBundles) {
    boolean atLeastOneUrl = false;
    if (likelyBundles == null) return false;
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    for (Bundle bundle : likelyBundles) {
        Uri uri;
        try {
            uri = IntentUtils.safeGetParcelable(bundle, CustomTabsService.KEY_URL);
        } catch (ClassCastException e) {
            continue;
        }
        String url = checkAndConvertUri(uri);
        if (url != null) {
            warmupManager.maybePreconnectUrlAndSubResources(profile, url);
            atLeastOneUrl = true;
        }
    }
    return atLeastOneUrl;
}
 
Example 2
Source File: NewTabPage.java    From delion with Apache License 2.0 6 votes vote down vote up
public static void launchInterestsDialog(Activity activity, final Tab tab) {
    InterestsPage page =
            new InterestsPage(activity, tab, Profile.getLastUsedProfile());
    final Dialog dialog = new NativePageDialog(activity, page);

    InterestsClickListener listener = new InterestsClickListener() {
        @Override
        public void onInterestClicked(String name) {
            tab.loadUrl(new LoadUrlParams(
                    TemplateUrlService.getInstance().getUrlForSearchQuery(name)));
            dialog.dismiss();
        }
    };

    page.setListener(listener);
    dialog.show();
}
 
Example 3
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Cancels the speculation for a given session, or any session if null. */
void cancelSpeculation(CustomTabsSessionToken session) {
    ThreadUtils.assertOnUiThread();
    if (mSpeculation == null) return;
    if (session == null || session.equals(mSpeculation.session)) {
        switch (mSpeculation.speculationMode) {
            case SpeculationParams.PRERENDER:
                if (mSpeculation.webContents == null) return;
                mExternalPrerenderHandler.cancelCurrentPrerender();
                mSpeculation.webContents.destroy();
                break;
            case SpeculationParams.PREFETCH:
                Profile profile = Profile.getLastUsedProfile();
                new LoadingPredictor(profile).cancelPageLoadHint(mSpeculation.url);
                break;
            default:
                return;
        }
        mSpeculation = null;
    }
}
 
Example 4
Source File: AccountManagementFragment.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    // Prevent sync from starting if it hasn't already to give the user a chance to change
    // their sync settings.
    ProfileSyncService syncService = ProfileSyncService.get();
    if (syncService != null) {
        syncService.setSetupInProgress(true);
    }

    mGaiaServiceType = AccountManagementScreenHelper.GAIA_SERVICE_TYPE_NONE;
    if (getArguments() != null) {
        mGaiaServiceType =
                getArguments().getInt(SHOW_GAIA_SERVICE_TYPE_EXTRA, mGaiaServiceType);
    }

    mProfile = Profile.getLastUsedProfile();

    AccountManagementScreenHelper.logEvent(
            ProfileAccountManagementMetrics.VIEW,
            mGaiaServiceType);

    startFetchingAccountsInformation(getActivity(), mProfile);
}
 
Example 5
Source File: SignInPreference.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private void setupSignedIn(String accountName) {
    String title = AccountManagementFragment.getCachedUserName(accountName);
    if (title == null) {
        Profile profile = Profile.getLastUsedProfile();
        String cachedName = ProfileDownloader.getCachedFullName(profile);
        Bitmap cachedBitmap = ProfileDownloader.getCachedAvatar(profile);
        if (TextUtils.isEmpty(cachedName) || cachedBitmap == null) {
            AccountManagementFragment.startFetchingAccountInformation(
                    getContext(), profile, accountName);
        }
        title = TextUtils.isEmpty(cachedName) ? accountName : cachedName;
    }
    setTitle(title);
    setSummary(SyncPreference.getSyncStatusSummary(getContext()));
    setFragment(AccountManagementFragment.class.getName());

    Resources resources = getContext().getResources();
    Bitmap bitmap = AccountManagementFragment.getUserPicture(accountName, resources);
    setIcon(new BitmapDrawable(resources, bitmap));

    setWidgetLayoutResource(
            SyncPreference.showSyncErrorIcon(getContext()) ? R.layout.sync_error_widget : 0);

    setViewEnabled(true);
}
 
Example 6
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
private boolean preconnectUrls(List<Bundle> likelyBundles) {
    boolean atLeastOneUrl = false;
    if (likelyBundles == null) return false;
    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();
    for (Bundle bundle : likelyBundles) {
        Uri uri;
        try {
            uri = IntentUtils.safeGetParcelable(bundle, CustomTabsService.KEY_URL);
        } catch (ClassCastException e) {
            continue;
        }
        String url = checkAndConvertUri(uri);
        if (url != null) {
            warmupManager.maybePreconnectUrlAndSubResources(profile, url);
            atLeastOneUrl = true;
        }
    }
    return atLeastOneUrl;
}
 
Example 7
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Transfers a prerendered WebContents if one exists.
 *
 * This resets the internal WebContents; a subsequent call to this method
 * returns null. Must be called from the UI thread.
 * If a prerender exists for a different URL with the same sessionId or with
 * a different referrer, then this is treated as a mispredict from the
 * client application, and cancels the previous prerender. This is done to
 * avoid keeping resources laying around for too long, but is subject to a
 * race condition, as the following scenario is possible:
 * The application calls:
 * 1. mayLaunchUrl(url1) <- IPC
 * 2. loadUrl(url2) <- Intent
 * 3. mayLaunchUrl(url3) <- IPC
 * If the IPC for url3 arrives before the intent for url2, then this methods
 * cancels the prerender for url3, which is unexpected. On the other
 * hand, not cancelling the previous prerender leads to wasted resources, as
 * a WebContents is lingering. This can be solved by requiring applications
 * to call mayLaunchUrl(null) to cancel a current prerender before 2, that
 * is for a mispredict.
 *
 * Note that this methods accepts URLs that don't exactly match the initially
 * prerendered URL. More precisely, the #fragment is ignored. In this case,
 * the client needs to navigate to the correct URL after the WebContents
 * swap. This can be tested using {@link UrlUtilities#urlsFragmentsDiffer()}.
 *
 * @param session The Binder object identifying a session.
 * @param url The URL the WebContents is for.
 * @param referrer The referrer to use for |url|.
 * @return The prerendered WebContents, or null.
 */
WebContents takePrerenderedUrl(CustomTabsSessionToken session, String url, String referrer) {
    ThreadUtils.assertOnUiThread();
    if (mSpeculation == null || session == null || !session.equals(mSpeculation.session)) {
        return null;
    }

    if (mSpeculation.prefetchOnly) {
        Profile profile = Profile.getLastUsedProfile();
        new ResourcePrefetchPredictor(profile).stopPrefetching(mSpeculation.url);
        mSpeculation = null;
        return null;
    }

    WebContents webContents = mSpeculation.webContents;
    String prerenderedUrl = mSpeculation.url;
    String prerenderReferrer = mSpeculation.referrer;
    if (referrer == null) referrer = "";
    boolean ignoreFragments = mClientManager.getIgnoreFragmentsForSession(session);
    boolean urlsMatch = TextUtils.equals(prerenderedUrl, url)
            || (ignoreFragments
                    && UrlUtilities.urlsMatchIgnoringFragments(prerenderedUrl, url));
    WebContents result = null;
    if (urlsMatch && TextUtils.equals(prerenderReferrer, referrer)) {
        result = webContents;
        mSpeculation = null;
    } else {
        cancelPrerender(session);
    }
    if (!mClientManager.usesDefaultSessionParameters(session) && webContents != null) {
        RecordHistogram.recordBooleanHistogram(
                "CustomTabs.NonDefaultSessionPrerenderMatched", result != null);
    }

    return result;
}
 
Example 8
Source File: OfflineContentAggregatorNotificationBridgeUiFactory.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @return An {@link OfflineContentAggregatorNotificationBridgeUi} instance singleton.  If one
 *         is not available this will create a new one.
 */
public static OfflineContentAggregatorNotificationBridgeUi instance() {
    ThreadUtils.assertOnUiThread();
    if (sBridgeUi == null) {
        Profile profile = Profile.getLastUsedProfile();
        OfflineContentProvider provider = OfflineContentAggregatorFactory.forProfile(profile);
        DownloadNotifier ui =
                DownloadManagerService.getDownloadManagerService().getDownloadNotifier();

        sBridgeUi = new OfflineContentAggregatorNotificationBridgeUi(provider, ui);
    }

    return sBridgeUi;
}
 
Example 9
Source File: OfflinePageDownloadBridge.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Waits for the download items to get loaded and opens the offline page identified by the GUID.
 * @param id The {@link ContentId} of the page to open.
 */
public static void openDownloadedPage(final ContentId id) {
    final OfflinePageDownloadBridge bridge =
            new OfflinePageDownloadBridge(Profile.getLastUsedProfile());
    bridge.addObserver(
            new Observer() {
                @Override
                public void onItemsLoaded() {
                    bridge.openItem(id.id, getComponentName());
                    bridge.destroyServiceDelegate();
                }
            });
}
 
Example 10
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * High confidence mayLaunchUrl() call, that is:
 * - Tries to prerender if possible.
 * - An empty URL cancels the current prerender if any.
 * - If prerendering is not possible, makes sure that there is a spare renderer.
 */
private void highConfidenceMayLaunchUrl(CustomTabsSessionToken session,
        int uid, String url, Bundle extras, List<Bundle> otherLikelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (TextUtils.isEmpty(url)) {
        cancelPrerender(session);
        return;
    }

    WarmupManager warmupManager = WarmupManager.getInstance();
    Profile profile = Profile.getLastUsedProfile();

    url = DataReductionProxySettings.getInstance().maybeRewriteWebliteUrl(url);
    int debugOverrideValue = NO_OVERRIDE;
    if (extras != null) debugOverrideValue = extras.getInt(DEBUG_OVERRIDE_KEY, NO_OVERRIDE);

    boolean didStartPrerender = false, didStartPrefetch = false;
    boolean mayPrerender = mayPrerender(session);
    if (mayPrerender) {
        if (debugOverrideValue == PREFETCH_ONLY) {
            didStartPrefetch = new ResourcePrefetchPredictor(profile).startPrefetching(url);
            if (didStartPrefetch) mSpeculation = SpeculationParams.forPrefetch(session, url);
        } else if (debugOverrideValue != NO_PRERENDERING) {
            didStartPrerender = prerenderUrl(session, url, extras, uid);
        }
    }
    preconnectUrls(otherLikelyBundles);
    if (!didStartPrefetch) warmupManager.maybePreconnectUrlAndSubResources(profile, url);
    if (!didStartPrerender) warmupManager.createSpareWebContents();
}
 
Example 11
Source File: OfflinePageDownloadBridge.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Waits for the download items to get loaded and opens the offline page identified by the GUID.
 * @param GUID of the item to open.
 */
public static void openDownloadedPage(final String guid) {
    final OfflinePageDownloadBridge bridge =
            new OfflinePageDownloadBridge(Profile.getLastUsedProfile());
    bridge.addObserver(
            new Observer() {
                @Override
                public void onItemsLoaded() {
                    bridge.openItem(guid, null);
                    bridge.destroyServiceDelegate();
                }
            });
}
 
Example 12
Source File: BluetoothChooserDialog.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Show the BluetoothChooserDialog.
 */
@VisibleForTesting
void show() {
    // Emphasize the origin.
    Profile profile = Profile.getLastUsedProfile();
    SpannableString origin = new SpannableString(mOrigin);
    OmniboxUrlEmphasizer.emphasizeUrl(
            origin, mActivity.getResources(), profile, mSecurityLevel, false, true, true);
    // Construct a full string and replace the origin text with emphasized version.
    SpannableString title =
            new SpannableString(mActivity.getString(R.string.bluetooth_dialog_title, mOrigin));
    int start = title.toString().indexOf(mOrigin);
    TextUtils.copySpansFrom(origin, 0, origin.length(), Object.class, title, start);

    String message = mActivity.getString(R.string.bluetooth_not_found);
    SpannableString noneFound = SpanApplier.applySpans(
            message, new SpanInfo("<link>", "</link>",
                             new BluetoothClickableSpan(LinkType.RESTART_SEARCH, mActivity)));

    SpannableString searching = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_searching),
            new SpanInfo("<link>", "</link>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)));

    String positiveButton = mActivity.getString(R.string.bluetooth_confirm_button);

    SpannableString statusIdleNoneFound = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_not_seeing_it_idle_none_found),
            new SpanInfo("<link>", "</link>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)));

    SpannableString statusIdleSomeFound = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_not_seeing_it_idle_some_found),
            new SpanInfo("<link1>", "</link1>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)),
            new SpanInfo("<link2>", "</link2>",
                    new BluetoothClickableSpan(LinkType.RESTART_SEARCH, mActivity)));

    ItemChooserDialog.ItemChooserLabels labels =
            new ItemChooserDialog.ItemChooserLabels(title, searching, noneFound,
                    statusIdleNoneFound, statusIdleSomeFound, positiveButton);
    mItemChooserDialog = new ItemChooserDialog(mActivity, this, labels);

    mActivity.registerReceiver(mLocationModeBroadcastReceiver,
            new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
}
 
Example 13
Source File: SuggestionsBottomSheetContent.java    From 365browser with Apache License 2.0 4 votes vote down vote up
public SuggestionsBottomSheetContent(final ChromeActivity activity, final BottomSheet sheet,
        TabModelSelector tabModelSelector, SnackbarManager snackbarManager) {
    Profile profile = Profile.getLastUsedProfile();
    SuggestionsNavigationDelegate navigationDelegate =
            new SuggestionsNavigationDelegateImpl(activity, profile, sheet, tabModelSelector);
    mTileGroupDelegate = new TileGroupDelegateImpl(
            activity, profile, tabModelSelector, navigationDelegate, snackbarManager);
    mSuggestionsUiDelegate = createSuggestionsDelegate(
            profile, navigationDelegate, sheet, activity.getReferencePool());

    mView = LayoutInflater.from(activity).inflate(
            R.layout.suggestions_bottom_sheet_content, null);
    mRecyclerView = (SuggestionsRecyclerView) mView.findViewById(R.id.recycler_view);

    TouchEnabledDelegate touchEnabledDelegate = new TouchEnabledDelegate() {
        @Override
        public void setTouchEnabled(boolean enabled) {
            activity.getBottomSheet().setTouchEnabled(enabled);
        }
    };
    mContextMenuManager =
            new ContextMenuManager(activity, navigationDelegate, touchEnabledDelegate);
    activity.getWindowAndroid().addContextMenuCloseListener(mContextMenuManager);
    mSuggestionsUiDelegate.addDestructionObserver(new DestructionObserver() {
        @Override
        public void onDestroy() {
            activity.getWindowAndroid().removeContextMenuCloseListener(mContextMenuManager);
        }
    });

    UiConfig uiConfig = new UiConfig(mRecyclerView);

    final NewTabPageAdapter adapter = new NewTabPageAdapter(mSuggestionsUiDelegate,
            /* aboveTheFoldView = */ null, uiConfig, OfflinePageBridge.getForProfile(profile),
            mContextMenuManager, mTileGroupDelegate);
    mRecyclerView.init(uiConfig, mContextMenuManager, adapter);

    mBottomSheetObserver = new SuggestionsSheetVisibilityChangeObserver(this, activity) {
        @Override
        public void onSheetOpened() {
            mRecyclerView.scrollToPosition(0);
            adapter.refreshSuggestions();
            mSuggestionsUiDelegate.getEventReporter().onSurfaceOpened();
            mRecyclerView.getScrollEventReporter().reset();

            if (ChromeFeatureList.isEnabled(
                        ChromeFeatureList.CONTEXTUAL_SUGGESTIONS_CAROUSEL)
                    && sheet.getActiveTab() != null) {
                updateContextualSuggestions(sheet.getActiveTab().getUrl());
            }

            super.onSheetOpened();
        }

        @Override
        public void onContentShown() {
            SuggestionsMetrics.recordSurfaceVisible();
        }

        @Override
        public void onContentHidden() {
            SuggestionsMetrics.recordSurfaceHidden();
        }

        @Override
        public void onContentStateChanged(@BottomSheet.SheetState int contentState) {
            if (contentState == BottomSheet.SHEET_STATE_HALF) {
                SuggestionsMetrics.recordSurfaceHalfVisible();
            } else if (contentState == BottomSheet.SHEET_STATE_FULL) {
                SuggestionsMetrics.recordSurfaceFullyVisible();
            }
        }
    };

    mShadowView = (FadingShadowView) mView.findViewById(R.id.shadow);
    mShadowView.init(
            ApiCompatibilityUtils.getColor(mView.getResources(), R.color.toolbar_shadow_color),
            FadingShadow.POSITION_TOP);

    mRecyclerView.addOnScrollListener(new OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            boolean shadowVisible = mRecyclerView.canScrollVertically(-1);
            mShadowView.setVisibility(shadowVisible ? View.VISIBLE : View.GONE);
        }
    });

    final LocationBar locationBar = (LocationBar) sheet.findViewById(R.id.location_bar);
    mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        @SuppressLint("ClickableViewAccessibility")
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (locationBar != null && locationBar.isUrlBarFocused()) {
                locationBar.setUrlBarFocus(false);
            }

            // Never intercept the touch event.
            return false;
        }
    });
}
 
Example 14
Source File: Tab.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes {@link Tab} with {@code webContents}.  If {@code webContents} is {@code null} a
 * new {@link WebContents} will be created for this {@link Tab}.
 * @param webContents       A {@link WebContents} object or {@code null} if one should be
 *                          created.
 * @param tabContentManager A {@link TabContentManager} instance or {@code null} if the web
 *                          content will be managed/displayed manually.
 * @param delegateFactory   The {@link TabDelegateFactory} to be used for delegate creation.
 * @param initiallyHidden   Only used if {@code webContents} is {@code null}.  Determines
 *                          whether or not the newly created {@link WebContents} will be hidden
 *                          or not.
 * @param unfreeze          Whether there should be an attempt to restore state at the end of
 *                          the initialization.
 */
public final void initialize(WebContents webContents, TabContentManager tabContentManager,
        TabDelegateFactory delegateFactory, boolean initiallyHidden, boolean unfreeze) {
    try {
        TraceEvent.begin("Tab.initialize");

        mDelegateFactory = delegateFactory;
        initializeNative();

        RevenueStats.getInstance().tabCreated(this);

        mBrowserControlsVisibilityDelegate =
                mDelegateFactory.createBrowserControlsVisibilityDelegate(this);

        mBlimp = BlimpClientContextFactory
                         .getBlimpClientContextForProfile(
                                 Profile.getLastUsedProfile().getOriginalProfile())
                         .isBlimpEnabled()
                && !mIncognito;

        // Attach the TabContentManager if we have one.  This will bind this Tab's content layer
        // to this manager.
        // TODO(dtrainor): Remove this and move to a pull model instead of pushing the layer.
        attachTabContentManager(tabContentManager);

        // If there is a frozen WebContents state or a pending lazy load, don't create a new
        // WebContents.
        if (getFrozenContentsState() != null || getPendingLoadParams() != null) {
            if (unfreeze) unfreezeContents();
            return;
        }

        if (isBlimpTab() && getBlimpContents() == null) {
            Profile profile = Profile.getLastUsedProfile();
            if (mIncognito) profile = profile.getOffTheRecordProfile();
            mBlimpContents = nativeInitBlimpContents(
                    mNativeTabAndroid, profile, mWindowAndroid.getNativePointer());
            if (mBlimpContents != null) {
                mBlimpContentsObserver = new TabBlimpContentsObserver(this);
                mBlimpContents.addObserver(mBlimpContentsObserver);
            } else {
                mBlimp = false;
            }
        }

        boolean creatingWebContents = webContents == null;
        if (creatingWebContents) {
            webContents = WarmupManager.getInstance().takeSpareWebContents(
                    isIncognito(), initiallyHidden);
            if (webContents == null) {
                webContents =
                        WebContentsFactory.createWebContents(isIncognito(), initiallyHidden);
            }
        }

        ContentViewCore contentViewCore = ContentViewCore.fromWebContents(webContents);

        if (contentViewCore == null) {
            initContentViewCore(webContents);
        } else {
            setContentViewCore(contentViewCore);
        }

        if (!creatingWebContents && webContents.isLoadingToDifferentDocument()) {
            didStartPageLoad(webContents.getUrl(), false);
        }

        getAppBannerManager().setIsEnabledForTab(mDelegateFactory.canShowAppBanners(this));
    } finally {
        if (mTimestampMillis == INVALID_TIMESTAMP) {
            mTimestampMillis = System.currentTimeMillis();
        }

        TraceEvent.end("Tab.initialize");
    }
}
 
Example 15
Source File: BluetoothChooserDialog.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Show the BluetoothChooserDialog.
 */
@VisibleForTesting
void show() {
    // Emphasize the origin.
    Profile profile = Profile.getLastUsedProfile();
    SpannableString origin = new SpannableString(mOrigin);
    OmniboxUrlEmphasizer.emphasizeUrl(
            origin, mActivity.getResources(), profile, mSecurityLevel, false, true, true);
    // Construct a full string and replace the origin text with emphasized version.
    SpannableString title =
            new SpannableString(mActivity.getString(R.string.bluetooth_dialog_title, mOrigin));
    int start = title.toString().indexOf(mOrigin);
    TextUtils.copySpansFrom(origin, 0, origin.length(), Object.class, title, start);

    String noneFound = mActivity.getString(R.string.bluetooth_not_found);

    SpannableString searching = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_searching),
            new SpanInfo("<link>", "</link>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)));

    String positiveButton = mActivity.getString(R.string.bluetooth_confirm_button);

    SpannableString statusIdleNoneFound = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_not_seeing_it_idle_none_found),
            new SpanInfo("<link1>", "</link1>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)),
            new SpanInfo("<link2>", "</link2>",
                    new BluetoothClickableSpan(LinkType.RESTART_SEARCH, mActivity)));

    SpannableString statusActive = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_not_seeing_it),
            new SpanInfo("<link>", "</link>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)));

    SpannableString statusIdleSomeFound = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_not_seeing_it_idle_some_found),
            new SpanInfo("<link1>", "</link1>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)),
            new SpanInfo("<link2>", "</link2>",
                    new BluetoothClickableSpan(LinkType.RESTART_SEARCH, mActivity)));

    ItemChooserDialog.ItemChooserLabels labels =
            new ItemChooserDialog.ItemChooserLabels(title, searching, noneFound, statusActive,
                    statusIdleNoneFound, statusIdleSomeFound, positiveButton);
    mItemChooserDialog = new ItemChooserDialog(mActivity, this, labels);

    mActivity.registerReceiver(mLocationModeBroadcastReceiver,
            new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
    mIsLocationModeChangedReceiverRegistered = true;
}
 
Example 16
Source File: OfflinePageDownloadBridge.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Gets DownloadServiceDelegate that is suitable for interacting with offline download items.
 */
public static DownloadServiceDelegate getDownloadServiceDelegate() {
    return new OfflinePageDownloadBridge(Profile.getLastUsedProfile());
}
 
Example 17
Source File: OfflinePageDownloadBridge.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Gets DownloadServiceDelegate that is suitable for interacting with offline download items.
 */
public static DownloadServiceDelegate getDownloadServiceDelegate() {
    return new OfflinePageDownloadBridge(Profile.getLastUsedProfile());
}
 
Example 18
Source File: SignInPreference.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Updates the title, summary, and image based on the current sign-in state.
 */
private void update() {
    String title;
    String summary;
    String fragment;

    Account account = ChromeSigninController.get(getContext()).getSignedInUser();
    if (account == null) {
        title = getContext().getString(R.string.sign_in_to_chrome);
        summary = getContext().getString(R.string.sign_in_to_chrome_summary);
        fragment = null;
    } else {
        summary = SyncPreference.getSyncStatusSummary(getContext());
        fragment = AccountManagementFragment.class.getName();
        title = AccountManagementFragment.getCachedUserName(account.name);
        if (title == null) {
            final Profile profile = Profile.getLastUsedProfile();
            String cachedName = ProfileDownloader.getCachedFullName(profile);
            Bitmap cachedBitmap = ProfileDownloader.getCachedAvatar(profile);
            if (TextUtils.isEmpty(cachedName) || cachedBitmap == null) {
                AccountManagementFragment.startFetchingAccountInformation(
                        getContext(), profile, account.name);
            }
            title = TextUtils.isEmpty(cachedName) ? account.name : cachedName;
        }
    }

    setTitle(title);
    setSummary(summary);
    setFragment(fragment);
    updateSyncStatusIcon();

    ChromeSigninController signinController = ChromeSigninController.get(getContext());
    boolean enabled = signinController.isSignedIn()
            || SigninManager.get(getContext()).isSignInAllowed();
    if (mViewEnabled != enabled) {
        mViewEnabled = enabled;
        notifyChanged();
    }
    if (!enabled) setFragment(null);

    if (SigninManager.get(getContext()).isSigninDisabledByPolicy()) {
        setIcon(ManagedPreferencesUtils.getManagedByEnterpriseIconId());
    } else {
        Resources resources = getContext().getResources();
        Bitmap bitmap = AccountManagementFragment.getUserPicture(
                signinController.getSignedInAccountName(), resources);
        setIcon(new BitmapDrawable(resources, bitmap));
    }

    setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!AccountSigninActivity.startIfAllowed(
                        getContext(), SigninAccessPoint.SETTINGS)) {
                return false;
            }

            setEnabled(false);
            return true;
        }
    });
}
 
Example 19
Source File: UsbChooserDialog.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Shows the UsbChooserDialog.
 *
 * @param activity Activity which is used for launching a dialog.
 * @param origin The origin for the site wanting to connect to the USB device.
 * @param securityLevel The security level of the connection to the site wanting to connect to
 *                      the USB device. For valid values see SecurityStateModel::SecurityLevel.
 */
@VisibleForTesting
void show(Activity activity, String origin, int securityLevel) {
    // Emphasize the origin.
    Profile profile = Profile.getLastUsedProfile();
    SpannableString originSpannableString = new SpannableString(origin);
    OmniboxUrlEmphasizer.emphasizeUrl(originSpannableString, activity.getResources(), profile,
            securityLevel, false /* isInternalPage */, true /* useDarkColors */,
            true /* emphasizeHttpsScheme */);
    // Construct a full string and replace the origin text with emphasized version.
    SpannableString title =
            new SpannableString(activity.getString(R.string.usb_chooser_dialog_prompt, origin));
    int start = title.toString().indexOf(origin);
    TextUtils.copySpansFrom(originSpannableString, 0, originSpannableString.length(),
            Object.class, title, start);

    String searching = "";
    String noneFound = activity.getString(R.string.usb_chooser_dialog_no_devices_found_prompt);
    SpannableString statusIdleNoneFound =
            SpanApplier.applySpans(
                    activity.getString(R.string.usb_chooser_dialog_footnote_text),
                    new SpanInfo("<link>", "</link>", new NoUnderlineClickableSpan() {
                        @Override
                        public void onClick(View view) {
                            if (mNativeUsbChooserDialogPtr == 0) {
                                return;
                            }

                            nativeLoadUsbHelpPage(mNativeUsbChooserDialogPtr);

                            // Get rid of the highlight background on selection.
                            view.invalidate();
                        }
                    }));
    SpannableString statusIdleSomeFound = statusIdleNoneFound;
    String positiveButton = activity.getString(R.string.usb_chooser_dialog_connect_button_text);

    ItemChooserDialog.ItemChooserLabels labels =
            new ItemChooserDialog.ItemChooserLabels(title, searching, noneFound,
                    statusIdleNoneFound, statusIdleSomeFound, positiveButton);
    mItemChooserDialog = new ItemChooserDialog(activity, this, labels);
}
 
Example 20
Source File: BluetoothChooserDialog.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Show the BluetoothChooserDialog.
 */
@VisibleForTesting
void show() {
    // Emphasize the origin.
    Profile profile = Profile.getLastUsedProfile();
    SpannableString origin = new SpannableString(mOrigin);
    OmniboxUrlEmphasizer.emphasizeUrl(
            origin, mActivity.getResources(), profile, mSecurityLevel, false, true, true);
    // Construct a full string and replace the origin text with emphasized version.
    SpannableString title =
            new SpannableString(mActivity.getString(R.string.bluetooth_dialog_title, mOrigin));
    int start = title.toString().indexOf(mOrigin);
    TextUtils.copySpansFrom(origin, 0, origin.length(), Object.class, title, start);

    String noneFound = mActivity.getString(R.string.bluetooth_not_found);

    SpannableString searching = SpanApplier.applySpans(
            mActivity.getString(R.string.bluetooth_searching),
            new SpanInfo("<link>", "</link>",
                    new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)));

    String positiveButton = mActivity.getString(R.string.bluetooth_confirm_button);

    SpannableString statusIdleNoneFound =
            SpanApplier.applySpans(mActivity.getString(R.string.bluetooth_not_seeing_it_idle),
                    new SpanInfo("<link1>", "</link1>",
                            new BluetoothClickableSpan(LinkType.EXPLAIN_BLUETOOTH, mActivity)),
                    new SpanInfo("<link2>", "</link2>",
                            new BluetoothClickableSpan(LinkType.RESTART_SEARCH, mActivity)));

    SpannableString statusActive = searching;

    SpannableString statusIdleSomeFound = statusIdleNoneFound;

    ItemChooserDialog.ItemChooserLabels labels =
            new ItemChooserDialog.ItemChooserLabels(title, searching, noneFound, statusActive,
                    statusIdleNoneFound, statusIdleSomeFound, positiveButton);
    mItemChooserDialog = new ItemChooserDialog(mActivity, this, labels);

    mActivity.registerReceiver(mLocationModeBroadcastReceiver,
            new IntentFilter(LocationManager.MODE_CHANGED_ACTION));
    mIsLocationModeChangedReceiverRegistered = true;
}