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

来源:互联网 发布:软件培训学校靠谱吗 编辑:程序博客网 时间:2024/06/05 08:07

Mainactivity:

public class MainActivity extends Activity {TextView  prcTxt=null;@Overrideprotected 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界面执行的操作@Overrideprotected void onPostExecute(Void result) {// 任务完成后在主界面中显示任务结果prcTxt.setText("下载完毕");}//在任务执行之前要做的准备工作@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();}//在任务执行过程中显示进度的操作@Overrideprotected void onProgressUpdate(Integer... values) {prcTxt.setText(""+values[0]+"%");}//在后台执行的任务@Overrideprotected Void doInBackground(Void... params) {int i=0;while(i<100){SystemClock.sleep(100);i++;//发布任务的进度  这里一执行 onProgressUpdate就会跟着执行   publishProgress(i);}//这里一返回 onPostExecute就会执行return null;}}@Overridepublic 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>