Java Code Examples for org.chromium.base.ThreadUtils#postOnUiThread()

The following examples show how to use org.chromium.base.ThreadUtils#postOnUiThread() . 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: PostMessageHandler.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Relay a postMessage request through the current channel assigned to this session.
 * @param message The message to be sent.
 * @return The result of the postMessage request. Returning true means the request was accepted,
 *         not necessarily that the postMessage was successful.
 */
public int postMessageFromClientApp(final String message) {
    if (mChannel == null || !mChannel[0].isReady() || mChannel[0].isClosed()) {
        return CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR;
    }
    if (mWebContents == null || mWebContents.isDestroyed()) {
        return CustomTabsService.RESULT_FAILURE_MESSAGING_ERROR;
    }
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            // It is still possible that the page has navigated while this task is in the queue.
            // If that happens fail gracefully.
            if (mChannel == null || mChannel[0].isClosed()) return;
            mChannel[0].postMessage(message, null);
        }
    });
    return CustomTabsService.RESULT_SUCCESS;
}
 
Example 2
Source File: ScreenshotTask.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares screenshot (possibly asynchronously) and invokes the callback when the screenshot
 * is available, or collection has failed. The asynchronous path is only taken when the activity
 * that is passed in is a {@link ChromeActivity}.
 * The callback is always invoked asynchronously.
 */
public static void create(Activity activity, final ScreenshotTaskCallback callback) {
    if (activity instanceof ChromeActivity) {
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getRootView().getWindowVisibleDisplayFrame(rect);
        createCompositorScreenshot(((ChromeActivity) activity).getWindowAndroid(), rect,
                callback);
        return;
    }

    final Bitmap bitmap = prepareScreenshot(activity, null);
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            callback.onGotBitmap(bitmap);
        }
    });
}
 
Example 3
Source File: UrlManager.java    From AndroidChromium 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(mContext, LibraryProcessType.PROCESS_BROWSER)
                    .addStartupCompletedObserver(new StartupCallback() {
                        @Override
                        public void onSuccess(boolean alreadyStarted) {
                            mNativePhysicalWebDataSourceAndroid = nativeInit();
                        }

                        @Override
                        public void onFailure() {
                            // Startup failed.
                        }
                    });
        }
    });
}
 
Example 4
Source File: UrlManager.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Notify native listeners with an updated estimate of the distance to the broadcasting device.
 * No notification will be sent if the feature is in the Onboarding state.
 * @param url The Physical Web URL.
 * @param distanceEstimate The updated distance estimate.
 */
private void safeNotifyNativeListenersOnDistanceChanged(
        final String url, final double distanceEstimate) {
    if (!isNativeInitialized() || PhysicalWeb.isOnboarding()) {
        return;
    }

    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (isNativeInitialized()) {
                nativeOnDistanceChanged(mNativePhysicalWebDataSourceAndroid, url,
                        distanceEstimate);
            }
        }
    });
}
 
Example 5
Source File: ScreenshotTask.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares screenshot (possibly asynchronously) and invokes the callback when the screenshot
 * is available, or collection has failed. The asynchronous path is only taken when the activity
 * that is passed in is a {@link ChromeActivity}.
 * The callback is always invoked asynchronously.
 */
public static void create(Activity activity, final ScreenshotTaskCallback callback) {
    if (activity instanceof ChromeActivity) {
        Rect rect = new Rect();
        activity.getWindow().getDecorView().getRootView().getWindowVisibleDisplayFrame(rect);
        createCompositorScreenshot(((ChromeActivity) activity).getWindowAndroid(), rect,
                callback);
        return;
    }

    final Bitmap bitmap = prepareScreenshot(activity, null);
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            callback.onGotBitmap(bitmap);
        }
    });
}
 
Example 6
Source File: ChromeBrowserProvider.java    From delion 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 7
Source File: ChildAccountService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@CalledByNative
private static void reauthenticateChildAccount(
        WindowAndroid windowAndroid, String accountName, final long nativeCallback) {
    ThreadUtils.assertOnUiThread();

    Activity activity = windowAndroid.getActivity().get();
    if (activity == null) {
        ThreadUtils.postOnUiThread(new Runnable() {
            @Override
            public void run() {
                nativeOnReauthenticationResult(nativeCallback, false);
            }
        });
        return;
    }

    Account account = AccountManagerHelper.createAccountFromName(accountName);
    AccountManagerHelper.get().updateCredentials(account, activity, new Callback<Boolean>() {
        @Override
        public void onResult(Boolean result) {
            nativeOnReauthenticationResult(nativeCallback, result);
        }
    });
}
 
Example 8
Source File: PartnerBrowserCustomizations.java    From delion with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a callback that will be executed when the initialization is done.
 *
 * @param callback  This is called when the initialization is done.
 */
public static void setOnInitializeAsyncFinished(final Runnable callback) {
    if (sIsInitialized) {
        ThreadUtils.postOnUiThread(callback);
    } else {
        sInitializeAsyncCallbacks.add(callback);
    }
}
 
Example 9
Source File: ConnectivityTask.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void postCallbackResult() {
    if (mCallback == null) return;
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mCallback.onResult(get());
        }
    });
}
 
Example 10
Source File: PostMessageHandler.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Asynchronously verify the postMessage origin for the given package name and initialize with
 * it if the result is a success. Can be called multiple times. If so, the previous requests
 * will be overridden.
 * @param origin The origin to verify for.
 */
public void verifyAndInitializeWithOrigin(final Uri origin) {
    if (mOriginVerifier == null) mOriginVerifier = new OriginVerifier(this, mPackageName);
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mOriginVerifier.start(origin);
        }
    });
}
 
Example 11
Source File: FeedbackCollector.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void maybePostResult() {
    ThreadUtils.assertOnUiThread();
    if (mCallback == null) return;
    if (mResultPosted) return;
    if (shouldWaitForScreenshot() || shouldWaitForConnectivityTask()) return;

    mResultPosted = true;
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mCallback.onResult(FeedbackCollector.this);
        }
    });
}
 
Example 12
Source File: UrlManager.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Notify native listeners that a previously-discovered Physical Web URL is no longer nearby.
 * No message will be sent if the feature is in the Onboarding state.
 * @param url The Physical Web URL.
 */
private void safeNotifyNativeListenersOnLost(final String url) {
    if (!isNativeInitialized() || PhysicalWeb.isOnboarding()) {
        return;
    }

    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (isNativeInitialized()) {
                nativeOnLost(mNativePhysicalWebDataSourceAndroid, url);
            }
        }
    });
}
 
Example 13
Source File: ThreadedInputConnection.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @see InputConnection#setComposingRegion(int, int)
 */
@Override
public boolean setComposingRegion(final int start, final int end) {
    if (DEBUG_LOGS) Log.i(TAG, "setComposingRegion [%d %d]", start, end);
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mImeAdapter.setComposingRegion(start, end);
        }
    });
    return true;
}
 
Example 14
Source File: CustomTabsConnection.java    From delion with Apache License 2.0 5 votes vote down vote up
private boolean mayLaunchUrlInternal(final CustomTabsSessionToken session, Uri url,
        final Bundle extras, final List<Bundle> otherLikelyBundles) {
    final boolean lowConfidence =
            (url == null || TextUtils.isEmpty(url.toString())) && otherLikelyBundles != null;
    final String urlString = checkAndConvertUri(url);
    if (url != null && urlString == null && !lowConfidence) return false;

    // Things below need the browser process to be initialized.

    // Forbids warmup() from creating a spare renderer, as prerendering wouldn't reuse
    // it. Checking whether prerendering is enabled requires the native library to be loaded,
    // which is not necessarily the case yet.
    if (!warmupInternal(false)) return false; // Also does the foreground check.

    final int uid = Binder.getCallingUid();
    // TODO(lizeb): Also throttle low-confidence mode.
    if (!lowConfidence
            && !mClientManager.updateStatsAndReturnWhetherAllowed(session, uid, urlString)) {
        return false;
    }
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (lowConfidence) {
                lowConfidenceMayLaunchUrl(otherLikelyBundles);
            } else {
                highConfidenceMayLaunchUrl(session, uid, urlString, extras, otherLikelyBundles);
            }
        }
    });
    return true;
}
 
Example 15
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 16
Source File: OAuth2TokenService.java    From AndroidChromium 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 17
Source File: ConnectivityTask.java    From delion with Apache License 2.0 5 votes vote down vote up
private void postCallbackResult() {
    if (mCallback == null) return;
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mCallback.onResult(get());
        }
    });
}
 
Example 18
Source File: ThreadedInputConnection.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * @see InputConnection#requestCursorUpdates(int)
 */
@Override
public boolean requestCursorUpdates(final int cursorUpdateMode) {
    if (DEBUG_LOGS) Log.i(TAG, "requestCursorUpdates [%x]", cursorUpdateMode);
    ThreadUtils.postOnUiThread(new Runnable() {
        @Override
        public void run() {
            mImeAdapter.onRequestCursorUpdates(cursorUpdateMode);
        }
    });
    return true;
}
 
Example 19
Source File: TabPersistentStore.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
private void loadNextTab() {
    if (mDestroyed) return;

    if (mTabsToRestore.isEmpty()) {
        mNormalTabsRestored = null;
        mIncognitoTabsRestored = null;
        mLoadInProgress = false;

        // If tabs are done being merged into this instance, save the tab metadata file for this
        // TabPersistentStore and delete the metadata file for the other instance, then notify
        // observers.
        if (mPersistencePolicy.isMergeInProgress()) {
            if (mMergeTabCount != 0) {
                long timePerTab = (SystemClock.uptimeMillis() - mRestoreMergedTabsStartTime)
                        / mMergeTabCount;
                RecordHistogram.recordTimesHistogram(
                        "Android.TabPersistentStore.MergeStateTimePerTab",
                        timePerTab,
                        TimeUnit.MILLISECONDS);
            }

            ThreadUtils.postOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // This eventually calls serializeTabModelSelector() which much be called
                    // from the UI thread. #mergeState() starts an async task in the background
                    // that goes through this code path.
                    saveTabListAsynchronously();
                }
            });
            deleteFileAsync(mPersistencePolicy.getStateToBeMergedFileName());
            if (mObserver != null) mObserver.onStateMerged();
        }

        cleanUpPersistentData();
        onStateLoaded();
        mLoadTabTask = null;
        Log.d(TAG, "Loaded tab lists; counts: " + mTabModelSelector.getModel(false).getCount()
                + "," + mTabModelSelector.getModel(true).getCount());
    } else {
        TabRestoreDetails tabToRestore = mTabsToRestore.removeFirst();
        mLoadTabTask = new LoadTabTask(tabToRestore);
        mLoadTabTask.execute();
    }
}
 
Example 20
Source File: ThreadedInputConnection.java    From 365browser with Apache License 2.0 4 votes vote down vote up
private void notifyUserAction() {
    ThreadUtils.postOnUiThread(mNotifyUserActionRunnable);
}