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

The following examples show how to use org.chromium.base.ThreadUtils#runOnUiThread() . 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: LocationProvider.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private boolean usePassiveOneShotLocation() {
    if (!isOnlyPassiveLocationProviderEnabled()) return false;

    // Do not request a location update if the only available location provider is
    // the passive one. Make use of the last known location and call
    // onLocationChanged directly.
    final Location location = mLocationManager.getLastKnownLocation(
            LocationManager.PASSIVE_PROVIDER);
    if (location != null) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateNewLocation(location);
            }
        });
    }
    return true;
}
 
Example 2
Source File: ExternalAuthUtils.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #canUseGooglePlayServices(Context, UserRecoverableErrorHandler)}.
 * @param context The current context.
 * @param errorHandler How to handle user-recoverable errors; must be non-null.
 * @return the result code specifying Google Play Services availability.
 */
public int canUseGooglePlayServicesResultCode(
        final Context context, final UserRecoverableErrorHandler errorHandler) {
    final int resultCode = checkGooglePlayServicesAvailable(context);
    recordConnectionResult(resultCode);
    if (resultCode != ConnectionResult.SUCCESS) {
        // resultCode is some kind of error.
        Log.v(TAG, "Unable to use Google Play Services: %s", describeError(resultCode));

        if (isUserRecoverableError(resultCode)) {
            Runnable errorHandlerTask = new Runnable() {
                @Override
                public void run() {
                    errorHandler.handleError(context, resultCode);
                }
            };
            ThreadUtils.runOnUiThread(errorHandlerTask);
        }
    }
    return resultCode;
}
 
Example 3
Source File: OmahaService.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
public void scheduleService(long currentTimestampMs, long nextTimestampMs) {
    if (Build.VERSION.SDK_INT < OmahaBase.MIN_API_JOB_SCHEDULER) {
        getScheduler().createAlarm(OmahaClient.createIntent(getContext()), nextTimestampMs);
        Log.i(TAG, "Scheduled using AlarmManager and IntentService");
    } else {
        final long delay = nextTimestampMs - currentTimestampMs;
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (scheduleJobService(getContext(), delay)) {
                    Log.i(TAG, "Scheduled using JobService");
                } else {
                    Log.e(TAG, "Failed to schedule job");
                }
            }
        });
    }
}
 
Example 4
Source File: SupervisedUserContentProvider.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean requestInsert(final String url) {
    // This will be called on multiple threads (but never the UI thread),
    // see http://developer.android.com/guide/components/processes-and-threads.html#ThreadSafe.
    // The reply comes back on a different thread (possibly the UI thread) some time later.
    // As such it needs to correctly match the replies to the calls. It does this by creating a
    // reply object for each query, and passing this through the callback structure. The reply
    // object also handles waiting for the reply.
    final SupervisedUserInsertReply insertReply = new SupervisedUserInsertReply();
    final long contentProvider = getSupervisedUserContentProvider();
    if (contentProvider == 0) return false;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            nativeRequestInsert(contentProvider, insertReply, url);
        }
    });
    try {
        Boolean result = insertReply.getResult();
        if (result == null) return false;
        return result;
    } catch (InterruptedException e) {
        return false;
    }
}
 
Example 5
Source File: ChromeGcmListenerService.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
private void pushMessageReceived(final String from, final Bundle data) {
    final String bundleSubtype = "subtype";
    if (!data.containsKey(bundleSubtype)) {
        Log.w(TAG, "Received push message with no subtype");
        return;
    }
    final String appId = data.getString(bundleSubtype);
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        @SuppressFBWarnings("DM_EXIT")
        public void run() {
            try {
                ChromeBrowserInitializer.getInstance(getApplicationContext())
                    .handleSynchronousStartup();
                GCMDriver.onMessageReceived(appId, from, data);
            } catch (ProcessInitException e) {
                Log.e(TAG, "ProcessInitException while starting the browser process");
                // Since the library failed to initialize nothing in the application
                // can work, so kill the whole application not just the activity.
                System.exit(-1);
            }
        }
    });
}
 
Example 6
Source File: NotificationService.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Called when a Notification has been interacted with by the user. If we can verify that
 * the Intent has a notification Id, start Chrome (if needed) on the UI thread.
 *
 * @param intent The intent containing the specific information.
 */
@Override
public void onHandleIntent(final Intent intent) {
    if (!intent.hasExtra(NotificationConstants.EXTRA_PERSISTENT_NOTIFICATION_ID)
            || !intent.hasExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN)
            || !intent.hasExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG)) {
        return;
    }

    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            dispatchIntentOnUIThread(intent);
        }
    });
}
 
Example 7
Source File: BookmarkWidgetService.java    From delion with Apache License 2.0 5 votes vote down vote up
@BinderThread
@Override
public void onDestroy() {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mBookmarkModel != null) mBookmarkModel.destroy();
        }
    });
    deleteWidgetState(mContext, mWidgetId);
}
 
Example 8
Source File: BeamCallback.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger an error about NFC if we don't want to send anything. Also
 * records a UMA stat. On ICS we only show the error if they attempt to
 * beam, since the recipient will receive the market link. On JB we'll
 * always show the error, since the beam animation won't trigger, which
 * could be confusing to the user.
 *
 * @param errorStringId The resid of the string to display as error.
 */
private void onInvalidBeam(final int errorStringId) {
    RecordUserAction.record("MobileBeamInvalidAppState");
    Runnable errorRunnable = new Runnable() {
        @Override
        public void run() {
            Toast.makeText(mActivity, errorStringId, Toast.LENGTH_SHORT).show();
        }
    };
    ThreadUtils.runOnUiThread(errorRunnable);
}
 
Example 9
Source File: CustomTabActivity.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void recordClientPackageName() {
    String clientName = CustomTabsConnection.getInstance(getApplication())
            .getClientPackageNameForSession(mSession);
    if (TextUtils.isEmpty(clientName)) clientName = mIntentDataProvider.getClientPackageName();
    final String packageName = clientName;
    if (TextUtils.isEmpty(packageName) || packageName.contains(getPackageName())) return;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            RapporServiceBridge.sampleString(
                    "CustomTabs.ServiceClient.PackageName", packageName);
        }
    });
}
 
Example 10
Source File: AccountsChangedReceiver.java    From delion with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("DM_EXIT")
private static void startBrowserIfNeededAndValidateAccounts(final Context context) {
    BrowserParts parts = new EmptyBrowserParts() {
        @Override
        public void finishNativeInitialization() {
            ThreadUtils.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SigninHelper.get(context).validateAccountSettings(true);
                }
            });
        }

        @Override
        public void onStartupFailure() {
            // Startup failed. So notify SigninHelper of changed accounts via
            // shared prefs.
            SigninHelper.markAccountsChangedPref(context);
        }
    };
    try {
        ChromeBrowserInitializer.getInstance(context).handlePreNativeStartup(parts);
        ChromeBrowserInitializer.getInstance(context).handlePostNativeStartup(true, parts);
    } catch (ProcessInitException e) {
        Log.e(TAG, "Unable to load native library.", e);
        ChromeApplication.reportStartupErrorAndExit(e);
    }
}
 
Example 11
Source File: TtsPlatformImpl.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Post a task to the UI thread to send the TTS "start" event.
 */
protected void sendStartEventOnUiThread(final String utteranceId) {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mNativeTtsPlatformImplAndroid != 0) {
                nativeOnStartEvent(mNativeTtsPlatformImplAndroid,
                        Integer.parseInt(utteranceId));
            }
        }
    });
}
 
Example 12
Source File: RecentTabsManager.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public void androidSyncSettingsChanged() {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mIsDestroyed) return;
            updateForeignSessions();
            postUpdate();
        }
    });
}
 
Example 13
Source File: ChromeBrowserProvider.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
protected void finalize() throws Throwable {
    try {
        // Per Object#finalize(), finalizers are run on a single VM-wide finalizer thread, and
        // the native objects need to be destroyed on the UI thread.
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ensureNativeChromeDestroyedOnUIThread();
            }
        });
    } finally {
        super.finalize();
    }
}
 
Example 14
Source File: AwContents.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void saveWebArchiveInternal(String path, final ValueCallback<String> callback) {
    if (path == null || mNativeAwContents == 0) {
        ThreadUtils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callback.onReceiveValue(null);
            }
        });
    } else {
        nativeGenerateMHTML(mNativeAwContents, path, callback);
    }
}
 
Example 15
Source File: SyncController.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * From {@link SyncStatusHelper.SyncSettingsChangedObserver}.
 */
@Override
public void syncSettingsChanged() {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            refreshSyncState();
        }
    });
}
 
Example 16
Source File: AccountsChangedReceiver.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void startBrowserProcessOnUiThread(final Context context,
        final BrowserStartupController.StartupCallback callback) {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            BrowserStartupController.get(context).startBrowserProcessesAsync(callback);
        }
    });
}
 
Example 17
Source File: LocationProviderAdapter.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Stop listening for location updates. May be called in any thread.
 */
@CalledByNative
public void stop() {
    FutureTask<Void> task = new FutureTask<Void>(new Runnable() {
        @Override
        public void run() {
            mImpl.stop();
        }
    }, null);
    ThreadUtils.runOnUiThread(task);
}
 
Example 18
Source File: JsResultHandler.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void cancel() {
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mBridge != null)
                mBridge.cancelJsResult(mId);
            mBridge = null;
        }
    });
}
 
Example 19
Source File: DefaultVideoPosterRequestHandler.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static InputStream getInputStream(final AwContentsClient contentClient)
        throws IOException {
    final PipedInputStream inputStream = new PipedInputStream();
    final PipedOutputStream outputStream = new PipedOutputStream(inputStream);

    // Send the request to UI thread to callback to the client, and if it provides a
    // valid bitmap bounce on to the worker thread pool to compress it into the piped
    // input/output stream.
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            final Bitmap defaultVideoPoster = contentClient.getDefaultVideoPoster();
            if (defaultVideoPoster == null) {
                closeOutputStream(outputStream);
                return;
            }
            AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        defaultVideoPoster.compress(Bitmap.CompressFormat.PNG, 100,
                                outputStream);
                        outputStream.flush();
                    } catch (IOException e) {
                        Log.e(TAG, null, e);
                    } finally {
                        closeOutputStream(outputStream);
                    }
                }
            });
        }
    });
    return inputStream;
}
 
Example 20
Source File: ChromeBackgroundService.java    From delion with Apache License 2.0 4 votes vote down vote up
@Override
@VisibleForTesting
public int onRunTask(final TaskParams params) {
    final String taskTag = params.getTag();
    Log.i(TAG, "[" + taskTag + "] Woken up at " + new java.util.Date().toString());
    final ChromeBackgroundServiceWaiter waiter = getWaiterIfNeeded(params.getExtras());
    final Context context = this;
    ThreadUtils.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            switch (taskTag) {
                case BackgroundSyncLauncher.TASK_TAG:
                    handleBackgroundSyncEvent(context, taskTag);
                    break;

                case OfflinePageUtils.TASK_TAG:
                    handleOfflinePageBackgroundLoad(
                            context, params.getExtras(), waiter, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_WIFI_CHARGING:
                case SnippetsLauncher.TASK_TAG_WIFI:
                case SnippetsLauncher.TASK_TAG_FALLBACK:
                    handleFetchSnippets(context, taskTag);
                    break;

                case SnippetsLauncher.TASK_TAG_RESCHEDULE:
                    handleRescheduleSnippets(context, taskTag);
                    break;

                case PrecacheController.PERIODIC_TASK_TAG:
                case PrecacheController.CONTINUATION_TASK_TAG:
                    handlePrecache(context, taskTag);
                    break;

                case DownloadResumptionScheduler.TASK_TAG:
                    DownloadResumptionScheduler.getDownloadResumptionScheduler(
                            context.getApplicationContext()).handleDownloadResumption();
                    break;

                default:
                    Log.i(TAG, "Unknown task tag " + taskTag);
                    break;
            }
        }
    });
    // If needed, block the GcmNetworkManager thread until the UI thread has finished its work.
    waitForTaskIfNeeded(waiter);

    return GcmNetworkManager.RESULT_SUCCESS;
}