类android.os.Looper源码实例Demo

下面列出了怎么用android.os.Looper的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: zulip-android   文件: UploadProgressRequest.java
@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();
    }
}
 
源代码2 项目: litho   文件: ComponentTreeHolderTest.java
@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"));
}
 
源代码3 项目: android-skeleton-project   文件: Settings.java
/**
 * 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);
                    }
                });
            }
        }
    });
}
 
源代码4 项目: EasyBluetoothFrame   文件: BleManager.java
@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();
        }

    }
 
/**
 * 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();
}
 
源代码6 项目: MiBandDecompiled   文件: d.java
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();
    }
}
 
源代码7 项目: mapwize-ui-android   文件: MapPresenter.java
@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);
            });
        }
    });
}
 
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;
    }
}
 
源代码9 项目: Abelana-Android   文件: Settings.java
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);
                    }
                });
            }
        }
    });
}
 
源代码10 项目: AndroidWear-OpenWear   文件: EventCallback.java
@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);
            }
        });

}
 
源代码11 项目: TelePlus-Android   文件: AdsMediaSource.java
/**
 * 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());
}
 
源代码12 项目: WiFiFlutter   文件: WifiIotPlugin.java
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();
}
 
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);
              });
    }
  }
 
源代码14 项目: MediaSDK   文件: SimpleExoPlayer.java
/**
 * 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;
}
 
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());
}
 
源代码16 项目: MixPush   文件: MixPushHandler.java
@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);
    }
}
 
源代码17 项目: QNotified   文件: RevokeMsgHook.java
@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);
                }
            });
        }
    }
}
 
源代码18 项目: Tok-Android   文件: DispatchQueue.java
@Override
public void run() {
    super.run();
    Looper.prepare();
    if (handler == null) {
        handler = new QueueHandler(this);
    }
    syncLatch.countDown();
    Looper.loop();
}
 
源代码19 项目: SlidingTabWithColorIcons   文件: ChangeColorItem.java
private void invalidateView() {
    if (Looper.getMainLooper() == Looper.myLooper()) {
        invalidate();
    } else {
        postInvalidate();
    }
}
 
源代码20 项目: arcusandroid   文件: StateMachine.java
/**
 * 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);
                }
                }
        });
    }
}
 
源代码21 项目: RairDemo   文件: MainThreadTasksHolder.java
@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);
            }
        });
    }
}
 
源代码22 项目: SugarAdapter   文件: SugarAdapter.java
@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);
        }
    }
}
 
@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();
    }
}
 
源代码24 项目: arcusandroid   文件: AlarmIncidentPresenter.java
@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);
                }
            }
        });
    }
}
 
源代码25 项目: MousePaint   文件: BaseHttp.java
protected BaseHttp()
{
    mGson = new Gson();
    mOkHttpClient = new OkHttpClient();
    mHandler = new Handler(Looper.getMainLooper());
    //cookie enabled
    mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
}
 
源代码26 项目: QuickNews   文件: NewsUtil.java
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();
  }
 
/**
 *
 * @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;
}
 
/**
 * 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);
    }
}
 
源代码29 项目: QrCodeScanner   文件: DecodeThread.java
@Override
public void run() {
    Looper.prepare();
    mHandler = new DecodeHandler(mActivity);
    mHandlerInitLatch.countDown();
    Looper.loop();
}
 
源代码30 项目: Android-Application-ZJB   文件: ViewAware.java
@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;
}
 
 类所在包
 同包方法