android.os.Looper Java Examples
The following examples show how to use
android.os.Looper.
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: AndroidHereFunctionHandler.java From commcare-android with Apache License 2.0 | 7 votes |
private void requestLocationUpdates() { Set<String> mProviders = GeoUtils.evaluateProvidersWithPermissions(mLocationManager, context); for (String provider : mProviders) { // Ignore the inspector warnings; the permissions are already checked in evaluateProvidersWithPermissions. if (location == null) { Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider); if (lastKnownLocation != null) { this.location = lastKnownLocation; this.lastDisplayedLocation = lastKnownLocation; Log.i("HereFunctionHandler", "last known location: " + this.location); } } // Looper is necessary because requestLocationUpdates is called inside an AsyncTask (EntityLoaderTask). // What values for minTime and minDistance? mLocationManager.requestLocationUpdates(provider, 0, 0, this, Looper.getMainLooper()); requestingLocationUpdates = true; } }
Example #2
Source File: Settings.java From Abelana-Android with Apache License 2.0 | 6 votes |
static void publishInstallAsync(final Context context, final String applicationId, final Request.Callback callback) { // grab the application context ahead of time, since we will return to the caller immediately. final Context applicationContext = context.getApplicationContext(); Settings.getExecutor().execute(new Runnable() { @Override public void run() { final Response response = Settings.publishInstallAndWaitForResponse(applicationContext, applicationId, false); if (callback != null) { // invoke the callback on the main thread. Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { callback.onCompleted(response); } }); } } }); }
Example #3
Source File: MapPresenter.java From mapwize-ui-android with MIT License | 6 votes |
@Override public void grantAccess(String accessKey, ApiCallback<Boolean> callback) { mapwizeMap.grantAccess(accessKey, new ApiCallback<Boolean>() { @Override public void onSuccess(@Nullable Boolean object) { new Handler(Looper.getMainLooper()).post(() -> { callback.onSuccess(object); preloadVenueSearchResults(); }); } @Override public void onFailure(@Nullable Throwable t) { new Handler(Looper.getMainLooper()).post(() -> { callback.onFailure(t); }); } }); }
Example #4
Source File: AdsMediaSource.java From TelePlus-Android with GNU General Public License v2.0 | 6 votes |
/** * Constructs a new source that inserts ads linearly with the content specified by {@code * contentMediaSource}. * * @param contentMediaSource The {@link MediaSource} providing the content to play. * @param adMediaSourceFactory Factory for media sources used to load ad media. * @param adsLoader The loader for ads. * @param adUiViewGroup A {@link ViewGroup} on top of the player that will show any ad UI. * @param eventHandler A handler for events. May be null if delivery of events is not required. * @param eventListener A listener of events. May be null if delivery of events is not required. * @deprecated To listen for ad load error events, add a listener via {@link * #addEventListener(Handler, MediaSourceEventListener)} and check for {@link * AdLoadException}s in {@link MediaSourceEventListener#onLoadError(int, MediaPeriodId, * LoadEventInfo, MediaLoadData, IOException, boolean)}. Individual ads loader implementations * should expose ad interaction events, if applicable. */ @Deprecated public AdsMediaSource( MediaSource contentMediaSource, MediaSourceFactory adMediaSourceFactory, AdsLoader adsLoader, ViewGroup adUiViewGroup, @Nullable Handler eventHandler, @Nullable EventListener eventListener) { this.contentMediaSource = contentMediaSource; this.adMediaSourceFactory = adMediaSourceFactory; this.adsLoader = adsLoader; this.adUiViewGroup = adUiViewGroup; this.eventHandler = eventHandler; this.eventListener = eventListener; mainHandler = new Handler(Looper.getMainLooper()); deferredMediaPeriodByAdMediaSource = new HashMap<>(); period = new Timeline.Period(); adGroupMediaSources = new MediaSource[0][]; adDurationsUs = new long[0][]; adsLoader.setSupportedContentTypes(adMediaSourceFactory.getSupportedTypes()); }
Example #5
Source File: d.java From MiBandDecompiled with Apache License 2.0 | 6 votes |
void a(long l, float f1) { try { Looper looper = g.getMainLooper(); if (Looper.myLooper() == null) { Looper.prepare(); } a.requestLocationUpdates("gps", l, f1, b, looper); return; } catch (Throwable throwable) { throwable.printStackTrace(); } }
Example #6
Source File: ThermalPrinterInstrumentedTest.java From contrib-drivers with Apache License 2.0 | 6 votes |
/** * Verify that the TextJob only prints the final string. */ @Test public void testTextJobPrinting() throws Exception { MockThermalPrinter mockThermalPrinter = new MockThermalPrinter(); Handler handler = new Handler(Looper.getMainLooper()); ThermalPrinter printer = new ThermalPrinter(mockThermalPrinter, handler); String stringToPrint = "hello world"; String stringToPrint2 = "hello world - 2"; printer.enqueue(new TextJob().printText(stringToPrint).printText(stringToPrint2)); CountDownLatch latch = new CountDownLatch(1); long delay = DELAY_INIT + stringToPrint2.length() * DELAY_CHARACTER; latch.await(delay * 2, TimeUnit.MILLISECONDS); Assert.assertEquals(BYTES_INIT_PRINTER + stringToPrint2.length() + BYTES_CLEANUP_TEXTJOB, mockThermalPrinter.mBytesSentList.size()); printer.close(); }
Example #7
Source File: WifiIotPlugin.java From WiFiFlutter with MIT License | 6 votes |
private void connect(final MethodCall poCall, final Result poResult) { new Thread() { public void run() { String ssid = poCall.argument("ssid"); String password = poCall.argument("password"); String security = poCall.argument("security"); Boolean joinOnce = poCall.argument("join_once"); final boolean connected = connectTo(ssid, password, security, joinOnce); final Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run () { poResult.success(connected); } }); } }.start(); }
Example #8
Source File: EventCallback.java From AndroidWear-OpenWear with MIT License | 6 votes |
@Override public void onFileReceived(final SpecialData data) { // TODO Auto-generated method stub if (Looper.myLooper() == Looper.getMainLooper()) callbackFile(data); else handler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub callbackFile(data); } }); }
Example #9
Source File: ConcurrencyWithSchedulersDemoFragment.java From RxJava-Android-Samples with Apache License 2.0 | 6 votes |
private void _log(String logMsg) { if (_isCurrentlyOnMainThread()) { _logs.add(0, logMsg + " (main thread) "); _adapter.clear(); _adapter.addAll(_logs); } else { _logs.add(0, logMsg + " (NOT main thread) "); // You can only do below stuff on main thread. new Handler(Looper.getMainLooper()) .post( () -> { _adapter.clear(); _adapter.addAll(_logs); }); } }
Example #10
Source File: BleManager.java From EasyBluetoothFrame with Apache License 2.0 | 6 votes |
@Override public void stopSearch() { if (isRegister) { // application.unregisterReceiver(mReceiver); isRegister = false; if (resultListener != null) { new Handler(Looper.getMainLooper()).post(() -> { resultListener.onFinish(); }); } } if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); if (scanTimer != null) { scanTimer.cancel(); } }
Example #11
Source File: ComponentTreeHolderTest.java From litho with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { mContext = new ComponentContext(getApplicationContext()); mComponent = SimpleMountSpecTester.create(mContext).build(); mRenderCompleteEventHandler = (EventHandler<RenderCompleteEvent>) mock(EventHandler.class); mComponentRenderInfo = ComponentRenderInfo.create() .component(mComponent) .renderCompleteHandler(mRenderCompleteEventHandler) .build(); mViewRenderInfo = ViewRenderInfo.create() .customViewType(0) .viewBinder(mock(ViewBinder.class)) .viewCreator(mock(ViewCreator.class)) .build(); mLayoutThreadShadowLooper = Shadows.shadowOf( (Looper) Whitebox.invokeMethod(ComponentTree.class, "getDefaultLayoutThreadLooper")); }
Example #12
Source File: UploadProgressRequest.java From zulip-android with Apache License 2.0 | 6 votes |
@Override public void writeTo(BufferedSink sink) throws IOException { long fileLength = mFile.length(); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; FileInputStream in = new FileInputStream(mFile); long uploaded = 0; try { int read; Handler handler = new Handler(Looper.getMainLooper()); while ((read = in.read(buffer)) != -1) { uploaded += read; sink.write(buffer, 0, read); // update progress on UI thread only handler.post(new ProgressUpdater(uploaded, fileLength)); } } finally { in.close(); } }
Example #13
Source File: SimpleExoPlayer.java From MediaSDK with Apache License 2.0 | 6 votes |
/** * Creates a builder with the specified custom components. * * <p>Note that this constructor is only useful if you try to ensure that ExoPlayer's default * components can be removed by ProGuard or R8. For most components except renderers, there is * only a marginal benefit of doing that. * * @param context A {@link Context}. * @param renderersFactory A factory for creating {@link Renderer Renderers} to be used by the * player. * @param trackSelector A {@link TrackSelector}. * @param loadControl A {@link LoadControl}. * @param bandwidthMeter A {@link BandwidthMeter}. * @param looper A {@link Looper} that must be used for all calls to the player. * @param analyticsCollector An {@link AnalyticsCollector}. * @param useLazyPreparation Whether media sources should be initialized lazily. * @param clock A {@link Clock}. Should always be {@link Clock#DEFAULT}. */ public Builder( Context context, RenderersFactory renderersFactory, TrackSelector trackSelector, LoadControl loadControl, BandwidthMeter bandwidthMeter, Looper looper, AnalyticsCollector analyticsCollector, boolean useLazyPreparation, Clock clock) { this.context = context; this.renderersFactory = renderersFactory; this.trackSelector = trackSelector; this.loadControl = loadControl; this.bandwidthMeter = bandwidthMeter; this.looper = looper; this.analyticsCollector = analyticsCollector; this.useLazyPreparation = useLazyPreparation; this.clock = clock; }
Example #14
Source File: BiometricActivity.java From cordova-plugin-fingerprint-aio with MIT License | 6 votes |
private void authenticate() { final Handler handler = new Handler(Looper.getMainLooper()); Executor executor = handler::post; BiometricPrompt biometricPrompt = new BiometricPrompt(this, executor, mAuthenticationCallback); BiometricPrompt.PromptInfo.Builder promptInfoBuilder = new BiometricPrompt.PromptInfo.Builder() .setTitle(mPromptInfo.getTitle()) .setSubtitle(mPromptInfo.getSubtitle()) .setConfirmationRequired(mPromptInfo.getConfirmationRequired()) .setDescription(mPromptInfo.getDescription()); if (mPromptInfo.isDeviceCredentialAllowed() && Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) { // TODO: remove after fix https://issuetracker.google.com/issues/142740104 promptInfoBuilder.setDeviceCredentialAllowed(true); } else { promptInfoBuilder.setNegativeButtonText(mPromptInfo.getCancelButtonTitle()); } biometricPrompt.authenticate(promptInfoBuilder.build()); }
Example #15
Source File: MixPushHandler.java From MixPush with Apache License 2.0 | 6 votes |
@Override public void onRegisterSucceed(final Context context, final MixPushPlatform pushPlatform) { if (passThroughPlatform != null) { logger.log(TAG, "已经响应onRegisterSucceed,不再重复调用"); return; } passThroughPlatform = pushPlatform; logger.log(TAG, "onRegisterSucceed " + pushPlatform.toString()); if (Thread.currentThread() == Looper.getMainLooper().getThread()) { // 在异步进程回调,避免阻塞主进程 new Thread(new Runnable() { @Override public void run() { handler.callPassThroughReceiver.onRegisterSucceed(context, pushPlatform); } }).start(); } else { handler.callPassThroughReceiver.onRegisterSucceed(context, pushPlatform); } }
Example #16
Source File: Settings.java From android-skeleton-project with MIT License | 6 votes |
/** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @param callback a callback to invoke with a Response object, carrying the server response, or an error. * * This method is deprecated. See {@link AppEventsLogger#activateApp(Context, String)} for more info. */ @Deprecated public static void publishInstallAsync(final Context context, final String applicationId, final Request.Callback callback) { // grab the application context ahead of time, since we will return to the caller immediately. final Context applicationContext = context.getApplicationContext(); Settings.getExecutor().execute(new Runnable() { @Override public void run() { final Response response = Settings.publishInstallAndWaitForResponse(applicationContext, applicationId); if (callback != null) { // invoke the callback on the main thread. Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { callback.onCompleted(response); } }); } } }); }
Example #17
Source File: RevokeMsgHook.java From QNotified with GNU General Public License v3.0 | 6 votes |
@Override public void setEnabled(boolean enabled) { try { ConfigManager mgr = ConfigManager.getDefaultConfig(); mgr.getAllConfig().put(qn_anti_revoke_msg, enabled); mgr.save(); } catch (final Exception e) { Utils.log(e); if (Looper.myLooper() == Looper.getMainLooper()) { Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT); } else { SyncUtils.post(new Runnable() { @Override public void run() { Utils.showToast(getApplication(), TOAST_TYPE_ERROR, e + "", Toast.LENGTH_SHORT); } }); } } }
Example #18
Source File: AsyncHttpResponseHandler.java From AndroidWear-OpenWear with MIT License | 5 votes |
/** * Creates a new AsyncHttpResponseHandler and decide whether the callbacks * will be fired on current thread's looper or the pool thread's. * * @param usePoolThread Whether to use the pool's thread to fire callbacks */ public AsyncHttpResponseHandler(boolean usePoolThread) { // Whether to use the pool's thread to fire callbacks. setUsePoolThread(usePoolThread); // When using the pool's thread, there's no sense in having a looper. if (!getUsePoolThread()) { // Use the current thread's looper. this.looper = Looper.myLooper(); // Use asynchronous mode by default. setUseSynchronousMode(false); } }
Example #19
Source File: ChangeColorItem.java From SlidingTabWithColorIcons with Apache License 2.0 | 5 votes |
private void invalidateView() { if (Looper.getMainLooper() == Looper.myLooper()) { invalidate(); } else { postInvalidate(); } }
Example #20
Source File: MapObjectManager.java From android-maps-utils with Apache License 2.0 | 5 votes |
public MapObjectManager(@NonNull GoogleMap map) { mMap = map; new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { setListenersOnUiThread(); } }); }
Example #21
Source File: Command.java From RedEnvelopeAssistant with MIT License | 5 votes |
private void createHandler(boolean handlerEnabled) { this.handlerEnabled = handlerEnabled; if (Looper.myLooper() != null && handlerEnabled) { RootTools.log("CommandHandler created"); mHandler = new CommandHandler(); } else { RootTools.log("CommandHandler not created"); } }
Example #22
Source File: SuggestedUpdateViewImpl.java From applivery-android-sdk with Apache License 2.0 | 5 votes |
public Looper getLooper() { if (Looper.myLooper() == Looper.getMainLooper()) { return Looper.myLooper(); } else { return Looper.getMainLooper(); } }
Example #23
Source File: AppLovinCustomEventInterstitial.java From SDK-Network-Adapters with MIT License | 5 votes |
/** * Performs the given runnable on the main thread. */ public static void runOnUiThread(final Runnable runnable) { if ( Looper.myLooper() == Looper.getMainLooper() ) { runnable.run(); } else { UI_HANDLER.post( runnable ); } }
Example #24
Source File: BasePlatformCreate.java From indigenous-android with GNU General Public License v3.0 | 5 votes |
/** * Initiate location updates. */ private void initiateLocationUpdates() { // Set wrapper and coordinates visible (if it wasn't already). toggleLocationVisibilities(true); mSettingsClient .checkLocationSettings(mLocationSettingsRequest) .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() { @SuppressLint("MissingPermission") @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { //noinspection MissingPermission mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper()); updateLocationUI(); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { int statusCode = ((ApiException) e).getStatusCode(); switch (statusCode) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). ResolvableApiException rae = (ResolvableApiException) e; rae.startResolutionForResult(BasePlatformCreate.this, REQUEST_CHECK_LOCATION_SETTINGS); } catch (IntentSender.SendIntentException sie) { Toast.makeText(getApplicationContext(), getString(R.string.location_intent_error), Toast.LENGTH_SHORT).show(); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Toast.makeText(getApplicationContext(), getString(R.string.location_settings_error), Toast.LENGTH_LONG).show(); } } }); }
Example #25
Source File: IdlingResourceRegistry.java From android-test with Apache License 2.0 | 5 votes |
/** * Registers the given resources. If any of the given resources are already registered, a warning * is logged. * * @return {@code true} if all resources were successfully registered */ public boolean registerResources(final List<? extends IdlingResource> resourceList) { if (Looper.myLooper() != looper) { return runSynchronouslyOnMainThread( new Callable<Boolean>() { @Override public Boolean call() { return registerResources(resourceList); } }); } else { boolean allRegisteredSuccessfully = true; for (IdlingResource resource : resourceList) { checkNotNull(resource.getName(), "IdlingResource.getName() should not be null"); boolean duplicate = false; for (IdlingState oldState : idlingStates) { if (resource.getName().equals(oldState.resource.getName())) { // This does not throw an error to avoid leaving tests that register resource in test // setup in an undeterministic state (we cannot assume that everyone clears vm state // between each test run) logDuplicateRegistrationError(resource, oldState.resource); duplicate = true; break; } } if (!duplicate) { IdlingState is = new IdlingState(resource, handler); idlingStates.add(is); is.registerSelf(); } else { allRegisteredSuccessfully = false; } } return allRegisteredSuccessfully; } }
Example #26
Source File: CachedCallAdapterFactory.java From retrocache with Apache License 2.0 | 5 votes |
public static CachedCallAdapterFactory create(@NonNull Context context, int appVersion) { return new CachedCallAdapterFactory(RetroCache.getDualCache(context, appVersion), new Executor() { @Override public void execute(@NonNull Runnable command) { new Handler(Looper.getMainLooper()).post(command); } }); }
Example #27
Source File: DispatchRunnable.java From android-performance with MIT License | 5 votes |
/** * 打印出来Task执行的日志 * * @param startTime * @param waitTime */ private void printTaskLog(long startTime, long waitTime) { long runTime = System.currentTimeMillis() - startTime; if (DispatcherLog.isDebug()) { DispatcherLog.i(mTask.getClass().getSimpleName() + " wait " + waitTime + " run " + runTime + " isMain " + (Looper.getMainLooper() == Looper.myLooper()) + " needWait " + (mTask.needWait() || (Looper.getMainLooper() == Looper.myLooper())) + " ThreadId " + Thread.currentThread().getId() + " ThreadName " + Thread.currentThread().getName() + " Situation " + TaskStat.getCurrentSituation() ); } }
Example #28
Source File: DecodeHandler.java From ZXingProject with MIT License | 5 votes |
@Override public void handleMessage(Message message) { if (!running) { return; } switch (message.what) { case R.id.decode: decode((byte[]) message.obj, message.arg1, message.arg2); break; case R.id.quit: running = false; Looper.myLooper().quit(); break; } }
Example #29
Source File: ViewAware.java From Android-Application-ZJB with Apache License 2.0 | 5 votes |
@Override public boolean setImageBitmap(Bitmap bitmap) { if (Looper.myLooper() == Looper.getMainLooper()) { View view = viewRef.get(); if (view != null) { setImageBitmapInto(bitmap, view); return true; } } else { L.w(WARN_CANT_SET_BITMAP); } return false; }
Example #30
Source File: DecodeThread.java From QrCodeScanner with GNU General Public License v3.0 | 5 votes |
@Override public void run() { Looper.prepare(); mHandler = new DecodeHandler(mActivity); mHandlerInitLatch.countDown(); Looper.loop(); }