android.support.annotation.WorkerThread Java Examples

The following examples show how to use android.support.annotation.WorkerThread. 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: PermutationActivity.java    From ncalc with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Command<ArrayList<String>, String> getCommand() {
    return new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {
            IExpr function = F.Binomial;
            if (type == TYPE_PERMUTATION) {
                // ( Gamma(#+1) / Gamm(#2+1) )&
                function = F.Function( //
                          F.Divide(F.Gamma(F.Plus(F.C1,F.Slot1)),F.Gamma(F.Plus(F.C1,F.Slot2))) //
                );
            }
            String fraction = MathEvaluator.getInstance().evaluateWithResultAsTex(
                        EvaluateConfig.loadFromSetting(getApplicationContext())
                                .setEvalMode(EvaluateConfig.FRACTION), function, mInputFormula.getCleanText(), mInputFormula2.getCleanText());

            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #2
Source File: DebugDevice.java    From Walrus with GNU General Public License v3.0 6 votes vote down vote up
@Override
@WorkerThread
public void execute(Context context, final ShouldContinueCallback shouldContinueCallback,
        final ResultSink resultSink) {
    int numSleeps = 0;
    for (; ; ) {
        SystemClock.sleep(100);
        ++numSleeps;

        if (!shouldContinueCallback.shouldContinue()) {
            break;
        }

        if (numSleeps % 10 == 0) {
            try {
                resultSink.onResult((CardData) getCardDataClass()
                        .getMethod("newDebugInstance").invoke(null));
            } catch (IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException e) {
                return;
            }
        }
    }
}
 
Example #3
Source File: Hook12306Impl2.java    From 12306XposedPlugin with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发起网络请求
 *
 * @param request RpcRequest
 * @param <T>     T
 * @return response
 */
@WorkerThread
private <T> T rpcWithBaseDTO(RpcRequest<T> request) {
    try {
        JSONObject requestData = request.requestData();
        JSONObject baseDTO = createBaseDTO();
        if (requestData.has("_requestBody")) {
            requestData.optJSONObject("_requestBody").put("baseDTO", baseDTO);
        } else {
            requestData.put("baseDTO", baseDTO);
        }
        JSONArray jsonArray = new JSONArray();
        jsonArray.put(requestData);
        Object result = rpcCallMethod.invoke(null, request.operationType(),
                jsonArray.toString(), "", true, null, null, false, null, 0, "", request.isHttpGet(),
                request.signType());
        String response = (String) getResponseMethod.invoke(result);
        return request.onResponse(response);
    } catch (Exception e) {
        Log.e(TAG, "rpcWithBaseDTO", e);
    }
    return null;
}
 
Example #4
Source File: QueueTaskRunner.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
@WorkerThread
protected void execNextTask() {
    if (mCanceled) return;
    if (getAllTask().isEmpty()) {
        onTasksComplete(mSuccessTask, mFailedTask);
    } else {
        Task task = getSingleTask();
        if (task != null && !task.isComplete()) {
            if (execTask(task)) {
                mSuccessTask.add(task);
            } else {
                mFailedTask.add(task);
            }
        }
        execNextTask();
    }
}
 
Example #5
Source File: FetchDataUseCase.java    From thread-poster with Apache License 2.0 6 votes vote down vote up
@WorkerThread
private void fetchDataSync() {
    try {
        final String data = mFakeDataFetcher.getData();
        mUiThreadPoster.post(new Runnable() { // notify listeners on UI thread
            @Override
            public void run() {
                notifySuccess(data);
            }
        });
    } catch (FakeDataFetcher.DataFetchException e) {
        mUiThreadPoster.post(new Runnable() { // notify listeners on UI thread
            @Override
            public void run() {
                notifyFailure();
            }
        });
    }

}
 
Example #6
Source File: OktaManagementActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@WorkerThread
private void handleCodeExchangeResponse(
        @Nullable TokenResponse tokenResponse,
        @Nullable AuthorizationException authException) {

    mStateManager.updateAfterTokenResponse(tokenResponse, authException);
    if (!mStateManager.getCurrent().isAuthorized()) {
        final String message = "Authorization Code exchange failed"
                + ((authException != null) ? authException.error : "");
        Log.e(TAG, message);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendPendingIntent(mCancelIntent);
            }
        });
    } else {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendPendingIntent(mCompleteIntent);
            }
        });
    }
}
 
Example #7
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@WorkerThread
private void doAuth(PendingIntent completionIntent,
                    PendingIntent cancelIntent,
                    AuthenticationPayload payload) {
    Log.d(TAG, "Starting authorization flow");
    if (payload != null) {
        createAuthRequest(payload);
    }
    AuthorizationRequest request = mAuthRequest.get();
    warmUpBrowser(request.toUri());
    createAuthorizationServiceIfNeeded().performAuthorizationRequest(
            request,
            completionIntent,
            cancelIntent,
            mAuthIntent.get());
}
 
Example #8
Source File: PasscodeViewPinAuthenticator.java    From PasscodeView with Apache License 2.0 6 votes vote down vote up
@WorkerThread
@Override
public PinAuthenticationState isValidPin(@NonNull final ArrayList<Integer> pinDigits) {
    //Check if the size of the entered pin matches the correct pin
    if (!isValidPinLength(pinDigits.size())) return PinAuthenticationState.NEED_MORE_DIGIT;

    //This calculations won't take much time.
    //We are not blocking the UI.
    for (int i = 0; i < mCorrectPin.length; i++) {
        if (mCorrectPin[i] != pinDigits.get(i)) {

            //Digit did not matched
            //Wrong PIN
            return PinAuthenticationState.FAIL;
        }
    }

    //PIN is correct
    return PinAuthenticationState.SUCCESS;
}
 
Example #9
Source File: MainActivity.java    From connectivity-samples with Apache License 2.0 6 votes vote down vote up
/** {@see ConnectionsActivity#onReceive(Endpoint, Payload)} */
@Override
protected void onReceive(Endpoint endpoint, Payload payload) {
  if (payload.getType() == Payload.Type.STREAM) {
    AudioPlayer player =
        new AudioPlayer(payload.asStream().asInputStream()) {
          @WorkerThread
          @Override
          protected void onFinish() {
            final AudioPlayer audioPlayer = this;
            post(
                new Runnable() {
                  @UiThread
                  @Override
                  public void run() {
                    mAudioPlayers.remove(audioPlayer);
                  }
                });
          }
        };
    mAudioPlayers.add(player);
    player.start();
  }
}
 
Example #10
Source File: FakeDataFetcher.java    From thread-poster with Apache License 2.0 6 votes vote down vote up
@WorkerThread
public String getData() throws DataFetchException {

    // simulate 2 seconds worth of work
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    mIsError = !mIsError; // error response every other time

    if (mIsError) {
        throw new DataFetchException();
    } else {
        return "fake data";
    }

}
 
Example #11
Source File: FactorExpressionActivity.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Command<ArrayList<String>, String> getCommand() {
    return new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {

            EvaluateConfig config = EvaluateConfig.loadFromSetting(getApplicationContext());
            String fraction = MathEvaluator.getInstance().factorPolynomial(input,
                    config.setEvalMode(EvaluateConfig.FRACTION));
            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #12
Source File: Dispatcher.java    From Pretty-Zhihu with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void performAddTask(int questionId) {
    Question question = mPrettyRepository.getQuestion(questionId);
    if (question != null) {
        for (int offset = 0; offset < question.getAnswerCount(); offset += 10) {
            UrlHunter hunter = new UrlHunter(questionId, 10, offset, mApi, this);
            mTaskArray.add(hunter);
            hunter.setFuture(mExecutor.submit(hunter));
            Log.d("Hans", "submit: " + hunter);
        }
    }
}
 
Example #13
Source File: Proxmark3Device.java    From Walrus with GNU General Public License v3.0 5 votes vote down vote up
@Override
@WorkerThread
public void execute(Context context, ShouldContinueCallback shouldContinueCallback)
        throws IOException {
    if (!isWrite()) {
        throw new RuntimeException("Can't emulate");
    }

    Proxmark3Device proxmark3Device = (Proxmark3Device) getCardDeviceOrThrow();

    if (!proxmark3Device.tryAcquireAndSetStatus(context.getString(R.string.writing))) {
        throw new IOException(context.getString(R.string.device_busy));
    }

    try {
        HIDCardData hidCardData = (HIDCardData) getCardData();

        if (!proxmark3Device.sendThenReceiveCommands(
                new Proxmark3Command(
                        Proxmark3Command.HID_CLONE_TAG,
                        new long[]{
                                hidCardData.data.shiftRight(64).intValue(),
                                hidCardData.data.shiftRight(32).intValue(),
                                hidCardData.data.intValue()
                        },
                        new byte[]{hidCardData.data.bitLength() > 44 ? (byte) 1 : 0}),
                new WatchdogReceiveSink<Proxmark3Command, Boolean>(DEFAULT_TIMEOUT) {
                    @Override
                    public Boolean onReceived(Proxmark3Command in) {
                        return in.op == Proxmark3Command.DEBUG_PRINT_STRING
                                && in.dataAsString().equals("DONE!") ? true : null;
                    }
                })) {
            throw new IOException(context.getString(R.string.write_card_timeout));
        }
    } finally {
        proxmark3Device.releaseAndSetStatus();
    }
}
 
Example #14
Source File: FactorPrimeActivity.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Command<ArrayList<String>, String> getCommand() {
    return new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {
            String fraction = MathEvaluator.getInstance().factorPrime(input);
            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #15
Source File: HistoryDatabase.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
private synchronized void addHistoryItem(@NonNull HistoryItem item) {
    ContentValues values = new ContentValues();
    values.put(KEY_URL, item.getUrl());
    values.put(KEY_TITLE, item.getTitle());
    values.put(KEY_TIME_VISITED, System.currentTimeMillis());
    lazyDatabase().insert(TABLE_HISTORY, null, values);
}
 
Example #16
Source File: SelfAware.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
@WorkerThread
private boolean waitIBM() {
    if (DEBUG) {
        MyLog.v(CLS_NAME, "waitIBM");
    }

    if (recogMic == null || recogIBM == null) {

        int sleepCount = 0;

        while (sleepCount < WARM_UP_LOOP) {
            try {
                Thread.sleep(WARM_UP_SLEEP);
            } catch (final InterruptedException e) {
                if (DEBUG) {
                    MyLog.w(CLS_NAME, "InterruptedException");
                    e.printStackTrace();
                }
            }

            if (recogMic == null || recogIBM == null) {
                if (DEBUG) {
                    MyLog.v(CLS_NAME, "recogIBM null: " + sleepCount);
                }
                sleepCount++;
            } else {
                break;
            }
        }
    }

    return recogMic == null && recogIBM != null;
}
 
Example #17
Source File: AaidClient.java    From tenor-android-core with Apache License 2.0 5 votes vote down vote up
@WorkerThread
public static void init(@NonNull Context app, @Nullable IAaidListener listener) {
    if (isOnMainThread()) {
        throw new IllegalStateException("Cannot be called from the main thread");
    }

    final AaidInfo info = getAdvertisingId(app);
    switch (info.getState()) {
        case AaidInfo.AAID_GRANTED:
            AbstractSessionUtils.setAndroidAdvertiseId(app, info.getId());
            break;
        case AaidInfo.AAID_DENIED:
            // remove the stored AAID if user explicitly chose to opt out of ad personalization
            AbstractSessionUtils.setAndroidAdvertiseId(app, StringConstant.EMPTY);
            break;
        default:
            // do nothing
            break;
    }

    AbstractLogUtils.e(app, "AAID: " + info.getId()
            + ", Opt out: " + info.isLimitAdTrackingEnabled()
            + ", state: " + info.getState());

    if (listener != null) {
        if (info.getState() == AaidInfo.AAID_GRANTED) {
            listener.success(info.getId());
        } else {
            listener.failure(info.getState());
        }
    }
}
 
Example #18
Source File: FrameSeqDecoder.java    From APNG4Android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private long step() {
    this.frameIndex++;
    if (this.frameIndex >= this.getFrameCount()) {
        this.frameIndex = 0;
        this.playCount++;
    }
    Frame frame = getFrame(this.frameIndex);
    if (frame == null) {
        return 0;
    }
    renderFrame(frame);
    return frame.frameDuration;
}
 
Example #19
Source File: SurfaceWaveView2.java    From AndroidDigIn with Apache License 2.0 5 votes vote down vote up
/**
 * 算Y轴坐标
 *
 * @param mapX
 * @param offset
 * @return
 */
//y = √(2π) exp(-x^2/2)
@WorkerThread
private double calcValue(float mapX, float offset, int factor) {
    offset %= 5;
    double result = Math.sqrt(2 * Math.PI) * Math.exp(-Math.pow(mapX - offset,2)/2);
    return result * offset/2;
}
 
Example #20
Source File: SelfAware.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
@WorkerThread
private boolean waitMicrosoft() {
    if (DEBUG) {
        MyLog.v(CLS_NAME, "waitMicrosoft");
    }

    if (recogOxford == null) {

        int sleepCount = 0;

        while (sleepCount < WARM_UP_LOOP) {
            try {
                Thread.sleep(WARM_UP_SLEEP);
            } catch (final InterruptedException e) {
                if (DEBUG) {
                    MyLog.w(CLS_NAME, "InterruptedException");
                    e.printStackTrace();
                }
            }

            if (recogOxford == null) {
                if (DEBUG) {
                    MyLog.v(CLS_NAME, "recogOxford null: " + sleepCount);
                }
                sleepCount++;
            } else {
                break;
            }
        }
    }

    return recogOxford != null;
}
 
Example #21
Source File: Dispatcher.java    From Pretty-Zhihu with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void performRemoveTask(int questionId) {
    Iterator<UrlHunter> iterator = mTaskArray.iterator();
    while (iterator.hasNext()) {
        UrlHunter h = iterator.next();
        if (h.getQuestionId() == questionId && h.cancel()) {
            iterator.remove();
        }
    }
}
 
Example #22
Source File: ModuleActivity.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Command<ArrayList<String>, String> getCommand() {
    return new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {
            String fraction = MathEvaluator.getInstance().evaluateWithResultAsTex(input,
                    EvaluateConfig.loadFromSetting(getApplicationContext())
                            .setEvalMode(EvaluateConfig.FRACTION));
            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #23
Source File: BookmarkDatabase.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Lazily initializes the database
 * field when called.
 *
 * @return a non null writable database.
 */
@WorkerThread
@NonNull
private synchronized SQLiteDatabase lazyDatabase() {
    if (mDatabase == null || !mDatabase.isOpen()) {
        mDatabase = getWritableDatabase();
    }

    return mDatabase;
}
 
Example #24
Source File: IdeActivity.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
@Override
public Command<ArrayList<String>, String> getCommand() {
    return new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {
            EvaluateConfig config = EvaluateConfig.loadFromSetting(getApplicationContext());
            String fraction = MathEvaluator.getInstance().evaluateWithResultAsTex(input,
                    config.setEvalMode(EvaluateConfig.FRACTION));
            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #25
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void doAuth(String sessionToken, OktaNativeAuthListener listener) {
    Log.d(TAG, "Starting native authorization flow");
    SessionAuthenticationService
            sessionAuthenticationService = new SessionAuthenticationService(
            mAuthStateManager,
            createAuthorizationServiceIfNeeded(),
            mConnectionBuilder);
    sessionAuthenticationService.performAuthorizationRequest(
            mAuthRequest.get(),
            sessionToken,
            listener);
}
 
Example #26
Source File: CalculateThread.java    From ncalc with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void execute(String expr, final EvaluateConfig config) {
    Command<ArrayList<String>, String> task = new Command<ArrayList<String>, String>() {
        @WorkerThread
        @Override
        public ArrayList<String> execute(String input) {
            return Lists.newArrayList(MathEvaluator.getInstance().evaluateWithResultAsTex(input, config));
        }
    };

    Thread thread = new Thread(task, resultCallback);
    thread.executeOnExecutor(EXECUTOR, expr);
}
 
Example #27
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void doInit(final Context context, final ConnectionBuilder connectionBuilder,
                    final OktaAuthListener listener) {
    mInitializationListener.set(listener);
    recreateAuthorizationService(context);

    if (mConfiguration.hasConfigurationChanged()) {
        // discard any existing authorization state due to the change of configuration
        Log.i(TAG, "Configuration change detected, discarding old state");
        mAuthStateManager.replace(new AuthState());
        if (!mConfiguration.isValid()) {
            Log.e(TAG, "Configuration was invalid: " + mConfiguration.getConfigurationError());
            listener.onTokenFailure(
                    AuthorizationException.GeneralErrors.INVALID_DISCOVERY_DOCUMENT);
            return;
        }
        mConfiguration.acceptConfiguration();
    }


    if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() != null) {
        // configuration is already created, skip to client initialization
        Log.i(TAG, "auth config already established");
        initializeClient();
        return;
    }

    Log.i(TAG, "Retrieving OpenID discovery doc");
    AuthorizationServiceConfiguration.fetchFromUrl(
            mConfiguration.getDiscoveryUri(),
            new AuthorizationServiceConfiguration.RetrieveConfigurationCallback() {
                @Override
                public void onFetchConfigurationCompleted(
                        @Nullable AuthorizationServiceConfiguration serviceConfiguration,
                        @Nullable AuthorizationException ex) {
                    handleConfigurationRetrievalResult(serviceConfiguration, ex);
                }
            },
            connectionBuilder);
}
 
Example #28
Source File: HistoryDatabase.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
@NonNull
synchronized List<HistoryItem> getAllHistoryItems() {
    List<HistoryItem> itemList = new ArrayList<>();

    Cursor cursor = lazyDatabase().query(TABLE_HISTORY, null, null, null, null, null, KEY_TIME_VISITED + " DESC");

    while (cursor.moveToNext()) {
        itemList.add(fromCursor(cursor));
    }

    cursor.close();

    return itemList;
}
 
Example #29
Source File: SampleClipApi.java    From leanback-homescreen-channels with Apache License 2.0 5 votes vote down vote up
@WorkerThread
static Clip getClipByIdBlocking(String clipId) {
    populatePlaylists();
    for (Playlist playlist : mPlaylists) {
        List<Clip> clips = playlist.getClips();
        for (Clip candidateClip : clips) {
            if (TextUtils.equals(candidateClip.getClipId(), clipId)) {
                return candidateClip;
            }
        }
    }
    return null;
}
 
Example #30
Source File: ProWebView.java    From prowebview with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void loadFromAssets(Context context) throws IOException {
    InputStream stream = context.getAssets().open(AD_HOSTS_FILE);
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    String line;
    while ((line = reader.readLine()) != null) {
        AD_HOSTS.add(line);
    }
    reader.close();
    stream.close();
}