标签:
public abstract class AsyncTask
extends Object
java.lang.Object | |
? | android.os.AsyncTask<Params, Progress, Result> |
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread
and Handler
and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent
package such as Executor
, ThreadPoolExecutor
and FutureTask
.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params
, Progress
and Result
, and 4 steps, called onPreExecute
, doInBackground
, onProgressUpdate
andonPostExecute
.
翻译:
package com.edwin.demoasynctask; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private String TAG = "Edwin"; private ProgressDialog mProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new MyAsyncTask().execute("网址地址", "请求参数"); } /** * AsyncTask<Params, Progress, Result>三个参数分别介绍一下 * Params 启动任务执行的输入参数,比如HTTP请求的URL。 * Progress 后台任务执行的百分比,比如下载的进度值。 * Result 后台执行任务最终返回的结果,比如String。 * <p/> * GO * 这里我做一个模拟下载文件的操作 */ private class MyAsyncTask extends AsyncTask<String, Integer, String> { /** * 1.在分线程工作开始之前在UI线程中执行,初始化进度条视图 */ @Override protected void onPreExecute() { //TODO 准备初始化View mProgressDialog = new ProgressDialog(MainActivity.this); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); Log.e(TAG, "onPreExecute"); } /** * 2.在分线程中执行,完成任务的主要工作,通常需要较长的时间 * * @param params url请求参数等等.. * @return 请求之后得到的结果 */ @Override protected String doInBackground(String... params) { //TODO 做一些耗时的操作 String url = params[0];//获取url参数进行网络请求操作 Log.e(TAG, "doInBackground"); int i = 0; // 下面我们模拟数据的加载,耗时的任务 for (i = 0; i < 100; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //在分线程中, 发布当前进度 publishProgress(i); } //返回结果 return "结果:" + i; } /** * 3.在主线程中更新进度 * * @param values 进度值 */ @Override protected void onProgressUpdate(Integer... values) { //TODO 获取进度值,更新View mProgressDialog.setProgress(values[0]); Log.e(TAG, "onProgressUpdate values[0] = " + values[0]); } /** * 4.执行完之后的结果 * * @param result 结果 */ @Override protected void onPostExecute(String result) { //TODO 获取结果,关闭View mProgressDialog.dismiss(); Log.e(TAG, "onPostExecute result = " + result); Toast.makeText(MainActivity.this, "文件下载成功", Toast.LENGTH_SHORT).show(); } } }
1 /** 2 * Creates a new asynchronous task. This constructor must be invoked on the UI thread. 3 */ 4 public AsyncTask() { 5 mWorker = new WorkerRunnable<Params, Result>() { 6 public Result call() throws Exception { 7 mTaskInvoked.set(true); 8 9 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 10 //noinspection unchecked 11 Result result = doInBackground(mParams); 12 Binder.flushPendingCommands(); 13 return postResult(result); 14 } 15 }; 16 17 mFuture = new FutureTask<Result>(mWorker) { 18 @Override 19 protected void done() { 20 try { 21 postResultIfNotInvoked(get()); 22 } catch (InterruptedException e) { 23 android.util.Log.w(LOG_TAG, e); 24 } catch (ExecutionException e) { 25 throw new RuntimeException("An error occurred while executing doInBackground()", 26 e.getCause()); 27 } catch (CancellationException e) { 28 postResultIfNotInvoked(null); 29 } 30 } 31 }; 32 }
第5行是初始化的一些参数,用于存放我们传入的参数execute(Params... params),源码点进去看WorkerRunnable是一个抽象类实现了Callable
1 private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { 2 Params[] mParams; 3 } 4 5 @SuppressWarnings({"RawUseOfParameterizedType"}) 6 private static class AsyncTaskResult<Data> { 7 final AsyncTask mTask; 8 final Data[] mData; 9 10 AsyncTaskResult(AsyncTask task, Data... data) { 11 mTask = task; 12 mData = data; 13 } 14 }
1 通过源码postResultfNotInvoked(get()),postResultfNotInvoked(null);点进入如下 2 private void postResultIfNotInvoked(Result result) { 3 final boolean wasTaskInvoked = mTaskInvoked.get(); //如果不为true就执行,因在初始化的时候已经设为了true,所以不会执行 4 if (!wasTaskInvoked) { 5 postResult(result); 6 } 7 }
1 public final AsyncTask<Params, Progress, Result> execute(Params... params) { 2 return executeOnExecutor(sDefaultExecutor, params); 3 } 4 5 public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, 6 Params... params) { 7 if (mStatus != Status.PENDING) { 8 switch (mStatus) { 9 case RUNNING: 10 throw new IllegalStateException("Cannot execute task:" 11 + " the task is already running."); 12 case FINISHED: 13 throw new IllegalStateException("Cannot execute task:" 14 + " the task has already been executed " 15 + "(a task can be executed only once)"); 16 } 17 } 18 19 mStatus = Status.RUNNING; 20 21 onPreExecute(); 22 23 mWorker.mParams = params; 24 exec.execute(mFuture); 25 26 return this; 27 }
1 private void postResultIfNotInvoked(Result result) { 2 final boolean wasTaskInvoked = mTaskInvoked.get(); 3 if (!wasTaskInvoked) { 4 postResult(result); //慢慢深入 5 } 6 } 7 8 9 private Result postResult(Result result) { 10 @SuppressWarnings("unchecked") 11 Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, 12 new AsyncTaskResult<Result>(this, result)); 13 message.sendToTarget(); 14 return result; 15 }
1 private static Handler getHandler() { 2 synchronized (AsyncTask.class) { 3 if (sHandler == null) { 4 sHandler = new InternalHandler(); 5 } 6 return sHandler; 7 } 8 } 9 10 11 private static class InternalHandler extends Handler { 12 public InternalHandler() { 13 super(Looper.getMainLooper()); 14 } 15 16 @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) 17 @Override 18 public void handleMessage(Message msg) { 19 AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; 20 switch (msg.what) { 21 case MESSAGE_POST_RESULT: 22 // There is only one result 23 result.mTask.finish(result.mData[0]);//源码跟踪进入调用的是onPostExecute() 24 break; 25 case MESSAGE_POST_PROGRESS: 26 result.mTask.onProgressUpdate(result.mData); //调用onProgressUpdate熟悉吧。 27 break; 28 } 29 } 30 }
1 public final AsyncTask<Params, Progress, Result> execute(Params... params) { 2 return executeOnExecutor(sDefaultExecutor, params); 3 } 4 5 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; 6 7 public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); 8 9 private static class SerialExecutor implements Executor { 10 final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); 11 Runnable mActive; 12 13 public synchronized void execute(final Runnable r) { 14 mTasks.offer(new Runnable() { 15 public void run() { 16 try { 17 r.run(); 18 } finally { 19 scheduleNext(); 20 } 21 } 22 }); 23 if (mActive == null) { 24 scheduleNext(); 25 } 26 } 27 28 protected synchronized void scheduleNext() { 29 if ((mActive = mTasks.poll()) != null) { 30 THREAD_POOL_EXECUTOR.execute(mActive); 31 } 32 } 33 } 34 35 36 public static final Executor THREAD_POOL_EXECUTOR 37 = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 38 TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 39 40 41 42 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();//可用的CPU个数 43 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;//线程池大小 44 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;//最大线程 45 private static final int KEEP_ALIVE = 1;//维持时间
1 private static final int CORE_POOL_SIZE = 5; 2 private static final int MAXIMUM_POOL_SIZE = 128; 3 private static final int KEEP_ALIVE = 1; 4 5 private static final BlockingQueue<Runnable> sWorkQueue = 6 new LinkedBlockingQueue<Runnable>(10); 7 8 private static final ThreadPoolExecutor sExecutor = 9 new ThreadPoolExecutor(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE, KEEP_ALIVE, 10 TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
1 private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); 2 private static final int CORE_POOL_SIZE = CPU_COUNT + 1; 3 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; 4 private static final int KEEP_ALIVE = 1; 5 private static final BlockingQueue<Runnable> sPoolWorkQueue = 6 new LinkedBlockingQueue<Runnable>(128); 7 8 /** 9 * An {@link Executor} that can be used to execute tasks in parallel. 10 * 一个可用于并行执行的任务。多线程模式 11 */ 12 public static final Executor THREAD_POOL_EXECUTOR 13 = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, 14 TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); 15 16 /** 17 * An {@link Executor} that executes tasks one at a time in serial 18 * order. This serialization is global to a particular process. 19 * 一个串行执行,一次完成一项任务秩序。这个序列化是全球性的一个特定的过程。单线程模式 20 */ 21 public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
在3.0以后,无论有多少任务,都会在其内部单线程执行;
标签:
原文地址:http://www.cnblogs.com/why168888/p/5597214.html