Android应用开发学习笔记之AsyncTask
作者:刘昊昱
博客: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 Executor, ThreadPoolExecutor 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 Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate 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的更多相关文章
- Android应用开发学习笔记之播放音频
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android支持常用音视频格式文件的播放,本文我们来学习怎样开发Android应用程序对音视频进行操作. Andr ...
- android移动开发学习笔记(二)神奇的Web API
本次分两个大方向去讲解Web Api,1.如何实现Web Api?2.如何Android端如何调用Web Api?对于Web Api是什么?有什么优缺点?为什么用WebApi而不用Webservice ...
- Android应用开发学习笔记之事件处理
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android提供的事件处理机制分为两类:一是基于监听的事件处理:二是基于回调的事件处理.对于基于监听的事件处理,主 ...
- [Android游戏开发学习笔记]View和SurfaceView
本文为阅读http://blog.csdn.net/xiaominghimi/article/details/6089594的笔记. 在Android游戏中充当主要角色的,除了控制类就是显示类.而在A ...
- Android应用开发学习笔记之Fragment
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Fragment翻译成中文就是“碎片”.“片断”的意思,Fragment通常用来作为一个Activity用户界面的一 ...
- Android应用开发学习笔记之菜单
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android中的菜单分为选项菜单(OptionMenu)和上下文菜单(Context Menu).通常使用菜单资源 ...
- Android应用开发学习笔记之Intent
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Intent是什么呢?来看Android官网上的定义: An intent is an abstractdescri ...
- Android应用开发学习笔记之多线程与Handler消息处理机制
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 和JAVA一样,Android下我们可以通过创建一个Thread对象实现多线程.Thread类有多个构造函数,一般通 ...
- Android应用开发学习笔记之BroadcastReceiver
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz 一.BroadcastReceiver机制概述 Broadcast Receiver是Android的一种“广播发布 ...
随机推荐
- Gridview实现银行选择列表
[MainActivity.java] package com.example.activitydemo; import android.os.Bundle; import android.view. ...
- [Angular 2] Validation
Define a filed should has validation: export class DemoFormSku { myForm: ControlGroup; sku: Abstract ...
- [转] 不要被C++“自动生成”所蒙骗
http://www.cnblogs.com/fanzhidongyzby/archive/2013/01/12/2858040.html C++对象可以使用两种方式进行创建:构造函数和复制构造函数. ...
- [转] C++指针加整数、两个指针相减的问题
http://blog.csdn.net/onlyou930/article/details/6725051 说来惭愧,写C++有一段时间了.这个问题从来没有认真考虑过,此次标记于此: 考虑如下问题: ...
- Camera2Raw
This sample demonstrates how to use the Camera2 API to capture RAW camera buffers and save them as D ...
- Android(java)学习笔记217:开发一个多界面的应用程序之清单文件
清单文件的重要参数: <intent-filter> 代表的应用程序的入口界面 <action android:name=&quo ...
- centos 安装nginx
centos 安装nginx 安装依赖 更换源 yum install http://mirrors.163.com/centos/6.8/extras/x86_64/Packages/epel-re ...
- Directive Definition Object
不知道为什么这个我并没有想翻译过来的欲望,或许我并没有都看熟透,不好误人子弟,原版奉上. Here's an example directive declared with a Directive D ...
- 浏览器中 for in 反射 对象成员 的差异
http://www.cnblogs.com/_franky/archive/2010/05/08/1730437.html 下面是例子 function test(url, obj) { if($( ...
- Linux下svn命令switch用法
# svn info /data/www/49you/api.49you.com Path: /data/www/49you/api.49you.comURL: svn://192.168.10.81 ...