Android中AsyncTask异步任务使用详细实例(一)
作者:mrr 发布时间:2022-05-28 19:08:15
标签:android,asynctask,异步任务
AsyncTask是Android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程。
使用AsyncTask最少要重写以下两个方法:
1、doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
2、onPostExecute(Result) 在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回 。
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>
以上内容是小编给大家介绍的Android中AsyncTask异步任务使用详细实例(一),希望对大家有所帮助!


猜你喜欢
- Maven 错误找不到符号问题,通常有三种原因: 1. 可能项目编码格式不统一。 2. 可能项目编码使用的JDK版本不统一。 3
- 举例:存在一个类:Public Class Student{ public string name; public int age;}Stu
- 一 概述:最近一直致力于Android自定义VIew的学习,主要在看《android群英传》,还有CSDN博客鸿洋大神和wing
- java 8的新特性之一就是lambda表达式,parallelStream()都说性能会比较高,现一探究竟。话不多说,上代码: @Test
- 项目中有几个batch需要检查所有的用户参与的活动的状态,以前是使用分页,一页一页的查出来到内存再处理,但是随着数据量的增加,效率越来越低。
- 本文实例讲述了Android编程实现调用相册、相机及拍照后直接裁剪的方法。分享给大家供大家参考,具体如下:package com.cvte.
- 环境springboot1.5.9完整代码,内有sql,先建库,在运行sql建表,sql中已插入测试的数据。https://github.c
- 微信聊天现在非常火,是因其界面漂亮吗,哈哈,也许吧。微信每条消息都带有一个气泡,非常迷人,看起来感觉实现起来非常难,其实并不难。下面小编给大
- 方式1. 使用HashtableMap<String,Object> hashtable=new Hashtable
- 需求背景需求一:SpringMVC构建的微服务系统,数据库对日期的存储是Long类型的时间戳,前端之前是默认使用Long类型时间,现在前端框
- 发生服务器 500 异常,如果默认方式处理,则是将异常捕获之后跳到 Tomcat 缺省的异常页面,如下图所示。不论哪个网站都是一样的,所以为
- 初级技巧 - 乐观锁乐观锁适合这样的场景:读不会冲突,写会冲突。同时读的频率远大于写。以下面的代码为例,悲观锁的实现:public Obje
- < drawable name="white">#FFFFFF< /drawable><
- android 在webView里面截图大概有四种方式,具体内容如下1.获取到DecorView然后将DecorView转换成bitmap然
- 项目中有需要多次统计 某些集合中 的某个属性值,所以考虑封装一个方法,让其其定义实现计算方式。 话不多说,看代码:1、封装的自定义集合工具类
- 本文实例为大家分享了C语言实现一个扫雷小游戏的具体代码,供大家参考,具体内容如下一、全部源码//棋盘大小#define ROW 9#defi
- 软引用简介软引用是用来表示某个引用会被GC(垃圾处理器)收集的类。当有引用指向某个obj的时候,通常发生GC的时候不会把这个对象处理掉,但是
- AndroidMaifest.xml中声明权限<!-- 声明所有需要的权限(包括普通权限和危险权限) --><uses-p
- 本文实例完成人机猜拳互动游戏的开发,供大家参考,具体内容如下阶段一:实验——分析业务,创建用户类1.分析业务,抽象出类、类的特征和行为2.创
- 本文实例讲述了WPF设置窗体可以使用鼠标拖动大小的方法。分享给大家供大家参考。具体实现方法如下:private void Window_Lo