Java 类android.support.annotation.MainThread 实例源码

项目:xlight_android_native    文件:ParticleDevice.java   
/**
 * Subscribes to system events of current device. Events emitted to EventBus listener.
 *
 * @throws ParticleCloudException Failure to subscribe to system events.
 * @see <a href="https://github.com/greenrobot/EventBus">EventBus</a>
 */
@MainThread
public void subscribeToSystemEvents() throws ParticleCloudException {
    try {
        EventBus eventBus = EventBus.getDefault();
        subscriptions.add(subscribeToSystemEvent("spark/status", (eventName, particleEvent) ->
                sendUpdateStatusChange(eventBus, particleEvent.dataPayload)));
        subscriptions.add(subscribeToSystemEvent("spark/flash/status", (eventName, particleEvent) ->
                sendUpdateFlashChange(eventBus, particleEvent.dataPayload)));
        subscriptions.add(subscribeToSystemEvent("spark/device/app-hash", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.APP_HASH_UPDATED), eventBus)));
        subscriptions.add(subscribeToSystemEvent("spark/status/safe-mode", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.SAFE_MODE_UPDATER), eventBus)));
        subscriptions.add(subscribeToSystemEvent("spark/safe-mode-updater/updating", (eventName, particleEvent) ->
                sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
                        ParticleDeviceState.ENTERED_SAFE_MODE), eventBus)));
    } catch (IOException e) {
        log.d("Failed to auto-subscribe to system events");
        throw new ParticleCloudException(e);
    }
}
项目:RIBs    文件:Router.java   
/**
 * Detaches the {@param childFactory} from the current {@link Interactor}. NOTE: No consumers of
 * this API should ever keep a reference to the detached child router, leak canary will enforce
 * that it gets garbage collected.
 *
 * <p>If you need to keep references to previous routers, use {@link RouterNavigator}.
 *
 * @param childRouter the {@link Router} to be detached.
 */
@MainThread
protected void detachChild(Router childRouter) {
  children.remove(childRouter);

  Interactor interactor = childRouter.getInteractor();
  ribRefWatcher.watchDeletedObject(interactor);
  ribRefWatcher.logBreadcrumb(
      "DETACHED", childRouter.getClass().getSimpleName(), this.getClass().getSimpleName());
  if (savedInstanceState != null) {
    Bundle childrenBundles =
        checkNotNull(savedInstanceState.getBundleExtra(KEY_CHILD_ROUTERS));
    childrenBundles.putBundleExtra(childRouter.tag, null);
  }

  childRouter.dispatchDetach();
}
项目:HtmlNative    文件:HNViewTypeManager.java   
@MainThread
static synchronized void registerViewType(HNViewType viewType) {
    if (viewType.getViewClass() != null && viewType.getHTMLType() != null) {
        ViewTypeRelations.registerExtraView(viewType.getViewClass().getName(), viewType
                .getHTMLType());

        StyleHandlerFactory.registerExtraStyleHandler(viewType.getViewClass(), viewType);
        HNRenderer.registerViewFactory(viewType.getViewClass().getName(), viewType);

        Set<String> inheritStyleNames = viewType.onInheritStyleNames();
        if (inheritStyleNames != null && !inheritStyleNames.isEmpty()) {
            for (String style : inheritStyleNames) {
                if (!InheritStylesRegistry.isPreserved(style)) {
                    InheritStylesRegistry.register(style);
                }
            }
        }
    }
}
项目:NewAndroidArchitecture    文件:CountriesViewModel.java   
@MainThread
@NonNull
LiveData<Response<List<Country>>> getMoviesList() {
    if (countriesLiveData == null) {
        countriesLiveData = new MutableLiveData<>();
        countriesRepository.getCountries()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> loadingLiveData.setValue(true))
                .doAfterTerminate(() -> loadingLiveData.setValue(false))
                .subscribe(
                        countries1 -> countriesLiveData.setValue(Response.success(countries1)),
                        throwable -> countriesLiveData.setValue(Response.error(throwable))
                );
    }
    return countriesLiveData;
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Camera to use
 *
 * @param cameraId Camera id (between {@code 0} and
 *                 {@link Camera#getNumberOfCameras()} - {@code 1})
 */
@MainThread
public void setCamera(int cameraId) {
    mInitializeLock.lock();
    try {
        if (mCameraId != cameraId) {
            mCameraId = cameraId;
            if (mInitialized) {
                boolean previewActive = mPreviewActive;
                releaseResources();
                if (previewActive) {
                    initialize();
                }
            }
        }
    } finally {
        mInitializeLock.unlock();
    }
}
项目:vlc-example-streamplayer    文件:AWindow.java   
@MainThread
private void onSurfaceCreated() {
    if (mSurfacesState.get() != SURFACE_STATE_ATTACHED)
        throw new IllegalArgumentException("invalid state");

    final SurfaceHelper videoHelper = mSurfaceHelpers[ID_VIDEO];
    final SurfaceHelper subtitlesHelper = mSurfaceHelpers[ID_SUBTITLES];
    if (videoHelper == null)
        throw new NullPointerException("videoHelper shouldn't be null here");

    if (videoHelper.isReady() && (subtitlesHelper == null || subtitlesHelper.isReady())) {
        mSurfacesState.set(SURFACE_STATE_READY);
        for (IVLCVout.Callback cb : mIVLCVoutCallbacks)
            cb.onSurfacesCreated(this);
        if (mSurfaceCallback != null)
            mSurfaceCallback.onSurfacesCreated(this);
    }
}
项目:RIBs    文件:Router.java   
/**
 * Attaches a child router to this router.
 *
 * @param childRouter the {@link Router} to be attached.
 * @param tag an identifier to namespace saved instance state {@link Bundle} objects.
 */
@MainThread
protected void attachChild(Router<?, ?> childRouter, String tag) {
  for (Router child : children) {
    if (tag.equals(child.tag)) {
      Rib.getConfiguration()
          .handleNonFatalWarning(
              String.format(
                  Locale.getDefault(), "There is already a child router with tag: %s", tag),
              null);
    }
  }

  children.add(childRouter);
  ribRefWatcher.logBreadcrumb(
      "ATTACHED", childRouter.getClass().getSimpleName(), this.getClass().getSimpleName());
  Bundle childBundle = null;
  if (this.savedInstanceState != null) {
    Bundle previousChildren =
        checkNotNull(this.savedInstanceState.getBundleExtra(KEY_CHILD_ROUTERS));
    childBundle = previousChildren.getBundleExtra(tag);
  }

  childRouter.dispatchAttach(childBundle, tag);
}
项目:Fairy    文件:MergeResource.java   
@MainThread
public void initData() {
    executors.getDiskIO().execute(() -> {
        LiveData<LocalType> dbSource = loadFromDb();
        executors.getMainExecutor().execute(() -> {
            result.addSource(dbSource, dbData -> {
                result.removeSource(dbSource);
                if (dbData != null) {
                    ZLog.d("db------" + dbData.toString());
                    setValue(dbData);
                    appendResult(castLocalToNet(dbData));
                }
            });
        });
    });
}
项目:Fairy    文件:GrepFilter.java   
@MainThread
static LiveData<LogcatContent> grepData(LiveData<LogcatContent> rawData, String grep) {
    return Transformations.map(rawData, logcatData -> {
        String content = logcatData.getContent();
        if (GREP_SIGNAL.equals(content)) {
            return logcatData;
        }


        if (content != null) {
            logcatData.setContent(parseHtml2(content,grep));
        }

        return logcatData;

    });
}
项目:vlc-example-streamplayer    文件:Dialog.java   
/**
 * Post an answer
 *
 * @param username valid username (can't be empty)
 * @param password valid password (can be empty)
 * @param store if true, store the credentials
 */
@MainThread
public void postLogin(String username, String password, boolean store) {
    if (mId != 0) {
        nativePostLogin(mId, username, password, store);
        mId = 0;
    }
}
项目:MiniDownloader    文件:MiniDownloader.java   
/**
 * Check task whether valid.
 *
 * @param task
 * @return
 */
@MainThread
private void checkTask(@NonNull Task task) {
    if (task == null
            || task.getUrlStr() == null
            || task.getFilePath() == null
            || task.getListener() == null
            || task.getErrorListener() == null) {
        throw new IllegalArgumentException("task ,urlStr, filePath, listener, errorListener must not be null!");
    }
}
项目:GitHub    文件:PresenterManager.java   
/**
 * Get the  {@link ActivityScopedCache} for the given Activity or <code>null</code> if no {@link
 * ActivityScopedCache} exists for the given Activity
 *
 * @param activity The activity
 * @return The {@link ActivityScopedCache} or null
 * @see #getOrCreateActivityScopedCache(Activity)
 */
@Nullable @MainThread static ActivityScopedCache getActivityScope(@NonNull Activity activity) {
  if (activity == null) {
    throw new NullPointerException("Activity is null");
  }
  String activityId = activityIdMap.get(activity);
  if (activityId == null) {
    return null;
  }

  return activityScopedCacheMap.get(activityId);
}
项目:SampleAppArch    文件:NetworkBoundResource.java   
@MainThread
public NetworkBoundResource(AppExecutors appExecutors) {
  this.appExecutors = appExecutors;
  result.setValue(Resource.loading(null));
  LiveData<ResultType> dbSource = loadFromDb();
  result.addSource(dbSource, data -> {
    result.removeSource(dbSource);
    if (shouldFetch(data)) {
      fetchFromNetwork(dbSource);
    } else {
      result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
    }
  });
}
项目:Android-Code-Demos    文件:SingleLiveEvent.java   
@MainThread
public void observe(LifecycleOwner owner, final Observer<T> observer) {
    if (hasActiveObservers()) {
        Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
    }

    super.observe(owner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t);
            }
        }
    });
}
项目:FitnessHabits    文件:FitnessHabitsApplication.java   
@MainThread
public ParamRepository getParamRepository() {
    if (paramRepository == null) {
        paramRepository = new ParamRepository(getDatabase().paramRecordDao());
    }
    return paramRepository;
}
项目:FitnessHabits    文件:FoodDataRepository.java   
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveFoodEntry(FoodEntry entry) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            foodDataDao.insertOrReplaceFoodEntry(entry);
            return null;
        }
    }.execute();
}
项目:LoadMoreHelper    文件:LoadController.java   
/**
 * Call when 1st page data loaded
 */
@MainThread
private void onPullDataEnd() {
    isPullingData = false;
    if (isDestoryed) {
        return;
    }
    if (paramBuilder.pullView != null) {
        paramBuilder.pullView.doPullEnd();
    }
}
项目:FitnessHabits    文件:DrinkRepository.java   
/**
 * Add value to a id for a certain date
 */
@SuppressLint("StaticFieldLeak")
@MainThread
public void replaceAmountCurrentDay(int categoryId, int amount) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            drinkDataDAO.replaceDrink(categoryId,amount);
            return null;
        }
    }.execute();
}
项目:FitnessHabits    文件:CommentDataRepository.java   
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolComment(CommentData comment) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            comment.setCategory(0);
            commentDataDao.insertOrUpdateComment(comment);
            return null;
        }
    }.execute();
}
项目:vlc-example-streamplayer    文件:MediaBrowser.java   
/**
 * Browse to the specified local path starting with '/'.
 *
 * @param path
 * @param flags see {@link Flag}
 */
@MainThread
public void browse(String path, int flags) {
    final Media media = new Media(mLibVlc, path);
    browse(media, flags);
    media.release();
}
项目:ViewPump    文件:ViewPump.java   
@MainThread
public static ViewPump get() {
    if (INSTANCE == null) {
        INSTANCE = builder().build();
    }
    return INSTANCE;
}
项目:tumbviewer    文件:TransferAction.java   
@MainThread
void transferFinish() {
    if (progressRef != null) {
        DownloadService.DownloadProgress progress = progressRef.get();
        if (progress != null) {
            progress.onDownloadFinish();
        }
    }
}
项目:FitnessHabits    文件:AlcoolRepository.java   
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolDrinkEntry(DrinkEntry entry) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            drinkDataDAO.insetOrReplaceDrinkEntry(entry);
            return null;
        }
    }.execute();
}
项目:FitnessHabits    文件:AlcoolRepository.java   
/**
 * Create a new alcool category
 * @param category (category.type is not required, it will be set anyways)
 */
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveAlcoolDrinkCategory(DrinkCategory category) {
    new AsyncTask<Void,Void,Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            category.setType(0);
            drinkDataDAO.insetOrReplaceDrinkCategory(category);
            return null;
        }
    }.execute();
}
项目:Watermark    文件:PresenterManager.java   
/**
 * Get the  {@link ActivityScopedCache} for the given Activity or <code>null</code> if no {@link
 * ActivityScopedCache} exists for the given Activity
 *
 * @param activity The activity
 * @return The {@link ActivityScopedCache} or null
 * @see #getOrCreateActivityScopedCache(Activity)
 */
@Nullable @MainThread static ActivityScopedCache getActivityScope(@NonNull Activity activity) {
  if (activity == null) {
    throw new NullPointerException("Activity is null");
  }
  String activityId = activityIdMap.get(activity);
  if (activityId == null) {
    return null;
  }

  return activityScopedCacheMap.get(activityId);
}
项目:FitnessHabits    文件:SleepRepository.java   
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveSleepEntry(SleepEntry entry) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            sleepEntryDAO.insertNewEntry(entry);
            return null;
        }
    }.execute();
}
项目:FitnessHabits    文件:ParamManager.java   
@SuppressLint("StaticFieldLeak")
@MainThread
public void saveParamRecord(ParamRecord record) {

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            paramRecordDao.saveParamRecord(record);
            return null;
        }
    }.execute();


}
项目:NSMPlayer-Android    文件:ConnectionUtils.java   
/**
 * 仅当监听到网络连接成功后触发一次,只触发唯一一次
 * @param listener 触发监听器
 */
@MainThread
public static void triggerOnceUponConnected(final OnConnectedListener listener) {
    register(new OnConnectionChangeListener() {
        @Override
        public void onConnectionChange(Intent connectivityIntent) {
            if (isNetworkConnected()) {
                unregister(this);
                listener.onConnected();
            }
        }
    });
}
项目:realm-helpers    文件:RealmComputableLiveData.java   
@MainThread
@Override
public void run() {
    boolean isActive = mLiveData.hasActiveObservers();
    if (mInvalid.compareAndSet(false, true)) {
        if (isActive) {
            realmQueryExecutor.execute(mRefreshRunnable);
        }
    }
}
项目:vlc-example-streamplayer    文件:MediaBrowser.java   
/**
 * Browse to the specified uri.
 *
 * @param uri
 * @param flags see {@link Flag}
 */
@MainThread
public void browse(Uri uri, int flags) {
    final Media media = new Media(mLibVlc, uri);
    browse(media, flags);
    media.release();
}
项目:vlc-example-streamplayer    文件:MediaBrowser.java   
/**
 * Release the MediaBrowser.
 */
@MainThread
public void release() {
    reset();
    if (!mAlive)
        throw new IllegalStateException("MediaBrowser released more than one time");
    mLibVlc.release();
    mAlive = false;
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Formats, decoder to react to ({@link #ALL_FORMATS} by default)
 *
 * @param formats Formats
 * @see BarcodeFormat
 * @see #ALL_FORMATS
 * @see #ONE_DIMENSIONAL_FORMATS
 * @see #TWO_DIMENSIONAL_FORMATS
 */
@MainThread
public void setFormats(@NonNull List<BarcodeFormat> formats) {
    mInitializeLock.lock();
    try {
        mFormats = formats;
        if (mInitialized) {
            mDecoderWrapper.getDecoder().setFormats(formats);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Auto focus mode, {@link AutoFocusMode#SAFE} by default
 *
 * @see AutoFocusMode
 */
@MainThread
public void setAutoFocusMode(@NonNull AutoFocusMode autoFocusMode) {
    mInitializeLock.lock();
    try {
        mAutoFocusMode = autoFocusMode;
        if (mInitialized && mAutoFocusEnabled) {
            setAutoFocusEnabledInternal(true);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Whether to enable or disable flash light if it's supported, {@code false} by default
 */
@MainThread
public void setFlashEnabled(boolean flashEnabled) {
    mInitializeLock.lock();
    try {
        boolean changed = mFlashEnabled != flashEnabled;
        mFlashEnabled = flashEnabled;
        mScannerView.setFlashEnabled(flashEnabled);
        if (mInitialized && mPreviewActive && changed && mDecoderWrapper.isFlashSupported()) {
            setFlashEnabledInternal(flashEnabled);
        }
    } finally {
        mInitializeLock.unlock();
    }
}
项目:EpubReaderAndroid    文件:WebViewHelper.java   
@MainThread
private void executeCommand(String javascriptCommand) {
    javascriptCommand = "javascript:" + javascriptCommand;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript(javascriptCommand, null);
    } else {
        webView.loadUrl(javascriptCommand);
    }
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Release resources, and stop preview if needed; call this method in {@link Activity#onPause()}
 */
@MainThread
public void releaseResources() {
    if (mInitialized) {
        if (mPreviewActive) {
            stopPreview();
        }
        releaseResourcesInternal();
    }
}
项目:Saiy-PS    文件:ClipboardHelper.java   
/**
 * Static method to get the primary clipboard content, or the relevant error string.
 *
 * @param ctx the application context
 * @return the clipboard content or error text
 */
@MainThread
public static Pair<Boolean, String> getClipboardContentPair(@NonNull final Context ctx, @NonNull final SupportedLanguage sl) {

    final String content = getClipboardContent();

    if (UtilsString.notNaked(content)) {
        return new Pair<>(true, content);
    } else {
        return new Pair<>(false, PersonalityResponse.getClipboardDataError(ctx, sl));
    }
}
项目:vlc-example-streamplayer    文件:Dumper.java   
/**
 * Create a Dumper that will download an Uri into a local filesystem path
 * @param uri the Uri to dump
 * @param filepath local filesystem path where to dump the Uri
 * @param listener listener in order to be notified when the dump is finished
 */
@MainThread
public Dumper(Uri uri, String filepath, Listener listener) {
    if (uri == null || filepath == null || listener == null)
        throw new IllegalArgumentException("arguments shouldn't be null");
    mListener = listener;

    ArrayList<String> options = new ArrayList<>(8);
    options.add("--demux");
    options.add("dump2,none");
    options.add("--demuxdump-file");
    options.add(filepath);
    options.add("--no-video");
    options.add("--no-audio");
    options.add("--no-spu");
    options.add("-vv");
    mLibVLC = new LibVLC(null, options);

    final Media media = new Media(mLibVLC, uri);
    mMediaPlayer = new MediaPlayer(media);
    mMediaPlayer.setEventListener(new MediaPlayer.EventListener() {
        @Override
        public void onEvent(MediaPlayer.Event event) {
            switch (event.type) {
                case MediaPlayer.Event.Buffering:
                    mListener.onProgress(event.getBuffering());
                    break;
                case MediaPlayer.Event.EncounteredError:
                case MediaPlayer.Event.EndReached:
                    mListener.onFinish(event.type == MediaPlayer.Event.EndReached);
                    cancel();
                    break;
            }

        }
    });
    media.release();
}
项目:code-scanner    文件:CodeScanner.java   
/**
 * Set auto focus mode, {@link AutoFocusMode#SAFE} by default
 *
 * @see AutoFocusMode
 */
@NonNull
@MainThread
public Builder autoFocusMode(@NonNull AutoFocusMode mode) {
    mAutoFocusMode = mode;
    return this;
}
项目:RxCommand    文件:RxCommand.java   
/**
 * If the receiver is enabled, this method will:
 * <p>
 * 1. Invoke the `func` given at the time of creation.
 * 2. Multicast the returned observable.
 * 3. Send the multicasted observable on {@link #executionObservables()}.
 * 4. Subscribe (connect) to the original observable on the main thread.
 *
 * @param input The input value to pass to the receiver's `func`. This may be null.
 * @return the multicasted observable, after subscription. If the receiver is not
 * enabled, returns a observable that will send an error.
 */
@MainThread
public final Observable<T> execute(@Nullable Object input) {
    boolean enabled = mImmediateEnabled.blockingFirst();
    if (!enabled) {
        return Observable.error(new IllegalStateException("The command is disabled and cannot be executed"));
    }
    try {
        Observable<T> observable = mFunc.apply(input);
        if (observable == null) {
            throw new RuntimeException(String.format("null Observable returned from observable func for value %s", input));
        }

        // This means that `executing` and `enabled` will send updated values before
        // the observable actually starts performing work.
        final ConnectableObservable<T> connection = observable
                .subscribeOn(AndroidSchedulers.mainThread())
                .replay();

        mAddedExecutionObservableSubject.onNext(connection);
        connection.connect();
        return connection;
    } catch (Exception e) {
        e.printStackTrace();
        return Observable.error(e);
    }
}