Android学习:AsyncTask方案解决UI线程阻塞

post方式能解决UI线程阻塞问题,但是代码的可读性较差。

一:看程序

package com.example.testuithread;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;

/**
 * AsyncTask解决UI线程阻塞
 * @author Administrator
 * 
 */
public class MainActivity extends Activity {

	private Button button2 = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// button1添加动画操作
		Button button1 = (Button) findViewById(R.id.button1);
		TranslateAnimation animation = new TranslateAnimation(0, 150, 0, 0);
		animation.setRepeatCount(3);
		animation.setDuration(2000);
		button1.setAnimation(animation);

		// 为button2添加一个点击事件,实现一个阻塞
		button2 = (Button) findViewById(R.id.button2);
		button2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {

				new testTask().execute();
			}
		});
	}

	private class testTask extends AsyncTask {

		protected Integer doInBackground(String... arg0) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int sum = 10;
			return 10;
		}

		protected void onPostExecute(Integer sum) {
			button2.setText("" + sum);
		}

	}

	@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;
	}

}

二:定义AsyncTask
private class testTask extends AsyncTask {

		protected Integer doInBackground(String... arg0) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			int sum = 10;
			return 10;
		}

		protected void onPostExecute(Integer sum) {
			button2.setText("" + sum);
		}

	}


执行task
new testTask().execute();


你可能感兴趣的:(Android学习:AsyncTask方案解决UI线程阻塞)