展会信息港展会大全

android开发使用AsyncTask类
来源:互联网   发布日期:2016-01-14 12:38:53   浏览:2119次  

导读:线程的异步操作主要用在了把某些操作或任务从UI主线程中剥离过程中,可以分成3类方法:1 使用AsyncTask类,这是个抽象类;2 使用Thread类;3 使用Loader类;这里简介AsyncTask类;1 首先要继承此类。继承该类时 ...

线程的异步操作主要用在了把某些操作或任务从UI主线程中剥离过程中,可以分成3类方法:

1.使用AsyncTask类,这是个抽象类;

2.使用Thread类;

3.使用Loader类;

这里简介AsyncTask类;

1. 首先要继承此类。

继承该类时,有三个泛型,解释如下

第一个参数Object,任务执行需要的数据类型

第二个参数Object,后台计算使用的进度单位数据类型

第三个参数Object,后台计算返回结果的数据类型

2.实现部分重要回调方法。

onPreExecute():在执行后台任务前要做的工作,一般是显示进度条。

doInBackground():在后台要执行的任务写在该方法中。

onProgressUpdate():这个方法是供UI主线程调用的,所以对UI中进度条的更新写在这个方法中;

publicProgress():该方法能周期性的给UI主线程发通知,所以在doInBackground()执行任务是需要调用该方法反馈进度;

onPostExecute():一旦任务执行结束就会回调该方法,所以该方法一般是显示执行任务后的结果以及dimiss进度条。

给段示例代码,

布局文件activity_main.xml:

<TextView

android:id="@+id/counter"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"

android:layout_marginLeft="80dp"

android:layout_marginTop="134dp"

android:text=" "/>

代码文件AsyncTaskDemo.java:

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

CountingTask ct = new CountingTask();

ct.execute();

}

class CountingTask extends AsyncTask<Void, Integer, Integer> {

public CountingTask(){}

@Override

protected Integer doInBackground(Void... voids) {

int i = 0;

while (i < 10) {

SystemClock.sleep(1000);

i++;

publishProgress(i);

}

return i;

}

@Override

protected void onProgressUpdate(Integer... integers) {

TextView tv = (TextView) findViewById(R.id.counter);

tv.setText(integers[0] + " % ");

}

@Override

protected void onPostExecute(Integer result) {

TextView tv = (TextView) findViewById(R.id.counter);

tv.setText(result + "% completed!");

}

}

}

另外,在API11以上的设备中,任务可以被并行执行,

此时启动Task改用启动,需要给出任务的ID,

CountingTask task = new CountingTask();

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,ID1);

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,ID1);

赞助本站

人工智能实验室

相关热词: AsyncTask android开发

相关内容
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港