Android中AsyncTask的使用

  • 内容
  • 评论
  • 相关

我们之前讲过handler+Thread实现非UI线程更新UI界面的例子,这一次我们讲个更好用的异步,我们同样可以使用这个异步来实现之前的功能

package com.gaoxueping;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RecoverySystem.ProgressListener;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private Button execute, cancel;
	private ProgressBar progressBar;
	private TextView textView;
	private MyTask mTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		execute = (Button) findViewById(R.id.execute);
		execute.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mTask = new MyTask();
				mTask.execute("http://www.baidu.com");
				
			}
		});
		
		progressBar = (ProgressBar) findViewById(R.id.progress_bar);
		textView = (TextView) findViewById(R.id.text_view);
	}

	@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;
	}
	
	private class MyTask extends AsyncTask<String, Integer, String>{

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			Log.i("canled","onCancelled called");
			textView.setText("calced");
			progressBar.setProgress(0);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.i("post","onPostExecute() called");
			textView.setText(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.i("pre","onPreExecute() called");
			textView.setText("hey,loading......");
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			Log.i("updateBar","onProgressUpdate called");
			progressBar.setProgress(values[0]);
			textView.setText("Loading......" + values[0] + "%");
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.i("backRun","doInBackground() called");
			try{
				HttpClient client = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(params[0]);
				HttpResponse response = client.execute(httpGet);
				if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();
					long total = entity.getContentLength();
					
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buf = new byte[1024];
					int count = 0;
					int length = -1;
					while((length = is.read(buf)) != -1){
						baos.write(buf,0,length);
						count += length;
						
						publishProgress((int) (count / (float) length) * 100);
						Thread.sleep(500);
					}
					
					return new String(baos.toByteArray(),"utf8");
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			
			return null;
		}


		
	}
	

}

布局文件

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent">  
    <Button  
        android:id="@+id/execute"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="execute"/>  
    <Button  
        android:id="@+id/cancel"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"   
        android:text="cancel"/>  
    <ProgressBar   
        android:id="@+id/progress_bar"   
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:progress="0"  
        android:max="100"  
        style="?android:attr/progressBarStyleHorizontal"/>  
    <ScrollView  
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content">  
        <TextView  
            android:id="@+id/text_view"  
            android:layout_width="fill_parent"   
            android:layout_height="wrap_content"/>  
    </ScrollView>  
</LinearLayout>  

当然不要忘记加入访问网络的权限。

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注