标签:
public class MainActivity extends Activity {
	private TextView show;
	private Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		show=(TextView)findViewById(R.id.show);
		show.setMovementMethod(ScrollingMovementMethod.getInstance());
		btn=(Button)findViewById(R.id.btn);
		btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				doTask();
			}
			
		});
	}
	
	private void doTask() {
		// TODO Auto-generated method stub
		DownTask task=new DownTask(this,show);
		try {
			task.execute(new URL("http://www.szit.edu.cn/"));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@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;
	}
}
public class DownTask extends AsyncTask<URL, Integer, String>
{
	ProgressDialog progressDialog;
	int hasRead=0;
	Context context;
	TextView show;
	public DownTask(Context context,TextView show)
	{
		this.context=context;
		this.show=show;
	}
	@Override
	protected String doInBackground(URL... arg0) {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		try {
			URLConnection conn=arg0[0].openConnection();
			BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"gb2312"));
			String line="";
			while ((line=br.readLine())!=null) {
				sb.append(line+"\n");
				hasRead++;
				publishProgress(hasRead);
				
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return sb.toString();
	}
	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		show.setText(result);
		progressDialog.dismiss();
	}
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		progressDialog=new ProgressDialog(context);
		progressDialog.setTitle("任务执行中");
		progressDialog.setMessage("敬请等待");
		progressDialog.setCancelable(false);
		progressDialog.setMax(300);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setIndeterminate(false);
		progressDialog.show();
	}
	@Override
	protected void onProgressUpdate(Integer... values) {
		// TODO Auto-generated method stub
		show.setText("已读取"+values[0]+"行");
		progressDialog.setProgress(values[0]);
	}
	
}
标签:
原文地址:http://www.cnblogs.com/zhouhb/p/5814981.html