标签:
在上一个例子中,我们是在LoadImage的onPostExecute中修改的UI,不是说只允许在主线程中修改UI吗?我们看一下源代码是如何操作的。
MainActicity.java
package cn.lixyz.asynctest; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class MainActivity extends Activity{ private Button button; private ImageView imageView; private ProgressBar progressBar; private String URL="http://ww3.sinaimg.cn/bmiddle/612c96afjw1ewwftl3uqkj20u00koq48.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取组件 button = (Button) findViewById(R.id.button); imageView = (ImageView) findViewById(R.id.imageView); progressBar = (ProgressBar) findViewById(R.id.progressBar); //给button设置点击事件,点击按钮,启动异步任务 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new LoadImage().execute(URL); } }); } class LoadImage extends AsyncTask<String,Void,Bitmap>{ //开始执行耗时操作,连接网络获取图片,并且将Bitmap返回 @Override protected Bitmap doInBackground(String... params) { String url = params[0]; Bitmap bitmap = null; URLConnection connection; InputStream is; try { connection = new URL(url).openConnection(); Thread.sleep(5000); is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bitmap = BitmapFactory.decodeStream(bis); is.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return bitmap; } //onPreExcute方法是在doInBackGround方法前执行,用于做一些初始化操作,这里将progressBar显示出来 @Override protected void onPreExecute() { super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); } //doInBackGround方法执行后,会自动执行该方法,获取到doInBackGround返回的对象,然后更改UI @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); progressBar.setVisibility(View.GONE); imageView.setImageBitmap(bitmap); } } }
acticity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="4"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> <ProgressBar android:id="@+id/progressBar" android:visibility="gone" android:layout_centerInParent="true" style="@style/Widget.AppCompat.ProgressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="点击载入" /> </LinearLayout>
先找到AsyncTask的构造函数:
public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked Result result = doInBackground(mParams); Binder.flushPendingCommands(); return postResult(result); } }; 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 occurred while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }
可以看到在AsyncTask的构造函数中,仅仅初始化了两个变量 mWorker 和 mFuture
接着启动AsyncTask,我们找到 execute 方法:
@MainThread public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
可以看到,在 execute() 方法中,只执行了一个 executeOnExecutor() ,我们继续看executeOnExecutor方法:
@MainThread 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; }
可以看到,在 executeOnExecutor() 方法中,先判断了AsyncTask的状态,如果是 RUNNING 或者是 FINISHED 的话,则会抛出 IllegalStateException 异常,如果不是,则将AsyncTask的状态设置为 RUNNING ,然后执行 onPreExecute() 方法,我们再看这个方法:
@MainThread protected void onPreExecute() { }
这个方法又没有做任何操作,之前我们讲过, onPreExecute() 方法是在执行 doInBackGround() 之前执行,用来做一些初始化操作的,所以如果我们有需要的话,就需要自己重写 onPreExecute() 方法了。
接着看 executeOnExecutor() 方法,在执行完 onPreExecute() 方法之后,继续往下,将 params 赋值给 mWorker.mParams 之后,又执行了 exec.execute(mFuture) ,我们找一下 Executor 的 execute() 方法:
public interface Executor { /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the {@code Executor} implementation. * * @param command the runnable task * @throws RejectedExecutionException if this task cannot be * accepted for execution * @throws NullPointerException if command is null */ void execute(Runnable command); }
似乎有些不对劲,到这里就完了吗? doInBackGround() 在哪里执行呢?我们仔细找一下上面的代码,在 execute() 方法中执行 executeOnExecutor() 方法的时候传入了一个 sDefaultExecutor ,我们找到这个 sDefaultExecutor :
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
继续找到 SERIAL_EXECUTOR 这个常量的定义:
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
可以看到 SERIAL_EXECUTOR 这个常量是一个 SerialExecutor 对象,找到它:
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); } } }
Android笔记(三十六) AsyncTask是如何执行的?
标签:
原文地址:http://www.cnblogs.com/xs104/p/4869669.html