android异步任务

Android默认UI线程阻塞超过20s,就会引发ANR异常。

AsyncTask 抽象类,

分别用于

启动任务,输入的参数

进度值的展示

结果的返回


	
		
			
				
				
			
		
	


重写相应方法


package down;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.example.asynctask.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity
{
	private TextView tx;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tx = (TextView) findViewById(R.id.textview);
	}

	public void download(View v)
	{
		try
		{
			//启动任务
			URL url = new URL("http://www.w3school.com.cn/");
			AsyncTaskTest ans = new AsyncTaskTest(this);
			ans.execute(url);
		} catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class AsyncTaskTest extends android.os.AsyncTask
	{
		private ProgressDialog pDialog;
		private Context mContext;
		private int hasRead = 0;

		public AsyncTaskTest(Context mContext)
		{
			// TODO Auto-generated constructor stub
			this.mContext = mContext;
		}
//任务
		@Override
		protected String doInBackground(URL... params)
		{
			// TODO Auto-generated method stub
			try
			{
				StringBuilder sb = new StringBuilder();
				URLConnection conn = params[0].openConnection();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						conn.getInputStream(), "UTF-8"));
				String line = null;
				while ((line = br.readLine()) != null)
				{
					hasRead++;
					sb.append(line + "\n");
					onProgressUpdate(hasRead);
				}
				return sb.toString();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
//执行任务后
		@Override
		protected void onPostExecute(String result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			tx.setText(result);
			pDialog.dismiss();
		}
//执行任务前
		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(mContext);
			pDialog.setTitle("任务下载中");
			pDialog.setMessage("任务正在下载中---");
			pDialog.setCancelable(false);
			pDialog.setMax(202);
			pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pDialog.setIndeterminate(false);
			pDialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			pDialog.setProgress(values[0]);
		}

	}
}




	
	


你可能感兴趣的:(Android)