怎么去阅读源码
什么时候要去阅读源码,带着思想去读
1. 为了验证某些在网上看到的一些技术文章:异步刚开会加载方法-->****方法-->最终会执行什么方法 异步加载只能调一次;
2.为了解决开发中的某些问题:5.0 以上和5.0以下的效果区别;
3.为了写某些架构性的框架:Okhttp的框架,阅读大量的源码,个人建议大家还是自己去参加一些开源的框架。
读的时候分为:精读和细读还有泛读
异步加载:带着疑问去读,然后思考比对我们自己写的一些好的地方,自己写类似的功能应该怎么去写?
AsyncTask
模板方法设计模式
@WorkerThread /*-子线程*/
protected abstract Result doInBackground(Params...params);
@MainThread
protected void onPreExecute(){}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onPostExecute(Result result){}
@SuppressWarnings({"UnusedDeclaration"})
@MainThread
protected void onProgressUpdate(Progress...values){}
源码阅读
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params...params){
return executeOnExecutor(sDefaultExecutor,params);
}
@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;
}
AsyncTask为什么只能执行一次
是因为在executeOnExecutor中判断了状态如果是在运行,提示已经运行,如果完成,就提示已经完成这些都是以抛异常的形式处理的
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return 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);
}
}
};
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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;
}
execute --> executeOnExecutor --> 执行 onPreExecute 方法 --> execute --> 调用FutureTask中的run方法
FutureTask它会调用它里面的Callable接口的call方法--> WorkerRunnable --> 执行 doInBackground 方法 --> postResult--> 发送消息MESSAGE_POST_RESULT到UI线程
--> finish --> 如果取消就调用onCancelled 如果没有取消就 执行onPostExecute方法
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
public class FutureTask<V> implements RunnableFuture<V> {
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
runner = null;
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
private void handlePossibleCancellationInterrupt(int s) {
if (s == INTERRUPTING)
while (state == INTERRUPTING)
Thread.yield(); // wait out pending interrupt
}
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}