org.chromium.base.ThreadUtils Java Examples

The following examples show how to use org.chromium.base.ThreadUtils. 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: ChromeBrowserProvider.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
private void notifyChange(final Uri uri) {
    // If the calling user is different than current one, we need to post a
    // task to notify change, otherwise, a system level hidden permission
    // INTERACT_ACROSS_USERS_FULL is needed.
    // The related APIs were added in API 17, it should be safe to fallback to
    // normal way for notifying change, because caller can't be other users in
    // devices whose API level is less than API 17.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        UserHandle callingUserHandle = Binder.getCallingUserHandle();
        if (callingUserHandle != null
                && !callingUserHandle.equals(android.os.Process.myUserHandle())) {
            ThreadUtils.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getContext().getContentResolver().notifyChange(uri, null);
                }
            });
            return;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
}
 
Example #2
Source File: DocumentModeAssassin.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Moves the user to tabbed mode by opting them out and removing all the tasks. */
final void switchToTabbedMode() {
    ThreadUtils.assertOnUiThread();
    if (!setStage(STAGE_WRITE_TABMODEL_METADATA_DONE, STAGE_CHANGE_SETTINGS_STARTED)) return;

    // Record that the user has opted-out of document mode now that their data has been
    // safely copied to the other directory.
    Log.d(TAG, "Setting tabbed mode preference.");
    setOptedOutState(OPTED_OUT_OF_DOCUMENT_MODE);
    TabSwitcherCallout.setIsTabSwitcherCalloutNecessary(true);

    // Remove all the {@link DocumentActivity} tasks from Android's Recents list.  Users
    // viewing Recents during migration will continue to see their tabs until they exit.
    // Reselecting a migrated tab will kick the user to the launcher without crashing.
    // TODO(dfalcantara): Confirm that the different Android flavors work the same way.
    createActivityDelegate().finishAllDocumentActivities();

    // Dismiss the "Close all incognito tabs" notification.
    IncognitoNotificationManager.dismissIncognitoNotification();

    setStage(STAGE_CHANGE_SETTINGS_STARTED, STAGE_CHANGE_SETTINGS_DONE);
}
 
Example #3
Source File: ChromeBrowserInitializer.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private void preInflationStartup() {
    ThreadUtils.assertOnUiThread();
    if (mPreInflationStartupComplete) return;
    PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX);

    // Ensure critical files are available, so they aren't blocked on the file-system
    // behind long-running accesses in next phase.
    // Don't do any large file access here!
    ContentApplication.initCommandLine(mApplication);
    waitForDebuggerIfNeeded();
    ChromeStrictMode.configureStrictMode();
    ChromeWebApkHost.init();

    warmUpSharedPrefs();

    DeviceUtils.addDeviceSpecificUserAgentSwitch(mApplication);
    ApplicationStatus.registerStateListenerForAllActivities(
            createActivityStateListener());

    mPreInflationStartupComplete = true;
}
 
Example #4
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Finishes the activity and removes the reference from the Android recents.
 *
 * @param reparenting true iff the activity finishes due to tab reparenting.
 */
public final void finishAndClose(boolean reparenting) {
    mIsClosing = true;
    if (!reparenting) {
        // Closing the activity destroys the renderer as well. Re-create a spare renderer some
        // time after, so that we have one ready for the next tab open. This does not increase
        // memory consumption, as the current renderer goes away. We create a renderer as a lot
        // of users open several Custom Tabs in a row. The delay is there to avoid jank in the
        // transition animation when closing the tab.
        ThreadUtils.postOnUiThreadDelayed(new Runnable() {
            @Override
            public void run() {
                WarmupManager.getInstance().createSpareWebContents();
            }
        }, 500);
    }

    handleFinishAndClose();
}
 
Example #5
Source File: UrlManager.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Register a StartupCallback to initialize the native portion of the JNI bridge.
 */
private void registerNativeInitStartupCallback() {
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER)
                    .addStartupCompletedObserver(new StartupCallback() {
                        @Override
                        public void onSuccess(boolean alreadyStarted) {
                            mNativePhysicalWebDataSourceAndroid = nativeInit();
                            for (UrlInfo urlInfo : getUrls()) {
                                safeNotifyNativeListenersOnFound(urlInfo.getUrl());
                            }
                        }

                        @Override
                        public void onFailure() {
                            // Startup failed.
                        }
                    });
        }
    });
}
 
Example #6
Source File: ThumbnailProviderImpl.java    From 365browser with Apache License 2.0 6 votes vote down vote up
private static LruCache<String, Pair<Bitmap, Integer>> getBitmapCache() {
    ThreadUtils.assertOnUiThread();

    LruCache<String, Pair<Bitmap, Integer>> cache =
            sBitmapCache == null ? null : sBitmapCache.get();
    if (cache != null) return cache;

    // Create a new weakly-referenced cache.
    cache = new LruCache<String, Pair<Bitmap, Integer>>(MAX_CACHE_BYTES) {
        @Override
        protected int sizeOf(String key, Pair<Bitmap, Integer> thumbnail) {
            return thumbnail == null ? 0 : thumbnail.second;
        }
    };
    sBitmapCache = new WeakReference<>(cache);
    return cache;
}
 
Example #7
Source File: BindingManagerImpl.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void onTrimMemory(final int level) {
    ThreadUtils.assertOnUiThread();
    LauncherThread.post(new Runnable() {
        @Override
        public void run() {
            Log.i(TAG, "onTrimMemory: level=%d, size=%d", level, mConnections.size());
            if (mConnections.isEmpty()) {
                return;
            }
            if (level <= TRIM_MEMORY_RUNNING_MODERATE) {
                reduce(MODERATE_BINDING_LOW_REDUCE_RATIO);
            } else if (level <= TRIM_MEMORY_RUNNING_LOW) {
                reduce(MODERATE_BINDING_HIGH_REDUCE_RATIO);
            } else if (level == TRIM_MEMORY_UI_HIDDEN) {
                // This will be handled by |mDelayedClearer|.
                return;
            } else {
                removeAllConnections();
            }
        }
    });
}
 
Example #8
Source File: SigninManager.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Performs an asynchronous check to see if the user is a managed user.
 * @param callback A callback to be called with true if the user is a managed user and false
 *         otherwise.
 */
public static void isUserManaged(String email, final Callback<Boolean> callback) {
    if (nativeShouldLoadPolicyForUser(email)) {
        nativeIsUserManaged(email, callback);
    } else {
        // Although we know the result immediately, the caller may not be able to handle the
        // callback being executed during this method call. So we post the callback on the
        // looper.
        ThreadUtils.postOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onResult(false);
            }
        });
    }
}
 
Example #9
Source File: ConnectivityTask.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the connectivity that has been collected up until this call. This method fills in
 * {@link ConnectivityCheckResult#UNKNOWN} for results that have not been retrieved yet.
 *
 * @return the {@link FeedbackData}.
 */
public FeedbackData get() {
    ThreadUtils.assertOnUiThread();
    Map<Type, Integer> result = new EnumMap<Type, Integer>(Type.class);
    // Ensure the map is filled with a result for all {@link Type}s.
    for (Type type : Type.values()) {
        if (mResult.containsKey(type)) {
            result.put(type, mResult.get(type));
        } else {
            result.put(type, ConnectivityCheckResult.UNKNOWN);
        }
    }
    long elapsedTimeMs = SystemClock.elapsedRealtime() - mStartCheckTimeMs;
    int connectionType = NetworkChangeNotifier.getInstance().getCurrentConnectionType();
    return new FeedbackData(result, mTimeoutMs, elapsedTimeMs, connectionType);
}
 
Example #10
Source File: TtsPlatformImpl.java    From delion with Apache License 2.0 6 votes vote down vote up
protected TtsPlatformImpl(long nativeTtsPlatformImplAndroid, Context context) {
    mInitialized = false;
    mNativeTtsPlatformImplAndroid = nativeTtsPlatformImplAndroid;
    mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initialize();
                        }
                    });
                }
            }
        });
    addOnUtteranceProgressListener();
}
 
Example #11
Source File: ProfileDownloader.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC")
public static PendingProfileDownloads get(Context context) {
    ThreadUtils.assertOnUiThread();
    if (sPendingProfileDownloads == null) {
        sPendingProfileDownloads = new PendingProfileDownloads();
        AccountTrackerService.get().addSystemAccountsSeededListener(
                sPendingProfileDownloads);
    }
    return sPendingProfileDownloads;
}
 
Example #12
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Low confidence mayLaunchUrl() call, that is:
 * - Preconnects to the ordered list of URLs.
 * - Makes sure that there is a spare renderer.
 */
@VisibleForTesting
boolean lowConfidenceMayLaunchUrl(List<Bundle> likelyBundles) {
    ThreadUtils.assertOnUiThread();
    if (!preconnectUrls(likelyBundles)) return false;
    WarmupManager.getInstance().createSpareWebContents();
    return true;
}
 
Example #13
Source File: SupervisedUserContentProvider.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
void setFilterForTesting() {
    ThreadUtils.runOnUiThreadBlocking(new Runnable() {
        @Override
        public void run() {
            try {
                nativeSetFilterForTesting(getSupervisedUserContentProvider());
            } catch (ProcessInitException e) {
                // There is no way of returning anything sensible here, so ignore the error and
                // do nothing.
            }
        }
    });
}
 
Example #14
Source File: OfflinePageBridge.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * @return True if offline pages sharing is enabled.
 */
@VisibleForTesting
public static boolean isPageSharingEnabled() {
    ThreadUtils.assertOnUiThread();
    if (sIsPageSharingEnabled == null) {
        sIsPageSharingEnabled = nativeIsPageSharingEnabled();
    }
    return sIsPageSharingEnabled;
}
 
Example #15
Source File: DocumentModeAssassin.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/** Migrates the user from document mode to tabbed mode if necessary. */
@VisibleForTesting
public final void migrateFromDocumentToTabbedMode() {
    ThreadUtils.assertOnUiThread();

    // Migration is already underway.
    if (mStage != STAGE_UNINITIALIZED) return;

    // If migration isn't necessary, don't do anything.
    if (!isMigrationNecessary()) {
        setStage(STAGE_UNINITIALIZED, STAGE_DONE);
        return;
    }

    // If we've crashed or failed too many times, send them to tabbed mode without their data.
    // - Any incorrect or invalid files in the tabbed mode directory will be wiped out by the
    //   TabPersistentStore when the ChromeTabbedActivity starts.
    //
    // - If it crashes in the step after being migrated, then the user will simply be left
    //   with a bunch of inaccessible document mode data instead of being stuck trying to
    //   migrate, which is a lesser evil.  This case will be caught by the check above to see if
    //   migration is even necessary.
    SharedPreferences prefs = ContextUtils.getAppSharedPreferences();
    int numMigrationAttempts = prefs.getInt(PREF_NUM_MIGRATION_ATTEMPTS, 0);
    if (numMigrationAttempts >= MAX_MIGRATION_ATTEMPTS_BEFORE_FAILURE) {
        Log.e(TAG, "Too many failures.  Migrating user to tabbed mode without data.");
        setStage(STAGE_UNINITIALIZED, STAGE_WRITE_TABMODEL_METADATA_DONE);
        return;
    }

    // Kick off the migration pipeline.
    // Using apply() instead of commit() seems to save the preference just fine, even if Chrome
    // crashes immediately afterward.
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(PREF_NUM_MIGRATION_ATTEMPTS, numMigrationAttempts + 1);
    editor.apply();
    setStage(STAGE_UNINITIALIZED, STAGE_INITIALIZED);
}
 
Example #16
Source File: DownloadManagerService.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * For tests only: sets the DownloadManagerService.
 * @param service An instance of DownloadManagerService.
 * @return Null or a currently set instance of DownloadManagerService.
 */
@VisibleForTesting
public static DownloadManagerService setDownloadManagerService(DownloadManagerService service) {
    ThreadUtils.assertOnUiThread();
    DownloadManagerService prev = sDownloadManagerService;
    sDownloadManagerService = service;
    return prev;
}
 
Example #17
Source File: DialogOverlayImpl.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Callback from native that we will be getting no additional tokens.
 */
@CalledByNative
public void onDismissed() {
    ThreadUtils.assertOnUiThread();

    // Notify the client that the overlay is going away.
    if (mClient != null) mClient.onDestroyed();

    // Notify |mDialogCore| that it lost the token, if it had one.
    sendWindowTokenToCore(null);

    cleanup();
}
 
Example #18
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 #19
Source File: CustomTabsConnection.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** Cancels a prerender for a given session, or any session if null. */
void cancelPrerender(CustomTabsSessionToken session) {
    ThreadUtils.assertOnUiThread();
    if (mSpeculation != null && (session == null || session.equals(mSpeculation.session))
            && mSpeculation.webContents != null) {
        mExternalPrerenderHandler.cancelCurrentPrerender();
        mSpeculation.webContents.destroy();
        mSpeculation = null;
    }
}
 
Example #20
Source File: NativeInitializationController.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Start loading the native library in the background. This kicks off the native initialization
 * process.
 *
 * @param allocateChildConnection Whether a spare child connection should be allocated. Set to
 *                                false if you know that no new renderer is needed.
 */
public void startBackgroundTasks(final boolean allocateChildConnection) {
    // TODO(yusufo) : Investigate using an AsyncTask for this.
    new Thread() {
        @Override
        public void run() {
            try {
                LibraryLoader libraryLoader =
                        LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER);
                libraryLoader.ensureInitialized(mContext.getApplicationContext());
                // The prefetch is done after the library load for two reasons:
                // - It is easier to know the library location after it has
                //   been loaded.
                // - Testing has shown that this gives the best compromise,
                //   by avoiding performance regression on any tested
                //   device, and providing performance improvement on
                //   some. Doing it earlier delays UI inflation and more
                //   generally startup on some devices, most likely by
                //   competing for IO.
                // For experimental results, see http://crbug.com/460438.
                libraryLoader.asyncPrefetchLibrariesToMemory();
            } catch (ProcessInitException e) {
                Log.e(TAG, "Unable to load native library.", e);
                mActivityDelegate.onStartupFailure();
                return;
            }
            if (allocateChildConnection) ChildProcessLauncher.warmUp(mContext);
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onLibraryLoaded();
                }
            });
        }
    }.start();
}
 
Example #21
Source File: AccountTrackerService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
* Notifies the AccountTrackerService about changed system accounts. without actually triggering
* @param reSeedAccounts Whether to also start seeding the new account information immediately.
*/
public void invalidateAccountSeedStatus(boolean reSeedAccounts) {
    ThreadUtils.assertOnUiThread();
    mSystemAccountsChanged = true;
    notifyObserversOnAccountsChange();
    if (reSeedAccounts) checkAndSeedSystemAccounts();
}
 
Example #22
Source File: ChromeBrowserInitializer.java    From delion with Apache License 2.0 5 votes vote down vote up
public static void initNetworkChangeNotifier(Context context) {
    ThreadUtils.assertOnUiThread();
    TraceEvent.begin("NetworkChangeNotifier.init");
    // Enable auto-detection of network connectivity state changes.
    NetworkChangeNotifier.init(context);
    NetworkChangeNotifier.setAutoDetectConnectivityState(true);
    TraceEvent.end("NetworkChangeNotifier.init");
}
 
Example #23
Source File: WarmupManager.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Transfers all the children in the view hierarchy to the giving ViewGroup as child.
 * @param contentView The parent ViewGroup to use for the transfer.
 */
public void transferViewHierarchyTo(ViewGroup contentView) {
    ThreadUtils.assertOnUiThread();
    ViewGroup viewHierarchy = mMainView;
    mMainView = null;
    if (viewHierarchy == null) return;
    while (viewHierarchy.getChildCount() > 0) {
        View currentChild = viewHierarchy.getChildAt(0);
        viewHierarchy.removeView(currentChild);
        contentView.addView(currentChild);
    }
}
 
Example #24
Source File: HelpAndFeedback.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the singleton instance of HelpAndFeedback, creating it if needed.
 */
@SuppressFBWarnings("LI_LAZY_INIT_STATIC")
public static HelpAndFeedback getInstance(Context context) {
    ThreadUtils.assertOnUiThread();
    if (sInstance == null) {
        sInstance = ((ChromeApplication) context.getApplicationContext())
                .createHelpAndFeedback();
    }
    return sInstance;
}
 
Example #25
Source File: OAuth2TokenService.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Called by native to retrieve OAuth2 tokens.
 *
 * @param username The native username (full address).
 * @param scope The scope to get an auth token for (without Android-style 'oauth2:' prefix).
 * @param nativeCallback The pointer to the native callback that should be run upon completion.
 */
@CalledByNative
public static void getOAuth2AuthToken(
        Context context, String username, String scope, final long nativeCallback) {
    Account account = getAccountOrNullFromUsername(context, username);
    if (account == null) {
        ThreadUtils.postOnUiThread(new Runnable() {
            @Override
            public void run() {
                nativeOAuth2TokenFetched(null, false, nativeCallback);
            }
        });
        return;
    }
    String oauth2Scope = OAUTH2_SCOPE_PREFIX + scope;

    AccountManagerHelper accountManagerHelper = AccountManagerHelper.get(context);
    accountManagerHelper.getAuthToken(
            account, oauth2Scope, new AccountManagerHelper.GetAuthTokenCallback() {
                @Override
                public void tokenAvailable(String token) {
                    nativeOAuth2TokenFetched(token, false, nativeCallback);
                }

                @Override
                public void tokenUnavailable(boolean isTransientError) {
                    nativeOAuth2TokenFetched(null, isTransientError, nativeCallback);
                }
            });
}
 
Example #26
Source File: FeatureUtilities.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether or not the {@link RecognizerIntent#ACTION_WEB_SEARCH} {@link Intent}
 * is handled by any {@link android.app.Activity}s in the system.  The result will be cached for
 * future calls.  Passing {@code false} to {@code useCachedValue} will force it to re-query any
 * {@link android.app.Activity}s that can process the {@link Intent}.
 * @param context        The {@link Context} to use to check to see if the {@link Intent} will
 *                       be handled.
 * @param useCachedValue Whether or not to use the cached value from a previous result.
 * @return {@code true} if recognition is supported.  {@code false} otherwise.
 */
public static boolean isRecognitionIntentPresent(Context context, boolean useCachedValue) {
    ThreadUtils.assertOnUiThread();
    if (sHasRecognitionIntentHandler == null || !useCachedValue) {
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        sHasRecognitionIntentHandler = activities.size() > 0;
    }

    return sHasRecognitionIntentHandler;
}
 
Example #27
Source File: CustomTabsConnection.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a hidden tab and initiates a navigation.
 */
private void launchUrlInHiddenTab(
        final CustomTabsSessionToken session, final String url, final Bundle extras) {
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            Intent extrasIntent = new Intent();
            if (extras != null) extrasIntent.putExtras(extras);
            if (IntentHandler.getExtraHeadersFromIntent(extrasIntent) != null) return;

            Tab tab = Tab.createDetached(new CustomTabDelegateFactory(false, false, null));

            // Updating post message as soon as we have a valid WebContents.
            mClientManager.resetPostMessageHandlerForSession(
                    session, tab.getContentViewCore().getWebContents());

            LoadUrlParams loadParams = new LoadUrlParams(url);
            String referrer = getReferrer(session, extrasIntent);
            if (referrer != null && !referrer.isEmpty()) {
                loadParams.setReferrer(
                        new Referrer(referrer, Referrer.REFERRER_POLICY_DEFAULT));
            }
            mSpeculation = SpeculationParams.forHiddenTab(session, url, tab, referrer, extras);
            mSpeculation.tab.loadUrl(loadParams);
        }
    });
}
 
Example #28
Source File: LocationProvider.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Start listening for location updates until we're told to quit. May be
 * called in any thread.
 * @param gpsEnabled Whether or not we're interested in high accuracy GPS.
 */
@CalledByNative
public boolean start(final boolean gpsEnabled) {
    FutureTask<Void> task = new FutureTask<Void>(new Runnable() {
        @Override
        public void run() {
            mImpl.start(gpsEnabled);
        }
    }, null);
    ThreadUtils.runOnUiThread(task);
    return true;
}
 
Example #29
Source File: PrecacheLauncher.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * If precaching is enabled, then allow the PrecacheController to be launched and signal Chrome
 * when conditions are right to start precaching. If precaching is disabled, prevent the
 * PrecacheController from ever starting.
 *
 * @param context any context within the application
 */
@VisibleForTesting
void updateEnabled(final Context context) {
    Log.v(TAG, "updateEnabled starting");
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mCalled = true;
            final ProfileSyncService sync = ProfileSyncService.get();

            if (mListener == null && sync != null) {
                mListener = new ProfileSyncService.SyncStateChangedListener() {
                    public void syncStateChanged() {
                        if (sync.isBackendInitialized()) {
                            mSyncInitialized = true;
                            updateEnabledSync(context);
                        }
                    }
                };
                sync.addSyncStateChangedListener(mListener);
            }

            if (mListener != null) {
                // Call the listener once, in case the sync backend is already initialized.
                mListener.syncStateChanged();
            }
            Log.v(TAG, "updateEnabled complete");
        }
    });
}
 
Example #30
Source File: DocumentModeAssassin.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/** Deletes all remnants of the document mode directory and preferences. */
final void deleteDocumentModeData() {
    ThreadUtils.assertOnUiThread();
    if (!setStage(STAGE_CHANGE_SETTINGS_DONE, STAGE_DELETION_STARTED)) return;

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            Log.d(TAG, "Starting to delete document mode data.");

            // Delete the old tab state directory.
            FileUtils.recursivelyDeleteFile(getDocumentDataDirectory());

            // Clean up the {@link DocumentTabModel} shared preferences.
            SharedPreferences prefs = getContext().getSharedPreferences(
                    DocumentTabModelImpl.PREF_PACKAGE, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
            editor.apply();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.d(TAG, "Finished deleting document mode data.");
            setStage(STAGE_DELETION_STARTED, STAGE_DONE);
        }
    }.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}