Android AsyncTask实例

下面是AsyncTask实例,AsyncTask使用说明详见注释。

package com.example.asynctask;

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 com.example.androidtestproject.R;

import android.app.Activity;  
import android.os.AsyncTask;  
import android.os.Bundle;  
import android.util.Log;  
import android.view.View;  
import android.widget.Button;  
import android.widget.ProgressBar;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
      
    private static final String TAG = "ASYNC_TASK";  
      
    private Button execute;  
    private Button cancel;  
    private ProgressBar progressBar;  
    private TextView textView;  
    private MyTask mTask;  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        execute = (Button) findViewById(R.id.execute);  
        execute.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                //注意每次需new一个实例,新建的任务只能执行一次,否则会出现异常  
                mTask = new MyTask();  
                mTask.execute("http://www.csdn.net");  
                  
                execute.setEnabled(false);  
                cancel.setEnabled(true);  
            }  
        });  
        
        cancel = (Button) findViewById(R.id.cancel);  
        cancel.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                //取消一个正在执行的任务,onCancelled方法将会被调用
            	if ((mTask != null)) {
            		mTask.cancel(true);  
            	}
            }  
        });  
        
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);  
        textView = (TextView) findViewById(R.id.text_view);  
    }  
    
    private class MyTask extends AsyncTask<String, Integer, String> {  
    	
        //onPreExecute方法用于在执行后台任务前做一些UI操作  
        @Override  
        protected void onPreExecute() {  
            Log.i(TAG, "onPreExecute() called");  
            textView.setText("loading...");  
        }  
          
        //doInBackground方法内部执行后台任务,不可在此方法内修改UI  
        @Override  
        protected String doInBackground(String... params) {  
            Log.i(TAG, "doInBackground(Params... params) called");  
            try {  
                HttpClient client = new DefaultHttpClient();  
                HttpGet get = new HttpGet(params[0]);  
                HttpResponse response = client.execute(get);  
                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];  
                    long count = 0;  
                    int length = -1;
                    Log.i(TAG, "total=" + total);
                    while ((length = is.read(buf)) != -1) {  
                        if (isCancelled()) {
                        	Log.i(TAG, "isCancelled=true");
                        	return null; // don't forget to terminate this method
                        }
                        
                        baos.write(buf, 0, length);  
                        count += length;  
                        //调用publishProgress公布进度,最后onProgressUpdate方法将被执行  
                        publishProgress((int) ((count / (float) total) * 100));  
                        //为了演示进度,休眠50毫秒  
                        Thread.sleep(50);
                    }  
                    
                    return new String(baos.toByteArray(), "utf-8");  
                }  
            } catch (Exception e) {  
                Log.e(TAG, "exception");  
            }  
            
            return null;  
        }  
          
        //onProgressUpdate方法用于更新进度信息  
        @Override  
        protected void onProgressUpdate(Integer... progresses) {  
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");  
            progressBar.setProgress(progresses[0]);  
            textView.setText("loading..." + progresses[0] + "%");  
        }  
          
        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果  
        @Override  
        protected void onPostExecute(String result) {  
            Log.i(TAG, "onPostExecute(Result result) called");  
            textView.setText(result);  
              
            execute.setEnabled(true);  
            cancel.setEnabled(false);
        }

        //onCancelled方法用于在取消执行中的任务时更改UI
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			Log.i(TAG, "onCancelled called");
			textView.append(", Cancelled");
			
			execute.setEnabled(true);
			cancel.setEnabled(false);
		}  
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i(TAG, "onDestroy called");
		// 当Activity Destory时判断任务是否还在运行,还在运行的话则取消任务运行,否则Activity Destory掉后mTask还在后台运行,直到结束。
		if ((mTask != null) && (mTask.getStatus() == AsyncTask.Status.RUNNING)) {
			Log.i(TAG, "mTask.cancel");
			mTask.cancel(true);
		}
	}  
    
    
}  

Android AsyncTask实例_第1张图片

说明,该实例中
long total = entity.getContentLength();

total可能返回-1,一旦返回-1则进度显示是错误的。只是测试实例,暂且不处理返回-1的情况。


源码下载


你可能感兴趣的:(android,AsyncTask,cancel)