android中的主要UI线程,最好不要包括太耗时的操作,否则会让该线程阻塞,所以我们就需要将这些耗时的操作放在其他地方执行,而又与主要UI线程有一定关联。androidSDK提供了几种将操作从主UI线程移除的方法,这里主要介绍两种:1.使用AsyncTask类;2.使用标准Thread类
今天我们说说AsynTask
测试代码:
package com.example.engineerjspasyntask;
/**
* AsynTask Test
* @author Engineer-Jsp
* @date 2014.10.27
*
* */
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar);
EngineerJspAsynTask task = new EngineerJspAsynTask();
task.execute();
}
private class EngineerJspAsynTask extends AsyncTask<Void, Integer, Integer>{
public EngineerJspAsynTask() {
}
@Override
protected Integer doInBackground(Void... params) {
int i =0;
while(i<100){
try {
Thread.sleep(500);
i++;
if(1%1==0){
publishProgress(i);
}
} catch (Exception e) {
}
}
return i;
}
@Override
protected void onProgressUpdate(Integer... values) {
TextView text = (TextView)findViewById(R.id.textview);
text.setText("加载中..."+values[0]+"%");
Log.d("加载数据的打印进度:", ""+values[0]+"%");
}
@Override
protected void onPostExecute(Integer result) {
TextView text = (TextView)findViewById(R.id.textview);
text.setText("加载完成"+result.toString()+"%"+"!");
Log.d("加载数据的打印进度:", result.toString()+"%");
}
}
}
测试效果图:
测试数据打印结果:
xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/progressBar"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
AsynTask在做一些长时间耗时的操作或者网络操作、访问登录注册接口之类的,都很适用,而且使用相当简便~~