Java Code Examples for android.os.Looper

The following examples show how to use android.os.Looper. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: zulip-android   Source File: UploadProgressRequest.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
Source Project: litho   Source File: ComponentTreeHolderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: android-skeleton-project   Source File: Settings.java    License: MIT License 6 votes vote down vote up
/**
 * 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 4
Source Project: EasyBluetoothFrame   Source File: BleManager.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
/**
 * 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 6
Source Project: MiBandDecompiled   Source File: d.java    License: Apache License 2.0 6 votes vote down vote up
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 7
Source Project: mapwize-ui-android   Source File: MapPresenter.java    License: MIT License 6 votes vote down vote up
@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 8
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 9
Source Project: Abelana-Android   Source File: Settings.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: AndroidWear-OpenWear   Source File: EventCallback.java    License: MIT License 6 votes vote down vote up
@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 11
/**
 * 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 12
Source Project: WiFiFlutter   Source File: WifiIotPlugin.java    License: MIT License 6 votes vote down vote up
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 13
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 14
Source Project: MediaSDK   Source File: SimpleExoPlayer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 15
Source Project: cordova-plugin-fingerprint-aio   Source File: BiometricActivity.java    License: MIT License 6 votes vote down vote up
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 16
Source Project: MixPush   Source File: MixPushHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 17
Source Project: QNotified   Source File: RevokeMsgHook.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 Project: Tok-Android   Source File: DispatchQueue.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    super.run();
    Looper.prepare();
    if (handler == null) {
        handler = new QueueHandler(this);
    }
    syncLatch.countDown();
    Looper.loop();
}
 
Example 19
Source Project: SlidingTabWithColorIcons   Source File: ChangeColorItem.java    License: Apache License 2.0 5 votes vote down vote up
private void invalidateView() {
    if (Looper.getMainLooper() == Looper.myLooper()) {
        invalidate();
    } else {
        postInvalidate();
    }
}
 
Example 20
Source Project: arcusandroid   Source File: StateMachine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Executes the given state. Package private to prevent clients from accessing this method
 * directly; typically only the state class should invoke this.
 *
 * @param state The state to be executed; null to indicate the machine has reached a terminal
 *              state.
 */
void execute(final State state) {
    if (!halted.get()) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (state == null) {
                    logger.debug("Terminal state {} reached. Machine has stopped.", currentState);
                    fireOnTerminated(currentState);
                    return;
                }

                logger.debug("Transitioning from state {} to {}", currentState, state);

                fireOnStateChanged(currentState, state);
                currentState = state;
                currentState.setExecutor(StateMachine.this);

                try {
                    state.execute();
                } catch (StateException e) {
                    handleException(e);
                }
                }
        });
    }
}
 
Example 21
Source Project: RairDemo   Source File: MainThreadTasksHolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void notifyErrorListeners(final Throwable throwable) {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        super.notifyErrorListeners(throwable);
    } else {
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                MainThreadTasksHolder.super.notifyErrorListeners(throwable);
            }
        });
    }
}
 
Example 22
Source Project: SugarAdapter   Source File: SugarAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView view) {
    if (mPreInflateHandler != null) {
        Looper.myQueue().removeIdleHandler(mPreInflateHandler);
        mPreInflateHandler = null;
    }

    for (ExtraDelegate delegate : mExtraDelegateList) {
        if (delegate != null) {
            delegate.onDetachedFromRecyclerView(view);
        }
    }
}
 
Example 23
Source Project: android-maps-utils   Source File: DefaultClusterRenderer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message msg) {
    if (!mListenerAdded) {
        Looper.myQueue().addIdleHandler(this);
        mListenerAdded = true;
    }
    removeMessages(BLANK);

    lock.lock();
    try {

        // Perform up to 10 tasks at once.
        // Consider only performing 10 remove tasks, not adds and animations.
        // Removes are relatively slow and are much better when batched.
        for (int i = 0; i < 10; i++) {
            performNextTask();
        }

        if (!isBusy()) {
            mListenerAdded = false;
            Looper.myQueue().removeIdleHandler(this);
            // Signal any other threads that are waiting.
            busyCondition.signalAll();
        } else {
            // Sometimes the idle queue may not be called - schedule up some work regardless
            // of whether the UI thread is busy or not.
            // TODO: try to remove this.
            sendEmptyMessageDelayed(BLANK, 10);
        }
    } finally {
        lock.unlock();
    }
}
 
Example 24
Source Project: arcusandroid   Source File: AlarmIncidentPresenter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(final Throwable throwable) {
    String exceptionMessage = ArcusApplication.getArcusApplication().getString(R.string.hub_local_offline_incident_exception_message);
    if (exceptionMessage.equals(throwable.getMessage())) {
        String warningDescription;
        String warningTitle = ArcusApplication.getArcusApplication().getString(R.string.hub_local_offline_incident_popup_title);
        String normalDescription = ArcusApplication.getArcusApplication().getString(R.string.hub_local_offline_incident_desc_text);
        String promonDescrition = ArcusApplication.getArcusApplication().getString(R.string.hub_local_offline_incident_promon_text);

        PlaceModel placeModel = SessionController.instance().getPlace();
        if (SubscriptionController.isProfessional()) {

            warningDescription = normalDescription + promonDescrition;
        }
        else {
            warningDescription = normalDescription;
        }

        presentCancel(warningTitle, Html.fromHtml(warningDescription.replaceAll("%s", GlobalSetting.PRO_MONITORING_STATION_NUMBER)));
    }
    else {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                logger.debug("Got error: {}", throwable);
                if (isPresenting()) {
                    getPresentedView().showError(throwable);
                }
            }
        });
    }
}
 
Example 25
Source Project: MousePaint   Source File: BaseHttp.java    License: MIT License 5 votes vote down vote up
protected BaseHttp()
{
    mGson = new Gson();
    mOkHttpClient = new OkHttpClient();
    mHandler = new Handler(Looper.getMainLooper());
    //cookie enabled
    mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}
 
Example 26
Source Project: QuickNews   Source File: NewsUtil.java    License: MIT License 5 votes vote down vote up
public static void showToast(final String toast, final Context context)
  {
  	new Thread(new Runnable() {
	
	@Override
	public void run() {
		Looper.prepare();
		Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
		Looper.loop();
	}
}).start();
  }
 
Example 27
/**
 *
 * @param fragmentManager
 * @param fullScreen
 * @param horizontalProgress
 * @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored
 */
public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,
    boolean horizontalProgress, boolean hideFullScreenTitle) {
    super();
    this.uiHandler = new Handler(Looper.getMainLooper());
    this.fragmentManager =
            new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));
    this.fullScreen = fullScreen;
    this.horizontalProgress = horizontalProgress;
    this.hideFullScreenTitle = hideFullScreenTitle;
}
 
Example 28
Source Project: AndroidWear-OpenWear   Source File: AsyncHttpResponseHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 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 29
Source Project: QrCodeScanner   Source File: DecodeThread.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    Looper.prepare();
    mHandler = new DecodeHandler(mActivity);
    mHandlerInitLatch.countDown();
    Looper.loop();
}
 
Example 30
Source Project: Android-Application-ZJB   Source File: ViewAware.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}