作者:刘昊昱

博客: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. Android 免费短信获取国家列表和国家代码

    StringBuffer str = new StringBuffer(); for (Map.Entry<Character, ArrayList<String[]>> en ...

  2. vim note(4)

    :new 文件名.词尾 新文件. :e 文件名 打开文件. :w 文件名.txt 保存文件. :wq 保存并退出. :x 辍学.假设文件更改被保存 版权声明:本文博主原创文章,博客,未经同意不得转载.

  3. MYSQL 体系结构图-LRU FREELIST FLUSH LIST

  4. IO流--转载

    第 1 部分 从输出流中读取 http://www.ibm.com/developerworks/cn/java/j-io1/ 自早期基于浏览器的 applet 和简单应用程序以来,Java 平台已有 ...

  5. NYOJ2括号配对问题

    括号配对是最基本的栈的问题,它是栈入门的经典题目,思路是,如果是左括号直接进栈,如果是右括号,这时就要比较栈顶的元素与他是否匹配,如果匹配则出栈,否则进栈,下面是代码的实现: #include < ...

  6. ubuntu 配置Java jdk

    本文参考:http://www.cnblogs.com/memory4young/p/ubuntu-install-jdk.html 一.下载 到oracle官方网站下载jdk,博主下载时的版本是8u ...

  7. ASP.NET 实现上一篇文章 下一篇文章

    select top 1 * from job_hrnews where newsid>162  --下一篇 select top 1 * from job_hrnews where newsi ...

  8. jquery.cookie用法详细解析

    本篇文章主要是对jquery.cookie的用法进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助 Cookie是由服务器端生成,发送给User-Agent(一般是浏览器),浏览器会将 ...

  9. JS格式化数字金额用逗号隔开保留两位小数

    JS格式化金额,正则方式修改. /** * 格式化金额 * @param {[type]} v [要转换的数字] * @param {[type]} len [小数点位数,默认2位] * @param ...

  10. 你好,C++(35)类是如何藏私房钱的?6.2.4 拷贝构造函数

    6.2.6  类成员的访问控制 类成员包括类的成员变量和成员函数,它们分别用来描述类的属性和行为.而类成员的访问控制决定了哪些成员是公开的,可以被外界访问,也可以被自身访问:哪些成员是私有的,只能在类 ...