編輯:關於Android編程
public abstract class AsyncTask
public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final int KEEP_ALIVE = 1; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueuesPoolWorkQueue = new LinkedBlockingQueue (10);
/** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static class SerialExecutor implements Executor { final ArrayDequemTasks = new ArrayDeque (); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } }
private static final int MESSAGE_POST_RESULT = 0x1;//當前消息類型--->任務完成消息 private static final int MESSAGE_POST_PROGRESS = 0x2;//當前消息類型-->進度消息 private static final InternalHandler sHandler = new InternalHandler(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;//默認線程池 private final WorkerRunnablemWorker; private final FutureTask mFuture; private volatile Status mStatus = Status.PENDING;//當前狀態 private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING,//等待執行 /** * Indicates that the task is running. */ RUNNING,//執行 /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED,//執行結束 }
private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } }
private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; }
public final AsyncTaskexecute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
public final AsyncTaskexecuteOnExecutor方法的作用是使用指定的線程池執行任務,這裡當然使用的是sDefaultExecutor,也就是SerialExecutor,但是我們注意到這個方法是公共的,也就是說我們可以手動配置線程池,讓AsyncTask並行執行起來,最簡單的方法就是使用內部定義好的THREAD_POOL_EXECUTOR。 executeOnExecutor方法首先檢查當前狀態,如果不是Pending狀態則拋出異常,緊接著修改狀態為Running態,接著調用onPreExecute方法(預處理,相信大家不陌生)。executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; }
mFuture = new FutureTask(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } };
private static abstract class WorkerRunnableimplements Callable { Params[] mParams; } mWorker = new WorkerRunnable () { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } };
private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult(this, result)); message.sendToTarget(); return result; }
private static class AsyncTaskResult { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } }2.任務進度更新消息是通過publishProgress方法發送的:
protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult
一、新建HelloWorld項目: Project-Android Application Project: 選擇項目保存位置,一路“next”完成項目創建
下拉菜單美團首頁類似的下拉彈出菜單工程中經常遇到的控件,不同工程中菜單條目的類型與數量也不一樣所以需要根據實際需要填充不同內容。先寫個demo,一倍不時之需吧。既然每個項
原創博客地址:點擊傳送 AndroidResideMenu 先看看如何使用: 把項目源碼下載下來導入工程,可以看到 ResideMenu為引用工程,再看
導航抽屜(navigationdrawer)是一個從屏幕左邊滑入的面板,用於顯示應用的主要導航項目。用戶可以通過在屏幕左邊緣滑入或者觸摸操作欄的應用圖標打開導航抽屜。導航