Android中AsyncTask的使用与源码分析(1)

2. onPreExecute(),在execute(Params… params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。

3. doInBackground(Params… params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress… values)来更新进度信息。

4. onProgressUpdate(Progress… values),在调用publishProgress(Progress… values)时,此方法被执行,直接将进度信息更新到UI组件上。

5. onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。

在使用的时候,有几点需要格外注意:

1. 异步任务的实例必须在UI线程中创建。

2. execute(Params… params)方法必须在UI线程中调用。

3. 不能在doInBackground(Params… params)中更改UI组件的信息。

4. 一个任务实例只能执行一次,如果执行第二次将会抛出异常。

一 、 AsyncTask的使用示例

==================

接下来,我们来看看如何使用AsyncTask执行异步任务操作,我们先建立一个项目,结构如下:

结构相对简单一些,让我们先看看MainActivity.java的代码:

package com.scott.async;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ProgressBar;

import android.widget.TextView;

public class MainActivity extends Activity {

private static final String TAG = “ASYNC_TASK”;

private Button execute;

private Button cancel;

private ProgressBar progressBar;

private TextView textView;

private MyTask mTask;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

execute = (Button) findViewById(R.id.execute);

execute.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// 注意每次需new一个实例,新建的任务只能执行一次,否则会出现异常

mTask = new MyTask();

mTask.execute(“http://www.baidu.com”);

execute.setEnabled(false);

cancel.setEnabled(true);

}

});

cancel = (Button) findViewById(R.id.cancel);

cancel.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//取消一个正在执行的任务,onCancelled方法将会被调用,实际上是调用了FutureTask的取消操作,关于FutureTask下文会有介绍

mTask.cancel(true);

}

});

progressBar = (ProgressBar) findViewById(R.id.progress_bar);

textView = (TextView) findViewById(R.id.text_view);

}

private class MyTask extends AsyncTask<String, Integer, String> {

//onPreExecute方法用于在执行后台任务前做一些UI操作

@Override

protected void onPreExecute() {

Log.i(TAG, “onPreExecute() called”);

textView.setText(“loading…”);

}

// doInBackground方法内部执行后台任务,不可在此方法内修改UI,运行在后台线程。

@Override

protected String doInBackground(String… params) {

Log.i(TAG, “doInBackground(Params… params) called”);

try {

HttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet(params[0]);

HttpResponse response = client.execute(get);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

HttpEntity entity = response.getEntity();

InputStream is = entity.getContent();

long total = entity.getContentLength();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] buf = new byte[1024];

int count = 0;

int length = -1;

while ((length = is.read(buf)) != -1) {

baos.write(buf, 0, length);

count += length;

//调用publishProgress公布进度,最后onProgressUpdate方法将被执行

publishProgress((int) ((count / (float) total) * 100));

//为了演示进度,休眠500毫秒

Thread.sleep(500);

}

return new String(baos.toByteArray(), “gb2312”);

}

} catch (Exception e) {

Log.e(TAG, e.getMessage());

}

return null;

}

// onProgressUpdate方法用于更新进度信息

@Override

protected void onProgressUpdate(Integer… progresses) {

Log.i(TAG, “onProgressUpdate(Progress… progresses) called”);

progressBar.setProgress(progresses[0]);

textView.setText(“loading…” + progresses[0] + “%”);

}

// onPostExecute方法用于在执行完后台任务后更新UI,显示结果。 运行在UI线程

@Override

protected void onPostExecute(String result) {

Log.i(TAG, “onPostExecute(Result result) called”);

textView.setText(result);

execute.setEnabled(true);

cancel.setEnabled(false);

}

//onCancelled方法用于在取消执行中的任务时更改UI

@Override

protected void onCancelled() {

Log.i(TAG, “onCancelled() called”);

textView.setText(“cancelled”);

progressBar.setProgress(0);

execute.setEnabled(true);

cancel.setEnabled(false);

}

}

}

布局文件main.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

android:orientation=“vertical”

android:layout_width=“fill_parent”

android:layout_height=“fill_parent”>

<Button

android:id=“@+id/execute”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:text=“execute”/>

<Button

android:id=“@+id/cancel”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:enabled=“false”

android:text=“cancel”/>

<ProgressBar

android:id=“@+id/progress_bar”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”

android:progress=“0”

android:max=“100”

style=“?android:attr/progressBarStyleHorizontal”/>

<ScrollView

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”>

<TextView

android:id=“@+id/text_view”

android:layout_width=“fill_parent”

android:layout_height=“wrap_content”/>

因为需要访问网络,所以我们还需要在AndroidManifest.xml中加入访问网络的权限:

二、 AsyncTask的实现基本原理

===================

上面介绍了AsyncTask的基本应用,有些朋友也许会有疑惑,AsyncTask内部是怎么执行的呢,它执行的过程跟我们使用Handler又有什么区别呢?答案是:AsyncTask是对Thread+Handler良好的封装,在android.os.AsyncTask代码里仍然可以看到Thread和Handler的踪迹。下面就向大家详细介绍一下AsyncTask的执行原理。

源代码如下 :

/**

  • 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.

  • This method can call {@link #publishProgress} to publish updates

  • on the UI thread.

  • @param params The parameters of the task.

  • @return A result, defined by the subclass of this task.

  • 这是一个abstract 方法,因此必须覆写。

  • @see #onPreExecute()

  • @see #onPostExecute

  • @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,

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
img

最后

答应大伙的备战金三银四,大厂面试真题来啦!

这份资料我从春招开始,就会将各博客、论坛。网站上等优质的Android开发中高级面试题收集起来,然后全网寻找最优的解答方案。每一道面试题都是百分百的大厂面经真题+最优解答。包知识脉络 + 诸多细节。
节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。
给文章留个小赞,就可以免费领取啦~

戳我领取:3000页Android开发者架构师核心知识笔记

《960全网最全Android开发笔记》

《379页Android开发面试宝典》

包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

如何使用它?
1.可以通过目录索引直接翻看需要的知识点,查漏补缺。
2.五角星数表示面试问到的频率,代表重要推荐指数

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

腾讯、字节跳动、阿里、百度等BAT大厂 2020-2021面试真题解析

资料收集不易,如果大家喜欢这篇文章,或者对你有帮助不妨多多点赞转发关注哦。文章会持续更新的。绝对干货!!!

优质的Android开发中高级面试题收集起来,然后全网寻找最优的解答方案。每一道面试题都是百分百的大厂面经真题+最优解答。包知识脉络 + 诸多细节。
节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。
给文章留个小赞,就可以免费领取啦~

戳我领取:3000页Android开发者架构师核心知识笔记

《960全网最全Android开发笔记》

[外链图片转存中…(img-J8d7ro9J-1710506961508)]

《379页Android开发面试宝典》

包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

如何使用它?
1.可以通过目录索引直接翻看需要的知识点,查漏补缺。
2.五角星数表示面试问到的频率,代表重要推荐指数

[外链图片转存中…(img-Ia0eS0PL-1710506961508)]

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

[外链图片转存中…(img-GjnG0HyM-1710506961508)]

腾讯、字节跳动、阿里、百度等BAT大厂 2020-2021面试真题解析

[外链图片转存中…(img-yxRfHFDC-1710506961509)]

资料收集不易,如果大家喜欢这篇文章,或者对你有帮助不妨多多点赞转发关注哦。文章会持续更新的。绝对干货!!!

  • 27
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值