天天看点

Android进程与线程基本知识三

3.android另外提供了一个工具类:asynctask。

它使得ui thread的使用变得异常简单。它使创建需要与用户界面交互的长时间运行的任务变得更简单,不需要借助线程和handler即可实现。

1) 子类化asynctask

2) 实现asynctask中定义的下面一个或几个方法

onpreexecute() 开始执行前的准备工作;

doinbackground(params...) 开始执行后台处理,可以调用publishprogress方法来更新实时的任务进度;

onprogressupdate(progress...) 在publishprogress方法被调用后,ui thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。

onpostexecute(result) 执行完成后的操作,传送结果给ui 线程。

这4个方法都不能手动调用。而且除了doinbackground(params...)方法,其余3个方法都是被ui线程所调用的,所以要求:

1) asynctask的实例必须在ui thread中创建;

2) asynctask.execute方法必须在ui thread中调用;

同时要注意:该task只能被执行一次,否则多次调用时将会出现异常。而且是不能手动停止的,这一点要注意,看是否符合你的需求!

在使用过程中,发现asynctask的构造函数的参数设置需要看明白:

asynctask<params, progress, result> params对应doinbackground(params...)的参数类型。

而new asynctask().execute(params... params),就是传进来的params数据,你可以execute(data)来传送一个数据,或者execute(data1, data2, data3)这样多个数据。

progress对应onprogressupdate(progress...)的参数类型;

result对应onpostexecute(result)的参数类型。 当以上的参数类型都不需要指明某个时,则使用void,注意不是void。不明白的可以参考上面的例子,或者api doc里面的例子。

下面是关于asynctask的使用示例:

((button) findviewbyid(r.id.load_asynctask)).setonclicklistener(new view.onclicklistener(){

@override

public void onclick(view view) {

data = null;

data = new arraylist<string>();

adapter = null;

//显示progressdialog放到asynctask.onpreexecute()里

//showdialog(progress_dialog);

new progresstask().execute(data);

}

});

private class progresstask extends asynctask<arraylist<string>, void, integer> {

/* 该方法将在执行实际的后台操作前被ui thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。*/

protected void onpreexecute() {

// 先显示progressdialog

showdialog(progress_dialog);

/* 执行那些很耗时的后台计算工作。可以调用publishprogress方法来更新实时的任务进度。 */

protected integer doinbackground(arraylist<string>... datas) {

arraylist<string> data = datas[0];

for (int i=0; i<8; i++) {

data.add("listitem");

return state_finish;

/* 在doinbackground 执行完成后,onpostexecute 方法将被ui thread调用,

* 后台的计算结果将通过该方法传递到ui thread.

*/

protected void onpostexecute(integer result) {

int state = result.intvalue();

switch(state){

case state_finish:

dismissdialog(progress_dialog);

toast.maketext(getapplicationcontext(),

"加载完成!",

toast.length_long)

.show();

adapter = new arrayadapter<string>(getapplicationcontext(),

android.r.layout.simple_list_item_1,

data );

setlistadapter(adapter);

break;

case state_error:

"处理过程发生错误!",

default:

以上是从网络获取数据,加载到listview中示例。

继续阅读