当前位置: 移动技术网 > IT编程>移动开发>Android > Android中AsyncTask异步任务使用详细实例(一)

Android中AsyncTask异步任务使用详细实例(一)

2019年07月24日  | 移动技术网IT编程  | 我要评论

上校姐夫别太霸道,艳照门第二季,日小岛入世遗名录

asynctask是android提供的轻量级的异步类,可以直接继承asynctask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现ui进度更新),最后反馈执行的结果给ui主线程。

使用asynctask最少要重写以下两个方法:

1、doinbackground(params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作ui。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicprogress(progress…)来更新任务的进度。

2、onpostexecute(result) 在这里面可以使用在doinbackground 得到的结果处理操作ui。 此方法在主线程执行,任务执行的结果作为此方法的参数返回 。

mainactivity如下:

package com.example.asynctasktest;
import java.io.bytearrayoutputstream;
import java.io.inputstream;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.httpstatus;
import org.apache.http.client.httpclient;
import org.apache.http.client.methods.httpget;
import org.apache.http.impl.client.defaulthttpclient;
import android.app.activity;
import android.os.asynctask;
import android.os.bundle;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.progressbar;
import android.widget.textview;
import android.widget.toast;
public class mainactivity extends activity {
private button satrtbutton;
private button cancelbutton;
private progressbar progressbar;
private textview textview;
private downloaderasynctask downloaderasynctask;
@override
public void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
initview();
}
public void initview() {
satrtbutton=(button) findviewbyid(r.id.startbutton);
cancelbutton=(button) findviewbyid(r.id.cancelbutton);
satrtbutton.setonclicklistener(new buttononclicklistener());
cancelbutton.setonclicklistener(new buttononclicklistener());
progressbar=(progressbar) findviewbyid(r.id.progressbar);
textview=(textview) findviewbyid(r.id.textview);
}
private class buttononclicklistener implements onclicklistener{
public void onclick(view v) {
switch (v.getid()) {
case r.id.startbutton:
//注意:
//1 每次需new一个实例,新建的任务只能执行一次,否则会出现异常
//2 异步任务的实例必须在ui线程中创建
//3 execute()方法必须在ui线程中调用。
downloaderasynctask=new downloaderasynctask();
downloaderasynctask.execute("http://www.baidu.com");
break;
case r.id.cancelbutton:
//取消一个正在执行的任务,oncancelled()方法将会被调用 
downloaderasynctask.cancel(true);
break;
default:
break;
}
}
}
//构造函数asynctask<params, progress, result>参数说明: 
//params 启动任务执行的输入参数
//progress 后台任务执行的进度
//result 后台计算结果的类型
private class downloaderasynctask extends asynctask<string, integer, string>{
//onpreexecute()方法用于在执行异步任务前,主线程做一些准备工作 
@override
protected void onpreexecute() {
super.onpreexecute();
textview.settext("调用onpreexecute()方法--->准备开始执行异步任务");
system.out.println("调用onpreexecute()方法--->准备开始执行异步任务");
}
//doinbackground()方法用于在执行异步任务,不可以更改主线程中ui 
@override
protected string doinbackground(string... params) {
system.out.println("调用doinbackground()方法--->开始执行异步任务");
try {
httpclient client = new defaulthttpclient();
httpget get = new httpget(params[0]);
httpresponse response = client.execute(get);
if (response.getstatusline().getstatuscode() == httpstatus.sc_ok) {
httpentity entity = response.getentity();
inputstream is = entity.getcontent();
long total = entity.getcontentlength();
bytearrayoutputstream bos = new bytearrayoutputstream();
byte[] buffer = new byte[1024];
int count = 0;
int length = -1;
while ((length = is.read(buffer)) != -1) {
bos.write(buffer, 0, length);
count += length;
//publishprogress()为asynctask类中的方法
//常在doinbackground()中调用此方法
//用于通知主线程,后台任务的执行情况.
//此时会触发asynctask中的onprogressupdate()方法
publishprogress((int) ((count / (float) total) * 100));
//为了演示进度,休眠1000毫秒
thread.sleep(1000);
}
return new string(bos.tobytearray(), "utf-8");
}
} catch (exception e) {
return null;
}
return null;
}
//onpostexecute()方法用于异步任务执行完成后,在主线程中执行的操作
@override
protected void onpostexecute(string result) {
super.onpostexecute(result); 
toast.maketext(getapplicationcontext(), "调用onpostexecute()方法--->异步任务执行完毕", 0).show();
//textview显示网络请求结果
textview.settext(result);
system.out.println("调用onpostexecute()方法--->异步任务执行完毕");
}
//onprogressupdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息 
@override
protected void onprogressupdate(integer... values) {
super.onprogressupdate(values);
//更改进度条
progressbar.setprogress(values[0]);
//更改textview
textview.settext("已经加载"+values[0]+"%");
}
//oncancelled()方法用于异步任务被取消时,在主线程中执行相关的操作 
@override
protected void oncancelled() {
super.oncancelled();
//更改进度条进度为0
progressbar.setprogress(0);
//更改textview
textview.settext("调用oncancelled()方法--->异步任务被取消");
system.out.println("调用oncancelled()方法--->异步任务被取消");
}
}
}

main.xml如下:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<button
android:id="@+id/startbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开始异步任务" />
<button
android:id="@+id/cancelbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="取消异步任务" />
<progressbar
android:id="@+id/progressbar"
style="?android:attr/progressbarstylehorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="0" />
<scrollview
android:id="@+id/scrollview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<textview
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test test" />
</scrollview>
</linearlayout>

以上内容是小编给大家介绍的android中asynctask异步任务使用详细实例(一),希望对大家有所帮助!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网