Example usage for android.os StrictMode allowThreadDiskReads

List of usage examples for android.os StrictMode allowThreadDiskReads

Introduction

In this page you can find the example usage for android.os StrictMode allowThreadDiskReads.

Prototype

public static ThreadPolicy allowThreadDiskReads() 

Source Link

Document

A convenience wrapper that takes the current ThreadPolicy from #getThreadPolicy , modifies it to permit disk reads, and sets the new policy with #setThreadPolicy , returning the old policy so you can restore it at the end of a block.

Usage

From source file:org.mozilla.gecko.LocaleAware.java

public static void initializeLocale(Context context) {
    final LocaleManager localeManager = BrowserLocaleManager.getInstance();
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();/*from w w  w.j  av  a  2  s . co m*/
    try {
        localeManager.getAndApplyPersistedLocale(context);
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}

From source file:org.chromium.chrome.browser.ntp.snippets.SnippetArticleViewHolder.java

public void onBindViewHolder(SnippetArticle article) {
    super.onBindViewHolder();

    mArticle = article;/*from w ww.j  a va2s  . c o  m*/
    updateLayout();

    mHeadlineTextView.setText(mArticle.mTitle);

    // DateUtils.getRelativeTimeSpanString(...) calls through to TimeZone.getDefault(). If this
    // has never been called before it loads the current time zone from disk. In most likelihood
    // this will have been called previously and the current time zone will have been cached,
    // but in some cases (eg instrumentation tests) it will cause a strict mode violation.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        long time = SystemClock.elapsedRealtime();
        CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(
                mArticle.mPublishTimestampMilliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS);
        RecordHistogram.recordTimesHistogram("Android.StrictMode.SnippetUIBuildTime",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);

        // We format the publisher here so that having a publisher name in an RTL language
        // doesn't mess up the formatting on an LTR device and vice versa.
        String publisherAttribution = String.format(PUBLISHER_FORMAT_STRING,
                BidiFormatter.getInstance().unicodeWrap(mArticle.mPublisher), relativeTimeSpan);
        mPublisherTextView.setText(publisherAttribution);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    // The favicon of the publisher should match the textview height.
    int widthSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    int heightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    mPublisherTextView.measure(widthSpec, heightSpec);
    mPublisherFaviconSizePx = mPublisherTextView.getMeasuredHeight();

    mArticleSnippetTextView.setText(mArticle.mPreviewText);

    // If there's still a pending thumbnail fetch, cancel it.
    cancelImageFetch();

    // If the article has a thumbnail already, reuse it. Otherwise start a fetch.
    // mThumbnailView's visibility is modified in updateLayout().
    if (mThumbnailView.getVisibility() == View.VISIBLE) {
        if (mArticle.getThumbnailBitmap() != null) {
            mThumbnailView.setImageBitmap(mArticle.getThumbnailBitmap());
        } else {
            mThumbnailView.setImageResource(R.drawable.ic_snippet_thumbnail_placeholder);
            mImageCallback = new FetchImageCallback(this, mArticle);
            mNewTabPageManager.getSuggestionsSource().fetchSuggestionImage(mArticle, mImageCallback);
        }
    }

    // Set the favicon of the publisher.
    try {
        fetchFaviconFromLocalCache(new URI(mArticle.mUrl), true);
    } catch (URISyntaxException e) {
        setDefaultFaviconOnView();
    }
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

private void restoreTab(TabRestoreDetails tabToRestore, boolean setAsActive) {
    // As we do this in startup, and restoring the active tab's state is critical, we permit
    // this read in the event that the prefetch task is not available. Either:
    // 1. The user just upgraded, has not yet set the new active tab id pref yet. Or
    // 2. restoreTab is used to preempt async queue and restore immediately on the UI thread.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {/*from   w w w.  j a v a 2  s  . co m*/
        long time = SystemClock.uptimeMillis();
        TabState state;
        int restoredTabId = mPreferences.getInt(PREF_ACTIVE_TAB_ID, Tab.INVALID_TAB_ID);
        if (restoredTabId == tabToRestore.id && mPrefetchActiveTabTask != null) {
            long timeWaitingForPrefetch = SystemClock.uptimeMillis();
            state = mPrefetchActiveTabTask.get();
            logExecutionTime("RestoreTabPrefetchTime", timeWaitingForPrefetch);
        } else {
            // Necessary to do on the UI thread as a last resort.
            state = TabState.restoreTabState(getStateDirectory(), tabToRestore.id);
        }
        logExecutionTime("RestoreTabTime", time);
        restoreTab(tabToRestore, state, setAsActive);
    } catch (Exception e) {
        // Catch generic exception to prevent a corrupted state from crashing the app
        // at startup.
        Log.d(TAG, "loadTabs exception: " + e.toString(), e);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
}

From source file:org.chromium.chrome.browser.customtabs.CustomTabActivity.java

/**
 * Opens the URL currently being displayed in the Custom Tab in the regular browser.
 * @param forceReparenting Whether tab reparenting should be forced for testing.
 *
 * @return Whether or not the tab was sent over successfully.
 *//* w ww .  j  av  a2s.  c  om*/
boolean openCurrentUrlInBrowser(boolean forceReparenting) {
    Tab tab = getActivityTab();
    if (tab == null)
        return false;

    String url = tab.getUrl();
    if (DomDistillerUrlUtils.isDistilledPage(url)) {
        url = DomDistillerUrlUtils.getOriginalUrlFromDistillerUrl(url);
    }
    if (TextUtils.isEmpty(url))
        url = getUrlToLoad();
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(ChromeLauncherActivity.EXTRA_IS_ALLOWED_TO_RETURN_TO_PARENT, false);

    boolean willChromeHandleIntent = getIntentDataProvider().isOpenedByChrome();
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        willChromeHandleIntent |= ExternalNavigationDelegateImpl.willChromeHandleIntent(this, intent, true);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    Bundle startActivityOptions = ActivityOptionsCompat
            .makeCustomAnimation(this, R.anim.abc_fade_in, R.anim.abc_fade_out).toBundle();
    if (willChromeHandleIntent || forceReparenting) {
        Runnable finalizeCallback = new Runnable() {
            @Override
            public void run() {
                finishAndClose();
            }
        };

        mMainTab = null;
        tab.detachAndStartReparenting(intent, startActivityOptions, finalizeCallback);
    } else {
        // Temporarily allowing disk access while fixing. TODO: http://crbug.com/581860
        StrictMode.allowThreadDiskReads();
        StrictMode.allowThreadDiskWrites();
        try {
            startActivity(intent, startActivityOptions);
        } finally {
            StrictMode.setThreadPolicy(oldPolicy);
        }
    }
    return true;
}

From source file:org.mozilla.gecko.BrowserApp.java

/**
 * Check and show the firstrun pane if the browser has never been launched and
 * is not opening an external link from another application.
 *
 * @param context Context of application; used to show firstrun pane if appropriate
 * @param intent Intent that launched this activity
 *//*from   ww  w . ja  va 2s.co  m*/
private void checkFirstrun(Context context, SafeIntent intent) {
    if (intent.getBooleanExtra(EXTRA_SKIP_STARTPANE, false)) {
        // Note that we don't set the pref, so subsequent launches can result
        // in the firstrun pane being shown.
        return;
    }
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();

    try {
        final SharedPreferences prefs = GeckoSharedPrefs.forProfile(this);

        if (prefs.getBoolean(FirstrunPane.PREF_FIRSTRUN_ENABLED, false)) {
            if (!Intent.ACTION_VIEW.equals(intent.getAction())) {
                showFirstrunPager();
            }
            // Don't bother trying again to show the v1 minimal first run.
            prefs.edit().putBoolean(FirstrunPane.PREF_FIRSTRUN_ENABLED, false).apply();
        }
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

/**
 * If a global max tab ID has not been computed and stored before, then check all the state
 * folders and calculate a new global max tab ID to be used. Must be called before any new tabs
 * are created.//from   ww  w  .  j  av a 2s .  co  m
 *
 * @throws IOException
 */
private void checkAndUpdateMaxTabId() throws IOException {
    if (mPreferences.getBoolean(PREF_HAS_COMPUTED_MAX_ID, false))
        return;

    int maxId = 0;
    // Calculation of the max tab ID is done only once per user and is stored in
    // SharedPreferences afterwards.  This is done on the UI thread because it is on the
    // critical patch to initializing the TabIdManager with the correct max tab ID.
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    try {
        File[] subDirectories = getOrCreateBaseStateDirectory().listFiles();
        if (subDirectories != null) {
            for (File subDirectory : subDirectories) {
                if (!subDirectory.isDirectory()) {
                    assert false : "Only directories should exist below the base state directory";
                    continue;
                }
                File[] files = subDirectory.listFiles();
                if (files == null)
                    continue;

                for (File file : files) {
                    Pair<Integer, Boolean> tabStateInfo = TabState.parseInfoFromFilename(file.getName());
                    if (tabStateInfo != null) {
                        maxId = Math.max(maxId, tabStateInfo.first);
                    } else if (isStateFile(file.getName())) {
                        DataInputStream stream = null;
                        try {
                            stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
                            maxId = Math.max(maxId, readSavedStateFile(stream, null, null, false));
                        } finally {
                            StreamUtil.closeQuietly(stream);
                        }
                    }
                }
            }
        }
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }
    TabIdManager.getInstance().incrementIdCounterTo(maxId);
    mPreferences.edit().putBoolean(PREF_HAS_COMPUTED_MAX_ID, true).apply();
}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
protected void onNewIntent(Intent intent) {
    String action = intent.getAction();

    final boolean isViewAction = Intent.ACTION_VIEW.equals(action);
    final boolean isBookmarkAction = GeckoApp.ACTION_HOMESCREEN_SHORTCUT.equals(action);
    final boolean isTabQueueAction = TabQueueHelper.LOAD_URLS_ACTION.equals(action);

    if (mInitialized && (isViewAction || isBookmarkAction)) {
        // Dismiss editing mode if the user is loading a URL from an external app.
        mBrowserToolbar.cancelEdit();//from  w  w  w .j a  v  a  2  s .c om

        // Hide firstrun-pane if the user is loading a URL from an external app.
        hideFirstrunPager();

        if (isBookmarkAction) {
            // GeckoApp.ACTION_HOMESCREEN_SHORTCUT means we're opening a bookmark that
            // was added to Android's homescreen.
            Telemetry.sendUIEvent(TelemetryContract.Event.LOAD_URL, TelemetryContract.Method.HOMESCREEN);
        }
    }

    showTabQueuePromptIfApplicable(intent);

    super.onNewIntent(intent);

    if (AppConstants.MOZ_ANDROID_BEAM && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        String uri = intent.getDataString();
        GeckoAppShell.sendEventToGecko(GeckoEvent.createURILoadEvent(uri));
    }

    // Only solicit feedback when the app has been launched from the icon shortcut.
    if (GuestSession.NOTIFICATION_INTENT.equals(action)) {
        GuestSession.handleIntent(this, intent);
    }

    // If the user has clicked the tab queue notification then load the tabs.
    if (AppConstants.NIGHTLY_BUILD && AppConstants.MOZ_ANDROID_TAB_QUEUE && mInitialized && isTabQueueAction) {
        Telemetry.sendUIEvent(TelemetryContract.Event.ACTION, TelemetryContract.Method.NOTIFICATION,
                "tabqueue");
        ThreadUtils.postToBackgroundThread(new Runnable() {
            @Override
            public void run() {
                openQueuedTabs();
            }
        });
    }

    if (!mInitialized || !Intent.ACTION_MAIN.equals(action)) {
        return;
    }

    // Check to see how many times the app has been launched.
    final String keyName = getPackageName() + ".feedback_launch_count";
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskReads();

    // Faster on main thread with an async apply().
    try {
        SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
        int launchCount = settings.getInt(keyName, 0);
        if (launchCount < FEEDBACK_LAUNCH_COUNT) {
            // Increment the launch count and store the new value.
            launchCount++;
            settings.edit().putInt(keyName, launchCount).apply();

            // If we've reached our magic number, show the feedback page.
            if (launchCount == FEEDBACK_LAUNCH_COUNT) {
                GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Feedback:Show", null));
            }
        }
    } finally {
        StrictMode.setThreadPolicy(savedPolicy);
    }
}