作者:刘昊昱

博客: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. 删除表中多余的重复记录(多个字段),只留有rowid最小的记录

    假如表Users,其中ID为自增长. ID,Name,Sex 1 张三,男 2 张三,男 3 李四,女 4 李四,女 5 王五,男 --查找出最小行号ID的重复记录 select Name,Sex,C ...

  2. 禁止执行某些讨厌的程序,如tadb.exe

    第一步:首先通过快捷键"Win+R"来打开"执行"菜单. 第二步:输入"gpedit.msc"回车确认,进入我们电脑中的组策略编辑器. 第三 ...

  3. dubbo(soa分布式)与cobar(mysql分布式)

    http://www.jianshu.com/p/0dde591f21d0 (Dubbo编译不是个顺利的事) Cobar是提供关系型数据库(MySQL)分布式服务的中间件,它可以让传统的数据库得到良好 ...

  4. TCP的封包与拆包

    对于基于TCP开发的通讯程序,有个很重要的问题需要解决,就是封包和拆包. 一.为什么基于TCP的通讯程序需要进行封包和拆包. TCP是个"流"协议,所谓流,就是没有界限的一串数据. ...

  5. CoreText实现图文混排之点击事件

    今天呢,我们继续把CoreText图文混排的点击事件补充上,这样我们的图文混排也算是圆满了. 哦,上一篇的链接在这里 http://www.jianshu.com/p/6db3289fb05d Cor ...

  6. 从页面底部向上弹出dialog,消失时逐渐向下(转)

    我想实现一个效果,从底部向上逐渐弹出.如下图所示: 1.点击 显示 按钮时,一个dialog对话框从底部慢慢向上弹出. 2.关闭dialog时, dialog缓慢的移动向底部消失.很平滑的效果.   ...

  7. HDU3853

    题意:给R*C的迷宫,起点为1,1 终点为R,C 且给定方格所走方向的概率,分别为原地,下边,右边,求到终点的期望. 思路:既然是求到终点的期望,那么DP代表期望,所以DP[i][j]=原地的概率*D ...

  8. JSON和JSONP区别

    JSON(JavaScript Object Notation)和JSONP(JSON with Padding) JSON是一种数据交换格式,JSONP是一种跨域数据交互协议 JSONP利用scri ...

  9. html.ex.day02

    1.同一个目录内页面跳转 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  10. Mac下Sublime快捷键

    由于自己笔记本是mac,造成window与mac中sublime快捷键不同,现在稍微整理下常用的方便于记忆: 1.control+alt+enter 打开Emmet(Zencoding) 2.supe ...