/** Gently killing AsyncTask */
 public static void stopTaskGracefully(AsyncTask<?, ?, ?> t) {
   if (t != null) {
     if (t.getStatus() == Status.RUNNING) {
       t.cancel(true);
     }
   }
 }
    void calculateProgress(
        final String name,
        final long fileBytes,
        final int id,
        final long size,
        final boolean move) {
      if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING)
        asyncTask.cancel(true);
      asyncTask =
          new AsyncTask<Void, Void, Void>() {
            int p1, p2;

            @Override
            protected Void doInBackground(Void... voids) {
              p1 = (int) ((copiedBytes / (float) totalBytes) * 100);
              p2 = (int) ((fileBytes / (float) size) * 100);
              lastpercent = (int) copiedBytes;
              return null;
            }

            @Override
            public void onPostExecute(Void v) {
              publishResults(name, p1, p2, id, totalBytes, copiedBytes, false, move);
            }
          }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
 private void startCameraSource() {
   try {
     mPreview.start(mCameraSource, mGraphicOverlay);
     boolean startAsyncTask = sp.getBoolean("vision_continuous_test", false);
     if (!startAsyncTask) {
       if (asyncTask != null) {
         // Check if there is an Async Task running. If so, cancel it
         switch (asyncTask.getStatus()) {
           case RUNNING:
             asyncTask.cancel(true);
             asyncTask = null;
             break;
           case PENDING:
             asyncTask.cancel(true);
             asyncTask = null;
             break;
           case FINISHED:
             asyncTask = null;
             break;
         }
       }
       asyncTask =
           new AsyncTaskWaitForBarcode(
                   this, Integer.parseInt(sp.getString("vision_sleep", "1500")))
               .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
     }
   } catch (IOException e) {
     mCameraSource.release();
     mCameraSource = null;
   }
 }
 @Override
 public void onDismiss(DialogInterface dialog) {
   if (loadApps != null && loadApps.getStatus() == AsyncTask.Status.RUNNING) {
     loadApps.cancel(true);
     loadApps = null;
   }
 }
 private synchronized void cancelOutstandingTask() {
   if (outstandingTask != null) {
     if (outstandingTask.getStatus() != AsyncTask.Status.FINISHED) {
       outstandingTask.cancel(true);
     }
     outstandingTask = null;
   }
 }
 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {
   if (operationTask == null || operationTask.getStatus() == Status.FINISHED) {
     menu.setGroupVisible(0, true);
   } else {
     menu.setGroupVisible(0, false);
   }
   return true;
 }
  @Override
  protected void onStop() {
    Log.d(TAG, "onStop");
    super.onStop();

    if (mLoadPictureTask != null && mLoadPictureTask.getStatus() != AsyncTask.Status.FINISHED) {
      mLoadPictureTask.cancel(false);
    }

    unregisterReceiver(mReceiver);
  }
 private void killPendingTasks() {
   for (final AsyncTask aTask : pendingTasks) {
     if (aTask == null) {
       continue;
     }
     if (aTask.getStatus() != AsyncTask.Status.FINISHED) {
       aTask.cancel(true);
     }
   }
   pendingTasks.clear();
   theAdapter.clearPredictions();
 }
Esempio n. 9
0
  public void playComputerMove(final boolean isFirstMoveOfGame) {
    if (mMinMaxTask == null || mMinMaxTask.getStatus() != AsyncTask.Status.RUNNING) {
      mMinMaxTask =
          new AsyncTask<Void, Void, MinMaxResult>() {
            @Override
            protected MinMaxResult doInBackground(Void... params) {
              // If we are playing the first move of the game, all moves on the board are
              // equally good. We will randomly pick a row and a column and play that and
              // save all the time calculating the minmax results.
              if (isFirstMoveOfGame) {
                Random rand = new Random();
                int row = rand.nextInt(3);
                int column = rand.nextInt(3);

                return new MinMaxResult(new Move(row, column, mComputerPlayer), 0);
              } else {
                GameBoard gameboard = new GameBoard(mGameBoard);
                return bestMinMaxMove(gameboard, 0, mComputerPlayer);
              }
            }

            @Override
            protected void onPostExecute(MinMaxResult result) {
              Move move = result.move;
              mGameBoard.playMove(move);

              if (mGameListener != null) {
                mGameListener.onBoardUpdated(mGameBoard.getBoard());
              }

              if (mGameBoard.isGameOver()) {
                if (mGameListener != null) {
                  Player winner = mGameBoard.getWinner(true);
                  mGameListener.onGameOver(winner, mGameBoard.getWinningBoard());
                }
              } else {
                updateCurrentPlayer(mHumanPlayer);
              }
            }
          };
      mMinMaxTask.execute();
    }
  }
  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mCameraSource != null) mCameraSource.release(); // release the resources

    if (asyncTask != null) {
      // Check if there is an Async Task running. If so, cancel it
      switch (asyncTask.getStatus()) {
        case RUNNING:
          asyncTask.cancel(true);
          asyncTask = null;
          break;
        case PENDING:
          asyncTask.cancel(true);
          asyncTask = null;
          break;
        case FINISHED:
          asyncTask = null;
          break;
      }
    }
  }
Esempio n. 11
0
 /**
  * 是否正在加载中
  *
  * @return
  */
 public boolean isLoading() {
   return asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED;
 }
Esempio n. 12
0
 /** 做销毁操作,比如关闭正在加载数据的异步线程等 */
 public void destory() {
   if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
     asyncTask.cancel(true);
     asyncTask = null;
   }
 }
Esempio n. 13
0
  /** 加载更多,开启异步线程,并且显示加载中的界面,当数据加载完成自动还原成加载完成的布局,并且刷新列表数据 */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public void loadMore() {
    if (isLoading()) {
      return;
    }
    if (dataAdapter.isEmpty()) {
      refresh();
      return;
    }

    if (dataAdapter == null || dataSource == null) {
      if (refreshView != null) {
        refreshView.showRefreshComplete();
      }
      return;
    }
    if (asyncTask != null && asyncTask.getStatus() != AsyncTask.Status.FINISHED) {
      asyncTask.cancel(true);
    }
    asyncTask =
        new AsyncTask<Void, Void, DATA>() {
          protected void onPreExecute() {
            onStateChangeListener.onStartLoadMore(dataAdapter);
            if (mLoadMoreView != null) {
              mLoadMoreView.showLoading();
            }
          }

          @Override
          protected DATA doInBackground(Void... params) {
            try {
              return dataSource.loadMore();
            } catch (Exception e) {
              e.printStackTrace();
            }
            return null;
          }

          protected void onPostExecute(DATA result) {
            if (result == null) {
              mLoadView.tipFail();
              if (mLoadMoreView != null) {
                mLoadMoreView.showFail();
              }
            } else {
              dataAdapter.notifyDataChanged(result, false);
              if (dataAdapter.isEmpty()) {
                mLoadView.showEmpty();
              } else {
                mLoadView.restore();
              }
              hasMoreData = dataSource.hasMore();
              if (mLoadMoreView != null) {
                if (hasMoreData) {
                  mLoadMoreView.showNormal();
                } else {
                  mLoadMoreView.showNomore();
                }
              }
            }
            onStateChangeListener.onEndLoadMore(dataAdapter, result);
          };
        };
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
      asyncTask.execute();
    }
  }
Esempio n. 14
0
 @Override
 public void onStartWithNative() {
   super.onStartWithNative();
   if (mCleanupTask.getStatus() == AsyncTask.Status.PENDING) mCleanupTask.execute();
 }
Esempio n. 15
0
  private void requestUpdateAvatar() {
    final File file = new File(filePath);
    if (file.exists() && file.canRead() && file.isFile()) {
      if (file.length() > Values.FILE_SIZE_LIMIT) {
        hideLoading();
        UIUtils.alert(context, getString(R.string.file_size_must_be_less_than_size_limit, "30MB"));
        return;
      }
    } else {
      hideLoading();
      UIUtils.alert(context, R.string.file_not_found);
      return;
    }
    //        Toast.makeText(context, "requestUpdateAvatar() called!", Toast.LENGTH_SHORT).show();
    try {
      final String url =
          Webservice.get(Webservice.URL_UPDATE_PROFILE_AVATAR, mActivity.getUserId());

      uploadTask =
          new AsyncTask<Object, Object, String>() {
            @Override
            protected String doInBackground(Object... params) {
              String response =
                  HttpUtils.uploadFileByPost(
                      url,
                      mActivity.getUserId(),
                      mActivity.getToken(),
                      mActivity.getDeviceId(),
                      mActivity.getVersion(),
                      mActivity.getLocale(),
                      file,
                      Contains.FILE_TYPE_IMAGE,
                      filePath);
              return response;
            }

            @Override
            protected void onPostExecute(String response) {
              if (response != null) {
                try {
                  JSONObject json = new JSONObject(response);
                  //                            Log.d(TAG, json.toString());
                  //                            UIUtils.alert(context, "return: " +
                  // json.toString());
                  if (json != null) {
                    int status = json.getInt("StatusCode");
                    if (status == 1) {
                      JSONObject userInfo = json.getJSONObject("Data");
                      BLSharePreferences.setUserInfo(context, userInfo.toString());
                      setInfo(userInfo);
                      sendBroadcastUpdateProfile();
                    } else {
                      try {
                        String errorCode = json.get("errorCode").toString();
                        if (errorCode.equals(ErrorCode.CODE_CONNECT_SERVER_FAIL)) {
                          UIUtils.alert(
                              context,
                              R.string.connect_to_server_failed_plz_wait_a_moment_and_try_again);
                        } else {
                          UIUtils.alert(context, "errorCode: " + errorCode);
                        }
                      } catch (Exception e) {
                        UIUtils.alert(context, json.toString());
                        Log.d(TAG, json.toString());
                      }
                    }
                  }
                } catch (Exception e) {
                  e.printStackTrace();
                  UIUtils.alert(context, "Exception: " + e.getMessage());
                }
              } else {
                UIUtils.alert(context, R.string.upload_failed);
              }
              hideLoading();
            }
          };

      boolean isPending = (uploadTask.getStatus().equals(AsyncTask.Status.PENDING));
      if (isPending) {
        Log.i(TAG, "upFile + " + isPending);
        uploadTask.execute();
        if (uploadTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
          uploadTask = null;
        }
      }

    } catch (Exception e) {
      hideLoading();
      e.printStackTrace();
    }
  }
Esempio n. 16
0
 /**
  * Cancel an {@link AsyncTask}.
  *
  * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this task should be
  *     interrupted; otherwise, in-progress tasks are allowed to complete.
  */
 public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) {
   if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
     task.cancel(mayInterruptIfRunning);
   }
 }
 public boolean initializeTaskIsFinished() {
   return initializeTask == null || initializeTask.getStatus() == Status.FINISHED;
 }
Esempio n. 18
0
  private void requestUpdateAvatar(final String filePath) {
    if (filePath == null) {
      UIUtils.alert(this, R.string.file_not_found);
      hideLoading();
      return;
    }
    if (UIUtils.ensureNetworkInternet(this, false)) {
      showLoading();
      final File file = new File(filePath);
      if (file.exists() && file.canRead() && file.isFile()) {
        if (file.length() > Values.FILE_SIZE_LIMIT) {
          UIUtils.alert(this, getString(R.string.file_size_must_be_less_than_size_limit, "30MB"));
          hideLoading();
          return;
        }
      } else {
        UIUtils.alert(this, R.string.file_not_found);
        hideLoading();
        return;
      }

      try {
        uploadTask =
            new AsyncTask<Object, Object, String>() {
              @Override
              protected String doInBackground(Object... params) {
                String response =
                    HttpUtils.uploadFileImageByPost(RemoteMethods.uploadImage, filePath);
                return response;
              }

              @Override
              protected void onPostExecute(String response) {
                if (response != null) {
                  try {
                    JSONObject json = new JSONObject(response);
                    Log.d(TAG, json.toString());
                    int status = json.getInt("status");
                    if (status == 1) {
                      urlImage = json.getString("data");
                      sendMessageImage(urlImage);
                    } else {
                      try {
                        String errorCode = json.get("errorCode").toString();
                        if (errorCode.equals(CallServicePOST.ErrorCode.CONNECT_SERVER_FAIL)) {
                          UIUtils.alert(
                              ChatScreen.this,
                              R.string.connect_to_server_failed_plz_wait_a_moment_and_try_again);
                        } else if (errorCode.equals(CallServiceCustomPOST.ErrorCode.FULL_STORAGE)) {
                          UIUtils.alert(
                              ChatScreen.this, R.string.full_storage_please_upgrade, R.string.oop);
                        } else {
                          UIUtils.alert(ChatScreen.this, "errorCode: " + errorCode);
                        }
                      } catch (Exception e) {
                        Log.d(TAG, json.toString());
                      }
                    }
                    hideLoading();
                  } catch (Exception e) {
                    hideLoading();
                    e.printStackTrace();
                  }
                } else {
                  hideLoading();
                  UIUtils.alert(ChatScreen.this, R.string.upload_failed);
                }
              }
            };

        boolean isPending = (uploadTask.getStatus().equals(AsyncTask.Status.PENDING));
        if (isPending) {
          Log.i(TAG, "upFile + " + isPending);
          uploadTask.execute();
          if (uploadTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
            uploadTask = null;
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  private void refreshSoundTrace() {
    if (refreshTask != null && refreshTask.getStatus() != AsyncTask.Status.FINISHED) return;

    //noinspection unchecked
    refreshTask = new UpdateSoundTraceTask().execute();
  }