AsnycTask更新主线程UI基本代码

  • Post author:
  • Post category:其他



<span style="font-size:18px;">package com.example.asynctask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		text = (TextView) findViewById(R.id.text);

		MyLongTimeTask task = new MyLongTimeTask(8);
		task.execute(1000, 2000);
	}
	//注意运行时里面方法的运行顺序
	private class MyLongTimeTask extends AsyncTask {
		//第一运行
		public MyLongTimeTask(int data) {
			Log.d("MyLongTimeTask", data + "");
		}
		//第二运行,主要做一些数据的初始化
		@Override
		protected void onPreExecute() {
			Log.d("onPreExecute", "done!");
		}
		//第三运行,主要做耗时操作
		@Override
		protected Object doInBackground(Object... params) {

			int a = (Integer) params[0];
			int b = (Integer) params[1];

			Log.d("doInBackground", a + "," + b);

			String result = a + "+" + b + "=" + (a + b);
			return result;
		}
		//第四运行。更新UI界面
		@Override
		protected void onPostExecute(Object result) {
			Log.d("onPostExecute", result + "");
			text.setText(result + "");
		}
	}
}
</span>



版权声明:本文为xiaoke804376088原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。