AsyncTask异步任务使用详细实例(一)

简介:  MainActivity如下: package com.example.asynctasktest;import java.io.ByteArrayOutputStream;import java.


MainActivity如下:

package com.example.asynctasktest;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
	private Button satrtButton;
	private Button cancelButton;
	private ProgressBar progressBar;
	private TextView textView;
	private DownLoaderAsyncTask downLoaderAsyncTask;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initView();
    }
	public void initView() {
		satrtButton=(Button) findViewById(R.id.startButton);
		cancelButton=(Button) findViewById(R.id.cancelButton);
		satrtButton.setOnClickListener(new ButtonOnClickListener());
		cancelButton.setOnClickListener(new ButtonOnClickListener());
		progressBar=(ProgressBar) findViewById(R.id.progressBar);
		textView=(TextView) findViewById(R.id.textView);
	}
   private class ButtonOnClickListener implements OnClickListener{
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.startButton:
				//注意:
				//1 每次需new一个实例,新建的任务只能执行一次,否则会出现异常
				//2 异步任务的实例必须在UI线程中创建
				//3 execute()方法必须在UI线程中调用。
				downLoaderAsyncTask=new DownLoaderAsyncTask();
				downLoaderAsyncTask.execute("http://www.baidu.com");
				break;
			case R.id.cancelButton:
				//取消一个正在执行的任务,onCancelled()方法将会被调用   
                downLoaderAsyncTask.cancel(true);
				break;
			default:
				break;
			}
		}
	   
   }
   //构造函数AsyncTask<Params, Progress, Result>参数说明: 
   //Params   启动任务执行的输入参数
   //Progress 后台任务执行的进度
   //Result   后台计算结果的类型
   private class DownLoaderAsyncTask extends AsyncTask<String, Integer, String>{
	//onPreExecute()方法用于在执行异步任务前,主线程做一些准备工作   
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		textView.setText("调用onPreExecute()方法--->准备开始执行异步任务");
		System.out.println("调用onPreExecute()方法--->准备开始执行异步任务");
	}
	
	//doInBackground()方法用于在执行异步任务,不可以更改主线程中UI 
	@Override
	protected String doInBackground(String... params) {
	   System.out.println("调用doInBackground()方法--->开始执行异步任务");
		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 bos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int count = 0;
				int length = -1;
				while ((length = is.read(buffer)) != -1) {
					bos.write(buffer, 0, length);
					count += length;
					//publishProgress()为AsyncTask类中的方法
					//常在doInBackground()中调用此方法
					//用于通知主线程,后台任务的执行情况.
					//此时会触发AsyncTask中的onProgressUpdate()方法
					publishProgress((int) ((count / (float) total) * 100));
					//为了演示进度,休眠1000毫秒
					Thread.sleep(1000);
				}
				return new String(bos.toByteArray(), "UTF-8");
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}
	
	//onPostExecute()方法用于异步任务执行完成后,在主线程中执行的操作
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);	
		Toast.makeText(getApplicationContext(), "调用onPostExecute()方法--->异步任务执行完毕", 0).show();
		//textView显示网络请求结果
		textView.setText(result);
		System.out.println("调用onPostExecute()方法--->异步任务执行完毕");
	}
	   
	//onProgressUpdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息   
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		//更改进度条
		progressBar.setProgress(values[0]);
		//更改TextView
		textView.setText("已经加载"+values[0]+"%");
	}
	
	//onCancelled()方法用于异步任务被取消时,在主线程中执行相关的操作 
	@Override
	protected void onCancelled() {
		super.onCancelled();
		//更改进度条进度为0
		progressBar.setProgress(0);
		//更改TextView
		textView.setText("调用onCancelled()方法--->异步任务被取消");
		System.out.println("调用onCancelled()方法--->异步任务被取消");
	}
   }
}


main.xml如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/startButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="开始异步任务" />

    <Button
        android:id="@+id/cancelButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="取消异步任务" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="0" />

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="test test" />
    </ScrollView>

</LinearLayout>


重要参考资料:

http://blog.csdn.net/liuhe688/article/details/6532519

Thank you very much

相关文章
|
8天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
7天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
348 130
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
|
19天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1332 8
|
7天前
|
人工智能 Java API
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
本文介绍AI大模型的核心概念、分类及开发者学习路径,重点讲解如何选择与接入大模型。项目基于Spring Boot,使用阿里云灵积模型(Qwen-Plus),对比SDK、HTTP、Spring AI和LangChain4j四种接入方式,助力开发者高效构建AI应用。
335 122
AI 超级智能体全栈项目阶段一:AI大模型概述、选型、项目初始化以及基于阿里云灵积模型 Qwen-Plus实现模型接入四种方式(SDK/HTTP/SpringAI/langchain4j)
|
6天前
|
监控 JavaScript Java
基于大模型技术的反欺诈知识问答系统
随着互联网与金融科技发展,网络欺诈频发,构建高效反欺诈平台成为迫切需求。本文基于Java、Vue.js、Spring Boot与MySQL技术,设计实现集欺诈识别、宣传教育、用户互动于一体的反欺诈系统,提升公众防范意识,助力企业合规与用户权益保护。
|
18天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1422 87
|
6天前
|
JavaScript Java 大数据
基于JavaWeb的销售管理系统设计系统
本系统基于Java、MySQL、Spring Boot与Vue.js技术,构建高效、可扩展的销售管理平台,实现客户、订单、数据可视化等全流程自动化管理,提升企业运营效率与决策能力。
|
7天前
|
弹性计算 安全 数据安全/隐私保护
2025年阿里云域名备案流程(新手图文详细流程)
本文图文详解阿里云账号注册、服务器租赁、域名购买及备案全流程,涵盖企业实名认证、信息模板创建、域名备案提交与管局审核等关键步骤,助您快速完成网站上线前的准备工作。
265 82
2025年阿里云域名备案流程(新手图文详细流程)