您的位置:首页 > 移动开发 > Android开发

Android学习篇章42-AsyncTask-异步任务类

2013-11-03 11:55 393 查看
Mainactivity:

public class MainActivity extends Activity {

TextView  prcTxt=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prcTxt=(TextView)findViewById(R.id.prcTxt);
}

public void clickBtn(View view)
{
new MyDownloadTask().execute();

}

//第一个参数 是task要执行时 传递给它的执行参数的类型  如果没有可以设为Void
//第2个参数是用来显示任务进度的数据 的数据类型
//第3个参数是任务完成的结果数据的数据类型
public  class  MyDownloadTask extends AsyncTask<Void, Integer, Void>
{
//任务结束后要在UI界面执行的操作
@Override
protected void onPostExecute(Void result) {
// 任务完成后在主界面中显示任务结果
prcTxt.setText("下载完毕");

}
//在任务执行之前要做的准备工作
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
//在任务执行过程中显示进度的操作
@Override
protected void onProgressUpdate(Integer... values) {
prcTxt.setText(""+values[0]+"%");
}
//在后台执行的任务
@Override
protected Void doInBackground(Void... params) {
int i=0;
while(i<100)
{
SystemClock.sleep(100);
i++;
//发布任务的进度  这里一执行 onProgressUpdate就会跟着执行
publishProgress(i);
}
//这里一返回 onPostExecute就会执行
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}


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"
tools:context=".MainActivity" >

<TextView android:id="@+id/prcTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="35sp"
android:textColor="#f00"
android:text="" />

<Button android:id="@+id/btn1"
android:onClick="clickBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始下载" />
</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: