Esempio n. 1
0
  /**
   * 执行后台任务
   *
   * @param bgTask
   * @param timeout 毫秒
   * @param mayInterruptIfRunning 是否打断已存在的任务(true 打断存在的任务并运行新任务,false 不打断已存在的任务,不运行新的任务)
   */
  public void run(final BgTask bgTask, int timeout, boolean mayInterruptIfRunning) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
      throw new RuntimeException("must be called in UI thread!");
    }
    if (bgTask == null) {
      return;
    }

    if (mayInterruptIfRunning) {
      cancel(bgTask);
    }

    Future<?> exists = getFuture(bgTask);
    if (exists == null) {
      final Future<?> future = cachedThreadPool.submit(bgTask);
      BG_TASK_TABLE.put(bgTask, future);
      if (timeout > 0) {
        uiHandler.postDelayed(
            new Runnable() {

              @Override
              public void run() {
                cancel(bgTask);
              }
            },
            timeout);
      }
      CLLog.d(TAG, "added task=" + bgTask);
    } else {
      CLLog.d(TAG, "discard task=" + bgTask);
    }
  }
Esempio n. 2
0
 public boolean cancel(BgTask bgTask) {
   boolean result = false;
   Future<?> f = getFuture(bgTask);
   if (f != null) {
     result = f.cancel(true);
     CLLog.d(TAG, "cancel task: " + bgTask + "; result=" + result);
   }
   return result;
 }