作者:刘昊昱

博客:http://blog.csdn.net/liuhaoyutz

在上一篇文章中我们学习了多线程和Handler消息处理机制,如果有计算量比较大的任务,可以创建一个新线程执行计算工作,但是子线程无法更新UI界面,所以通过Handler消息处理机制与UI线程通信,更新UI界面。

有一个问题需要注意,创建的子线程太多时,会影响系统性能。针对这个问题,Android为我们提供了代替使用Thread和Handler的方案,这就是AsyncTask。下面看Android官方文档对AsyncTask的描述:

AsyncTask enables properand easy use of the UI thread. This class allows to perform backgroundoperations and publish results on the UI thread without having to manipulatethreads and/or handlers.

AsyncTask is designed tobe a helper class around Thread and Handler anddoes not constitute a generic threading framework. AsyncTasks should ideally beused for short operations (a few seconds at the most.) If you need to keepthreads running for long periods of time, it is highly recommended you use thevarious APIs provided by thejava.util.concurrent pacakgesuch as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task isdefined by a computation that runs on a background thread and whose result ispublished on the UI thread. An asynchronous task is defined by 3 generic types,called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

下面看一个使用AsyncTask的例子,该程序运行效果如下:

先来看主布局文件,其内容如下:

<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" > <TextView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:id="@+id/textView"
android:textSize="20dp"
android:gravity="center" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_gravity="center"
android:textSize="20dp"
android:text="启动AsyncTask" /> </LinearLayout>

下面看主Activity文件,其内容如下:

package com.liuhaoyu;

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.TextView; public classMainActivity extends Activity {
private static final String TAG = "liuhaoyu";
TextViewtextView;
Buttonbutton; /** Called when the activity is firstcreated. */
@Override
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); textView = (TextView)findViewById(R.id.textView);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
MyAsyncTaskasyncTask = newMyAsyncTask();
asyncTask.execute(1000);
}
});
} classMyAsyncTask extends AsyncTask<Integer, Integer, String>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Log.d(TAG, "onPreExecute");
} @Override
protected StringdoInBackground(Integer... params) {
// TODO Auto-generated method stub
Log.d(TAG, "doInBackground");
for(int i = 0; i < 10; i++)
{
publishProgress(i);
try {
Thread.sleep(params[0]);
}catch(InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d(TAG, "Background work over");
return "Background work over.";
} @Override
protected voidonProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
Log.d(TAG, "onProgressUpdate");
textView.setText(Integer.toString(values[0]));
} @Override
protected void onPostExecute(Stringresult) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d(TAG, "onPostExecute, result = " + result);
}
}
}

打印的LOG信息如下:

Android应用开发学习笔记之AsyncTask的更多相关文章

  1. Android应用开发学习笔记之播放音频

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android支持常用音视频格式文件的播放,本文我们来学习怎样开发Android应用程序对音视频进行操作. Andr ...

  2. android移动开发学习笔记(二)神奇的Web API

    本次分两个大方向去讲解Web Api,1.如何实现Web Api?2.如何Android端如何调用Web Api?对于Web Api是什么?有什么优缺点?为什么用WebApi而不用Webservice ...

  3. Android应用开发学习笔记之事件处理

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android提供的事件处理机制分为两类:一是基于监听的事件处理:二是基于回调的事件处理.对于基于监听的事件处理,主 ...

  4. [Android游戏开发学习笔记]View和SurfaceView

    本文为阅读http://blog.csdn.net/xiaominghimi/article/details/6089594的笔记. 在Android游戏中充当主要角色的,除了控制类就是显示类.而在A ...

  5. Android应用开发学习笔记之Fragment

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Fragment翻译成中文就是“碎片”.“片断”的意思,Fragment通常用来作为一个Activity用户界面的一 ...

  6. Android应用开发学习笔记之菜单

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android中的菜单分为选项菜单(OptionMenu)和上下文菜单(Context Menu).通常使用菜单资源 ...

  7. Android应用开发学习笔记之Intent

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Intent是什么呢?来看Android官网上的定义: An intent is an abstractdescri ...

  8. Android应用开发学习笔记之多线程与Handler消息处理机制

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 和JAVA一样,Android下我们可以通过创建一个Thread对象实现多线程.Thread类有多个构造函数,一般通 ...

  9. Android应用开发学习笔记之BroadcastReceiver

    作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 一.BroadcastReceiver机制概述 Broadcast Receiver是Android的一种“广播发布 ...

随机推荐

  1. Fiddler 抓包 教程

    Fiddler的基本介绍 Fiddler的官方网站:  www.fiddler2.com Fiddler官方网站提供了大量的帮助文档和视频教程, 这是学习Fiddler的最好资料. Fiddler是最 ...

  2. js事件防止冒泡

    原文连接:http://www.cnblogs.com/jams742003/archive/2009/08/29/1556187.html 1. 事件目标 如今.事件处理程序中的变量event保存着 ...

  3. linux中 vi / vim显示行号或取消行号命令

    1. 显示行号 :set number 或者 :set nu 2. 取消行号显示 :set nu! 3. 每次打开都显示行号 修改vi ~/.vimrc 文件,添加:set number

  4. 从零开始写一个Tomcat(叁)--请求解析

    挖坑挖了这么长时间也该继续填坑了,上文书讲到从零开始写一个Tomcat(贰)--建立动态服务器,讲了如何让服务器解析请求,分离servlet请求和静态资源请求,读取静态资源文件输出或是通过URLCla ...

  5. UIView不能使用UITableView的Static表格的解决方法

    在UIView中嵌入一个Container,用Container来包含UITableViewController即可,到storyboard上显示如下:

  6. Exception in thread "main" brut.androlib.err.UndefinedResObject: resource spec: 0x01030200(转)

    反编译时遇到标题中的异常,根据描述,原因是找不到资源文件,最有可能的原因是apk中使用了系统资源. 解决办法如下: 从手机中导出framework-res.apk文件,该文件在/system/fram ...

  7. 使用搬瓦工搭建javaweb环境

        /* 本文是基于搬瓦工vps的centos-6-x86_64的Linux系统搭建. 需准备的工具:1.putty(用于连接Linux系统)  2.WinSCP(搬瓦工官方提供的ftp上传下载工 ...

  8. Android Service生命周期及用法

    Service概念及用途:Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行, ...

  9. tableView创建方法调用的研究

    当两个section的cell数量都为5的时候,方法的调用顺序: -[ViewController numberOfSectionsInTableView:] -[ViewController tab ...

  10. iOS开发实现登陆

    Assumption假设:iOS端加载Web页,然后用户输入用户名密码登陆,WebServer会把用户登陆信息记载在Cookie.那么iOS客户端如何取到Cookie中的登陆信息. 客户端监听 NSH ...