先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7
深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年最新Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新
如果你需要这些资料,可以添加V获取:vip204888 (备注Android)
正文
- @see #publishProgress
*/
protected abstract Result doInBackground(Params… params);
/**
-
Runs on the UI thread before {@link #doInBackground}.
-
@see #onPostExecute
-
@see #doInBackground
*/
protected void onPreExecute() {
}
/**
-
Runs on the UI thread after {@link #doInBackground}. The
-
specified result is the value returned by {@link #doInBackground}
-
or null if the task was cancelled or an exception occured.
*后台操作执行完后会调用的方法,在此更新UI。
-
@param result The result of the operation computed by {@link #doInBackground}.
-
@see #onPreExecute
-
@see #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.
-
传值更新进度条
-
@see #publishProgress
-
@see #doInBackground
*/
@SuppressWarnings({“UnusedDeclaration”})
protected void onProgressUpdate(Progress… values) {
}
/**
-
Executes the task with the specified parameters. The task returns
-
itself (this) so that the caller can keep a reference to it.
-
This method must be invoked on the UI thread. 注意execute方法必须在UI线程中调用
-
@param params The parameters of the task.
-
@return This instance of AsyncTask.
-
@throws IllegalStateException If {@link #getStatus()} returns either
-
{@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*/
public final AsyncTask<Params, Progress, Result> execute(Params… params) {
if (mStatus != Status.PENDING) {
// 状态检测,只有在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();
// 获得从UI现存传递来的参数
mWorker.mParams = params;
// 交给线程池管理器进行调度,参数为FutureTask类型,构造mFuture时mWorker被传递了进去,后边会继续分析
sExecutor.execute(mFuture);
// 返回自身,使得调用者可以保持一个引用
return this;
}
/**
-
This method can be invoked from {@link #doInBackground} to
-
publish updates on the UI thread while the background computation is
-
still running. Each call to this method will trigger the execution of
-
{@link #onProgressUpdate} on the UI thread.
-
@param values The progress values to update the UI with.
-
@see #onProgressUpdate
-
@see #doInBackground
*/
protected final void publishProgress(Progress… values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult(this, values)).sendToTarget();
}
我们可以看到关键几个步骤的方法都在其中。
1、 doInBackground(Params… params) 是一个抽象方法,我们继承AsyncTask时必须覆写此方法;
2、 onPreExecute()、onProgressUpdate(Progress… values)、onPostExecute(Result result)、onCancelled() 这几个方法体都是空的,我们需要的时候可以选择性的覆写它们;
3、 publishProgress(Progress… values) 是final修饰的,不能覆写,只能去调用,我们一般会在doInBackground(Params… params)中调用此方法来更新进度条;
**4、**另外,我们可以看到有一个Status的枚举类和getStatus()方法,Status枚举类代码段如下:
//初始状态
private volatile Status mStatus = Status.PENDING;
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,
}
/**
-
Returns the current status of this task.
-
@return The current status.
*/
public final Status getStatus() {
return mStatus;
}
可以看到,AsyncTask的初始状态为 PENDING ,代表待定状态, RUNNING 代表执行状态, FINISHED 代表结束状态,这几种状态在AsyncTask一次生命周期内的很多地方被使用,非常重要。
在execute函数中涉及到三个陌生的变量:mWorker、sExecutor、mFuture,我们也会看一下:
关于sExecutor,它是java.util.concurrent.ThreadPoolExecutor的实例,用于管理线程的执行。代码如下:
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 10;
//新建一个队列用来存放线程
private static final BlockingQueue sWorkQueue =
new LinkedBlockingQueue(10);
//新建一个线程工厂
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 ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
mWorker实际上是AsyncTask的一个的抽象内部类的实现对象实例,它实现了Callable接口中的call()方法,代码如下:
[java] view plaincopy
private static abstract class WorkerRunnable<Params, Result> implements Callable {
Params[] mParams;
}
而mFuture实际上是 java.util.concurrent.FutureTask 的实例,下面是它的FutureTask类的相关信息:
/**
-
A cancellable asynchronous computation.
-
…
*/
public class FutureTask implements RunnableFuture {
public interface RunnableFuture extends Runnable, Future {
/**
-
Sets this Future to the result of its computation
-
unless it has been cancelled.
*/
void run();
}
可以看到FutureTask是一个可以中途取消的用于异步计算的类。
下面是mWorker和mFuture实例在AsyncTask中的体现:
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask mFuture;
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
//call方法被调用后,将设置优先级为后台级别, 然后调用AsyncTask的doInBackground方法
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return doInBackground(mParams);
}
};
// 在mFuture实例中,将会调用mWorker做后台任务,完成后会调用done方法。
// 这里将mWorker作为参数传递给了mFuture对象
mFuture = new FutureTask(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = 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) {
//发送取消任务的消息
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new AsyncTaskResult(AsyncTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
- “doInBackground()”, t);
}
//发送显示结果的消息
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(AsyncTask.this, result));
message.sendToTarget();
}
};
}
我们看到上面的代码中,mFuture实例对象的done()方法中,如果捕捉到了CancellationException类型的异常,则发送一条“MESSAGE_POST_CANCEL”的消息;如果顺利执行,则发送一条“MESSAGE_POST_RESULT”的消息,而消息都与一个sHandler对象关联。
我们继续按着执行流程跟踪代码,
// 正在执行任务前的准备处理
onPreExecute();
// 获得从UI现存传递来的参数
mWorker.mParams = params;
// 交给线程池管理器进行调度,参数为FutureTask类型,构造mFuture时mWorker被传递了进去,后边会继续分析
sExecutor.execute(mFuture);
进入到ThreadPoolExecutor的execute函数,如下 :
[java] view plaincopy
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
-
Proceed in 3 steps:
-
- If fewer than corePoolSize threads are running, try to
-
start a new thread with the given command as its first
-
task. The call to addWorker atomically checks runState and
-
workerCount, and so prevents false alarms that would add
-
threads when it shouldn’t, by returning false.
-
- If a task can be successfully queued, then we still need
-
to double-check whether we should have added a thread
-
(because existing ones died since last checking) or that
-
the pool shut down since entry into this method. So we
-
recheck state and if necessary roll back the enqueuing if
-
stopped, or start a new thread if there are none.
-
- If we cannot queue task, then we try to add a new
-
thread. If it fails, we know we are shut down or saturated
-
and so reject the task.
*/
int c = ctl.get();
if (workerCountOf© < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning© && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
可以看到,这段代码的主要功能是将异步任务mFuture加入到将要执行的队列中,重要的函数为addWoker,我们继续跟踪代码到该函数。
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;😉 {
int c = ctl.get();
int rs = runStateOf©;
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;😉 {
int wc = workerCountOf©;
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount©)
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf© != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
// 这里又生成了一个Worker的对象,将异步任务传递给了w
Worker w = new Worker(firstTask);
Thread t = w.thread;
… // 后续代码省略
wokers.add( w );// 将w添加到了wokers里,这是一个HashSet集合对象
…
w.start(); // 启动该异步任务,即启动了mFuture任务。
…
return true;
}
由于mFuture是FutureTask类型,因此继续跟踪到FutureTask的代码。可以看到该构造函数,即上文中构造mFuture时用的构造函数,参数我们传递的是mWorker。
public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
sync = new Sync(callable);
}
可以看到构造函数又将mWorker交给了Sync类型。
而启动mFuture时就会执行其中的run函数,如下 :
public void run() {
sync.innerRun();
}
可知,实际上调用的是Sync的innerRun()函数,我们继续查看Sync类型。
private volatile Thread runner;
造函数,传递进来的就是最先说的那个mWorker
Sync(Callable callable) {
this.callable = callable;
}
… // 部分代码省略
// innerRun函数
void innerRun() {
if (!compareAndSetState(READY, RUNNING))
return;
runner = Thread.currentThread();
if (getState() == RUNNING) { // recheck after setting thread
V result;
try {
// 可以发现调用的是callable的.call()函数,即mWorker的call函数,而在mWorker的call函数中才真正的调用了doInBackground函数,至此线程真正启动了!
result = callable.call();
} catch (Throwable ex) {
setException(ex);
return;
}
set(result);
} else {
releaseShared(0); // cancel
}
}
我们看到,最后调用了set(result);我们看看这段代码 :
protected void set(V v) {
sync.innerSet(v);
}
我们在看看sync中的innerSet方法 :
void innerSet(V v) {
for (;😉 {
int s = getState();
if (s == RAN)
return;
if (s == CANCELLED) {
// aggressively release to set runner to null,
// in case we are racing with a cancel request
// that will try to interrupt runner
releaseShared(0);
return;
}
if (compareAndSetState(s, RAN)) {
result = v;
releaseShared(0);
done(); // 调用了done方法
return;
}
}
}
我们前面说过,在AsyncTask构造方法中创建的mFuture对象覆写了done方法,在这个方法中获取调用结果,最终通过postResult将结果投递给UI线程。
再来分析AsyncTask中的sHandler。这个sHandler实例实际上是AsyncTask内部类InternalHandler的实例,而InternalHandler正是继承了Handler,下面我们来分析一下它的代码:
private static final int MESSAGE_POST_RESULT = 0x1; //显示结果
private static final int MESSAGE_POST_PROGRESS = 0x2; //更新进度
private static final int MESSAGE_POST_CANCEL = 0x3; //取消任务
private static final InternalHandler sHandler = new InternalHandler();
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
//调用AsyncTask.finish方法
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
//调用AsyncTask.onProgressUpdate方法
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
//调用AsyncTask.onCancelled方法
result.mTask.onCancelled();
break;
}
}
}
我们看到,在处理消息时,遇到“MESSAGE_POST_RESULT”时,它会调用AsyncTask中的finish()方法,我们来看一下finish()方法的定义:
private void finish(Result result) {
if (isCancelled()) result = null;
onPostExecute(result); //调用onPostExecute显示结果
mStatus = Status.FINISHED; //改变状态为FINISHED
}
原来finish()方法是负责调用onPostExecute(Result result)方法显示结果并改变任务状态的啊。
另外,在mFuture对象的done()方法里,构建一个消息时,这个消息包含了一个AsyncTaskResult类型的对象,然后在sHandler实例对象的handleMessage(Message msg)方法里,使用下面这种方式取得消息中附带的对象:
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
最后
都说三年是程序员的一个坎,能否晋升或者提高自己的核心竞争力,这几年就十分关键。
技术发展的这么快,从哪些方面开始学习,才能达到高级工程师水平,最后进阶到Android架构师/技术专家?我总结了这 5大块;
我搜集整理过这几年阿里,以及腾讯,字节跳动,华为,小米等公司的面试题,把面试的要求和技术点梳理成一份大而全的“ Android架构师”面试 PDF(实际上比预期多花了不少精力),包含知识脉络 + 分支细节。
Java语言与原理;
大厂,小厂。Android面试先看你熟不熟悉Java语言
高级UI与自定义view;
自定义view,Android开发的基本功。
性能调优;
数据结构算法,设计模式。都是这里面的关键基础和重点需要熟练的。
NDK开发;
未来的方向,高薪必会。
前沿技术;
组件化,热升级,热修复,框架设计
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
我在搭建这些技术框架的时候,还整理了系统的高级进阶教程,会比自己碎片化学习效果强太多
当然,想要深入学习并掌握这些能力,并不简单。关于如何学习,做程序员这一行什么工作强度大家都懂,但是不管工作多忙,每周也要雷打不动的抽出 2 小时用来学习。
不出半年,你就能看出变化!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
及腾讯,字节跳动,华为,小米等公司的面试题,把面试的要求和技术点梳理成一份大而全的“ Android架构师”面试 PDF(实际上比预期多花了不少精力),包含知识脉络 + 分支细节。
[外链图片转存中…(img-InsxvSXt-1713703977767)]
Java语言与原理;
大厂,小厂。Android面试先看你熟不熟悉Java语言
[外链图片转存中…(img-MtmhfgkD-1713703977768)]
高级UI与自定义view;
自定义view,Android开发的基本功。
[外链图片转存中…(img-tPTId3Xc-1713703977768)]
性能调优;
数据结构算法,设计模式。都是这里面的关键基础和重点需要熟练的。
[外链图片转存中…(img-IgC672Nx-1713703977768)]
NDK开发;
未来的方向,高薪必会。
[外链图片转存中…(img-r7LJrRAp-1713703977769)]
前沿技术;
组件化,热升级,热修复,框架设计
[外链图片转存中…(img-AM64gMvq-1713703977769)]
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。
我在搭建这些技术框架的时候,还整理了系统的高级进阶教程,会比自己碎片化学习效果强太多
当然,想要深入学习并掌握这些能力,并不简单。关于如何学习,做程序员这一行什么工作强度大家都懂,但是不管工作多忙,每周也要雷打不动的抽出 2 小时用来学习。
不出半年,你就能看出变化!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-CSAcESBM-1713703977769)]
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!