/**
  * Run an ASync task on the corresponding executor
  *
  * @param task
  * @return
  */
 private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
   } else {
     return task.execute();
   }
 }
예제 #2
0
 public static void startWithParams(AsyncTask task, Object[] params) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
   } else {
     task.execute(params);
   }
 }
 @Override
 public synchronized void onAutoFocus(boolean success, Camera theCamera) {
   if (active) {
     outstandingTask = new AutoFocusTask();
     outstandingTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
   }
 }
예제 #4
0
 public static void start(AsyncTask task) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[] {});
   } else {
     task.execute(new Void[] {});
   }
 }
예제 #5
0
  @SuppressLint("NewApi")
  public DiskLruCache(Context context, String cacheName, long cacheSize) {
    mContext = context;
    mCacheName = cacheName;
    mCacheSize = cacheSize;

    int version;
    PackageManager pm = context.getPackageManager();
    try {
      PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
      version = pi.versionCode;
    } catch (NameNotFoundException e) {
      version = 1;
    }

    AsyncTask<Integer, Object, Object> task =
        new AsyncTask<Integer, Object, Object>() {
          @Override
          protected Object doInBackground(Integer... params) {
            initDiskCache(params[0]);
            return null;
          }
        };

    if (Build.VERSION.SDK_INT >= 11) {
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, version);
    } else {
      task.execute(version);
    }
  }
예제 #6
0
  private void fetchPhotoAsync(final RecipientEntry entry, final Uri photoThumbnailUri) {
    final AsyncTask<Void, Void, Void> photoLoadTask =
        new AsyncTask<Void, Void, Void>() {
          @Override
          protected Void doInBackground(Void... params) {
            final Cursor photoCursor =
                mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null, null, null);
            if (photoCursor != null) {
              try {
                if (photoCursor.moveToFirst()) {
                  final byte[] photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
                  entry.setPhotoBytes(photoBytes);

                  mHandler.post(
                      new Runnable() {
                        @Override
                        public void run() {
                          mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
                          notifyDataSetChanged();
                        }
                      });
                }
              } finally {
                photoCursor.close();
              }
            }
            return null;
          }
        };
    photoLoadTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
  }
 /** 首先终止之前的监控任务,然后新起一个监控任务 */
 @SuppressWarnings("unchecked")
 @SuppressLint("NewApi")
 public synchronized void onActivity() {
   cancel();
   inactivityTask = new InactivityAsyncTask();
   inactivityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 }
예제 #8
0
 public void onClickAsyncThreadSerial(final View view) {
   AsyncTask a = new CustomAsyncTask();
   Integer i = (Integer) view.getTag();
   if (i == null) i = 1;
   view.setTag(i + 1);
   a.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, "Some", i, "SERIAL_EXECUTOR");
 }
예제 #9
0
 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 private <A, B, C> void executeTask(AsyncTask<A, B, C> task, A... params) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
   } else {
     task.execute(params);
   }
 }
예제 #10
0
 @TargetApi(11)
 public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> task, T... params) {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
     task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
   } else {
     task.execute(params);
   }
 }
예제 #11
0
  public static void startMyTask(AsyncTask asyncTask) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

      asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
    } else {

      asyncTask.execute();
    }
  }
예제 #12
0
파일: Server.java 프로젝트: wenchr/DidiCol
  public Server(int _port, PollListener _pollListener) {
    port = _port;
    client = new Socket[2];
    objectInputStreams = new ObjectInputStream[2];
    clientPoll = new ArrayList<AsyncTask<Integer, Object, Void>>();
    pollListener = _pollListener;

    serverStart =
        new AsyncTask<Void, Socket, Void>() {
          @Override
          protected Void doInBackground(Void... params) {
            Thread.currentThread().setName("ServerThread");
            try {
              serverSocket = new ServerSocket(port);
              serverSocket.setSoTimeout(1000);
            } catch (IOException e) {
            }
            while ((client[0] == null || client[1] == null) && !isCancelled()) {
              try {
                publishProgress(serverSocket.accept());
              } catch (IOException e) {
              }
            }
            return null;
          }

          @Override
          protected void onProgressUpdate(Socket... values) {
            new AsyncTask<Socket, Void, Void>() {
              @Override
              protected Void doInBackground(Socket... params) {
                Thread.currentThread().setName("TryClientThread");
                tryClient(params[0]);
                return null;
              }
            }.executeOnExecutor(Executors.newSingleThreadExecutor(), values[0]);
          };

          @Override
          protected void onPostExecute(Void result) {
            Log.d("netconnect", "serverFinished");
            serverWorking = true;
            AsyncPoll();
          };

          @Override
          protected void onCancelled() {
            asyncClean();
          }
        };
    serverStart.executeOnExecutor(Executors.newSingleThreadExecutor(), new Void[] {null});
  }
 private void launchSearch() {
   String query = queryTextView.getText().toString();
   if (query != null && !query.isEmpty()) {
     AsyncTask<?, ?, ?> oldTask = networkTask;
     if (oldTask != null) {
       oldTask.cancel(true);
     }
     networkTask = new NetworkTask();
     networkTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, query, isbn);
     headerView.setText(R.string.msg_sbc_searching_book);
     resultListView.setAdapter(null);
     queryTextView.setEnabled(false);
     queryButton.setEnabled(false);
   }
 }
  /**
   * {@link AsyncTask#execute(Object...)}は,API level 11以降ではシリアルに実行されます.<br>
   * (複数個登録した場合,1つ終わらないと次が開始されない)<br>
   * このメソッドを介して呼んだ場合,パラレルに実行されます.<br>
   *
   * @param task
   * @param params
   * @see <a href="http://daichan4649.hatenablog.jp/entry/20120125/1327467103">参考ページ</a>
   */
  @SuppressLint("NewApi")
  public static <T> void executeTask(AsyncTask<T, ?, ?> task, T... params) {
    try {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
      } else {
        task.execute(params);
      }

    } catch (RejectedExecutionException e) {
      LogUtils.d("Pool is full. Retrying...");
      executeTask(task, params);
    } catch (IllegalStateException e) {
      LogUtils.w("This Task may be already runnning. " + e.toString());
    }
  }
예제 #15
0
 @TargetApi(11)
 public static <T> AsyncTask<T, ?, ?> executeTaskOnExecutor(AsyncTask<T, ?, ?> task, T... arg) {
   for (int i = 0; i < 2; i++) {
     try {
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, arg);
       } else {
         task.execute(arg);
       }
       break;
     } catch (RejectedExecutionException ignore) {
       Logger.w("unable to start thread", ignore);
       sleep(1000);
     }
   }
   return task;
 }
예제 #16
0
 private void connect(final LoLin1Account acc) {
   mSmackAndroid = LoLChat.init(getApplicationContext());
   mLoginTask =
       new AsyncTask<LoLin1Account, Void, Void>() {
         @Override
         protected Void doInBackground(LoLin1Account... params) {
           Boolean loginSuccess = login(params[0]);
           if (loginSuccess) {
             launchBroadcastLoginSuccessful();
             setUpChatOverviewListener();
           } else {
             launchBroadcastLoginFailed();
           }
           return null;
         }
       };
   mLoginTask.executeOnExecutor(Executors.newSingleThreadExecutor(), acc);
 }
  private void registerInBackground() {
    AsyncTask<String, String, Boolean> task =
        new AsyncTask<String, String, Boolean>() {
          @Override
          protected Boolean doInBackground(String... objects) {
            if (gcm == null) {
              gcm = GoogleCloudMessaging.getInstance(applicationContext);
            }
            int count = 0;
            while (count < 1000) {
              try {
                count++;
                regid = gcm.register(BuildVars.GCM_SENDER_ID);
                sendRegistrationIdToBackend(true);
                storeRegistrationId(applicationContext, regid);
                return true;
              } catch (Exception e) {
                FileLog.e("tmessages", e);
              }
              try {
                if (count % 20 == 0) {
                  Thread.sleep(60000 * 30);
                } else {
                  Thread.sleep(5000);
                }
              } catch (InterruptedException e) {
                FileLog.e("tmessages", e);
              }
            }
            return false;
          }
        };

    if (android.os.Build.VERSION.SDK_INT >= 11) {
      task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
    } else {
      task.execute(null, null, null);
    }
  }
예제 #18
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();
    }
  }
 static <Params, Progress, Result> void m692a(
     AsyncTask<Params, Progress, Result> asyncTask, Params... paramsArr) {
   asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, paramsArr);
 }
 @Override
 public <T> AsyncTask<T, ?, ?> submit(Object identifer, AsyncTask<T, ?, ?> task, T... params) {
   checkCalledFromUiThread();
   return task.executeOnExecutor(mExecutor, params);
 }
예제 #21
0
 synchronized void onActivity() {
   cancel();
   inactivityTask = new InactivityAsyncTask();
   inactivityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 }
 @TargetApi(Constants.HONEYCOMB)
 private static void executeTaskHoneycomb(AsyncTask<Void, Void, Void> task) {
   task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 }
  private void reloadFrames(int frameNum) {
    if (mediaMetadataRetriever == null) {
      return;
    }
    if (frameNum == 0) {
      frameHeight = AndroidUtilities.dp(40);
      framesToLoad = (getMeasuredWidth() - AndroidUtilities.dp(16)) / frameHeight;
      frameWidth =
          (int)
              Math.ceil(
                  (float) (getMeasuredWidth() - AndroidUtilities.dp(16)) / (float) framesToLoad);
      frameTimeOffset = videoLength / framesToLoad;
    }
    currentTask =
        new AsyncTask<Integer, Integer, Bitmap>() {
          private int frameNum = 0;

          @Override
          protected Bitmap doInBackground(Integer... objects) {
            frameNum = objects[0];
            Bitmap bitmap = null;
            if (isCancelled()) {
              return null;
            }
            try {
              bitmap = mediaMetadataRetriever.getFrameAtTime(frameTimeOffset * frameNum * 1000);
              if (isCancelled()) {
                return null;
              }
              if (bitmap != null) {
                Bitmap result = Bitmap.createBitmap(frameWidth, frameHeight, bitmap.getConfig());
                Canvas canvas = new Canvas(result);
                float scaleX = (float) frameWidth / (float) bitmap.getWidth();
                float scaleY = (float) frameHeight / (float) bitmap.getHeight();
                float scale = scaleX > scaleY ? scaleX : scaleY;
                int w = (int) (bitmap.getWidth() * scale);
                int h = (int) (bitmap.getHeight() * scale);
                Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
                Rect destRect = new Rect((frameWidth - w) / 2, (frameHeight - h) / 2, w, h);
                Paint paint = new Paint();
                canvas.drawBitmap(bitmap, srcRect, destRect, null);
                bitmap.recycle();
                bitmap = result;
              }
            } catch (Exception e) {
              FileLog.e("tmessages", e);
            }
            return bitmap;
          }

          @Override
          protected void onPostExecute(Bitmap bitmap) {
            if (!isCancelled()) {
              frames.add(bitmap);
              invalidate();
              if (frameNum < framesToLoad) {
                reloadFrames(frameNum + 1);
              }
            }
          }
        };

    if (android.os.Build.VERSION.SDK_INT >= 11) {
      currentTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, frameNum, null, null);
    } else {
      currentTask.execute(frameNum, null, null);
    }
  }
 static transient void executeParallel(AsyncTask asynctask, Object aobj[]) {
   asynctask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aobj);
 }
예제 #25
0
  @TargetApi(11)
  /**
   * Execute the given task
   *
   * <p>The busy state is notified to the client
   *
   * <p>Tasks should throw an exception to indicate (and return) error
   *
   * @param task the Runnable task to be performed
   */
  public void performTask(Runnable task) throws ModelException {
    final Runnable rTask = task;

    if (mCommander == null) {
      throw (new ModelException("There is no AsciiCommander set for this model!"));
    } else {
      if (mTaskRunner != null) {
        throw (new ModelException("Task is already running!"));
      } else {
        mTaskRunner =
            new AsyncTask<Void, Void, Void>() {
              @Override
              protected void onPreExecute() {
                mLastTaskExecutionDuration = -1.0;
                mTaskStartTime = new Date();
              }

              protected Void doInBackground(Void... voids) {
                try {
                  setBusy(true);
                  mException = null;

                  rTask.run();

                } catch (Exception e) {
                  mException = e;
                }
                return null;
              }

              @Override
              protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                mTaskRunner = null;
                setBusy(false);

                // Update the time taken
                Date finishTime = new Date();
                mLastTaskExecutionDuration =
                    (finishTime.getTime() - mTaskStartTime.getTime()) / 1000.0;

                if (D)
                  Log.i(
                      getClass().getName(),
                      String.format(
                          "Time taken (ms): %d %.2f",
                          finishTime.getTime() - mTaskStartTime.getTime(),
                          mLastTaskExecutionDuration));
              }
            };

        try {
          if (android.os.Build.VERSION.SDK_INT >= 11) {
            // Ensure the tasks are executed serially whatever newer API versions may choose by
            // default
            mTaskRunner.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, (Void[]) null);
          } else {
            // Tasks will be executed concurrently on API < 11
            mTaskRunner.execute((Void[]) null);
          }
        } catch (Exception e) {
          mException = e;
        }
      }
    }
  }