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 Project: connectivity-samples   Author: android   File: MainActivity.java    License: 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 #2
Source Project: 12306XposedPlugin   Author: pengwei1024   File: Hook12306Impl2.java    License: 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 #3
Source Project: thread-poster   Author: techyourchance   File: FetchDataUseCase.java    License: 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 #4
Source Project: okta-sdk-appauth-android   Author: okta   File: OktaAppAuth.java    License: 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 #5
Source Project: ncalc   Author: tranleduy2000   File: PermutationActivity.java    License: 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 #6
Source Project: VideoOS-Android-SDK   Author: VideoOS   File: QueueTaskRunner.java    License: 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 #7
Source Project: PasscodeView   Author: kevalpatel2106   File: PasscodeViewPinAuthenticator.java    License: 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 #8
Source Project: thread-poster   Author: techyourchance   File: FakeDataFetcher.java    License: 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 #9
Source Project: Walrus   Author: TeamWalrus   File: DebugDevice.java    License: 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 #10
Source Project: okta-sdk-appauth-android   Author: okta   File: OktaManagementActivity.java    License: 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 #11
Source Project: connectivity-samples   Author: android   File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
/** {@see ConnectionsActivity#onReceive(Endpoint, Payload)} */
@Override
protected void onReceive(Endpoint endpoint, Payload payload) {
  if (payload.getType() == Payload.Type.STREAM) {
    if (mAudioPlayer != null) {
      mAudioPlayer.stop();
      mAudioPlayer = null;
    }

    AudioPlayer player =
        new AudioPlayer(payload.asStream().asInputStream()) {
          @WorkerThread
          @Override
          protected void onFinish() {
            runOnUiThread(
                new Runnable() {
                  @UiThread
                  @Override
                  public void run() {
                    mAudioPlayer = null;
                  }
                });
          }
        };
    mAudioPlayer = player;
    player.start();
  }
}
 
Example #12
Source Project: ncalc   Author: tranleduy2000   File: LimitActivity.java    License: 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().evaluateWithResultAsTex(input,
                    config.setEvalMode(EvaluateConfig.FRACTION));

            return Lists.newArrayList(fraction);
        }
    };
}
 
Example #13
Source Project: APNG4Android   Author: penfeizhou   File: FrameSeqDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void innerStart() {
    paused.compareAndSet(true, false);

    final long start = System.currentTimeMillis();
    try {
        if (frames.size() == 0) {
            try {
                if (mReader == null) {
                    mReader = getReader(mLoader.obtain());
                } else {
                    mReader.reset();
                }
                initCanvasBounds(read(mReader));
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    } finally {
        Log.i(TAG, debugInfo() + " Set state to RUNNING,cost " + (System.currentTimeMillis() - start));
        mState = State.RUNNING;
    }
    if (getNumPlays() == 0 || !finished) {
        this.frameIndex = -1;
        renderTask.run();
        renderListener.onStart();
    } else {
        Log.i(TAG, debugInfo() + " No need to started");
    }
}
 
Example #14
Source Project: APNG4Android   Author: penfeizhou   File: FrameSeqDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void innerStop() {
    workerHandler.removeCallbacks(renderTask);
    frames.clear();
    for (Bitmap bitmap : cacheBitmaps) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }
    cacheBitmaps.clear();
    if (frameBuffer != null) {
        frameBuffer = null;
    }
    cachedCanvas.clear();
    try {
        if (mReader != null) {
            mReader.close();
            mReader = null;
        }
        if (mWriter != null) {
            mWriter.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    release();
    if (DEBUG) {
        Log.i(TAG, debugInfo() + " release and Set state to IDLE");
    }
    mState = State.IDLE;
    renderListener.onEnd();
}
 
Example #15
Source Project: APNG4Android   Author: penfeizhou   File: FrameSeqDecoder.java    License: 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 #16
Source Project: Xndroid   Author: XndroidDev   File: HistoryDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@WorkerThread
@Nullable
synchronized String getHistoryItem(@NonNull String url) {
    Cursor cursor = lazyDatabase().query(TABLE_HISTORY, new String[]{KEY_ID, KEY_URL, KEY_TITLE},
        KEY_URL + " = ?", new String[]{url}, null, null, null, "1");
    String m = null;
    if (cursor != null) {
        cursor.moveToFirst();
        m = cursor.getString(0);

        cursor.close();
    }
    return m;
}
 
Example #17
Source Project: 1Rramp-Android   Author: hapramp   File: SteemVoterFetcher.java    License: MIT License 5 votes vote down vote up
@WorkerThread
public void requestVoters(final String authorOfPost, final String permlink) {
  final String rtag = "voters_" + authorOfPost + permlink;
  currentRequestTag = rtag;
  final String reqBody = "{\"jsonrpc\":\"2.0\", \"method\":\"condenser_api.get_active_votes\"," +
    " \"params\":[\""+authorOfPost+"\"," +
    " \""+permlink+"\"]," +
    " \"id\":1}";
  StringRequest newBlogRequest = new StringRequest(Request.Method.POST, URLS.STEEMIT_API_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
      parseVoters(response, rtag);
    }
  }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
      returnErrorCallback();
    }
  }) {
    @Override
    public byte[] getBody() {
      try {
        return reqBody.getBytes("utf-8");
      }
      catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      return null;
    }
  };
  VolleyUtils.getInstance().addToRequestQueue(newBlogRequest, currentRequestTag, context);
}
 
Example #18
Source Project: 1Rramp-Android   Author: hapramp   File: SteemReplyFetcher.java    License: MIT License 5 votes vote down vote up
@WorkerThread
public void requestReplyForPost(final String authorOfPost, final String permlink) {
  final String rtag = "reply_" + authorOfPost + permlink;
  currentRequestTag = rtag;
  final String reqBody = "{\"jsonrpc\":\"2.0\", \"method\":\"condenser_api.get_content_replies\"," +
    " \"params\":[\"" + authorOfPost + "\", \"" + permlink + "\"], \"id\":1}";
  StringRequest newBlogRequest = new StringRequest(Request.Method.POST, URLS.STEEMIT_API_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
      parseReplies(response, rtag);
    }
  }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
      returnErrorCallback();
    }
  }) {
    @Override
    public byte[] getBody() {
      try {
        return reqBody.getBytes("utf-8");
      }
      catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      return null;
    }
  };
  VolleyUtils.getInstance().addToRequestQueue(newBlogRequest, currentRequestTag, context);
}
 
Example #19
Source Project: tenor-android-core   Author: Tenor-Inc   File: AaidClient.java    License: 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 #20
Source Project: Saiy-PS   Author: brandall76   File: SelfAware.java    License: 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 #21
Source Project: Saiy-PS   Author: brandall76   File: SelfAware.java    License: 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 #22
Source Project: Xndroid   Author: XndroidDev   File: HistoryDatabase.java    License: 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 #23
Source Project: ncalc   Author: tranleduy2000   File: FactorPrimeActivity.java    License: 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 #24
Source Project: Walrus   Author: TeamWalrus   File: Proxmark3Device.java    License: 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 #25
Source Project: ncalc   Author: tranleduy2000   File: FactorExpressionActivity.java    License: 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 #26
Source Project: AndroidDigIn   Author: halohoop   File: SurfaceWaveView2.java    License: 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 #27
Source Project: Pretty-Zhihu   Author: shensky711   File: Dispatcher.java    License: 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 #28
Source Project: Pretty-Zhihu   Author: shensky711   File: Dispatcher.java    License: 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 #29
Source Project: ncalc   Author: tranleduy2000   File: ModuleActivity.java    License: 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 #30
Source Project: Xndroid   Author: XndroidDev   File: BookmarkDatabase.java    License: 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;
}