android 后台耗时,android教程之使用asynctask在后台运行耗时任务

, android中实现了默认的进度提示对话框,即progressdialog,通过实例化和一些简单设置,就可以使用了。

private class downloaddbtask extends asynctask {

// 可变长的输入参数,与asynctask.exucute()对应

progressdialog pdialog;

public downloaddbtask(context context){

pdialog = new progressdialog(context, 0);

pdialog.setbutton("取消", new dialoginterface.onclicklistener() {

public void onclick(dialoginterface dialog, int i) {

dialog.cancel();

}

});

pdialog.setoncancellistener(new dialoginterface.oncancellistener() {

public void oncancel(dialoginterface dialog) {

finish();

}

});

pdialog.settitle("第一次使用,正在下载数据...");

pdialog.setcancelable(true);

pdialog.setmax(100);

pdialog.setprogressstyle(progressdialog.style_horizontal);

pdialog.show();

}

@override

protected string doinbackground(string... params) {

try{

if (dataoper.gettopnearestpois(1, mdbhelper).size()==0)

dataoper.getallptsfromnet(mdbhelper, pdialog); // 从网络上下载数据记录的功能

} catch(exception e) {

e.printstacktrace();

}

return null;

}

@override

protected void oncancelled() {

super.oncancelled();

}

@override

protected void onpostexecute(string result) {

pdialog.dismiss();

}

@override

protected void onpreexecute() {

}

@override

protected void onprogressupdate(integer... values) {

}

}

对于写好的异步任务类,调用方法为:

downloaddbtask task = new downloaddbtask(context);

task.execute("");

注意asynctask为泛型类,具有三个泛型参数,此处设计为 ,对应于运行参数、进度值类型和返回参数。

从sdk的文档中看到,当一个asynctask运行的过程中,经历了4个步骤:

1、onpreexecute(), 在excute调用后立即在ui线程中执行。 this step is normally used to setup the task, for instance by showing a progress bar in the user interface.

2、doinbackground, 当 onpreexecute() 完成后, 立即在后台线程中运行. this step is used to perform background computation that can take a long time. the parameters of the asynchronous task are passed to this step. the result of the computation must be returned by this step and will be passed back to the last step. this step can also use publishprogress to publish one or more units of progress. these values are published on the ui thread, in the onprogressupdate step.

3、onprogressupdate, 在调用publishprogress后,在ui线程中运行. the timing of the execution is undefined. this method is used to display any form of progress in the user interface while the background computation is still executing. for instance, it can be used to animate a progress bar or show logs in a text field.

4、onpostexecute, 后台运算完成时在ui线程中调用. the result of the background computation is passed to this step as a parameter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值