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

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值