AsyncTask 源码阅读

1.参考资料

1. http://developer.android.com/reference/android/os/AsyncTask.html
2. http://blog.csdn.net/pi9nc/article/details/12622797
3. http://www.tuicool.com/articles/VnMf2i3

下面详细解析Asynctask的源码流程。我们在阅读源码的时候需要知道的重要点是:输入输出(参数)、以及程序入口(什么地方进入调用)。

2 传递的三个泛型参数 

(1)Params, the type of the parameters sent to the task upon execution.  本文传递URL数据
(2)Progress, the type of the progress units published during the background computation.//进度条
(3)Result, the type of the result of the background computation.  //结果

3 提供给外部调用的方法

  这些函数的功能很多大牛做过解释 由于篇幅原因 不在赘述:

/**
     * Override this method to perform a computation on a background thread. The
     * specified parameters are the parameters passed to {@link #execute}
     * by the caller of this task.参数为传给execute的方法参数 看方法名称此方法在非主线程中调用
     *
     * This method can call {@link #publishProgress} to publish updates
     * on the UI thread.
     *
     * @param params The parameters of the task. 任务参数如不同的URL等
     *
     * @return A result, defined by the subclass of this task. 结果
     *
   
     */
    protected abstract Result doInBackground(Params... params);

    /**
     * Runs on the UI thread before {@link #doInBackground}.
     * 运行在UI线程 在调用doInBackground
     */
    protected void onPreExecute() {
    }

    /**
     * <p>Runs on the UI thread after {@link #doInBackground}. The
     * specified result is the value returned by {@link #doInBackground}.</p>
     * 
     * <p>This method won't be invoked if the task was cancelled.</p>
     *
     * @param result The result of the operation computed by {@link #doInBackground}.
     */
    @SuppressWarnings({"UnusedDeclaration"})
    protected void onPostExecute(Result result) {
    }

    /**
     * Runs on the UI thread after {@link #publishProgress} is invoked.
     * The specified values are the values passed to {@link #publishProgress}.
     *
     * @param values The values indicating progress.泛型参数为进度条
     *
     */
    @SuppressWarnings({"UnusedDeclaration"})
    protected void onProgressUpdate(Progress... values) {
    }

4. 程序入口

 http://blog.csdn.net/nothingl3/article/details/44415195 ,执行该任务时调用了如下:
new  DownloadFilesTask().execute(url);  
很明显调用了AsyncTask的execute方法。

5 源码阅读

从程序入口跳入该方法:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
一句话又开始跳转:
 public final AsyncTask<Params, Progress, Result> 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;
    }
3-13行是检查任务启动是否合理 17行调用:
onPreExecute();
明显该方法在主线程调用。19行更新mWorker参数(实现此为callable接口的对象 后面会提到)。20行为
exec.execute(mFuture);
看又开始跳转。exec为传输的参数:
sDefaultExecutor
故接着跳入:
 public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

几个跳转 我将源码放在了一起。可以看出exec.execute(mFuture)执行了SerialExecutor 的excute方法//注意参数mFuture后面会详细提到。
private static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        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);
            }
        }
    }
mTask为ArrayDeque为Runnable 数组双端队列。但同时存在线程不安全性 故方法名前添加synchronized关键字。mTask.offer  每添加一个元素,就把元素加到数组的尾部。这里每次回去创建一个线程。在线程run方法中执行r.run。重点来了r是之前提到的mFutrue。查找下源码的该成员变量。
 private final FutureTask<Result> mFuture;
mFuture = new FutureTask<Result>(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);
                }
            }
        };
    }

我们先看FutrueTask是个什么东东 如果对多线程很熟悉的童鞋不会陌生。 FutureTask是一个RunnableFuture<V>,而RunnableFuture实现了Runnbale又实现了Futrue<V>这两个接口。
public class FutureTask<V> implements RunnableFuture<V>
  public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
  }
此处源码码mFuture = new FutureTask<Result>(mWorker) 调用的是
public FutureTask(Callable<V> callable)
mWorker实现callable方法。具体mFuture如何调用callable方法参见:
mFuture会调用mWorker的call方法:
mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };
有人会奇怪 mWork怎么会实现了callable方法?看此处:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
callable接口与runnable很相似。不过最大好处在于callable接口的call方法有返回值。回到mWorker的call方法中。返回了postResult(doInBackground(mParams)) 这里先是调用了我们的 doInBackground(mParams)显然此处在非主线程 故可以处理耗时任务 最后通过postResult返回结果 
private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }
我们发现熟悉的了 通过sHandler来处理消息。
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;
            }
        }
    }
result为AsyncTaskResult<Data>对象即传入的new AsyncTaskResult<Result>(this, result)
private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
回到handleMessage方法。由于postResult发出的消息msg.what为 MESSAGE_POST_RESULT故跳到
private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }
这里判断任务 是否被cancelled 否的话调用onPostExecute(result); 是的话调用 onCancelled(result);并更新状态。此处完成。 回到handleMessage MESSAGE_POST_PROGRESS是什么谁发出的呢?
protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }
那什么时候调用的呢?使用过AsyncTask的童鞋会记得。我们会在doInbackgroud方法中调用  publishProgress()方法。整个asyncTask方法阅读完成。但有些坑。比如为什么采用线程池+FutureTask方式。又比如
public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
此处线程池的个数与之前3.0 版本AsyncTask设置不一样。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android拍照上传主要分为两个部分,即照相和上传。在照相方面需要使用Android提供的API,如Camera类来实现;而在上传方面则可以使用HTTP POST请求或其他方式实现,如FTP的方式上传。以下是一个简单的拍照上传的源代码: ``` public class MainActivity extends AppCompatActivity { private static final int REQUEST_IMAGE_CAPTURE = 1; private ImageView mImageView; private Bitmap mBitmap; private String mFilePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = findViewById(R.id.imageView); Button captureButton = findViewById(R.id.captureButton); captureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); Button uploadButton = findViewById(R.id.uploadButton); uploadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UploadTask uploadTask = new UploadTask(); uploadTask.execute(mFilePath); } }); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { ex.printStackTrace(); } if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "com.example.android.fileprovider", photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } } private File createImageFile() throws IOException { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); mFilePath = image.getAbsolutePath(); return image; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { mBitmap = BitmapFactory.decodeFile(mFilePath); mImageView.setImageBitmap(mBitmap); } } private class UploadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String filePath = params[0]; HttpsURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1024 * 1024; File sourceFile = new File(filePath); if(!sourceFile.isFile()){ return null; } try{ FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL("http://example.com/upload.php"); conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filePath + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0){ dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); int responseCode = conn.getResponseCode(); if (responseCode == 200) { return "success"; } fileInputStream.close(); dos.flush(); dos.close(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result) { if(result != null && result.equals("success")){ Toast.makeText(MainActivity.this, "Upload Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show(); } } } } ``` 上述代码中,setOnClickListener()方法可以监听拍照和上传按钮的点击事件,dispatchTakePictureIntent()方法用于调用系统相机拍照,createImageFile()方法用于创建保存拍照图片的文件,而HTTP POST上传的实现则在UploadTask类中的doInBackground()方法中。当上传成功或失败时会通过Toast提示用户。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值